mirror of
https://github.com/Sonny93/my-links.git
synced 2025-12-11 08:43:04 +00:00
Compare commits
26 Commits
56b52adac0
...
3.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4aea038fe | ||
|
|
d03004b841 | ||
|
|
64cd4820c5 | ||
|
|
1c81a6a86f | ||
|
|
208f2c631f | ||
|
|
9aa71dad30 | ||
|
|
d00b6b9edd | ||
|
|
376e9e32c3 | ||
|
|
c2a1d06008 | ||
|
|
44c187acaf | ||
|
|
a076560285 | ||
|
|
3d986bd662 | ||
|
|
8537eeb375 | ||
|
|
7672a719ea | ||
|
|
23ad1fda75 | ||
|
|
4ef2b639b6 | ||
|
|
18fe979069 | ||
|
|
5f7fad26fa | ||
|
|
87ced07d20 | ||
|
|
ac0605caf5 | ||
|
|
11df24128f | ||
|
|
42f391d99a | ||
|
|
1d1e182523 | ||
|
|
81d02d3d80 | ||
|
|
d57f3ec486 | ||
|
|
9ff3ca112c |
@@ -99,7 +99,7 @@ type FaviconGetHead = {
|
|||||||
type LinksCreateGetHead = {
|
type LinksCreateGetHead = {
|
||||||
request: unknown;
|
request: unknown;
|
||||||
response: MakeTuyauResponse<
|
response: MakeTuyauResponse<
|
||||||
import('../app/links/controllers/links_controller.ts').default['showCreatePage'],
|
import('../app/links/controllers/delete_link_controller.js').default['showCreatePage'],
|
||||||
false
|
false
|
||||||
>;
|
>;
|
||||||
};
|
};
|
||||||
@@ -110,14 +110,14 @@ type LinksPost = {
|
|||||||
>
|
>
|
||||||
>;
|
>;
|
||||||
response: MakeTuyauResponse<
|
response: MakeTuyauResponse<
|
||||||
import('../app/links/controllers/links_controller.ts').default['store'],
|
import('../app/links/controllers/delete_link_controller.js').default['store'],
|
||||||
true
|
true
|
||||||
>;
|
>;
|
||||||
};
|
};
|
||||||
type LinksEditGetHead = {
|
type LinksEditGetHead = {
|
||||||
request: unknown;
|
request: unknown;
|
||||||
response: MakeTuyauResponse<
|
response: MakeTuyauResponse<
|
||||||
import('../app/links/controllers/links_controller.ts').default['showEditPage'],
|
import('../app/links/controllers/delete_link_controller.js').default['showEditPage'],
|
||||||
false
|
false
|
||||||
>;
|
>;
|
||||||
};
|
};
|
||||||
@@ -128,7 +128,7 @@ type LinksIdPut = {
|
|||||||
>
|
>
|
||||||
>;
|
>;
|
||||||
response: MakeTuyauResponse<
|
response: MakeTuyauResponse<
|
||||||
import('../app/links/controllers/links_controller.ts').default['update'],
|
import('../app/links/controllers/delete_link_controller.js').default['update'],
|
||||||
true
|
true
|
||||||
>;
|
>;
|
||||||
};
|
};
|
||||||
@@ -139,14 +139,14 @@ type LinksIdFavoritePut = {
|
|||||||
>
|
>
|
||||||
>;
|
>;
|
||||||
response: MakeTuyauResponse<
|
response: MakeTuyauResponse<
|
||||||
import('../app/links/controllers/links_controller.ts').default['toggleFavorite'],
|
import('../app/links/controllers/delete_link_controller.js').default['toggleFavorite'],
|
||||||
true
|
true
|
||||||
>;
|
>;
|
||||||
};
|
};
|
||||||
type LinksDeleteGetHead = {
|
type LinksDeleteGetHead = {
|
||||||
request: unknown;
|
request: unknown;
|
||||||
response: MakeTuyauResponse<
|
response: MakeTuyauResponse<
|
||||||
import('../app/links/controllers/links_controller.ts').default['showDeletePage'],
|
import('../app/links/controllers/delete_link_controller.js').default['showDeletePage'],
|
||||||
false
|
false
|
||||||
>;
|
>;
|
||||||
};
|
};
|
||||||
@@ -157,7 +157,7 @@ type LinksIdDelete = {
|
|||||||
>
|
>
|
||||||
>;
|
>;
|
||||||
response: MakeTuyauResponse<
|
response: MakeTuyauResponse<
|
||||||
import('../app/links/controllers/links_controller.ts').default['delete'],
|
import('../app/links/controllers/delete_link_controller.js').default['execute'],
|
||||||
true
|
true
|
||||||
>;
|
>;
|
||||||
};
|
};
|
||||||
|
|||||||
14
.env.example
14
.env.example
@@ -1,16 +1,22 @@
|
|||||||
# node ace generate:key
|
# App
|
||||||
APP_KEY=soY8ZAtItT_fCkNUADfgffZUUo675lOj
|
|
||||||
TZ=UTC
|
TZ=UTC
|
||||||
PORT=3333
|
PORT=3333
|
||||||
HOST=localhost
|
HOST=localhost
|
||||||
LOG_LEVEL=info
|
LOG_LEVEL=debug
|
||||||
|
APP_KEY=soY8ZAtItT_fCkNUADfgffZUUo675lOj # node ace generate:key
|
||||||
NODE_ENV=development
|
NODE_ENV=development
|
||||||
SESSION_DRIVER=cookie
|
SESSION_DRIVER=cookie
|
||||||
|
|
||||||
|
# App url
|
||||||
|
APP_URL=http://localhost:3333
|
||||||
|
|
||||||
|
# Database
|
||||||
DB_HOST=127.0.0.1
|
DB_HOST=127.0.0.1
|
||||||
DB_PORT=5432
|
DB_PORT=5432
|
||||||
DB_USER=root
|
DB_USER=root
|
||||||
DB_PASSWORD=root
|
DB_PASSWORD=root
|
||||||
DB_DATABASE=app
|
DB_DATABASE=app
|
||||||
|
|
||||||
|
# Google
|
||||||
GOOGLE_CLIENT_ID=
|
GOOGLE_CLIENT_ID=
|
||||||
GOOGLE_CLIENT_SECRET=
|
GOOGLE_CLIENT_SECRET=
|
||||||
GOOGLE_CLIENT_CALLBACK_URL=http://localhost:3333/auth/callback
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Source : https://github.com/adonisjs-community/adonis-packages/blob/main/Dockerfile
|
# Source : https://github.com/adonisjs-community/adonis-packages/blob/main/Dockerfile
|
||||||
|
|
||||||
FROM node:24.1-alpine3.20 AS base
|
FROM node:24.11-alpine3.22 AS base
|
||||||
|
|
||||||
RUN apk --no-cache add curl
|
RUN apk --no-cache add curl
|
||||||
RUN corepack enable
|
RUN corepack enable
|
||||||
@@ -34,9 +34,9 @@ ENV DB_PORT=5432
|
|||||||
ENV DB_USER=db_user
|
ENV DB_USER=db_user
|
||||||
ENV DB_PASSWORD=db_password
|
ENV DB_PASSWORD=db_password
|
||||||
ENV DB_DATABASE=db_db
|
ENV DB_DATABASE=db_db
|
||||||
|
ENV APP_URL=http://localhost:3333
|
||||||
ENV GOOGLE_CLIENT_ID=client_id
|
ENV GOOGLE_CLIENT_ID=client_id
|
||||||
ENV GOOGLE_CLIENT_SECRET=client_secret
|
ENV GOOGLE_CLIENT_SECRET=client_secret
|
||||||
ENV GOOGLE_CLIENT_CALLBACK_URL=http://localhost:3333/auth/callback
|
|
||||||
|
|
||||||
RUN node ace izzy:routes
|
RUN node ace izzy:routes
|
||||||
RUN node ace build
|
RUN node ace build
|
||||||
|
|||||||
21
README.md
21
README.md
@@ -92,6 +92,27 @@ pnpm run start
|
|||||||
openssl rand -base64 32
|
openssl rand -base64 32
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Google OAuth
|
||||||
|
|
||||||
|
Pour obtenir le Client ID et Secret Google nécessaires à l'authentification :
|
||||||
|
|
||||||
|
1. Accédez à la [Console Google Cloud](https://console.cloud.google.com/)
|
||||||
|
2. Créez un nouveau projet ou sélectionnez un projet existant
|
||||||
|
3. Activez l'API **Google+ API** (ou utilisez directement l'API OAuth 2.0)
|
||||||
|
4. Allez dans **Identifiants** (Credentials) > **Créer des identifiants** > **ID client OAuth 2.0**
|
||||||
|
5. Configurez l'écran de consentement OAuth si ce n'est pas déjà fait :
|
||||||
|
- Type d'application : **Interne** ou **Externe**
|
||||||
|
- Remplissez les informations requises (nom de l'application, email de support, etc.)
|
||||||
|
6. Créez l'ID client OAuth 2.0 :
|
||||||
|
- Type d'application : **Application Web**
|
||||||
|
- Nom : choisissez un nom pour votre application
|
||||||
|
- URI de redirection autorisés : ajoutez `http://localhost:3333/auth/callback` pour le développement (ou votre URL de production + `/auth/callback`)
|
||||||
|
7. Une fois créé, vous obtiendrez :
|
||||||
|
- **Client ID** : à définir dans `GOOGLE_CLIENT_ID`
|
||||||
|
- **Client Secret** : à définir dans `GOOGLE_CLIENT_SECRET`
|
||||||
|
|
||||||
|
> **Note** : Pour la production, assurez-vous d'ajouter votre URL de production dans les URI de redirection autorisés (ex: `https://votre-domaine.com/auth/callback`)
|
||||||
|
|
||||||
### GitHub Actions
|
### GitHub Actions
|
||||||
|
|
||||||
Env var to define :
|
Env var to define :
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import AuthController from '#auth/controllers/auth_controller';
|
import AuthController from '#auth/controllers/auth_controller';
|
||||||
import CollectionsController from '#collections/controllers/show_collections_controller';
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
import LinksController from '#links/controllers/links_controller';
|
import LinksController from '#links/controllers/delete_link_controller';
|
||||||
import User from '#user/models/user';
|
import User from '#user/models/user';
|
||||||
import { inject } from '@adonisjs/core';
|
import { inject } from '@adonisjs/core';
|
||||||
import { HttpContext } from '@adonisjs/core/http';
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
@@ -28,14 +28,14 @@ export default class AdminController {
|
|||||||
constructor(
|
constructor(
|
||||||
protected usersController: AuthController,
|
protected usersController: AuthController,
|
||||||
protected linksController: LinksController,
|
protected linksController: LinksController,
|
||||||
protected collectionsController: CollectionsController
|
protected collectionService: CollectionService
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async index({ inertia }: HttpContext) {
|
async index({ inertia }: HttpContext) {
|
||||||
const users = await this.usersController.getAllUsersWithTotalRelations();
|
const users = await this.usersController.getAllUsersWithTotalRelations();
|
||||||
const linksCount = await this.linksController.getTotalLinksCount();
|
const linksCount = await this.linksController.getTotalLinksCount();
|
||||||
const collectionsCount =
|
const collectionsCount =
|
||||||
await this.collectionsController.getTotalCollectionsCount();
|
await this.collectionService.getTotalCollectionsCount();
|
||||||
|
|
||||||
return inertia.render('admin/dashboard', {
|
return inertia.render('admin/dashboard', {
|
||||||
users: users.map((user) => new UserWithRelationCountDto(user).toJson()),
|
users: users.map((user) => new UserWithRelationCountDto(user).toJson()),
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
|
import { createCollectionValidator } from '#collections/validators/create_collection_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { type HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class CreateCollectionController {
|
||||||
|
constructor(private collectionService: CollectionService) {}
|
||||||
|
|
||||||
|
async execute({ request, response }: HttpContext) {
|
||||||
|
console.log('avant');
|
||||||
|
const payload = await request.validateUsing(createCollectionValidator);
|
||||||
|
const collection = await this.collectionService.createCollection(payload);
|
||||||
|
console.log('après', collection);
|
||||||
|
return response.json({
|
||||||
|
message: 'Collection created successfully',
|
||||||
|
collection: collection.serialize(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
|
import { deleteCollectionValidator } from '#collections/validators/delete_collection_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class DeleteCollectionController {
|
||||||
|
constructor(private collectionService: CollectionService) {}
|
||||||
|
|
||||||
|
async execute({ request, response }: HttpContext) {
|
||||||
|
const { params } = await request.validateUsing(deleteCollectionValidator);
|
||||||
|
await this.collectionService.deleteCollection(params.id);
|
||||||
|
return response.json({
|
||||||
|
message: 'Collection deleted successfully',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class GetCollectionsController {
|
||||||
|
constructor(private collectionService: CollectionService) {}
|
||||||
|
|
||||||
|
async show({ response }: HttpContext) {
|
||||||
|
const collections =
|
||||||
|
await this.collectionService.getCollectionsForAuthenticatedUser();
|
||||||
|
return response.json({
|
||||||
|
collections: collections.map((collection) => collection.serialize()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
|
import { updateCollectionValidator } from '#collections/validators/update_collection_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class UpdateCollectionController {
|
||||||
|
constructor(private collectionService: CollectionService) {}
|
||||||
|
|
||||||
|
async execute({ request, response }: HttpContext) {
|
||||||
|
const {
|
||||||
|
params: { id: collectionId },
|
||||||
|
...payload
|
||||||
|
} = await request.validateUsing(updateCollectionValidator);
|
||||||
|
|
||||||
|
await this.collectionService.updateCollection(collectionId, payload);
|
||||||
|
return response.json({
|
||||||
|
message: 'Collection updated successfully',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
14
app/api/collections/routes/api_create_collections_routes.ts
Normal file
14
app/api/collections/routes/api_create_collections_routes.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const CreateCollectionsController = () =>
|
||||||
|
import('#api/collections/controllers/create_collection_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router
|
||||||
|
.post('', [CreateCollectionsController, 'execute'])
|
||||||
|
.as('api-collections.create');
|
||||||
|
})
|
||||||
|
.prefix('/api/v1/collections')
|
||||||
|
.middleware([middleware.auth({ guards: ['api'] })]);
|
||||||
14
app/api/collections/routes/api_delete_collections_routes.ts
Normal file
14
app/api/collections/routes/api_delete_collections_routes.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const DeleteCollectionsController = () =>
|
||||||
|
import('#api/collections/controllers/delete_collection_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router
|
||||||
|
.delete('/:id', [DeleteCollectionsController, 'execute'])
|
||||||
|
.as('api-collections.delete');
|
||||||
|
})
|
||||||
|
.prefix('/api/v1/collections')
|
||||||
|
.middleware([middleware.auth({ guards: ['api'] })]);
|
||||||
14
app/api/collections/routes/api_get_collections_routes.ts
Normal file
14
app/api/collections/routes/api_get_collections_routes.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const GetCollectionsController = () =>
|
||||||
|
import('#api/collections/controllers/get_collections_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router
|
||||||
|
.get('', [GetCollectionsController, 'show'])
|
||||||
|
.as('api-collections.index');
|
||||||
|
})
|
||||||
|
.prefix('/api/v1/collections')
|
||||||
|
.middleware([middleware.auth({ guards: ['api'] })]);
|
||||||
14
app/api/collections/routes/api_update_collections_routes.ts
Normal file
14
app/api/collections/routes/api_update_collections_routes.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const UpdateCollectionsController = () =>
|
||||||
|
import('#api/collections/controllers/update_collection_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router
|
||||||
|
.put('/:id', [UpdateCollectionsController, 'execute'])
|
||||||
|
.as('api-collections.update');
|
||||||
|
})
|
||||||
|
.prefix('/api/v1/collections')
|
||||||
|
.middleware([middleware.auth({ guards: ['api'] })]);
|
||||||
4
app/api/collections/routes/routes.ts
Normal file
4
app/api/collections/routes/routes.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
import '#api/collections/routes/api_create_collections_routes';
|
||||||
|
import '#api/collections/routes/api_delete_collections_routes';
|
||||||
|
import '#api/collections/routes/api_get_collections_routes';
|
||||||
|
import '#api/collections/routes/api_update_collections_routes';
|
||||||
23
app/api/links/controllers/create_link_controller.ts
Normal file
23
app/api/links/controllers/create_link_controller.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { LinkService } from '#links/services/link_service';
|
||||||
|
import { createLinkValidator } from '#links/validators/create_link_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class CreateLinkController {
|
||||||
|
constructor(private linkService: LinkService) {}
|
||||||
|
|
||||||
|
async execute({ request, response }: HttpContext) {
|
||||||
|
const { collectionId, ...payload } =
|
||||||
|
await request.validateUsing(createLinkValidator);
|
||||||
|
|
||||||
|
const link = await this.linkService.createLink({
|
||||||
|
...payload,
|
||||||
|
collectionId,
|
||||||
|
});
|
||||||
|
return response.json({
|
||||||
|
message: 'Link created successfully',
|
||||||
|
link: link.serialize(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
39
app/api/links/controllers/delete_link_controller.ts
Normal file
39
app/api/links/controllers/delete_link_controller.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
|
import { LinkService } from '#links/services/link_service';
|
||||||
|
import { deleteLinkValidator } from '#links/validators/delete_link_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import db from '@adonisjs/lucid/services/db';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class DeleteLinkController {
|
||||||
|
constructor(
|
||||||
|
protected collectionsService: CollectionService,
|
||||||
|
protected linkService: LinkService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async render({ auth, inertia, request }: HttpContext) {
|
||||||
|
const linkId = request.qs()?.linkId;
|
||||||
|
if (!linkId) {
|
||||||
|
return this.collectionsService.redirectToDashboard();
|
||||||
|
}
|
||||||
|
|
||||||
|
const link = await this.linkService.getLinkById(linkId, auth.user!.id);
|
||||||
|
await link.load('collection');
|
||||||
|
return inertia.render('links/delete', { link });
|
||||||
|
}
|
||||||
|
|
||||||
|
async execute({ request, auth }: HttpContext) {
|
||||||
|
const { params } = await request.validateUsing(deleteLinkValidator);
|
||||||
|
|
||||||
|
const link = await this.linkService.getLinkById(params.id, auth.user!.id);
|
||||||
|
await this.linkService.deleteLink(params.id);
|
||||||
|
|
||||||
|
return this.collectionsService.redirectToCollectionId(link.collectionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTotalLinksCount() {
|
||||||
|
const totalCount = await db.from('links').count('* as total');
|
||||||
|
return Number(totalCount[0].total);
|
||||||
|
}
|
||||||
|
}
|
||||||
13
app/api/links/controllers/get_favorite_links_controller.ts
Normal file
13
app/api/links/controllers/get_favorite_links_controller.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { LinkService } from '#links/services/link_service';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class GetFavoriteLinksController {
|
||||||
|
constructor(private linkService: LinkService) {}
|
||||||
|
|
||||||
|
public async execute({ response }: HttpContext) {
|
||||||
|
const links = await this.linkService.getFavoriteLinksForAuthenticatedUser();
|
||||||
|
return response.json(links);
|
||||||
|
}
|
||||||
|
}
|
||||||
19
app/api/links/controllers/update_link_controller.ts
Normal file
19
app/api/links/controllers/update_link_controller.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { LinkService } from '#links/services/link_service';
|
||||||
|
import { updateLinkValidator } from '#links/validators/update_link_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class UpdateLinkController {
|
||||||
|
constructor(private linkService: LinkService) {}
|
||||||
|
|
||||||
|
async execute({ request, response }: HttpContext) {
|
||||||
|
const { params, ...payload } =
|
||||||
|
await request.validateUsing(updateLinkValidator);
|
||||||
|
|
||||||
|
await this.linkService.updateLink(params.id, payload);
|
||||||
|
return response.json({
|
||||||
|
message: 'Link updated successfully',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
12
app/api/links/routes/api_create_link_routes.ts
Normal file
12
app/api/links/routes/api_create_link_routes.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const CreateLinkController = () =>
|
||||||
|
import('#api/links/controllers/create_link_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router.post('', [CreateLinkController, 'execute']).as('api-links.create');
|
||||||
|
})
|
||||||
|
.prefix('/api/v1/links')
|
||||||
|
.middleware([middleware.auth({ guards: ['api'] })]);
|
||||||
14
app/api/links/routes/api_delete_link_route.ts
Normal file
14
app/api/links/routes/api_delete_link_route.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const DeleteLinkController = () =>
|
||||||
|
import('#api/links/controllers/delete_link_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router
|
||||||
|
.delete('/:id', [DeleteLinkController, 'execute'])
|
||||||
|
.as('api-links.delete');
|
||||||
|
})
|
||||||
|
.prefix('/api/v1/links')
|
||||||
|
.middleware([middleware.auth({ guards: ['api'] })]);
|
||||||
14
app/api/links/routes/api_get_favorite_links_routes.ts
Normal file
14
app/api/links/routes/api_get_favorite_links_routes.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const GetFavoriteLinksController = () =>
|
||||||
|
import('#api/links/controllers/get_favorite_links_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router
|
||||||
|
.get('', [GetFavoriteLinksController, 'execute'])
|
||||||
|
.as('api-links.get-favorite-links');
|
||||||
|
})
|
||||||
|
.prefix('/api/v1/links/favorites')
|
||||||
|
.middleware([middleware.auth({ guards: ['api'] })]);
|
||||||
14
app/api/links/routes/api_update_link_route.ts
Normal file
14
app/api/links/routes/api_update_link_route.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const UpdateLinkController = () =>
|
||||||
|
import('#api/links/controllers/update_link_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router
|
||||||
|
.put('/:id', [UpdateLinkController, 'execute'])
|
||||||
|
.as('api-links.update');
|
||||||
|
})
|
||||||
|
.prefix('/api/v1/links')
|
||||||
|
.middleware([middleware.auth({ guards: ['api'] })]);
|
||||||
4
app/api/links/routes/routes.ts
Normal file
4
app/api/links/routes/routes.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
import '#api/links/routes/api_create_link_routes';
|
||||||
|
import '#api/links/routes/api_delete_link_route';
|
||||||
|
import '#api/links/routes/api_get_favorite_links_routes';
|
||||||
|
import '#api/links/routes/api_update_link_route';
|
||||||
18
app/api/tokens/controllers/api_token_controller.ts
Normal file
18
app/api/tokens/controllers/api_token_controller.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import UnAuthorizedException from '#api/tokens/exceptions/un_authorized_exception';
|
||||||
|
import { getTokenFromHeader } from '#api/tokens/lib/index';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class ApiTokenController {
|
||||||
|
async index(ctx: HttpContext) {
|
||||||
|
const token = getTokenFromHeader(ctx);
|
||||||
|
if (!token) {
|
||||||
|
throw new UnAuthorizedException();
|
||||||
|
}
|
||||||
|
|
||||||
|
return ctx.response.json({
|
||||||
|
message: 'Token is valid',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
7
app/api/tokens/exceptions/un_authorized_exception.ts
Normal file
7
app/api/tokens/exceptions/un_authorized_exception.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { Exception } from '@adonisjs/core/exceptions';
|
||||||
|
|
||||||
|
export default class UnAuthorizedException extends Exception {
|
||||||
|
static status = 401;
|
||||||
|
message = 'Missing or invalid authorization header';
|
||||||
|
code = 'UNAUTHORIZED';
|
||||||
|
}
|
||||||
11
app/api/tokens/lib/index.ts
Normal file
11
app/api/tokens/lib/index.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
export function getTokenFromHeader(ctx: HttpContext) {
|
||||||
|
const authHeader = ctx.request.header('Authorization');
|
||||||
|
|
||||||
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return authHeader.substring(7);
|
||||||
|
}
|
||||||
12
app/api/tokens/routes/api_token_routes.ts
Normal file
12
app/api/tokens/routes/api_token_routes.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const ApiTokenController = () =>
|
||||||
|
import('#api/tokens/controllers/api_token_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router.get('/check', [ApiTokenController, 'index']).as('api-tokens.index');
|
||||||
|
})
|
||||||
|
.prefix('/api/v1/tokens')
|
||||||
|
.middleware([middleware.auth({ guards: ['api'] })]);
|
||||||
1
app/api/tokens/routes/routes.ts
Normal file
1
app/api/tokens/routes/routes.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
import '#api/tokens/routes/api_token_routes';
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
import Collection from '#collections/models/collection';
|
|
||||||
import { HttpContext } from '@adonisjs/core/http';
|
|
||||||
import vine from '@vinejs/vine';
|
|
||||||
|
|
||||||
export default class BaseCollectionController {
|
|
||||||
protected collectionIdValidator = vine.compile(
|
|
||||||
vine.object({
|
|
||||||
collectionId: vine.number().positive().optional(),
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
async validateCollectionId(collectionIdRequired: boolean = true) {
|
|
||||||
const ctx = HttpContext.getOrFail();
|
|
||||||
const { collectionId } = await ctx.request.validateUsing(
|
|
||||||
this.collectionIdValidator
|
|
||||||
);
|
|
||||||
if (!collectionId && collectionIdRequired) {
|
|
||||||
console.log('redirecting to dashboard');
|
|
||||||
ctx.response.redirectToNamedRoute('dashboard');
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
console.log('collectionId', collectionId);
|
|
||||||
return collectionId;
|
|
||||||
}
|
|
||||||
|
|
||||||
redirectToCollectionId(collectionId: Collection['id']) {
|
|
||||||
const ctx = HttpContext.getOrFail();
|
|
||||||
return ctx.response.redirectToNamedRoute('dashboard', {
|
|
||||||
qs: { collectionId },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +1,15 @@
|
|||||||
import BaseCollectionController from '#collections/controllers/base_collection_controller';
|
|
||||||
import { CollectionService } from '#collections/services/collection_service';
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
import { createCollectionValidator } from '#collections/validators/create_collection_validator';
|
import { createCollectionValidator } from '#collections/validators/create_collection_validator';
|
||||||
import { inject } from '@adonisjs/core';
|
import { inject } from '@adonisjs/core';
|
||||||
import { type HttpContext } from '@adonisjs/core/http';
|
import { type HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
@inject()
|
@inject()
|
||||||
export default class CreateCollectionController extends BaseCollectionController {
|
export default class CreateCollectionController {
|
||||||
constructor(private collectionService: CollectionService) {
|
constructor(private collectionService: CollectionService) {}
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
async render({ inertia }: HttpContext) {
|
async render({ inertia }: HttpContext) {
|
||||||
const collections = await this.collectionService.getCollectionsByAuthorId();
|
const collections =
|
||||||
|
await this.collectionService.getCollectionsForAuthenticatedUser();
|
||||||
return inertia.render('collections/create', {
|
return inertia.render('collections/create', {
|
||||||
disableHomeLink: collections.length === 0,
|
disableHomeLink: collections.length === 0,
|
||||||
});
|
});
|
||||||
@@ -20,6 +18,6 @@ export default class CreateCollectionController extends BaseCollectionController
|
|||||||
async execute({ request }: HttpContext) {
|
async execute({ request }: HttpContext) {
|
||||||
const payload = await request.validateUsing(createCollectionValidator);
|
const payload = await request.validateUsing(createCollectionValidator);
|
||||||
const collection = await this.collectionService.createCollection(payload);
|
const collection = await this.collectionService.createCollection(payload);
|
||||||
return this.redirectToCollectionId(collection.id);
|
return this.collectionService.redirectToCollectionId(collection.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,14 @@
|
|||||||
import BaseCollectionController from '#collections/controllers/base_collection_controller';
|
|
||||||
import { CollectionService } from '#collections/services/collection_service';
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
import { deleteCollectionValidator } from '#collections/validators/delete_collection_validator';
|
import { deleteCollectionValidator } from '#collections/validators/delete_collection_validator';
|
||||||
import { inject } from '@adonisjs/core';
|
import { inject } from '@adonisjs/core';
|
||||||
import { HttpContext } from '@adonisjs/core/http';
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
@inject()
|
@inject()
|
||||||
export default class DeleteCollectionController extends BaseCollectionController {
|
export default class DeleteCollectionController {
|
||||||
constructor(private collectionService: CollectionService) {
|
constructor(private collectionService: CollectionService) {}
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
async render({ inertia }: HttpContext) {
|
async render({ inertia }: HttpContext) {
|
||||||
const collectionId = await this.validateCollectionId();
|
const collectionId = await this.collectionService.validateCollectionId();
|
||||||
if (!collectionId) return;
|
if (!collectionId) return;
|
||||||
|
|
||||||
const collection =
|
const collection =
|
||||||
|
|||||||
@@ -1,21 +1,23 @@
|
|||||||
import BaseCollectionController from '#collections/controllers/base_collection_controller';
|
|
||||||
import { CollectionService } from '#collections/services/collection_service';
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
|
import { LinkService } from '#links/services/link_service';
|
||||||
import { inject } from '@adonisjs/core';
|
import { inject } from '@adonisjs/core';
|
||||||
import type { HttpContext } from '@adonisjs/core/http';
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
@inject()
|
@inject()
|
||||||
export default class ShowCollectionsController extends BaseCollectionController {
|
export default class ShowCollectionsController {
|
||||||
constructor(private collectionService: CollectionService) {
|
constructor(
|
||||||
super();
|
private collectionService: CollectionService,
|
||||||
}
|
private linkService: LinkService
|
||||||
|
) {}
|
||||||
|
|
||||||
// Dashboard
|
// Dashboard
|
||||||
async render({ inertia, response }: HttpContext) {
|
async render({ inertia, response }: HttpContext) {
|
||||||
const activeCollectionId = await this.validateCollectionId(false);
|
const activeCollectionId =
|
||||||
const collections = await this.collectionService.getCollectionsByAuthorId();
|
await this.collectionService.validateCollectionId(false);
|
||||||
if (collections.length === 0) {
|
const [collections, favoriteLinks] = await Promise.all([
|
||||||
return response.redirectToNamedRoute('collection.create-form');
|
this.collectionService.getCollectionsForAuthenticatedUser(),
|
||||||
}
|
this.linkService.getFavoriteLinksForAuthenticatedUser(),
|
||||||
|
]);
|
||||||
|
|
||||||
const activeCollection = collections.find(
|
const activeCollection = collections.find(
|
||||||
(c) => c.id === activeCollectionId
|
(c) => c.id === activeCollectionId
|
||||||
@@ -27,8 +29,8 @@ export default class ShowCollectionsController extends BaseCollectionController
|
|||||||
|
|
||||||
return inertia.render('dashboard', {
|
return inertia.render('dashboard', {
|
||||||
collections: collections.map((collection) => collection.serialize()),
|
collections: collections.map((collection) => collection.serialize()),
|
||||||
activeCollection:
|
favoriteLinks: favoriteLinks.map((link) => link.serialize()),
|
||||||
activeCollection?.serialize() || collections[0].serialize(),
|
activeCollection: activeCollection?.serialize(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,19 @@
|
|||||||
import BaseCollectionController from '#collections/controllers/base_collection_controller';
|
|
||||||
import { CollectionService } from '#collections/services/collection_service';
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
import { updateCollectionValidator } from '#collections/validators/update_collection_validator';
|
import { updateCollectionValidator } from '#collections/validators/update_collection_validator';
|
||||||
import { inject } from '@adonisjs/core';
|
import { inject } from '@adonisjs/core';
|
||||||
import { HttpContext } from '@adonisjs/core/http';
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
@inject()
|
@inject()
|
||||||
export default class UpdateCollectionController extends BaseCollectionController {
|
export default class UpdateCollectionController {
|
||||||
constructor(private collectionService: CollectionService) {
|
constructor(private collectionService: CollectionService) {}
|
||||||
super();
|
|
||||||
}
|
|
||||||
|
|
||||||
async render({ inertia }: HttpContext) {
|
async render({ inertia }: HttpContext) {
|
||||||
const collectionId = await this.validateCollectionId();
|
const collectionId = await this.collectionService.validateCollectionId();
|
||||||
if (!collectionId) return;
|
if (!collectionId) return;
|
||||||
|
|
||||||
const collection =
|
const collection =
|
||||||
await this.collectionService.getCollectionById(collectionId);
|
await this.collectionService.getCollectionById(collectionId);
|
||||||
return inertia.render('collections/update', {
|
return inertia.render('collections/edit', {
|
||||||
collection: collection.serialize(),
|
collection: collection.serialize(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -28,6 +25,6 @@ export default class UpdateCollectionController extends BaseCollectionController
|
|||||||
} = await request.validateUsing(updateCollectionValidator);
|
} = await request.validateUsing(updateCollectionValidator);
|
||||||
|
|
||||||
await this.collectionService.updateCollection(collectionId, payload);
|
await this.collectionService.updateCollection(collectionId, payload);
|
||||||
return this.redirectToCollectionId(collectionId);
|
return this.collectionService.redirectToCollectionId(collectionId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Visibility } from '#collections/enums/visibility';
|
import { Visibility } from '#collections/enums/visibility';
|
||||||
import Collection from '#collections/models/collection';
|
import Collection from '#collections/models/collection';
|
||||||
|
import { collectionIdValidator } from '#collections/validators/collection_id_validator';
|
||||||
import { HttpContext } from '@adonisjs/core/http';
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
import db from '@adonisjs/lucid/services/db';
|
import db from '@adonisjs/lucid/services/db';
|
||||||
|
|
||||||
@@ -20,12 +21,12 @@ export class CollectionService {
|
|||||||
.firstOrFail();
|
.firstOrFail();
|
||||||
}
|
}
|
||||||
|
|
||||||
async getCollectionsByAuthorId() {
|
async getCollectionsForAuthenticatedUser() {
|
||||||
const context = this.getAuthContext();
|
const context = this.getAuthContext();
|
||||||
return await Collection.query()
|
return await Collection.query()
|
||||||
.where('author_id', context.auth.user!.id)
|
.where('author_id', context.auth.user!.id)
|
||||||
.orderBy('created_at')
|
.orderBy('created_at')
|
||||||
.preload('links');
|
.preload('links', (q) => q.orderBy('favorite', 'desc'));
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTotalCollectionsCount() {
|
async getTotalCollectionsCount() {
|
||||||
@@ -60,11 +61,44 @@ export class CollectionService {
|
|||||||
.delete();
|
.delete();
|
||||||
}
|
}
|
||||||
|
|
||||||
getAuthContext() {
|
getPublicCollectionById(id: Collection['id']) {
|
||||||
|
return Collection.query()
|
||||||
|
.where('id', id)
|
||||||
|
.andWhere('visibility', Visibility.PUBLIC)
|
||||||
|
.preload('links')
|
||||||
|
.preload('author')
|
||||||
|
.firstOrFail();
|
||||||
|
}
|
||||||
|
|
||||||
|
private getAuthContext() {
|
||||||
const context = HttpContext.getOrFail();
|
const context = HttpContext.getOrFail();
|
||||||
if (!context.auth.user || !context.auth.user.id) {
|
if (!context.auth.user || !context.auth.user.id) {
|
||||||
throw new Error('User not authenticated');
|
throw new Error('User not authenticated');
|
||||||
}
|
}
|
||||||
return context;
|
return context;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async validateCollectionId(collectionIdRequired: boolean = true) {
|
||||||
|
const ctx = HttpContext.getOrFail();
|
||||||
|
const { collectionId } = await ctx.request.validateUsing(
|
||||||
|
collectionIdValidator
|
||||||
|
);
|
||||||
|
if (!collectionId && collectionIdRequired) {
|
||||||
|
this.redirectToDashboard();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return collectionId;
|
||||||
|
}
|
||||||
|
|
||||||
|
redirectToCollectionId(collectionId: Collection['id']) {
|
||||||
|
const ctx = HttpContext.getOrFail();
|
||||||
|
return ctx.response.redirectToNamedRoute('dashboard', {
|
||||||
|
qs: { collectionId },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
redirectToDashboard() {
|
||||||
|
const ctx = HttpContext.getOrFail();
|
||||||
|
return ctx.response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
7
app/collections/validators/collection_id_validator.ts
Normal file
7
app/collections/validators/collection_id_validator.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
|
export const collectionIdValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
collectionId: vine.number().positive().optional(),
|
||||||
|
})
|
||||||
|
);
|
||||||
@@ -36,6 +36,13 @@ export default class HttpExceptionHandler extends ExceptionHandler {
|
|||||||
* response to the client
|
* response to the client
|
||||||
*/
|
*/
|
||||||
async handle(error: unknown, ctx: HttpContext) {
|
async handle(error: unknown, ctx: HttpContext) {
|
||||||
|
if (ctx.request.url()?.startsWith('/api/v1')) {
|
||||||
|
return ctx.response.status(400).json({
|
||||||
|
message: 'Bad Request',
|
||||||
|
errors: [error],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (error instanceof errors.E_ROW_NOT_FOUND) {
|
if (error instanceof errors.E_ROW_NOT_FOUND) {
|
||||||
return ctx.response.redirectToNamedRoute('dashboard');
|
return ctx.response.redirectToNamedRoute('dashboard');
|
||||||
}
|
}
|
||||||
|
|||||||
30
app/links/controllers/create_link_controller.ts
Normal file
30
app/links/controllers/create_link_controller.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
|
import { LinkService } from '#links/services/link_service';
|
||||||
|
import { createLinkValidator } from '#links/validators/create_link_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class CreateLinkController {
|
||||||
|
constructor(
|
||||||
|
private linkService: LinkService,
|
||||||
|
private collectionsService: CollectionService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async render({ inertia }: HttpContext) {
|
||||||
|
const collections =
|
||||||
|
await this.collectionsService.getCollectionsForAuthenticatedUser();
|
||||||
|
return inertia.render('links/create', { collections });
|
||||||
|
}
|
||||||
|
|
||||||
|
async execute({ request }: HttpContext) {
|
||||||
|
const { collectionId, ...payload } =
|
||||||
|
await request.validateUsing(createLinkValidator);
|
||||||
|
|
||||||
|
await this.linkService.createLink({
|
||||||
|
...payload,
|
||||||
|
collectionId,
|
||||||
|
});
|
||||||
|
return this.collectionsService.redirectToCollectionId(collectionId);
|
||||||
|
}
|
||||||
|
}
|
||||||
39
app/links/controllers/delete_link_controller.ts
Normal file
39
app/links/controllers/delete_link_controller.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
|
import { LinkService } from '#links/services/link_service';
|
||||||
|
import { deleteLinkValidator } from '#links/validators/delete_link_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
import db from '@adonisjs/lucid/services/db';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class DeleteLinkController {
|
||||||
|
constructor(
|
||||||
|
protected collectionsService: CollectionService,
|
||||||
|
protected linkService: LinkService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async render({ auth, inertia, request }: HttpContext) {
|
||||||
|
const linkId = request.qs()?.linkId;
|
||||||
|
if (!linkId) {
|
||||||
|
return this.collectionsService.redirectToDashboard();
|
||||||
|
}
|
||||||
|
|
||||||
|
const link = await this.linkService.getLinkById(linkId, auth.user!.id);
|
||||||
|
await link.load('collection');
|
||||||
|
return inertia.render('links/delete', { link });
|
||||||
|
}
|
||||||
|
|
||||||
|
async execute({ request, auth }: HttpContext) {
|
||||||
|
const { params } = await request.validateUsing(deleteLinkValidator);
|
||||||
|
|
||||||
|
const link = await this.linkService.getLinkById(params.id, auth.user!.id);
|
||||||
|
await this.linkService.deleteLink(params.id);
|
||||||
|
|
||||||
|
return this.collectionsService.redirectToCollectionId(link.collectionId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getTotalLinksCount() {
|
||||||
|
const totalCount = await db.from('links').count('* as total');
|
||||||
|
return Number(totalCount[0].total);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,129 +0,0 @@
|
|||||||
import CollectionsController from '#collections/controllers/show_collections_controller';
|
|
||||||
import Link from '#links/models/link';
|
|
||||||
import { createLinkValidator } from '#links/validators/create_link_validator';
|
|
||||||
import { deleteLinkValidator } from '#links/validators/delete_link_validator';
|
|
||||||
import { updateLinkFavoriteStatusValidator } from '#links/validators/update_favorite_link_validator';
|
|
||||||
import { updateLinkValidator } from '#links/validators/update_link_validator';
|
|
||||||
import { inject } from '@adonisjs/core';
|
|
||||||
import { HttpContext } from '@adonisjs/core/http';
|
|
||||||
import db from '@adonisjs/lucid/services/db';
|
|
||||||
|
|
||||||
@inject()
|
|
||||||
export default class LinksController {
|
|
||||||
constructor(protected collectionsController: CollectionsController) {}
|
|
||||||
|
|
||||||
async showCreatePage({ auth, inertia }: HttpContext) {
|
|
||||||
const collections =
|
|
||||||
await this.collectionsController.getCollectionsByAuthorId(auth.user!.id);
|
|
||||||
return inertia.render('links/create', { collections });
|
|
||||||
}
|
|
||||||
|
|
||||||
async store({ auth, request, response }: HttpContext) {
|
|
||||||
const { collectionId, ...payload } =
|
|
||||||
await request.validateUsing(createLinkValidator);
|
|
||||||
|
|
||||||
await this.collectionsController.getCollectionById(
|
|
||||||
collectionId,
|
|
||||||
auth.user!.id
|
|
||||||
);
|
|
||||||
await Link.create({
|
|
||||||
...payload,
|
|
||||||
collectionId,
|
|
||||||
authorId: auth.user?.id!,
|
|
||||||
});
|
|
||||||
return this.collectionsController.redirectToCollectionId(
|
|
||||||
response,
|
|
||||||
collectionId
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
async showEditPage({ auth, inertia, request, response }: HttpContext) {
|
|
||||||
const linkId = request.qs()?.linkId;
|
|
||||||
if (!linkId) {
|
|
||||||
return response.redirectToNamedRoute('dashboard');
|
|
||||||
}
|
|
||||||
|
|
||||||
const userId = auth.user!.id;
|
|
||||||
const collections =
|
|
||||||
await this.collectionsController.getCollectionsByAuthorId(userId);
|
|
||||||
const link = await this.getLinkById(linkId, userId);
|
|
||||||
|
|
||||||
return inertia.render('links/edit', { collections, link });
|
|
||||||
}
|
|
||||||
|
|
||||||
async update({ request, auth, response }: HttpContext) {
|
|
||||||
const { params, ...payload } =
|
|
||||||
await request.validateUsing(updateLinkValidator);
|
|
||||||
|
|
||||||
// Throw if invalid link id provided
|
|
||||||
await this.getLinkById(params.id, auth.user!.id);
|
|
||||||
|
|
||||||
await Link.updateOrCreate(
|
|
||||||
{
|
|
||||||
id: params.id,
|
|
||||||
},
|
|
||||||
payload
|
|
||||||
);
|
|
||||||
|
|
||||||
return response.redirectToNamedRoute('dashboard', {
|
|
||||||
qs: { collectionId: payload.collectionId },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async toggleFavorite({ request, auth, response }: HttpContext) {
|
|
||||||
const { params, favorite } = await request.validateUsing(
|
|
||||||
updateLinkFavoriteStatusValidator
|
|
||||||
);
|
|
||||||
|
|
||||||
// Throw if invalid link id provided
|
|
||||||
await this.getLinkById(params.id, auth.user!.id);
|
|
||||||
|
|
||||||
await Link.updateOrCreate(
|
|
||||||
{
|
|
||||||
id: params.id,
|
|
||||||
},
|
|
||||||
{ favorite }
|
|
||||||
);
|
|
||||||
|
|
||||||
return response.json({ status: 'ok' });
|
|
||||||
}
|
|
||||||
|
|
||||||
async showDeletePage({ auth, inertia, request, response }: HttpContext) {
|
|
||||||
const linkId = request.qs()?.linkId;
|
|
||||||
if (!linkId) {
|
|
||||||
return response.redirectToNamedRoute('dashboard');
|
|
||||||
}
|
|
||||||
|
|
||||||
const link = await this.getLinkById(linkId, auth.user!.id);
|
|
||||||
await link.load('collection');
|
|
||||||
return inertia.render('links/delete', { link });
|
|
||||||
}
|
|
||||||
|
|
||||||
async delete({ request, auth, response }: HttpContext) {
|
|
||||||
const { params } = await request.validateUsing(deleteLinkValidator);
|
|
||||||
|
|
||||||
const link = await this.getLinkById(params.id, auth.user!.id);
|
|
||||||
await link.delete();
|
|
||||||
|
|
||||||
return response.redirectToNamedRoute('dashboard', {
|
|
||||||
qs: { collectionId: link.id },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async getTotalLinksCount() {
|
|
||||||
const totalCount = await db.from('links').count('* as total');
|
|
||||||
return Number(totalCount[0].total);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get link by id.
|
|
||||||
*
|
|
||||||
* /!\ Only return private link (create by the current user)
|
|
||||||
*/
|
|
||||||
private async getLinkById(id: Link['id'], userId: Link['id']) {
|
|
||||||
return await Link.query()
|
|
||||||
.where('id', id)
|
|
||||||
.andWhere('author_id', userId)
|
|
||||||
.firstOrFail();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
19
app/links/controllers/toggle_favorite_controller.ts
Normal file
19
app/links/controllers/toggle_favorite_controller.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { LinkService } from '#links/services/link_service';
|
||||||
|
import { updateLinkFavoriteStatusValidator } from '#links/validators/update_favorite_link_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class ToggleFavoriteController {
|
||||||
|
constructor(private linkService: LinkService) {}
|
||||||
|
|
||||||
|
async toggleFavorite({ request, response }: HttpContext) {
|
||||||
|
const { params, favorite } = await request.validateUsing(
|
||||||
|
updateLinkFavoriteStatusValidator
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.linkService.updateFavorite(params.id, favorite);
|
||||||
|
|
||||||
|
return response.json({ status: 'ok' });
|
||||||
|
}
|
||||||
|
}
|
||||||
34
app/links/controllers/update_link_controller.ts
Normal file
34
app/links/controllers/update_link_controller.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
|
import { LinkService } from '#links/services/link_service';
|
||||||
|
import { updateLinkValidator } from '#links/validators/update_link_validator';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class UpdateLinkController {
|
||||||
|
constructor(
|
||||||
|
private linkService: LinkService,
|
||||||
|
private collectionsService: CollectionService
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async render({ auth, inertia, request, response }: HttpContext) {
|
||||||
|
const linkId = request.qs()?.linkId;
|
||||||
|
if (!linkId) {
|
||||||
|
return response.redirectToNamedRoute('dashboard');
|
||||||
|
}
|
||||||
|
|
||||||
|
const collections =
|
||||||
|
await this.collectionsService.getCollectionsForAuthenticatedUser();
|
||||||
|
const link = await this.linkService.getLinkById(linkId, auth.user!.id);
|
||||||
|
|
||||||
|
return inertia.render('links/edit', { collections, link });
|
||||||
|
}
|
||||||
|
|
||||||
|
async execute({ request }: HttpContext) {
|
||||||
|
const { params, ...payload } =
|
||||||
|
await request.validateUsing(updateLinkValidator);
|
||||||
|
|
||||||
|
await this.linkService.updateLink(params.id, payload);
|
||||||
|
return this.collectionsService.redirectToCollectionId(payload.collectionId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,14 @@
|
|||||||
import { middleware } from '#start/kernel';
|
import { middleware } from '#start/kernel';
|
||||||
import router from '@adonisjs/core/services/router';
|
import router from '@adonisjs/core/services/router';
|
||||||
const LinksController = () => import('#links/controllers/links_controller');
|
|
||||||
|
const CreateLinkController = () =>
|
||||||
|
import('#links/controllers/create_link_controller');
|
||||||
|
const DeleteLinkController = () =>
|
||||||
|
import('#links/controllers/delete_link_controller');
|
||||||
|
const UpdateLinkController = () =>
|
||||||
|
import('#links/controllers/update_link_controller');
|
||||||
|
const ToggleFavoriteController = () =>
|
||||||
|
import('#links/controllers/toggle_favorite_controller');
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Routes for authenticated users
|
* Routes for authenticated users
|
||||||
@@ -8,21 +16,21 @@ const LinksController = () => import('#links/controllers/links_controller');
|
|||||||
router
|
router
|
||||||
.group(() => {
|
.group(() => {
|
||||||
router
|
router
|
||||||
.get('/create', [LinksController, 'showCreatePage'])
|
.get('/create', [CreateLinkController, 'render'])
|
||||||
.as('link.create-form');
|
.as('link.create-form');
|
||||||
router.post('/', [LinksController, 'store']).as('link.create');
|
router.post('/', [CreateLinkController, 'execute']).as('link.create');
|
||||||
|
|
||||||
router.get('/edit', [LinksController, 'showEditPage']).as('link.edit-form');
|
router.get('/edit', [UpdateLinkController, 'render']).as('link.edit-form');
|
||||||
router.put('/:id', [LinksController, 'update']).as('link.edit');
|
router.put('/:id', [UpdateLinkController, 'execute']).as('link.edit');
|
||||||
|
|
||||||
router
|
router
|
||||||
.put('/:id/favorite', [LinksController, 'toggleFavorite'])
|
.put('/:id/favorite', [ToggleFavoriteController, 'toggleFavorite'])
|
||||||
.as('link.toggle-favorite');
|
.as('link.toggle-favorite');
|
||||||
|
|
||||||
router
|
router
|
||||||
.get('/delete', [LinksController, 'showDeletePage'])
|
.get('/delete', [DeleteLinkController, 'render'])
|
||||||
.as('link.delete-form');
|
.as('link.delete-form');
|
||||||
router.delete('/:id', [LinksController, 'delete']).as('link.delete');
|
router.delete('/:id', [DeleteLinkController, 'execute']).as('link.delete');
|
||||||
})
|
})
|
||||||
.middleware([middleware.auth()])
|
.middleware([middleware.auth()])
|
||||||
.prefix('/links');
|
.prefix('/links');
|
||||||
|
|||||||
68
app/links/services/link_service.ts
Normal file
68
app/links/services/link_service.ts
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
import Link from '#links/models/link';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
type CreateLinkPayload = {
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
url: string;
|
||||||
|
favorite: boolean;
|
||||||
|
collectionId: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type UpdateLinkPayload = CreateLinkPayload;
|
||||||
|
|
||||||
|
export class LinkService {
|
||||||
|
createLink(payload: CreateLinkPayload) {
|
||||||
|
const context = this.getAuthContext();
|
||||||
|
return Link.create({
|
||||||
|
...payload,
|
||||||
|
authorId: context.auth.user!.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
updateLink(id: number, payload: UpdateLinkPayload) {
|
||||||
|
const context = this.getAuthContext();
|
||||||
|
return Link.query()
|
||||||
|
.where('id', id)
|
||||||
|
.andWhere('author_id', context.auth.user!.id)
|
||||||
|
.update(payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteLink(id: number) {
|
||||||
|
const context = this.getAuthContext();
|
||||||
|
return Link.query()
|
||||||
|
.where('id', id)
|
||||||
|
.andWhere('author_id', context.auth.user!.id)
|
||||||
|
.delete();
|
||||||
|
}
|
||||||
|
|
||||||
|
async getLinkById(id: Link['id'], userId: Link['id']) {
|
||||||
|
return await Link.query()
|
||||||
|
.where('id', id)
|
||||||
|
.andWhere('author_id', userId)
|
||||||
|
.firstOrFail();
|
||||||
|
}
|
||||||
|
|
||||||
|
updateFavorite(id: number, favorite: boolean) {
|
||||||
|
return Link.query()
|
||||||
|
.where('id', id)
|
||||||
|
.andWhere('author_id', this.getAuthContext().auth.user!.id)
|
||||||
|
.update({ favorite });
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFavoriteLinksForAuthenticatedUser() {
|
||||||
|
const context = this.getAuthContext();
|
||||||
|
return await Link.query()
|
||||||
|
.where('author_id', context.auth.user!.id)
|
||||||
|
.where('favorite', true)
|
||||||
|
.orderBy('created_at');
|
||||||
|
}
|
||||||
|
|
||||||
|
getAuthContext() {
|
||||||
|
const context = HttpContext.getOrFail();
|
||||||
|
if (!context.auth.user || !context.auth.user.id) {
|
||||||
|
throw new Error('User not authenticated');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
}
|
||||||
9
app/links/validators/base_link_validator.ts
Normal file
9
app/links/validators/base_link_validator.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
|
export const baseLinkValidator = vine.object({
|
||||||
|
name: vine.string().trim().minLength(1).maxLength(254),
|
||||||
|
description: vine.string().trim().maxLength(300).optional(),
|
||||||
|
url: vine.string().url({ require_tld: false }).trim(),
|
||||||
|
favorite: vine.boolean(),
|
||||||
|
collectionId: vine.number(),
|
||||||
|
});
|
||||||
@@ -1,11 +1,8 @@
|
|||||||
|
import { baseLinkValidator } from '#links/validators/base_link_validator';
|
||||||
import vine from '@vinejs/vine';
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
export const createLinkValidator = vine.compile(
|
export const createLinkValidator = vine.compile(
|
||||||
vine.object({
|
vine.object({
|
||||||
name: vine.string().trim().minLength(1).maxLength(254),
|
...baseLinkValidator.getProperties(),
|
||||||
description: vine.string().trim().maxLength(300).optional(),
|
|
||||||
url: vine.string().trim(),
|
|
||||||
favorite: vine.boolean(),
|
|
||||||
collectionId: vine.number(),
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,13 +1,10 @@
|
|||||||
import { params } from '#core/validators/params_object';
|
import { params } from '#core/validators/params_object';
|
||||||
|
import { baseLinkValidator } from '#links/validators/base_link_validator';
|
||||||
import vine from '@vinejs/vine';
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
export const updateLinkValidator = vine.compile(
|
export const updateLinkValidator = vine.compile(
|
||||||
vine.object({
|
vine.object({
|
||||||
name: vine.string().trim().minLength(1).maxLength(254),
|
...baseLinkValidator.getProperties(),
|
||||||
description: vine.string().trim().maxLength(300).optional(),
|
|
||||||
url: vine.string().trim(),
|
|
||||||
favorite: vine.boolean(),
|
|
||||||
collectionId: vine.number(),
|
|
||||||
|
|
||||||
params,
|
params,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,61 +1,19 @@
|
|||||||
import { Visibility } from '#collections/enums/visibility';
|
import { CollectionService } from '#collections/services/collection_service';
|
||||||
import Collection from '#collections/models/collection';
|
import { inject } from '@adonisjs/core';
|
||||||
import Link from '#links/models/link';
|
|
||||||
import User from '#user/models/user';
|
|
||||||
import type { HttpContext } from '@adonisjs/core/http';
|
import type { HttpContext } from '@adonisjs/core/http';
|
||||||
import { getSharedCollectionValidator } from '../validators/shared_collection.js';
|
import { getSharedCollectionValidator } from '../validators/shared_collection.js';
|
||||||
|
|
||||||
class LinkWithoutFavoriteDto {
|
@inject()
|
||||||
constructor(private link: Link) {}
|
|
||||||
|
|
||||||
toJson = () => ({
|
|
||||||
id: this.link.id,
|
|
||||||
name: this.link.name,
|
|
||||||
description: this.link.description,
|
|
||||||
url: this.link.url,
|
|
||||||
collectionId: this.link.collectionId,
|
|
||||||
createdAt: this.link.createdAt.toString(),
|
|
||||||
updatedAt: this.link.updatedAt.toString(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
class UserWithoutEmailDto {
|
|
||||||
constructor(private user: User) {}
|
|
||||||
|
|
||||||
toJson = () => ({
|
|
||||||
id: this.user.id,
|
|
||||||
fullname: this.user.name,
|
|
||||||
avatarUrl: this.user.avatarUrl,
|
|
||||||
isAdmin: this.user.isAdmin,
|
|
||||||
createdAt: this.user.createdAt.toString(),
|
|
||||||
updatedAt: this.user.updatedAt.toString(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export default class SharedCollectionsController {
|
export default class SharedCollectionsController {
|
||||||
|
constructor(private collectionService: CollectionService) {}
|
||||||
|
|
||||||
async index({ request, inertia }: HttpContext) {
|
async index({ request, inertia }: HttpContext) {
|
||||||
const { params } = await request.validateUsing(
|
const { params } = await request.validateUsing(
|
||||||
getSharedCollectionValidator
|
getSharedCollectionValidator
|
||||||
);
|
);
|
||||||
|
|
||||||
const collection = await this.getSharedCollectionById(params.id);
|
const activeCollection =
|
||||||
return inertia.render('shared', { collection });
|
await this.collectionService.getPublicCollectionById(params.id);
|
||||||
}
|
return inertia.render('shared', { activeCollection });
|
||||||
|
|
||||||
private async getSharedCollectionById(id: Collection['id']) {
|
|
||||||
const collection = await Collection.query()
|
|
||||||
.where('id', id)
|
|
||||||
.andWhere('visibility', Visibility.PUBLIC)
|
|
||||||
.preload('links')
|
|
||||||
.preload('author')
|
|
||||||
.firstOrFail();
|
|
||||||
|
|
||||||
return {
|
|
||||||
...collection.serialize(),
|
|
||||||
links: collection.links.map((link) =>
|
|
||||||
new LinkWithoutFavoriteDto(link).toJson()
|
|
||||||
),
|
|
||||||
author: new UserWithoutEmailDto(collection.author).toJson(),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
45
app/user/controllers/api_token_controller.ts
Normal file
45
app/user/controllers/api_token_controller.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
import { ApiTokenService } from '#user/services/api_token_service';
|
||||||
|
import { createApiTokenValidator } from '#user/validators/token/create_api_token';
|
||||||
|
import { deleteApiTokenValidator } from '#user/validators/token/delete_api_token';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class ApiTokenController {
|
||||||
|
constructor(private apiTokenService: ApiTokenService) {}
|
||||||
|
|
||||||
|
async store({ request, response, auth, session }: HttpContext) {
|
||||||
|
const { name, expiresAt } = await request.validateUsing(
|
||||||
|
createApiTokenValidator
|
||||||
|
);
|
||||||
|
const token = await this.apiTokenService.createToken(auth.user!, {
|
||||||
|
name,
|
||||||
|
expiresAt,
|
||||||
|
});
|
||||||
|
session.flash('token', {
|
||||||
|
...token.toJSON(),
|
||||||
|
token: token.value?.release(),
|
||||||
|
identifier: token.identifier,
|
||||||
|
});
|
||||||
|
return response.redirect().withQs().back();
|
||||||
|
}
|
||||||
|
|
||||||
|
async destroy({ request, response, auth }: HttpContext) {
|
||||||
|
const { params } = await request.validateUsing(deleteApiTokenValidator);
|
||||||
|
const tokenId = params.tokenId;
|
||||||
|
|
||||||
|
const token = await this.apiTokenService.getTokenByValue(
|
||||||
|
auth.user!,
|
||||||
|
tokenId
|
||||||
|
);
|
||||||
|
if (!token) {
|
||||||
|
return response.notFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.apiTokenService.revokeToken(
|
||||||
|
auth.user!,
|
||||||
|
Number(token.identifier)
|
||||||
|
);
|
||||||
|
return response.redirect().withQs().back();
|
||||||
|
}
|
||||||
|
}
|
||||||
26
app/user/controllers/display_preferences_controller.ts
Normal file
26
app/user/controllers/display_preferences_controller.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { getDisplayPreferences } from '#shared/lib/display_preferences';
|
||||||
|
import { updateDisplayPreferencesValidator } from '#user/validators/update_display_preferences';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
export default class DisplayPreferencesController {
|
||||||
|
async update({ request, response, auth }: HttpContext) {
|
||||||
|
const { displayPreferences } = await request.validateUsing(
|
||||||
|
updateDisplayPreferencesValidator
|
||||||
|
);
|
||||||
|
const userPrefs = auth.user!.displayPreferences ?? {};
|
||||||
|
const mergedPrefs = {
|
||||||
|
linkListDisplay:
|
||||||
|
displayPreferences.linkListDisplay ??
|
||||||
|
userPrefs.linkListDisplay ??
|
||||||
|
getDisplayPreferences().linkListDisplay,
|
||||||
|
collectionListDisplay:
|
||||||
|
displayPreferences.collectionListDisplay ??
|
||||||
|
userPrefs.collectionListDisplay ??
|
||||||
|
getDisplayPreferences().collectionListDisplay,
|
||||||
|
};
|
||||||
|
auth.user!.displayPreferences = mergedPrefs;
|
||||||
|
console.log(auth.user!.displayPreferences);
|
||||||
|
await auth.user!.save();
|
||||||
|
return response.redirect().withQs().back();
|
||||||
|
}
|
||||||
|
}
|
||||||
12
app/user/lib/index.ts
Normal file
12
app/user/lib/index.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { type DisplayPreferences } from '#shared/types/index';
|
||||||
|
import User from '#user/models/user';
|
||||||
|
|
||||||
|
export function ensureDisplayPreferences(user: User): DisplayPreferences {
|
||||||
|
const defaults: DisplayPreferences = {
|
||||||
|
linkListDisplay: 'grid',
|
||||||
|
collectionListDisplay: 'list',
|
||||||
|
};
|
||||||
|
|
||||||
|
user.displayPreferences = { ...defaults, ...user.displayPreferences };
|
||||||
|
return user.displayPreferences;
|
||||||
|
}
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
import Collection from '#collections/models/collection';
|
import Collection from '#collections/models/collection';
|
||||||
import AppBaseModel from '#core/models/app_base_model';
|
import AppBaseModel from '#core/models/app_base_model';
|
||||||
import Link from '#links/models/link';
|
import Link from '#links/models/link';
|
||||||
|
import { type DisplayPreferences } from '#shared/types/index';
|
||||||
|
import { ensureDisplayPreferences } from '#user/lib/index';
|
||||||
import type { GoogleToken } from '@adonisjs/ally/types';
|
import type { GoogleToken } from '@adonisjs/ally/types';
|
||||||
|
import { DbAccessTokensProvider } from '@adonisjs/auth/access_tokens';
|
||||||
import { column, computed, hasMany } from '@adonisjs/lucid/orm';
|
import { column, computed, hasMany } from '@adonisjs/lucid/orm';
|
||||||
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
||||||
import { DateTime } from 'luxon';
|
import { DateTime } from 'luxon';
|
||||||
@@ -51,4 +54,17 @@ export default class User extends AppBaseModel {
|
|||||||
autoUpdate: true,
|
autoUpdate: true,
|
||||||
})
|
})
|
||||||
declare lastSeenAt: DateTime;
|
declare lastSeenAt: DateTime;
|
||||||
|
|
||||||
|
@column({
|
||||||
|
serialize: (value) => {
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
return ensureDisplayPreferences(JSON.parse(value));
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
},
|
||||||
|
prepare: (value) => JSON.stringify(value),
|
||||||
|
})
|
||||||
|
declare displayPreferences: DisplayPreferences;
|
||||||
|
|
||||||
|
static accessTokens = DbAccessTokensProvider.forModel(User);
|
||||||
}
|
}
|
||||||
|
|||||||
15
app/user/routes/api_token_routes.ts
Normal file
15
app/user/routes/api_token_routes.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const ApiTokenController = () =>
|
||||||
|
import('#user/controllers/api_token_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.group(() => {
|
||||||
|
router.post('/', [ApiTokenController, 'store']).as('user.api-tokens.store');
|
||||||
|
router
|
||||||
|
.delete('/:tokenId', [ApiTokenController, 'destroy'])
|
||||||
|
.as('user.api-tokens.destroy');
|
||||||
|
})
|
||||||
|
.prefix('/user/api-tokens')
|
||||||
|
.middleware([middleware.auth()]);
|
||||||
@@ -1 +1,3 @@
|
|||||||
|
import './api_token_routes.js';
|
||||||
|
import './user_display_preferences_route.js';
|
||||||
import './user_theme_route.js';
|
import './user_theme_route.js';
|
||||||
|
|||||||
10
app/user/routes/user_display_preferences_route.ts
Normal file
10
app/user/routes/user_display_preferences_route.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { middleware } from '#start/kernel';
|
||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const DisplayPreferencesController = () =>
|
||||||
|
import('#user/controllers/display_preferences_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.post('/user/display-preferences', [DisplayPreferencesController, 'update'])
|
||||||
|
.as('user.update-display-preferences')
|
||||||
|
.middleware([middleware.auth()]);
|
||||||
28
app/user/services/api_token_service.ts
Normal file
28
app/user/services/api_token_service.ts
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import User from '#user/models/user';
|
||||||
|
|
||||||
|
type CreateTokenParams = {
|
||||||
|
name: string;
|
||||||
|
expiresAt?: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class ApiTokenService {
|
||||||
|
createToken(user: User, { name, expiresAt }: CreateTokenParams) {
|
||||||
|
const expiresIn = expiresAt ? expiresAt.getTime() - Date.now() : undefined;
|
||||||
|
return User.accessTokens.create(user, undefined, {
|
||||||
|
name,
|
||||||
|
expiresIn,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
getTokens(user: User) {
|
||||||
|
return User.accessTokens.all(user);
|
||||||
|
}
|
||||||
|
|
||||||
|
revokeToken(user: User, identifier: number) {
|
||||||
|
return User.accessTokens.delete(user, identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
getTokenByValue(user: User, value: string) {
|
||||||
|
return User.accessTokens.find(user, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
8
app/user/validators/token/create_api_token.ts
Normal file
8
app/user/validators/token/create_api_token.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
|
export const createApiTokenValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
name: vine.string().trim().minLength(1).maxLength(255),
|
||||||
|
expiresAt: vine.date().optional(),
|
||||||
|
})
|
||||||
|
);
|
||||||
9
app/user/validators/token/delete_api_token.ts
Normal file
9
app/user/validators/token/delete_api_token.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
|
export const deleteApiTokenValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
params: vine.object({
|
||||||
|
tokenId: vine.string().trim().minLength(1).maxLength(255),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
);
|
||||||
26
app/user/validators/update_display_preferences.ts
Normal file
26
app/user/validators/update_display_preferences.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import {
|
||||||
|
COLLECTION_LIST_DISPLAYS,
|
||||||
|
DEFAULT_LIST_DISPLAY_PREFERENCES,
|
||||||
|
LINK_LIST_DISPLAYS,
|
||||||
|
} from '#shared/lib/display_preferences';
|
||||||
|
import vine from '@vinejs/vine';
|
||||||
|
|
||||||
|
export const updateDisplayPreferencesValidator = vine.compile(
|
||||||
|
vine.object({
|
||||||
|
displayPreferences: vine.object({
|
||||||
|
linkListDisplay: vine
|
||||||
|
.enum(LINK_LIST_DISPLAYS)
|
||||||
|
.optional()
|
||||||
|
.transform(
|
||||||
|
(value) => value ?? DEFAULT_LIST_DISPLAY_PREFERENCES.linkListDisplay
|
||||||
|
),
|
||||||
|
collectionListDisplay: vine
|
||||||
|
.enum(COLLECTION_LIST_DISPLAYS)
|
||||||
|
.optional()
|
||||||
|
.transform(
|
||||||
|
(value) =>
|
||||||
|
value ?? DEFAULT_LIST_DISPLAY_PREFERENCES.collectionListDisplay
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
);
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { ApiTokenService } from '#user/services/api_token_service';
|
||||||
|
import { inject } from '@adonisjs/core';
|
||||||
|
import { HttpContext } from '@adonisjs/core/http';
|
||||||
|
|
||||||
|
@inject()
|
||||||
|
export default class ShowUserSettingsController {
|
||||||
|
constructor(private apiTokenService: ApiTokenService) {}
|
||||||
|
|
||||||
|
public async render({ auth, inertia }: HttpContext) {
|
||||||
|
const user = await auth.authenticate();
|
||||||
|
const tokens = await this.apiTokenService.getTokens(user);
|
||||||
|
return inertia.render('user_settings/show', {
|
||||||
|
user,
|
||||||
|
tokens: tokens.map((token) => {
|
||||||
|
return {
|
||||||
|
...token.toJSON(),
|
||||||
|
identifier: token.identifier,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
1
app/user_settings/routes/routes.ts
Normal file
1
app/user_settings/routes/routes.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
import './user_settings_routes.js';
|
||||||
8
app/user_settings/routes/user_settings_routes.ts
Normal file
8
app/user_settings/routes/user_settings_routes.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import router from '@adonisjs/core/services/router';
|
||||||
|
|
||||||
|
const ShowUserSettingsController = () =>
|
||||||
|
import('#user_settings/controllers/show_user_settings_controller');
|
||||||
|
|
||||||
|
router
|
||||||
|
.get('/user/settings', [ShowUserSettingsController, 'render'])
|
||||||
|
.as('user.settings');
|
||||||
@@ -5,7 +5,7 @@ const allyConfig = defineConfig({
|
|||||||
google: services.google({
|
google: services.google({
|
||||||
clientId: env.get('GOOGLE_CLIENT_ID'),
|
clientId: env.get('GOOGLE_CLIENT_ID'),
|
||||||
clientSecret: env.get('GOOGLE_CLIENT_SECRET'),
|
clientSecret: env.get('GOOGLE_CLIENT_SECRET'),
|
||||||
callbackUrl: env.get('GOOGLE_CLIENT_CALLBACK_URL'),
|
callbackUrl: env.get('APP_URL') + '/auth/callback',
|
||||||
prompt: 'select_account',
|
prompt: 'select_account',
|
||||||
display: 'page',
|
display: 'page',
|
||||||
scopes: ['userinfo.email', 'userinfo.profile'],
|
scopes: ['userinfo.email', 'userinfo.profile'],
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { defineConfig } from '@adonisjs/auth';
|
import { defineConfig } from '@adonisjs/auth';
|
||||||
|
import { tokensGuard, tokensUserProvider } from '@adonisjs/auth/access_tokens';
|
||||||
import { sessionGuard, sessionUserProvider } from '@adonisjs/auth/session';
|
import { sessionGuard, sessionUserProvider } from '@adonisjs/auth/session';
|
||||||
import { Authenticators, InferAuthEvents } from '@adonisjs/auth/types';
|
import { Authenticators, InferAuthEvents } from '@adonisjs/auth/types';
|
||||||
|
|
||||||
@@ -11,6 +12,12 @@ const authConfig = defineConfig({
|
|||||||
model: () => import('#user/models/user'),
|
model: () => import('#user/models/user'),
|
||||||
}),
|
}),
|
||||||
}),
|
}),
|
||||||
|
api: tokensGuard({
|
||||||
|
provider: tokensUserProvider({
|
||||||
|
tokens: 'accessTokens',
|
||||||
|
model: () => import('#user/models/user'),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { isSSREnableForPage } from '#config/ssr';
|
import { isSSREnableForPage } from '#config/ssr';
|
||||||
|
import env from '#start/env';
|
||||||
import { DEFAULT_USER_THEME, KEY_USER_THEME } from '#user/constants/theme';
|
import { DEFAULT_USER_THEME, KEY_USER_THEME } from '#user/constants/theme';
|
||||||
import logger from '@adonisjs/core/services/logger';
|
import logger from '@adonisjs/core/services/logger';
|
||||||
import { defineConfig } from '@adonisjs/inertia';
|
import { defineConfig } from '@adonisjs/inertia';
|
||||||
@@ -14,6 +15,7 @@ export default defineConfig({
|
|||||||
*/
|
*/
|
||||||
sharedData: {
|
sharedData: {
|
||||||
errors: (ctx) => ctx.session?.flashMessages.get('errors'),
|
errors: (ctx) => ctx.session?.flashMessages.get('errors'),
|
||||||
|
token: (ctx) => ctx.session?.flashMessages.get('token'),
|
||||||
user: (ctx) => ({
|
user: (ctx) => ({
|
||||||
theme: ctx.session?.get(KEY_USER_THEME, DEFAULT_USER_THEME),
|
theme: ctx.session?.get(KEY_USER_THEME, DEFAULT_USER_THEME),
|
||||||
}),
|
}),
|
||||||
@@ -24,6 +26,7 @@ export default defineConfig({
|
|||||||
isAuthenticated: ctx.auth?.isAuthenticated || false,
|
isAuthenticated: ctx.auth?.isAuthenticated || false,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
appUrl: env.get('APP_URL'),
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { BaseSchema } from '@adonisjs/lucid/schema';
|
||||||
|
|
||||||
|
export default class extends BaseSchema {
|
||||||
|
protected tableName = 'users';
|
||||||
|
|
||||||
|
async up() {
|
||||||
|
this.schema.alterTable(this.tableName, (table) => {
|
||||||
|
table.jsonb('display_preferences').defaultTo('{}');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async down() {
|
||||||
|
this.schema.alterTable(this.tableName, (table) => {
|
||||||
|
table.dropColumn('display_preferences');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { BaseSchema } from '@adonisjs/lucid/schema';
|
||||||
|
|
||||||
|
export default class CreateAuthAccessTokensTable extends BaseSchema {
|
||||||
|
protected tableName = 'auth_access_tokens';
|
||||||
|
|
||||||
|
async up() {
|
||||||
|
this.schema.createTable(this.tableName, (table) => {
|
||||||
|
table.increments('id');
|
||||||
|
table
|
||||||
|
.integer('tokenable_id')
|
||||||
|
.notNullable()
|
||||||
|
.unsigned()
|
||||||
|
.references('id')
|
||||||
|
.inTable('users')
|
||||||
|
.onDelete('CASCADE');
|
||||||
|
|
||||||
|
table.string('type').notNullable();
|
||||||
|
table.string('name').nullable();
|
||||||
|
table.string('hash').notNullable();
|
||||||
|
table.text('abilities').notNullable();
|
||||||
|
table.timestamp('created_at');
|
||||||
|
table.timestamp('updated_at');
|
||||||
|
table.timestamp('last_used_at').nullable();
|
||||||
|
table.timestamp('expires_at').nullable();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async down() {
|
||||||
|
this.schema.dropTable(this.tableName);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,9 +20,11 @@ createInertiaApp({
|
|||||||
import.meta.glob('../pages/**/*.tsx')
|
import.meta.glob('../pages/**/*.tsx')
|
||||||
);
|
);
|
||||||
|
|
||||||
currentPage.default.layout =
|
if (currentPage?.default) {
|
||||||
currentPage.default.layout ||
|
currentPage.default.layout =
|
||||||
((p: any) => <DefaultLayout children={p} />);
|
currentPage.default.layout ||
|
||||||
|
((p: any) => <DefaultLayout children={p} />);
|
||||||
|
}
|
||||||
|
|
||||||
return currentPage;
|
return currentPage;
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -9,9 +9,13 @@ export default function render(page: any) {
|
|||||||
resolve: (name) => {
|
resolve: (name) => {
|
||||||
const pages = import.meta.glob('../pages/**/*.tsx', { eager: true });
|
const pages = import.meta.glob('../pages/**/*.tsx', { eager: true });
|
||||||
let pageComponent: any = pages[`../pages/${name}.tsx`];
|
let pageComponent: any = pages[`../pages/${name}.tsx`];
|
||||||
pageComponent.default.layout =
|
|
||||||
pageComponent?.default?.layout ||
|
if (pageComponent?.default) {
|
||||||
((pageChildren: any) => <DefaultLayout children={pageChildren} />);
|
pageComponent.default.layout =
|
||||||
|
pageComponent.default.layout ||
|
||||||
|
((pageChildren: any) => <DefaultLayout children={pageChildren} />);
|
||||||
|
}
|
||||||
|
|
||||||
return pageComponent;
|
return pageComponent;
|
||||||
},
|
},
|
||||||
setup: ({ App, props }) => <App {...props} />,
|
setup: ({ App, props }) => <App {...props} />,
|
||||||
|
|||||||
128
inertia/components/common/api_tokens/api_tokens.tsx
Normal file
128
inertia/components/common/api_tokens/api_tokens.tsx
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
import { usePage } from '@inertiajs/react';
|
||||||
|
import {
|
||||||
|
ActionIcon,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
CopyButton,
|
||||||
|
Group,
|
||||||
|
Text,
|
||||||
|
} from '@mantine/core';
|
||||||
|
import { modals } from '@mantine/modals';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { TbPlus, TbTrash } from 'react-icons/tb';
|
||||||
|
import { SimpleTable } from '~/components/common/simple_table/simple_table';
|
||||||
|
import { useApiTokens } from '~/hooks/use_api_tokens';
|
||||||
|
import { ApiToken } from '~/types/app';
|
||||||
|
import { CreateTokenModal } from './create_token_modal';
|
||||||
|
|
||||||
|
const useGetCreatedToken = () => {
|
||||||
|
const newlyCreatedToken = usePage<{
|
||||||
|
token?: ApiToken;
|
||||||
|
}>().props.token;
|
||||||
|
return newlyCreatedToken;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ApiTokens() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { tokens, createToken, revokeToken } = useApiTokens();
|
||||||
|
|
||||||
|
const newlyCreatedToken = useGetCreatedToken();
|
||||||
|
|
||||||
|
const handleCreateTokenModal = () => {
|
||||||
|
modals.open({
|
||||||
|
title: t('api-tokens.create-new'),
|
||||||
|
children: (
|
||||||
|
<CreateTokenModal
|
||||||
|
onCreate={(name) => createToken(name)}
|
||||||
|
onClose={() => modals.closeAll()}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRevokeToken = async (tokenId: number) => {
|
||||||
|
const token = tokens.find((t) => t.identifier === tokenId);
|
||||||
|
if (!token) return;
|
||||||
|
|
||||||
|
modals.openConfirmModal({
|
||||||
|
title: (
|
||||||
|
<>
|
||||||
|
{t('api-tokens.revoke')} "<strong>{token.name}</strong>"
|
||||||
|
</>
|
||||||
|
),
|
||||||
|
children: <Text size="sm">{t('api-tokens.confirm-revoke')}</Text>,
|
||||||
|
labels: {
|
||||||
|
confirm: t('api-tokens.revoke'),
|
||||||
|
cancel: t('cancel'),
|
||||||
|
},
|
||||||
|
confirmProps: { color: 'red' },
|
||||||
|
onConfirm: () => revokeToken(tokenId),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const generateTokenRow = (token: ApiToken) =>
|
||||||
|
newlyCreatedToken?.identifier === token.identifier && (
|
||||||
|
<>
|
||||||
|
<Text c="green" size="sm">
|
||||||
|
{t('api-tokens.new-token')}{' '}
|
||||||
|
{newlyCreatedToken.token && (
|
||||||
|
<CopyButton value={newlyCreatedToken.token}>
|
||||||
|
{({ copied, copy }) => (
|
||||||
|
<Button
|
||||||
|
color={copied ? 'teal' : 'blue'}
|
||||||
|
onClick={copy}
|
||||||
|
size="xs"
|
||||||
|
variant="light"
|
||||||
|
>
|
||||||
|
{copied ? t('copied') : t('copy')}
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</CopyButton>
|
||||||
|
)}
|
||||||
|
</Text>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
|
||||||
|
const generateRow = (token: ApiToken) => ({
|
||||||
|
key: token.identifier.toString(),
|
||||||
|
name: token.name,
|
||||||
|
token: generateTokenRow(token) || undefined,
|
||||||
|
expiresAt: token.expiresAt,
|
||||||
|
lastUsedAt: token.lastUsedAt,
|
||||||
|
actions: [
|
||||||
|
<ActionIcon
|
||||||
|
color="red"
|
||||||
|
variant="subtle"
|
||||||
|
onClick={() => handleRevokeToken(token.identifier)}
|
||||||
|
>
|
||||||
|
<TbTrash size={16} />
|
||||||
|
</ActionIcon>,
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const rows = tokens.map(generateRow);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card withBorder>
|
||||||
|
<Group justify="space-between" mb="md">
|
||||||
|
<Text fw={500}>{t('api-tokens.title')}</Text>
|
||||||
|
<Button
|
||||||
|
leftSection={<TbPlus size={16} />}
|
||||||
|
onClick={handleCreateTokenModal}
|
||||||
|
size="sm"
|
||||||
|
variant="light"
|
||||||
|
>
|
||||||
|
{t('api-tokens.create')}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
|
||||||
|
{tokens.length === 0 && (
|
||||||
|
<Text c="dimmed" ta="center" py="xl">
|
||||||
|
{t('api-tokens.no-tokens')}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tokens.length > 0 && <SimpleTable data={rows} />}
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
53
inertia/components/common/api_tokens/create_token_modal.tsx
Normal file
53
inertia/components/common/api_tokens/create_token_modal.tsx
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import { Button, Group, Stack, Text, TextInput } from '@mantine/core';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
|
||||||
|
interface CreateTokenModalProps {
|
||||||
|
onCreate: (name: string) => Promise<void>;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CreateTokenModal({ onCreate, onClose }: CreateTokenModalProps) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [tokenName, setTokenName] = useState('');
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
const handleCreate = async () => {
|
||||||
|
if (!tokenName.trim()) return;
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
await onCreate(tokenName);
|
||||||
|
onClose();
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t('api-tokens.create-description')}
|
||||||
|
</Text>
|
||||||
|
<TextInput
|
||||||
|
label={t('api-tokens.name')}
|
||||||
|
placeholder={t('api-tokens.name-placeholder')}
|
||||||
|
value={tokenName}
|
||||||
|
onChange={(e) => setTokenName(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<Group justify="flex-end">
|
||||||
|
<Button variant="subtle" onClick={onClose}>
|
||||||
|
{t('cancel')}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
onClick={handleCreate}
|
||||||
|
disabled={!tokenName.trim() || isLoading}
|
||||||
|
loading={isLoading}
|
||||||
|
>
|
||||||
|
{t('api-tokens.create')}
|
||||||
|
</Button>
|
||||||
|
</Group>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
66
inertia/components/common/combo_list/combo_list.tsx
Normal file
66
inertia/components/common/combo_list/combo_list.tsx
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import { Combobox, Input, InputBase, useCombobox } from '@mantine/core';
|
||||||
|
import { ComboListItem } from '~/components/common/combo_list/combo_list_item';
|
||||||
|
|
||||||
|
export type ValueWithIcon = {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
icon: React.ReactNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ComboList({
|
||||||
|
selectedValue,
|
||||||
|
values,
|
||||||
|
setValue,
|
||||||
|
}: {
|
||||||
|
selectedValue: string;
|
||||||
|
values: ValueWithIcon[];
|
||||||
|
setValue: (value: string) => void;
|
||||||
|
}) {
|
||||||
|
const combobox = useCombobox({
|
||||||
|
onDropdownClose: () => combobox.resetSelectedOption(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const selectedOption = values.find((item) => item.value === selectedValue);
|
||||||
|
|
||||||
|
const options = values.map((item) => (
|
||||||
|
<Combobox.Option value={item.value} key={item.value}>
|
||||||
|
<ComboListItem emoji={item.icon} label={item.label} />
|
||||||
|
</Combobox.Option>
|
||||||
|
));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Combobox
|
||||||
|
store={combobox}
|
||||||
|
withinPortal={false}
|
||||||
|
onOptionSubmit={(val) => {
|
||||||
|
setValue(val as string);
|
||||||
|
combobox.closeDropdown();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Combobox.Target>
|
||||||
|
<InputBase
|
||||||
|
component="button"
|
||||||
|
type="button"
|
||||||
|
pointer
|
||||||
|
rightSection={<Combobox.Chevron />}
|
||||||
|
onClick={() => combobox.toggleDropdown()}
|
||||||
|
rightSectionPointerEvents="none"
|
||||||
|
multiline
|
||||||
|
>
|
||||||
|
{selectedOption ? (
|
||||||
|
<ComboListItem
|
||||||
|
emoji={selectedOption.icon}
|
||||||
|
label={selectedOption.label}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<Input.Placeholder>Pick value</Input.Placeholder>
|
||||||
|
)}
|
||||||
|
</InputBase>
|
||||||
|
</Combobox.Target>
|
||||||
|
|
||||||
|
<Combobox.Dropdown>
|
||||||
|
<Combobox.Options>{options}</Combobox.Options>
|
||||||
|
</Combobox.Dropdown>
|
||||||
|
</Combobox>
|
||||||
|
);
|
||||||
|
}
|
||||||
16
inertia/components/common/combo_list/combo_list_item.tsx
Normal file
16
inertia/components/common/combo_list/combo_list_item.tsx
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
import { Group, Text } from '@mantine/core';
|
||||||
|
|
||||||
|
export const ComboListItem = ({
|
||||||
|
emoji,
|
||||||
|
label,
|
||||||
|
}: {
|
||||||
|
emoji: React.ReactNode;
|
||||||
|
label: string;
|
||||||
|
}) => (
|
||||||
|
<Group gap="xs" align="center">
|
||||||
|
{emoji}
|
||||||
|
<Text fz="sm" fw={500}>
|
||||||
|
{label}
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
);
|
||||||
@@ -19,6 +19,8 @@ import { useEffect } from 'react';
|
|||||||
import { UserDropdown } from '~/components/common/floating_navbar/user_dropdown';
|
import { UserDropdown } from '~/components/common/floating_navbar/user_dropdown';
|
||||||
import { ExternalLinkUnstyled } from '~/components/common/links/external_link_unstyled';
|
import { ExternalLinkUnstyled } from '~/components/common/links/external_link_unstyled';
|
||||||
import { InternalLink } from '~/components/common/links/internal_link';
|
import { InternalLink } from '~/components/common/links/internal_link';
|
||||||
|
import { LocaleSwitcher } from '~/components/common/locale_switcher';
|
||||||
|
import { ThemeSwitcher } from '~/components/common/theme_switcher';
|
||||||
import { useAuth } from '~/hooks/use_auth';
|
import { useAuth } from '~/hooks/use_auth';
|
||||||
import classes from './floating_navbar.module.css';
|
import classes from './floating_navbar.module.css';
|
||||||
|
|
||||||
@@ -40,9 +42,11 @@ export function FloatingNavbar({ width }: FloatingNavbarProps) {
|
|||||||
|
|
||||||
const links = (
|
const links = (
|
||||||
<>
|
<>
|
||||||
<InternalLink route="dashboard" style={{ fontSize: rem(16) }}>
|
{auth.isAuthenticated && (
|
||||||
Dashboard
|
<InternalLink route="dashboard" style={{ fontSize: rem(16) }}>
|
||||||
</InternalLink>
|
Dashboard
|
||||||
|
</InternalLink>
|
||||||
|
)}
|
||||||
<ExternalLinkUnstyled
|
<ExternalLinkUnstyled
|
||||||
href={PROJECT_REPO_GITHUB_URL}
|
href={PROJECT_REPO_GITHUB_URL}
|
||||||
style={{ fontSize: rem(16) }}
|
style={{ fontSize: rem(16) }}
|
||||||
@@ -74,8 +78,8 @@ export function FloatingNavbar({ width }: FloatingNavbarProps) {
|
|||||||
</Group>
|
</Group>
|
||||||
<Group>
|
<Group>
|
||||||
{!isMobile && <Group>{links}</Group>}
|
{!isMobile && <Group>{links}</Group>}
|
||||||
{isMobile && <Burger opened={opened} onClick={handler.toggle} />}
|
|
||||||
{auth.isAuthenticated && <UserDropdown />}
|
{auth.isAuthenticated && <UserDropdown />}
|
||||||
|
{isMobile && <Burger opened={opened} onClick={handler.toggle} />}
|
||||||
{!auth.isAuthenticated && (
|
{!auth.isAuthenticated && (
|
||||||
<Button
|
<Button
|
||||||
variant="default"
|
variant="default"
|
||||||
@@ -101,6 +105,10 @@ export function FloatingNavbar({ width }: FloatingNavbarProps) {
|
|||||||
<Flex direction="column" gap="md">
|
<Flex direction="column" gap="md">
|
||||||
{links}
|
{links}
|
||||||
</Flex>
|
</Flex>
|
||||||
|
<Group mt="md">
|
||||||
|
<ThemeSwitcher />
|
||||||
|
<LocaleSwitcher />
|
||||||
|
</Group>
|
||||||
</Drawer>
|
</Drawer>
|
||||||
</Box>
|
</Box>
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -10,10 +10,6 @@
|
|||||||
var(--mantine-color-dark-8)
|
var(--mantine-color-dark-8)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.userActive {
|
.userActive {
|
||||||
|
|||||||
@@ -2,8 +2,7 @@ import { Avatar, Group, Menu, Text, UnstyledButton } from '@mantine/core';
|
|||||||
import { useDisclosure } from '@mantine/hooks';
|
import { useDisclosure } from '@mantine/hooks';
|
||||||
import cx from 'clsx';
|
import cx from 'clsx';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { TbChevronDown, TbLogout, TbUser } from 'react-icons/tb';
|
import { TbChevronDown, TbLogout, TbSettings, TbShield } from 'react-icons/tb';
|
||||||
import { InternalLink } from '~/components/common/links/internal_link';
|
|
||||||
import { InternalLinkUnstyled } from '~/components/common/links/internal_link_unstyled';
|
import { InternalLinkUnstyled } from '~/components/common/links/internal_link_unstyled';
|
||||||
import { useAuth } from '~/hooks/use_auth';
|
import { useAuth } from '~/hooks/use_auth';
|
||||||
import classes from './user_dropdown.module.css';
|
import classes from './user_dropdown.module.css';
|
||||||
@@ -13,6 +12,7 @@ export function UserDropdown() {
|
|||||||
const [userMenuOpened, { open: openUserMenu, close: closeUserMenu }] =
|
const [userMenuOpened, { open: openUserMenu, close: closeUserMenu }] =
|
||||||
useDisclosure(false);
|
useDisclosure(false);
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Menu
|
<Menu
|
||||||
width={260}
|
width={260}
|
||||||
@@ -32,6 +32,9 @@ export function UserDropdown() {
|
|||||||
alt={auth.user?.fullname}
|
alt={auth.user?.fullname}
|
||||||
radius="xl"
|
radius="xl"
|
||||||
size={20}
|
size={20}
|
||||||
|
imageProps={{
|
||||||
|
referrerPolicy: 'no-referrer',
|
||||||
|
}}
|
||||||
/>
|
/>
|
||||||
<Text fw={500} size="sm" lh={1} mr={3}>
|
<Text fw={500} size="sm" lh={1} mr={3}>
|
||||||
{auth.user?.fullname}
|
{auth.user?.fullname}
|
||||||
@@ -41,29 +44,32 @@ export function UserDropdown() {
|
|||||||
</UnstyledButton>
|
</UnstyledButton>
|
||||||
</Menu.Target>
|
</Menu.Target>
|
||||||
<Menu.Dropdown>
|
<Menu.Dropdown>
|
||||||
<Menu.Label>{t('common:user')}</Menu.Label>
|
|
||||||
<Menu.Item
|
|
||||||
leftSection={<TbUser size={16} />}
|
|
||||||
component={InternalLinkUnstyled}
|
|
||||||
href={`/user/${auth.user?.fullname}`}
|
|
||||||
color="inherit"
|
|
||||||
>
|
|
||||||
{t('common:profile')}
|
|
||||||
</Menu.Item>
|
|
||||||
|
|
||||||
{auth.user?.isAdmin && (
|
{auth.user?.isAdmin && (
|
||||||
<>
|
<>
|
||||||
<Menu.Label>{t('common:admin')}</Menu.Label>
|
<Menu.Label>{t('common:admin')}</Menu.Label>
|
||||||
<InternalLink href="/admin">{t('common:admin')}</InternalLink>
|
<Menu.Item
|
||||||
|
leftSection={<TbShield size={16} />}
|
||||||
|
component={InternalLinkUnstyled}
|
||||||
|
href="/admin"
|
||||||
|
color="red"
|
||||||
|
>
|
||||||
|
{t('common:manage-users')}
|
||||||
|
</Menu.Item>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Menu.Label>{t('common:settings')}</Menu.Label>
|
<Menu.Label>{t('common:user')}</Menu.Label>
|
||||||
|
<Menu.Item
|
||||||
|
leftSection={<TbSettings size={16} />}
|
||||||
|
component={InternalLinkUnstyled}
|
||||||
|
href="/user/settings"
|
||||||
|
>
|
||||||
|
{t('common:settings')}
|
||||||
|
</Menu.Item>
|
||||||
<Menu.Item
|
<Menu.Item
|
||||||
leftSection={<TbLogout size={16} />}
|
leftSection={<TbLogout size={16} />}
|
||||||
component={InternalLinkUnstyled}
|
component={InternalLinkUnstyled}
|
||||||
href="/auth/logout"
|
href="/auth/logout"
|
||||||
color="inherit"
|
|
||||||
>
|
>
|
||||||
{t('common:logout')}
|
{t('common:logout')}
|
||||||
</Menu.Item>
|
</Menu.Item>
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
.list {
|
||||||
|
position: relative;
|
||||||
|
margin-bottom: var(--mantine-spacing-md);
|
||||||
|
}
|
||||||
|
|
||||||
|
.indicator {
|
||||||
|
z-index: -1 !important;
|
||||||
|
background-color: var(--mantine-color-white);
|
||||||
|
border-radius: var(--mantine-radius-md);
|
||||||
|
border: 1px solid var(--mantine-color-gray-2);
|
||||||
|
box-shadow: var(--mantine-shadow-sm);
|
||||||
|
|
||||||
|
@mixin dark {
|
||||||
|
background-color: var(--mantine-color-dark-6);
|
||||||
|
border-color: var(--mantine-color-dark-4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab {
|
||||||
|
z-index: 1;
|
||||||
|
font-weight: 500;
|
||||||
|
transition: color 100ms ease;
|
||||||
|
color: var(--mantine-color-gray-7);
|
||||||
|
|
||||||
|
&[data-active] {
|
||||||
|
color: var(--mantine-color-black);
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin dark {
|
||||||
|
color: var(--mantine-color-dark-1);
|
||||||
|
|
||||||
|
&[data-active] {
|
||||||
|
color: var(--mantine-color-white);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
79
inertia/components/common/floating_tabs/floating_tabs.tsx
Normal file
79
inertia/components/common/floating_tabs/floating_tabs.tsx
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import {
|
||||||
|
FloatingIndicator,
|
||||||
|
Indicator,
|
||||||
|
Tabs as MantineTabs,
|
||||||
|
Stack,
|
||||||
|
} from '@mantine/core';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import classes from './floating_tabs.module.css';
|
||||||
|
|
||||||
|
export type FloatingTab = {
|
||||||
|
value: string;
|
||||||
|
label: string;
|
||||||
|
content: React.ReactNode;
|
||||||
|
disabled?: boolean;
|
||||||
|
indicator?: {
|
||||||
|
content: string;
|
||||||
|
color?: string;
|
||||||
|
pulse?: boolean;
|
||||||
|
disabled?: boolean;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
interface FloatingTabsProps {
|
||||||
|
tabs: FloatingTab[];
|
||||||
|
keepMounted?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FloatingTabs({ tabs, keepMounted = false }: FloatingTabsProps) {
|
||||||
|
const [rootRef, setRootRef] = useState<HTMLDivElement | null>(null);
|
||||||
|
const [value, setValue] = useState<string | null>(tabs[0].value);
|
||||||
|
const [controlsRefs, setControlsRefs] = useState<
|
||||||
|
Record<string, HTMLButtonElement | null>
|
||||||
|
>({});
|
||||||
|
const setControlRef = (val: string) => (node: HTMLButtonElement) => {
|
||||||
|
controlsRefs[val] = node;
|
||||||
|
setControlsRefs(controlsRefs);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MantineTabs
|
||||||
|
variant="none"
|
||||||
|
value={value}
|
||||||
|
onChange={setValue}
|
||||||
|
keepMounted={keepMounted}
|
||||||
|
>
|
||||||
|
<MantineTabs.List ref={setRootRef} className={classes.list}>
|
||||||
|
{tabs.map((tab) => (
|
||||||
|
<Indicator
|
||||||
|
label={tab.indicator?.content}
|
||||||
|
color={tab.indicator?.color}
|
||||||
|
processing={tab.indicator?.pulse}
|
||||||
|
disabled={!tab.indicator || tab.indicator.disabled}
|
||||||
|
size={16}
|
||||||
|
key={tab.value}
|
||||||
|
>
|
||||||
|
<MantineTabs.Tab
|
||||||
|
value={tab.value}
|
||||||
|
ref={setControlRef(tab.value)}
|
||||||
|
className={classes.tab}
|
||||||
|
disabled={tab.disabled}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</MantineTabs.Tab>
|
||||||
|
</Indicator>
|
||||||
|
))}
|
||||||
|
<FloatingIndicator
|
||||||
|
target={value ? controlsRefs[value] : null}
|
||||||
|
parent={rootRef}
|
||||||
|
className={classes.indicator}
|
||||||
|
/>
|
||||||
|
</MantineTabs.List>
|
||||||
|
{tabs.map((tab) => (
|
||||||
|
<MantineTabs.Panel key={tab.value} value={tab.value}>
|
||||||
|
<Stack>{tab.content}</Stack>
|
||||||
|
</MantineTabs.Panel>
|
||||||
|
))}
|
||||||
|
</MantineTabs>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,33 +1,38 @@
|
|||||||
import { AUTHOR_GITHUB_URL, AUTHOR_NAME } from '#config/project';
|
import { AUTHOR_GITHUB_URL, AUTHOR_NAME } from '#config/project';
|
||||||
import PATHS from '#core/constants/paths';
|
import PATHS from '#core/constants/paths';
|
||||||
|
import { route } from '@izzyjs/route/client';
|
||||||
import { Anchor, Group, Text } from '@mantine/core';
|
import { Anchor, Group, Text } from '@mantine/core';
|
||||||
|
import { withTranslation, WithTranslation } from 'react-i18next';
|
||||||
import ExternalLink from '~/components/common/external_link';
|
import ExternalLink from '~/components/common/external_link';
|
||||||
import { ExternalLinkStyled } from '~/components/common/links/external_link_styled';
|
import { ExternalLinkStyled } from '~/components/common/links/external_link_styled';
|
||||||
|
import { InternalLink } from '~/components/common/links/internal_link';
|
||||||
import { LocaleSwitcher } from '~/components/common/locale_switcher';
|
import { LocaleSwitcher } from '~/components/common/locale_switcher';
|
||||||
import { ThemeSwitcher } from '~/components/common/theme_switcher';
|
import { ThemeSwitcher } from '~/components/common/theme_switcher';
|
||||||
import packageJson from '../../../../package.json';
|
import packageJson from '../../../../package.json';
|
||||||
import classes from './footer.module.css';
|
import classes from './footer.module.css';
|
||||||
|
|
||||||
export const Footer = () => (
|
export const Footer = withTranslation()(({ t }: WithTranslation) => (
|
||||||
<Group className={classes.footer}>
|
<Group className={classes.footer}>
|
||||||
<Group className={classes.footer__content}>
|
<Group className={classes.footer__content}>
|
||||||
<Text>
|
<Text>
|
||||||
Made with ❤️ by{' '}
|
{t('footer.made_by')}{' '}
|
||||||
<ExternalLinkStyled href={AUTHOR_GITHUB_URL}>
|
<ExternalLinkStyled href={AUTHOR_GITHUB_URL}>
|
||||||
{AUTHOR_NAME}
|
{AUTHOR_NAME}
|
||||||
</ExternalLinkStyled>
|
</ExternalLinkStyled>
|
||||||
</Text>
|
</Text>
|
||||||
•
|
•
|
||||||
<Text>
|
<Group gap="sm">
|
||||||
<Anchor size="sm" component={ExternalLink} href={PATHS.REPO_GITHUB}>
|
|
||||||
{packageJson.version}
|
|
||||||
</Anchor>
|
|
||||||
</Text>
|
|
||||||
•
|
|
||||||
<Group gap="sm" mt={4} mb={4}>
|
|
||||||
<ThemeSwitcher />
|
<ThemeSwitcher />
|
||||||
<LocaleSwitcher />
|
<LocaleSwitcher />
|
||||||
</Group>
|
</Group>
|
||||||
|
•
|
||||||
|
<Group gap="sm">
|
||||||
|
<Anchor size="sm" component={ExternalLink} href={PATHS.REPO_GITHUB}>
|
||||||
|
{packageJson.version}
|
||||||
|
</Anchor>
|
||||||
|
<InternalLink href={route('privacy').path}>{t('privacy')}</InternalLink>
|
||||||
|
<InternalLink href={route('terms').path}>{t('terms')}</InternalLink>
|
||||||
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
</Group>
|
</Group>
|
||||||
);
|
));
|
||||||
|
|||||||
@@ -0,0 +1,20 @@
|
|||||||
|
.header {
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
background-color: var(--mantine-color-body);
|
||||||
|
transition: box-shadow 150ms ease;
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
border-bottom: 1px solid
|
||||||
|
light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-3));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.scrolled {
|
||||||
|
box-shadow: var(--mantine-shadow-sm);
|
||||||
|
}
|
||||||
56
inertia/components/common/simple_table/simple_table.tsx
Normal file
56
inertia/components/common/simple_table/simple_table.tsx
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
import { ScrollArea, Table, Text } from '@mantine/core';
|
||||||
|
import cx from 'clsx';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import classes from './simple_table.module.css';
|
||||||
|
|
||||||
|
export type SimpleTableData = {
|
||||||
|
key: string;
|
||||||
|
[key: string]: string | React.ReactNode | undefined;
|
||||||
|
actions?: React.ReactNode[];
|
||||||
|
};
|
||||||
|
|
||||||
|
interface SimpleTableProps {
|
||||||
|
data: SimpleTableData[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SimpleTable({ data }: SimpleTableProps) {
|
||||||
|
const [scrolled, setScrolled] = useState(false);
|
||||||
|
|
||||||
|
const columns = data.length > 0 ? Object.keys(data[0]) : [];
|
||||||
|
|
||||||
|
const rows = data.map((row) => {
|
||||||
|
return (
|
||||||
|
<Table.Tr key={row.key}>
|
||||||
|
{columns.map((column) => (
|
||||||
|
<Table.Td key={column}>
|
||||||
|
{row[column] ?? (
|
||||||
|
<Text c="dimmed" size="sm">
|
||||||
|
N/A
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
</Table.Td>
|
||||||
|
))}
|
||||||
|
</Table.Tr>
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ScrollArea
|
||||||
|
h={300}
|
||||||
|
onScrollPositionChange={({ y }) => setScrolled(y !== 0)}
|
||||||
|
>
|
||||||
|
<Table miw={700}>
|
||||||
|
<Table.Thead
|
||||||
|
className={cx(classes.header, { [classes.scrolled]: scrolled })}
|
||||||
|
>
|
||||||
|
<Table.Tr>
|
||||||
|
{columns.map((column) => (
|
||||||
|
<Table.Th key={column}>{column}</Table.Th>
|
||||||
|
))}
|
||||||
|
</Table.Tr>
|
||||||
|
</Table.Thead>
|
||||||
|
<Table.Tbody>{rows}</Table.Tbody>
|
||||||
|
</Table>
|
||||||
|
</ScrollArea>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { Fieldset, Stack, Text } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { CollectionListSelector } from '~/components/dashboard/collection/collection_list_selector';
|
||||||
|
import { LinkListSelector } from '~/components/dashboard/link/link_list_selector';
|
||||||
|
import { useIsMobile } from '~/hooks/use_is_mobile';
|
||||||
|
|
||||||
|
export function UserPreferences() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Fieldset legend={t('preferences')}>
|
||||||
|
{isMobile && (
|
||||||
|
<Text size="xs" c="orange" mb="sm">
|
||||||
|
{t('preferences-description')}
|
||||||
|
</Text>
|
||||||
|
)}
|
||||||
|
<Stack>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t('display-preferences.collection-list-display')}
|
||||||
|
</Text>
|
||||||
|
<CollectionListSelector />
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
{t('display-preferences.link-list-display')}
|
||||||
|
</Text>
|
||||||
|
<LinkListSelector />
|
||||||
|
</Stack>
|
||||||
|
</Fieldset>
|
||||||
|
);
|
||||||
|
}
|
||||||
29
inertia/components/dashboard/collection/collection_list.tsx
Normal file
29
inertia/components/dashboard/collection/collection_list.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { ScrollArea, Stack, Text } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { CollectionFavoriteItem } from '~/components/dashboard/collection/item/collection_favorite_item';
|
||||||
|
import { CollectionItem } from '~/components/dashboard/collection/item/collection_item';
|
||||||
|
import { useCollections } from '~/hooks/collections/use_collections';
|
||||||
|
import { useIsMobile } from '~/hooks/use_is_mobile';
|
||||||
|
import styles from './list/collection_list.module.css';
|
||||||
|
|
||||||
|
export function CollectionList() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const collections = useCollections();
|
||||||
|
const isMobile = useIsMobile();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Stack gap="xs" h="100%" w={isMobile ? '100%' : '350px'}>
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column' }}>
|
||||||
|
<Text c="dimmed" ml="md" mb="sm">
|
||||||
|
{t('collection.collections')} • {collections.length}
|
||||||
|
</Text>
|
||||||
|
<ScrollArea className={styles.collectionList}>
|
||||||
|
<CollectionFavoriteItem />
|
||||||
|
{collections.map((collection) => (
|
||||||
|
<CollectionItem collection={collection} />
|
||||||
|
))}
|
||||||
|
</ScrollArea>
|
||||||
|
</div>
|
||||||
|
</Stack>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import { COLLECTION_LIST_DISPLAYS } from '#shared/lib/display_preferences';
|
||||||
|
import { CollectionListDisplay } from '#shared/types/index';
|
||||||
|
import { SegmentedControl } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useDisplayPreferences } from '~/hooks/use_display_preferences';
|
||||||
|
|
||||||
|
export function CollectionListSelector() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { displayPreferences, handleUpdateDisplayPreferences } =
|
||||||
|
useDisplayPreferences();
|
||||||
|
|
||||||
|
const data = COLLECTION_LIST_DISPLAYS.map((display) => ({
|
||||||
|
label: t(`display-preferences.${display}`),
|
||||||
|
value: display,
|
||||||
|
}));
|
||||||
|
return (
|
||||||
|
<SegmentedControl
|
||||||
|
data={data}
|
||||||
|
value={displayPreferences.collectionListDisplay}
|
||||||
|
onChange={(value) =>
|
||||||
|
handleUpdateDisplayPreferences({
|
||||||
|
collectionListDisplay: value as CollectionListDisplay,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
w="50%"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { router } from '@inertiajs/react';
|
||||||
|
import { route } from '@izzyjs/route/client';
|
||||||
|
import { Chip, Group, Text } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useActiveCollection } from '~/hooks/collections/use_active_collection';
|
||||||
|
import { useCollections } from '~/hooks/collections/use_collections';
|
||||||
|
import { appendCollectionId } from '~/lib/navigation';
|
||||||
|
|
||||||
|
export function InlineCollectionList() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const collections = useCollections();
|
||||||
|
const activeCollection = useActiveCollection();
|
||||||
|
|
||||||
|
const handleCollectionChange = (value?: string) => {
|
||||||
|
if (value) {
|
||||||
|
router.visit(appendCollectionId(route('dashboard').path, Number(value)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
router.visit(route('dashboard').path);
|
||||||
|
};
|
||||||
|
|
||||||
|
const fields = [
|
||||||
|
{
|
||||||
|
label: t('common:favorite'),
|
||||||
|
value: 'favorite',
|
||||||
|
},
|
||||||
|
...collections.map((c) => ({
|
||||||
|
label: (
|
||||||
|
<Group gap="xs" wrap="nowrap">
|
||||||
|
<>{c.name}</>
|
||||||
|
<Text size="xs" c="dimmed">
|
||||||
|
{c.links.length}
|
||||||
|
</Text>
|
||||||
|
</Group>
|
||||||
|
),
|
||||||
|
value: c.id.toString(),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Group gap="xs" w="100%">
|
||||||
|
{fields.map((field) => (
|
||||||
|
<Chip
|
||||||
|
key={field.value}
|
||||||
|
checked={
|
||||||
|
activeCollection?.id
|
||||||
|
? activeCollection.id === Number(field.value)
|
||||||
|
: field.value === 'favorite'
|
||||||
|
}
|
||||||
|
variant="light"
|
||||||
|
onClick={() => handleCollectionChange(field.value)}
|
||||||
|
>
|
||||||
|
{field.label}
|
||||||
|
</Chip>
|
||||||
|
))}
|
||||||
|
</Group>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { Link } from '@inertiajs/react';
|
||||||
|
import { route } from '@izzyjs/route/client';
|
||||||
|
import { Text } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { TbStar, TbStarFilled } from 'react-icons/tb';
|
||||||
|
import { useActiveCollection } from '~/hooks/collections/use_active_collection';
|
||||||
|
import classes from './collection_item.module.css';
|
||||||
|
|
||||||
|
export function CollectionFavoriteItem() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const activeCollection = useActiveCollection();
|
||||||
|
const isActiveCollection = !activeCollection?.id;
|
||||||
|
const FolderIcon = isActiveCollection ? TbStarFilled : TbStar;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Link
|
||||||
|
className={classes.link}
|
||||||
|
data-active={isActiveCollection || undefined}
|
||||||
|
href={route('dashboard').path}
|
||||||
|
key="favorite"
|
||||||
|
title="Favorite"
|
||||||
|
>
|
||||||
|
<FolderIcon className={classes.linkIcon} />
|
||||||
|
<Text maw={'200px'} style={{ wordBreak: 'break-all' }}>
|
||||||
|
{t('favorite')}
|
||||||
|
</Text>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,18 +3,18 @@ import { route } from '@izzyjs/route/client';
|
|||||||
import { Text } from '@mantine/core';
|
import { Text } from '@mantine/core';
|
||||||
import { useEffect, useRef } from 'react';
|
import { useEffect, useRef } from 'react';
|
||||||
import { AiFillFolderOpen, AiOutlineFolder } from 'react-icons/ai';
|
import { AiFillFolderOpen, AiOutlineFolder } from 'react-icons/ai';
|
||||||
|
import { useActiveCollection } from '~/hooks/collections/use_active_collection';
|
||||||
import { appendCollectionId } from '~/lib/navigation';
|
import { appendCollectionId } from '~/lib/navigation';
|
||||||
import { useActiveCollection } from '~/stores/collection_store';
|
|
||||||
import { CollectionWithLinks } from '~/types/app';
|
import { CollectionWithLinks } from '~/types/app';
|
||||||
import classes from './collection_item.module.css';
|
import classes from './collection_item.module.css';
|
||||||
|
|
||||||
export default function CollectionItem({
|
interface CollectionItemProps {
|
||||||
collection,
|
|
||||||
}: {
|
|
||||||
collection: CollectionWithLinks;
|
collection: CollectionWithLinks;
|
||||||
}) {
|
}
|
||||||
|
|
||||||
|
export function CollectionItem({ collection }: CollectionItemProps) {
|
||||||
const itemRef = useRef<HTMLAnchorElement>(null);
|
const itemRef = useRef<HTMLAnchorElement>(null);
|
||||||
const { activeCollection } = useActiveCollection();
|
const activeCollection = useActiveCollection();
|
||||||
const isActiveCollection = collection.id === activeCollection?.id;
|
const isActiveCollection = collection.id === activeCollection?.id;
|
||||||
const FolderIcon = isActiveCollection ? AiFillFolderOpen : AiOutlineFolder;
|
const FolderIcon = isActiveCollection ? AiFillFolderOpen : AiOutlineFolder;
|
||||||
|
|
||||||
@@ -34,7 +34,10 @@ export default function CollectionItem({
|
|||||||
title={collection.name}
|
title={collection.name}
|
||||||
>
|
>
|
||||||
<FolderIcon className={classes.linkIcon} />
|
<FolderIcon className={classes.linkIcon} />
|
||||||
<Text lineClamp={1} maw={'200px'} style={{ wordBreak: 'break-all' }}>
|
<Text
|
||||||
|
lineClamp={1}
|
||||||
|
style={{ wordBreak: 'break-all', whiteSpace: 'pre-line' }}
|
||||||
|
>
|
||||||
{collection.name}
|
{collection.name}
|
||||||
</Text>
|
</Text>
|
||||||
</Link>
|
</Link>
|
||||||
|
|||||||
@@ -1,50 +1,12 @@
|
|||||||
import { router } from '@inertiajs/react';
|
|
||||||
import { route } from '@izzyjs/route/client';
|
|
||||||
import { Box, ScrollArea, Text } from '@mantine/core';
|
import { Box, ScrollArea, Text } from '@mantine/core';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import CollectionItem from '~/components/dashboard/collection/item/collection_item';
|
import CollectionItem from '~/components/dashboard/collection/item/collection_item';
|
||||||
import useShortcut from '~/hooks/use_shortcut';
|
import { useCollections } from '~/hooks/collections/use_collections';
|
||||||
import { appendCollectionId } from '~/lib/navigation';
|
|
||||||
import { useActiveCollection, useCollections } from '~/stores/collection_store';
|
|
||||||
import styles from './collection_list.module.css';
|
import styles from './collection_list.module.css';
|
||||||
|
|
||||||
export default function CollectionList() {
|
export default function CollectionList() {
|
||||||
const { t } = useTranslation('common');
|
const { t } = useTranslation('common');
|
||||||
const { collections } = useCollections();
|
const collections = useCollections();
|
||||||
const { activeCollection, setActiveCollection } = useActiveCollection();
|
|
||||||
|
|
||||||
const replaceUrl = (collectionId: number) =>
|
|
||||||
router.get(appendCollectionId(route('dashboard').path, collectionId));
|
|
||||||
|
|
||||||
const goToPreviousCollection = () => {
|
|
||||||
const currentCategoryIndex = collections.findIndex(
|
|
||||||
({ id }) => id === activeCollection?.id
|
|
||||||
);
|
|
||||||
if (currentCategoryIndex === -1 || currentCategoryIndex === 0) return;
|
|
||||||
|
|
||||||
const collection = collections[currentCategoryIndex - 1];
|
|
||||||
replaceUrl(collection.id);
|
|
||||||
setActiveCollection(collection);
|
|
||||||
};
|
|
||||||
|
|
||||||
const goToNextCollection = () => {
|
|
||||||
const currentCategoryIndex = collections.findIndex(
|
|
||||||
({ id }) => id === activeCollection?.id
|
|
||||||
);
|
|
||||||
if (
|
|
||||||
currentCategoryIndex === -1 ||
|
|
||||||
currentCategoryIndex === collections.length - 1
|
|
||||||
)
|
|
||||||
return;
|
|
||||||
|
|
||||||
const collection = collections[currentCategoryIndex + 1];
|
|
||||||
replaceUrl(collection.id);
|
|
||||||
setActiveCollection(collection);
|
|
||||||
};
|
|
||||||
|
|
||||||
useShortcut('ARROW_UP', goToPreviousCollection);
|
|
||||||
useShortcut('ARROW_DOWN', goToNextCollection);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box className={styles.sideMenu}>
|
<Box className={styles.sideMenu}>
|
||||||
<Box className={styles.listContainer}>
|
<Box className={styles.listContainer}>
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { Button, Drawer, Portal, rem, Text } from '@mantine/core';
|
||||||
|
import { useDisclosure, useHeadroom } from '@mantine/hooks';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { TbFolder } from 'react-icons/tb';
|
||||||
|
import { CollectionFavoriteItem } from '~/components/dashboard/collection/item/collection_favorite_item';
|
||||||
|
import { useCollections } from '~/hooks/collections/use_collections';
|
||||||
|
import { CollectionItem } from './item/collection_item';
|
||||||
|
|
||||||
|
export function MobileCollectionList() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const [opened, handler] = useDisclosure();
|
||||||
|
const collections = useCollections();
|
||||||
|
const pinned = useHeadroom({ fixedAt: 0 });
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Drawer
|
||||||
|
opened={opened}
|
||||||
|
onClose={handler.close}
|
||||||
|
title={t('collection.collections', { count: collections.length })}
|
||||||
|
>
|
||||||
|
<CollectionFavoriteItem />
|
||||||
|
{collections.map((collection) => (
|
||||||
|
<CollectionItem collection={collection} />
|
||||||
|
))}
|
||||||
|
</Drawer>
|
||||||
|
<Portal>
|
||||||
|
<Button
|
||||||
|
onClick={handler.open}
|
||||||
|
variant="outline"
|
||||||
|
size="xs"
|
||||||
|
style={{
|
||||||
|
position: 'fixed',
|
||||||
|
left: '50%',
|
||||||
|
bottom: pinned ? rem(16) : rem(-100),
|
||||||
|
width: `calc(100% - ${rem(16)} * 2)`,
|
||||||
|
backgroundColor: 'var(--mantine-color-body)',
|
||||||
|
transition: 'all 0.2s ease-in-out',
|
||||||
|
transform: 'translateX(-50%)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<TbFolder size={18} />
|
||||||
|
<Text ml={4}>
|
||||||
|
{t('collection.collections', { count: collections.length })}
|
||||||
|
</Text>
|
||||||
|
</Button>
|
||||||
|
</Portal>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { Badge, CopyButton } from '@mantine/core';
|
||||||
|
import { t } from 'i18next';
|
||||||
|
import { TbCopy } from 'react-icons/tb';
|
||||||
|
import { useActiveCollection } from '~/hooks/collections/use_active_collection';
|
||||||
|
import { useAppUrl } from '~/hooks/use_app_url';
|
||||||
|
|
||||||
|
const COPY_TIMEOUT = 3_000;
|
||||||
|
|
||||||
|
export function SharedCollectionCopyLink() {
|
||||||
|
const appUrl = useAppUrl();
|
||||||
|
const activeCollection = useActiveCollection();
|
||||||
|
|
||||||
|
if (!activeCollection) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const copyUrl = `${appUrl}/shared/${activeCollection.id}`;
|
||||||
|
return (
|
||||||
|
<CopyButton value={copyUrl} timeout={COPY_TIMEOUT}>
|
||||||
|
{({ copied, copy }) => (
|
||||||
|
<Badge
|
||||||
|
variant={copied ? 'filled' : 'light'}
|
||||||
|
onClick={copy}
|
||||||
|
style={{ cursor: 'pointer' }}
|
||||||
|
>
|
||||||
|
{copied ? t('success-copy') : t('visibility.public')}
|
||||||
|
{!copied && <TbCopy style={{ marginLeft: 4 }} />}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</CopyButton>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -16,8 +16,8 @@ import { GoPencil } from 'react-icons/go';
|
|||||||
import { IoIosAddCircleOutline } from 'react-icons/io';
|
import { IoIosAddCircleOutline } from 'react-icons/io';
|
||||||
import { IoTrashOutline } from 'react-icons/io5';
|
import { IoTrashOutline } from 'react-icons/io5';
|
||||||
import { ShareCollection } from '~/components/share/share_collection';
|
import { ShareCollection } from '~/components/share/share_collection';
|
||||||
|
import { useActiveCollection } from '~/hooks/collections/use_active_collection';
|
||||||
import { appendCollectionId } from '~/lib/navigation';
|
import { appendCollectionId } from '~/lib/navigation';
|
||||||
import { useActiveCollection } from '~/stores/collection_store';
|
|
||||||
import { Visibility } from '~/types/app';
|
import { Visibility } from '~/types/app';
|
||||||
|
|
||||||
interface DashboardHeaderProps {
|
interface DashboardHeaderProps {
|
||||||
@@ -32,7 +32,7 @@ interface DashboardHeaderProps {
|
|||||||
}
|
}
|
||||||
export function DashboardHeader({ navbar, aside }: DashboardHeaderProps) {
|
export function DashboardHeader({ navbar, aside }: DashboardHeaderProps) {
|
||||||
const { t } = useTranslation('common');
|
const { t } = useTranslation('common');
|
||||||
const { activeCollection } = useActiveCollection();
|
const activeCollection = useActiveCollection();
|
||||||
return (
|
return (
|
||||||
<AppShell.Header style={{ display: 'flex', alignItems: 'center' }}>
|
<AppShell.Header style={{ display: 'flex', alignItems: 'center' }}>
|
||||||
<Group justify="space-between" px="md" flex={1} wrap="nowrap">
|
<Group justify="space-between" px="md" flex={1} wrap="nowrap">
|
||||||
|
|||||||
@@ -20,10 +20,10 @@ import { PiGearLight } from 'react-icons/pi';
|
|||||||
import { UserCard } from '~/components/common/user_card';
|
import { UserCard } from '~/components/common/user_card';
|
||||||
import { FavoriteList } from '~/components/dashboard/favorite/favorite_list';
|
import { FavoriteList } from '~/components/dashboard/favorite/favorite_list';
|
||||||
import { SearchSpotlight } from '~/components/search/search';
|
import { SearchSpotlight } from '~/components/search/search';
|
||||||
|
import { useActiveCollection } from '~/hooks/collections/use_active_collection';
|
||||||
import { useAuth } from '~/hooks/use_auth';
|
import { useAuth } from '~/hooks/use_auth';
|
||||||
import useShortcut from '~/hooks/use_shortcut';
|
import useShortcut from '~/hooks/use_shortcut';
|
||||||
import { appendCollectionId } from '~/lib/navigation';
|
import { appendCollectionId } from '~/lib/navigation';
|
||||||
import { useActiveCollection } from '~/stores/collection_store';
|
|
||||||
import { useGlobalHotkeysStore } from '~/stores/global_hotkeys_store';
|
import { useGlobalHotkeysStore } from '~/stores/global_hotkeys_store';
|
||||||
|
|
||||||
interface DashboardNavbarProps {
|
interface DashboardNavbarProps {
|
||||||
@@ -34,7 +34,7 @@ export function DashboardNavbar({ isOpen, toggle }: DashboardNavbarProps) {
|
|||||||
const { t } = useTranslation('common');
|
const { t } = useTranslation('common');
|
||||||
const { isAuthenticated, user } = useAuth();
|
const { isAuthenticated, user } = useAuth();
|
||||||
|
|
||||||
const { activeCollection } = useActiveCollection();
|
const activeCollection = useActiveCollection();
|
||||||
const { globalHotkeysEnabled, setGlobalHotkeysEnabled } =
|
const { globalHotkeysEnabled, setGlobalHotkeysEnabled } =
|
||||||
useGlobalHotkeysStore();
|
useGlobalHotkeysStore();
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { Flex, Group, Stack, Text } from '@mantine/core';
|
import { Flex, Group, Stack, Text } from '@mantine/core';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { FavoriteItem } from '~/components/dashboard/favorite/item/favorite_item';
|
import { FavoriteItem } from '~/components/dashboard/favorite/item/favorite_item';
|
||||||
import { useFavorites } from '~/stores/collection_store';
|
import { useFavoriteLinks } from '~/hooks/collections/use_favorite_links';
|
||||||
|
|
||||||
export function FavoriteList() {
|
export function FavoriteList() {
|
||||||
const { t } = useTranslation('common');
|
const { t } = useTranslation('common');
|
||||||
const { favorites } = useFavorites();
|
const favoriteLinks = useFavoriteLinks();
|
||||||
|
|
||||||
if (favorites.length === 0) {
|
if (favoriteLinks.length === 0) {
|
||||||
return (
|
return (
|
||||||
<Group justify="center">
|
<Group justify="center">
|
||||||
<Text c="dimmed" size="sm" mt="sm">
|
<Text c="dimmed" size="sm" mt="sm">
|
||||||
@@ -20,10 +20,10 @@ export function FavoriteList() {
|
|||||||
return (
|
return (
|
||||||
<Flex direction="column">
|
<Flex direction="column">
|
||||||
<Text c="dimmed" mt="xs" ml="md" mb={4}>
|
<Text c="dimmed" mt="xs" ml="md" mb={4}>
|
||||||
{t('favorite')} • {favorites.length}
|
{t('favorite')} • {favoriteLinks.length}
|
||||||
</Text>
|
</Text>
|
||||||
<Stack gap={4}>
|
<Stack gap={4}>
|
||||||
{favorites.map((link) => (
|
{favoriteLinks.map((link) => (
|
||||||
<FavoriteItem link={link} key={link.id} />
|
<FavoriteItem link={link} key={link.id} />
|
||||||
))}
|
))}
|
||||||
</Stack>
|
</Stack>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Link as InertiaLink } from '@inertiajs/react';
|
import { Link as InertiaLink, router } from '@inertiajs/react';
|
||||||
import { route } from '@izzyjs/route/client';
|
import { route } from '@izzyjs/route/client';
|
||||||
import { ActionIcon, Menu } from '@mantine/core';
|
import { ActionIcon, Menu } from '@mantine/core';
|
||||||
import { MouseEvent } from 'react';
|
import { MouseEvent } from 'react';
|
||||||
@@ -10,7 +10,6 @@ import { IoTrashOutline } from 'react-icons/io5';
|
|||||||
import { MdFavorite, MdFavoriteBorder } from 'react-icons/md';
|
import { MdFavorite, MdFavoriteBorder } from 'react-icons/md';
|
||||||
import { onFavorite } from '~/lib/favorite';
|
import { onFavorite } from '~/lib/favorite';
|
||||||
import { appendCollectionId, appendLinkId } from '~/lib/navigation';
|
import { appendCollectionId, appendLinkId } from '~/lib/navigation';
|
||||||
import { useFavorites } from '~/stores/collection_store';
|
|
||||||
import { Link, PublicLink } from '~/types/app';
|
import { Link, PublicLink } from '~/types/app';
|
||||||
|
|
||||||
interface LinksControlsProps {
|
interface LinksControlsProps {
|
||||||
@@ -21,10 +20,14 @@ export default function LinkControls({
|
|||||||
link,
|
link,
|
||||||
showGoToCollection = false,
|
showGoToCollection = false,
|
||||||
}: LinksControlsProps) {
|
}: LinksControlsProps) {
|
||||||
const { toggleFavorite } = useFavorites();
|
|
||||||
const { t } = useTranslation('common');
|
const { t } = useTranslation('common');
|
||||||
|
|
||||||
const onFavoriteCallback = () => toggleFavorite(link.id);
|
const onFavoriteCallback = () => {
|
||||||
|
const path = route('link.toggle-favorite', {
|
||||||
|
params: { id: link.id.toString() },
|
||||||
|
}).path;
|
||||||
|
router.put(path);
|
||||||
|
};
|
||||||
const handleStopPropagation = (event: MouseEvent<HTMLButtonElement>) =>
|
const handleStopPropagation = (event: MouseEvent<HTMLButtonElement>) =>
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|
||||||
|
|||||||
@@ -28,7 +28,13 @@ export function LinkItem({ link, hideMenu: hideMenu = false }: LinkItemProps) {
|
|||||||
{!hideMenu && <LinkControls link={link} />}
|
{!hideMenu && <LinkControls link={link} />}
|
||||||
</Group>
|
</Group>
|
||||||
{description && (
|
{description && (
|
||||||
<Text c="dimmed" size="sm" mt="xs" lineClamp={3}>
|
<Text
|
||||||
|
c="dimmed"
|
||||||
|
size="sm"
|
||||||
|
mt="xs"
|
||||||
|
lineClamp={3}
|
||||||
|
style={{ wordBreak: 'break-word', whiteSpace: 'pre-line' }}
|
||||||
|
>
|
||||||
{description}
|
{description}
|
||||||
</Text>
|
</Text>
|
||||||
)}
|
)}
|
||||||
|
|||||||
28
inertia/components/dashboard/link/link_list_selector.tsx
Normal file
28
inertia/components/dashboard/link/link_list_selector.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import { LINK_LIST_DISPLAYS } from '#shared/lib/display_preferences';
|
||||||
|
import { LinkListDisplay } from '#shared/types/index';
|
||||||
|
import { SegmentedControl } from '@mantine/core';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { useDisplayPreferences } from '~/hooks/use_display_preferences';
|
||||||
|
|
||||||
|
export function LinkListSelector() {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
const { displayPreferences, handleUpdateDisplayPreferences } =
|
||||||
|
useDisplayPreferences();
|
||||||
|
|
||||||
|
const data = LINK_LIST_DISPLAYS.map((display) => ({
|
||||||
|
label: t(`display-preferences.${display}`),
|
||||||
|
value: display,
|
||||||
|
}));
|
||||||
|
return (
|
||||||
|
<SegmentedControl
|
||||||
|
data={data}
|
||||||
|
value={displayPreferences.linkListDisplay}
|
||||||
|
onChange={(value) =>
|
||||||
|
handleUpdateDisplayPreferences({
|
||||||
|
linkListDisplay: value as LinkListDisplay,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
w="50%"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,24 +1,48 @@
|
|||||||
import { Stack } from '@mantine/core';
|
import { DisplayPreferences } from '#shared/types/index';
|
||||||
|
import { SimpleGrid, Stack, StyleProp } from '@mantine/core';
|
||||||
import { LinkItem } from '~/components/dashboard/link/item/link_item';
|
import { LinkItem } from '~/components/dashboard/link/item/link_item';
|
||||||
import { NoLink } from '~/components/dashboard/link/no_link/no_link';
|
import { NoLink } from '~/components/dashboard/link/no_link/no_link';
|
||||||
import { useActiveCollection } from '~/stores/collection_store';
|
import { useActiveCollection } from '~/hooks/collections/use_active_collection';
|
||||||
|
import { useFavoriteLinks } from '~/hooks/collections/use_favorite_links';
|
||||||
|
import { useDisplayPreferences } from '~/hooks/use_display_preferences';
|
||||||
|
|
||||||
export interface LinkListProps {
|
export interface LinkListProps {
|
||||||
hideMenu?: boolean;
|
hideMenu?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function LinkList({ hideMenu = false }: LinkListProps) {
|
export function LinkList({ hideMenu = false }: LinkListProps) {
|
||||||
const { activeCollection } = useActiveCollection();
|
const activeCollection = useActiveCollection();
|
||||||
|
const favoriteLinks = useFavoriteLinks();
|
||||||
|
const { displayPreferences } = useDisplayPreferences();
|
||||||
|
|
||||||
if (!activeCollection?.links || activeCollection.links.length === 0) {
|
const links = activeCollection?.links || favoriteLinks;
|
||||||
|
|
||||||
|
if (links.length === 0) {
|
||||||
return <NoLink hideMenu={hideMenu} />;
|
return <NoLink hideMenu={hideMenu} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Stack gap="xs">
|
<Stack gap="xs">
|
||||||
{activeCollection?.links.map((link) => (
|
<SimpleGrid cols={getColsByView(displayPreferences)} spacing="xs">
|
||||||
<LinkItem link={link} key={link.id} hideMenu={hideMenu} />
|
{links.map((link) => (
|
||||||
))}
|
<LinkItem link={link} key={link.id} hideMenu={hideMenu} />
|
||||||
|
))}
|
||||||
|
</SimpleGrid>
|
||||||
</Stack>
|
</Stack>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getColsByView(
|
||||||
|
displayPreferences: DisplayPreferences
|
||||||
|
): StyleProp<number> {
|
||||||
|
const { linkListDisplay } = displayPreferences;
|
||||||
|
|
||||||
|
if (linkListDisplay === 'grid') {
|
||||||
|
return {
|
||||||
|
sm: 1,
|
||||||
|
md: 2,
|
||||||
|
lg: 3,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,30 +3,36 @@ import { route } from '@izzyjs/route/client';
|
|||||||
import { Anchor, Box, Text } from '@mantine/core';
|
import { Anchor, Box, Text } from '@mantine/core';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import type { LinkListProps } from '~/components/dashboard/link/list/link_list';
|
import type { LinkListProps } from '~/components/dashboard/link/list/link_list';
|
||||||
|
import { useActiveCollection } from '~/hooks/collections/use_active_collection';
|
||||||
import { appendCollectionId } from '~/lib/navigation';
|
import { appendCollectionId } from '~/lib/navigation';
|
||||||
import { useActiveCollection } from '~/stores/collection_store';
|
|
||||||
import styles from './no_link.module.css';
|
import styles from './no_link.module.css';
|
||||||
|
|
||||||
interface NoLinkProps extends LinkListProps {}
|
interface NoLinkProps extends LinkListProps {}
|
||||||
|
|
||||||
export function NoLink({ hideMenu }: NoLinkProps) {
|
export function NoLink({ hideMenu }: NoLinkProps) {
|
||||||
const { t } = useTranslation('common');
|
const { t } = useTranslation('common');
|
||||||
const { activeCollection } = useActiveCollection();
|
const activeCollection = useActiveCollection();
|
||||||
|
const isFavorite = !activeCollection?.id;
|
||||||
|
|
||||||
|
const noLinkForCollection = t(
|
||||||
|
'home:no-link',
|
||||||
|
{ name: activeCollection?.name ?? '' } as any,
|
||||||
|
{
|
||||||
|
interpolation: { escapeValue: false },
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const noLinkForFavorite = t('home:no-link-favorite');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Box className={styles.noCollection} p="xl">
|
<Box className={styles.noCollection} p="xl">
|
||||||
<Text
|
<Text
|
||||||
className={styles.text}
|
className={styles.text}
|
||||||
dangerouslySetInnerHTML={{
|
dangerouslySetInnerHTML={{
|
||||||
__html: t(
|
__html: isFavorite ? noLinkForFavorite : noLinkForCollection,
|
||||||
'home:no-link',
|
|
||||||
{ name: activeCollection?.name ?? '' } as any,
|
|
||||||
{
|
|
||||||
interpolation: { escapeValue: false },
|
|
||||||
}
|
|
||||||
),
|
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
{!hideMenu && (
|
{!hideMenu && !isFavorite && (
|
||||||
<Anchor
|
<Anchor
|
||||||
component={Link}
|
component={Link}
|
||||||
href={appendCollectionId(
|
href={appendCollectionId(
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
.footer {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.inner {
|
|
||||||
display: flex;
|
|
||||||
justify-content: space-between;
|
|
||||||
align-items: center;
|
|
||||||
|
|
||||||
@media (max-width: $mantine-breakpoint-xs) {
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.links {
|
|
||||||
@media (max-width: $mantine-breakpoint-xs) {
|
|
||||||
margin-top: var(--mantine-spacing-md);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
import PATHS from '#core/constants/paths';
|
|
||||||
import { Link } from '@inertiajs/react';
|
|
||||||
import { route } from '@izzyjs/route/client';
|
|
||||||
import { Anchor, Group, Text } from '@mantine/core';
|
|
||||||
import { useTranslation } from 'react-i18next';
|
|
||||||
import ExternalLink from '~/components/common/external_link';
|
|
||||||
import { LocaleSwitcher } from '~/components/common/locale_switcher';
|
|
||||||
import { ThemeSwitcher } from '~/components/common/theme_switcher';
|
|
||||||
import packageJson from '../../../package.json';
|
|
||||||
import classes from './footer.module.css';
|
|
||||||
|
|
||||||
export function MantineFooter() {
|
|
||||||
const { t } = useTranslation('common');
|
|
||||||
|
|
||||||
const links = [
|
|
||||||
{ link: route('privacy').path, label: t('privacy'), external: false },
|
|
||||||
{ link: route('terms').path, label: t('terms'), external: false },
|
|
||||||
{ link: PATHS.EXTENSION, label: 'Extension', external: true },
|
|
||||||
];
|
|
||||||
|
|
||||||
const items = links.map((link) => (
|
|
||||||
<Anchor
|
|
||||||
c="dimmed"
|
|
||||||
// @ts-expect-error
|
|
||||||
component={link.external ? ExternalLink : Link}
|
|
||||||
key={link.label}
|
|
||||||
href={link.link}
|
|
||||||
size="sm"
|
|
||||||
>
|
|
||||||
{link.label}
|
|
||||||
</Anchor>
|
|
||||||
));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={classes.footer}>
|
|
||||||
<div className={classes.inner}>
|
|
||||||
<Group gap={4} c="dimmed">
|
|
||||||
<Text size="sm">{t('footer.made_by')}</Text>{' '}
|
|
||||||
<Anchor size="sm" component={ExternalLink} href={PATHS.AUTHOR}>
|
|
||||||
Sonny
|
|
||||||
</Anchor>
|
|
||||||
{' • '}
|
|
||||||
<Anchor size="sm" component={ExternalLink} href={PATHS.REPO_GITHUB}>
|
|
||||||
{packageJson.version}
|
|
||||||
</Anchor>
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Group gap="sm" mt={4} mb={4}>
|
|
||||||
<ThemeSwitcher />
|
|
||||||
<LocaleSwitcher />
|
|
||||||
</Group>
|
|
||||||
|
|
||||||
<Group gap="xs" justify="flex-end" wrap="nowrap">
|
|
||||||
{items}
|
|
||||||
</Group>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -2,6 +2,7 @@ import { Box, Group, SegmentedControl, Text, TextInput } from '@mantine/core';
|
|||||||
import { FormEvent } from 'react';
|
import { FormEvent } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import BackToDashboard from '~/components/common/navigation/back_to_dashboard';
|
import BackToDashboard from '~/components/common/navigation/back_to_dashboard';
|
||||||
|
import useSearchParam from '~/hooks/use_search_param';
|
||||||
import { FormLayout, FormLayoutProps } from '~/layouts/form_layout';
|
import { FormLayout, FormLayoutProps } from '~/layouts/form_layout';
|
||||||
import { Visibility } from '~/types/app';
|
import { Visibility } from '~/types/app';
|
||||||
|
|
||||||
@@ -20,7 +21,7 @@ interface FormCollectionProps extends FormLayoutProps {
|
|||||||
handleSubmit: () => void;
|
handleSubmit: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function MantineFormCollection({
|
export function MantineFormCollection({
|
||||||
data,
|
data,
|
||||||
errors,
|
errors,
|
||||||
disableInputs = false,
|
disableInputs = false,
|
||||||
@@ -29,6 +30,7 @@ export default function MantineFormCollection({
|
|||||||
...props
|
...props
|
||||||
}: FormCollectionProps) {
|
}: FormCollectionProps) {
|
||||||
const { t } = useTranslation('common');
|
const { t } = useTranslation('common');
|
||||||
|
const collectionId = Number(useSearchParam('collectionId'));
|
||||||
|
|
||||||
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
|
const onSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -36,7 +38,7 @@ export default function MantineFormCollection({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<FormLayout handleSubmit={onSubmit} {...props}>
|
<FormLayout handleSubmit={onSubmit} collectionId={collectionId} {...props}>
|
||||||
<BackToDashboard disabled={props.disableHomeLink}>
|
<BackToDashboard disabled={props.disableHomeLink}>
|
||||||
<TextInput
|
<TextInput
|
||||||
label={t('form.name')}
|
label={t('form.name')}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user