refactor: use tabs instead of spaces

This commit is contained in:
Sonny
2024-10-07 01:33:59 +02:00
parent f425decf2c
commit eea9732100
197 changed files with 5206 additions and 5209 deletions

View File

@@ -3,7 +3,7 @@
root = true
[*]
indent_style = space
indent_style = tab
indent_size = 2
end_of_line = lf
charset = utf-8
@@ -17,8 +17,5 @@ insert_final_newline = unset
indent_style = unset
insert_final_newline = unset
[MakeFile]
indent_style = space
[*.md]
trim_trailing_whitespace = false

View File

@@ -1,7 +1,7 @@
import { defineConfig } from '@adonisjs/core/app';
export default defineConfig({
/*
/*
|--------------------------------------------------------------------------
| Commands
|--------------------------------------------------------------------------
@@ -10,13 +10,13 @@ export default defineConfig({
| will be scanned automatically from the "./commands" directory.
|
*/
commands: [
() => import('@adonisjs/core/commands'),
() => import('@adonisjs/lucid/commands'),
() => import('@izzyjs/route/commands'),
],
commands: [
() => import('@adonisjs/core/commands'),
() => import('@adonisjs/lucid/commands'),
() => import('@izzyjs/route/commands'),
],
/*
/*
|--------------------------------------------------------------------------
| Service providers
|--------------------------------------------------------------------------
@@ -25,29 +25,29 @@ export default defineConfig({
| application
|
*/
providers: [
() => import('@adonisjs/core/providers/app_provider'),
() => import('@adonisjs/core/providers/hash_provider'),
{
file: () => import('@adonisjs/core/providers/repl_provider'),
environment: ['repl', 'test'],
},
() => import('@adonisjs/core/providers/vinejs_provider'),
() => import('@adonisjs/core/providers/edge_provider'),
() => import('@adonisjs/session/session_provider'),
() => import('@adonisjs/vite/vite_provider'),
() => import('@adonisjs/shield/shield_provider'),
() => import('@adonisjs/static/static_provider'),
() => import('@adonisjs/cors/cors_provider'),
() => import('@adonisjs/lucid/database_provider'),
() => import('@adonisjs/auth/auth_provider'),
() => import('@adonisjs/inertia/inertia_provider'),
() => import('@adonisjs/ally/ally_provider'),
() => import('@izzyjs/route/izzy_provider'),
() => import('#providers/route_provider'),
],
providers: [
() => import('@adonisjs/core/providers/app_provider'),
() => import('@adonisjs/core/providers/hash_provider'),
{
file: () => import('@adonisjs/core/providers/repl_provider'),
environment: ['repl', 'test'],
},
() => import('@adonisjs/core/providers/vinejs_provider'),
() => import('@adonisjs/core/providers/edge_provider'),
() => import('@adonisjs/session/session_provider'),
() => import('@adonisjs/vite/vite_provider'),
() => import('@adonisjs/shield/shield_provider'),
() => import('@adonisjs/static/static_provider'),
() => import('@adonisjs/cors/cors_provider'),
() => import('@adonisjs/lucid/database_provider'),
() => import('@adonisjs/auth/auth_provider'),
() => import('@adonisjs/inertia/inertia_provider'),
() => import('@adonisjs/ally/ally_provider'),
() => import('@izzyjs/route/izzy_provider'),
() => import('#providers/route_provider'),
],
/*
/*
|--------------------------------------------------------------------------
| Preloads
|--------------------------------------------------------------------------
@@ -55,9 +55,9 @@ export default defineConfig({
| List of modules to import before starting the application.
|
*/
preloads: [() => import('#start/routes'), () => import('#start/kernel')],
preloads: [() => import('#start/routes'), () => import('#start/kernel')],
/*
/*
|--------------------------------------------------------------------------
| Tests
|--------------------------------------------------------------------------
@@ -66,23 +66,23 @@ export default defineConfig({
| and add additional suites.
|
*/
tests: {
suites: [
{
files: ['tests/unit/**/*.spec(.ts|.js)'],
name: 'unit',
timeout: 2000,
},
{
files: ['tests/functional/**/*.spec(.ts|.js)'],
name: 'functional',
timeout: 30000,
},
],
forceExit: false,
},
tests: {
suites: [
{
files: ['tests/unit/**/*.spec(.ts|.js)'],
name: 'unit',
timeout: 2000,
},
{
files: ['tests/functional/**/*.spec(.ts|.js)'],
name: 'functional',
timeout: 30000,
},
],
forceExit: false,
},
/*
/*
|--------------------------------------------------------------------------
| Metafiles
|--------------------------------------------------------------------------
@@ -91,20 +91,20 @@ export default defineConfig({
| the production build.
|
*/
metaFiles: [
{
pattern: 'resources/views/**/*.edge',
reloadServer: false,
},
{
pattern: 'public/**',
reloadServer: false,
},
],
metaFiles: [
{
pattern: 'resources/views/**/*.edge',
reloadServer: false,
},
{
pattern: 'public/**',
reloadServer: false,
},
],
assetsBundler: false,
unstable_assembler: {
onBuildStarting: [() => import('@adonisjs/vite/build_hook')],
onDevServerStarted: [() => import('@izzyjs/route/dev_hook')],
},
assetsBundler: false,
unstable_assembler: {
onBuildStarting: [() => import('@adonisjs/vite/build_hook')],
onDevServerStarted: [() => import('@izzyjs/route/dev_hook')],
},
});

View File

@@ -8,12 +8,12 @@ const ARROW_UP = 'ArrowUp';
const ARROW_DOWN = 'ArrowDown';
const KEYS = {
ARROW_DOWN,
ARROW_UP,
ESCAPE_KEY,
OPEN_CREATE_COLLECTION_KEY,
OPEN_CREATE_LINK_KEY,
OPEN_SEARCH_KEY,
ARROW_DOWN,
ARROW_UP,
ESCAPE_KEY,
OPEN_CREATE_COLLECTION_KEY,
OPEN_CREATE_LINK_KEY,
OPEN_SEARCH_KEY,
};
export default KEYS;

View File

@@ -1,8 +1,8 @@
const PATHS = {
AUTHOR: 'https://www.sonny.dev/',
REPO_GITHUB: 'https://github.com/Sonny93/my-links',
EXTENSION:
'https://chromewebstore.google.com/detail/mylinks/agkmlplihacolkakgeccnbhphnepphma',
AUTHOR: 'https://www.sonny.dev/',
REPO_GITHUB: 'https://github.com/Sonny93/my-links',
EXTENSION:
'https://chromewebstore.google.com/detail/mylinks/agkmlplihacolkakgeccnbhphnepphma',
} as const;
export default PATHS;

View File

@@ -6,41 +6,41 @@ import { inject } from '@adonisjs/core';
import type { HttpContext } from '@adonisjs/core/http';
class UserWithRelationCountDto {
constructor(private user: User) {}
constructor(private user: User) {}
toJson = () => ({
id: this.user.id,
email: this.user.email,
fullname: this.user.name,
avatarUrl: this.user.avatarUrl,
isAdmin: this.user.isAdmin,
createdAt: this.user.createdAt,
updatedAt: this.user.updatedAt,
count: {
link: Number(this.user.$extras.totalLinks),
collection: Number(this.user.$extras.totalCollections),
},
});
toJson = () => ({
id: this.user.id,
email: this.user.email,
fullname: this.user.name,
avatarUrl: this.user.avatarUrl,
isAdmin: this.user.isAdmin,
createdAt: this.user.createdAt,
updatedAt: this.user.updatedAt,
count: {
link: Number(this.user.$extras.totalLinks),
collection: Number(this.user.$extras.totalCollections),
},
});
}
@inject()
export default class AdminController {
constructor(
protected usersController: UsersController,
protected linksController: LinksController,
protected collectionsController: CollectionsController
) {}
constructor(
protected usersController: UsersController,
protected linksController: LinksController,
protected collectionsController: CollectionsController
) {}
async index({ inertia }: HttpContext) {
const users = await this.usersController.getAllUsersWithTotalRelations();
const linksCount = await this.linksController.getTotalLinksCount();
const collectionsCount =
await this.collectionsController.getTotalCollectionsCount();
async index({ inertia }: HttpContext) {
const users = await this.usersController.getAllUsersWithTotalRelations();
const linksCount = await this.linksController.getTotalLinksCount();
const collectionsCount =
await this.collectionsController.getTotalCollectionsCount();
return inertia.render('admin/dashboard', {
users: users.map((user) => new UserWithRelationCountDto(user).toJson()),
totalLinks: linksCount,
totalCollections: collectionsCount,
});
}
return inertia.render('admin/dashboard', {
users: users.map((user) => new UserWithRelationCountDto(user).toJson()),
totalLinks: linksCount,
totalCollections: collectionsCount,
});
}
}

View File

@@ -3,11 +3,11 @@ import { updateUserThemeValidator } from '#validators/user';
import type { HttpContext } from '@adonisjs/core/http';
export default class AppsController {
async updateUserTheme({ request, session, response }: HttpContext) {
const { preferDarkTheme } = await request.validateUsing(
updateUserThemeValidator
);
session.put(PREFER_DARK_THEME, preferDarkTheme);
return response.ok({ message: 'ok' });
}
async updateUserTheme({ request, session, response }: HttpContext) {
const { preferDarkTheme } = await request.validateUsing(
updateUserThemeValidator
);
session.put(PREFER_DARK_THEME, preferDarkTheme);
return response.ok({ message: 'ok' });
}
}

View File

@@ -1,143 +1,143 @@
import Collection from '#models/collection';
import User from '#models/user';
import {
createCollectionValidator,
deleteCollectionValidator,
updateCollectionValidator,
createCollectionValidator,
deleteCollectionValidator,
updateCollectionValidator,
} from '#validators/collection';
import type { HttpContext } from '@adonisjs/core/http';
import db from '@adonisjs/lucid/services/db';
export default class CollectionsController {
// Dashboard
async index({ auth, inertia, request, response }: HttpContext) {
const collections = await this.getCollectionsByAuthorId(auth.user!.id);
if (collections.length === 0) {
return response.redirectToNamedRoute('collection.create-form');
}
// Dashboard
async index({ auth, inertia, request, response }: HttpContext) {
const collections = await this.getCollectionsByAuthorId(auth.user!.id);
if (collections.length === 0) {
return response.redirectToNamedRoute('collection.create-form');
}
const activeCollectionId = Number(request.qs()?.collectionId ?? '');
const activeCollection = collections.find(
(c) => c.id === activeCollectionId
);
const activeCollectionId = Number(request.qs()?.collectionId ?? '');
const activeCollection = collections.find(
(c) => c.id === activeCollectionId
);
if (!activeCollection && !!activeCollectionId) {
return response.redirectToNamedRoute('dashboard');
}
if (!activeCollection && !!activeCollectionId) {
return response.redirectToNamedRoute('dashboard');
}
// TODO: Create DTOs
return inertia.render('dashboard', {
collections: collections.map((collection) => collection.serialize()),
activeCollection:
activeCollection?.serialize() || collections[0].serialize(),
});
}
// TODO: Create DTOs
return inertia.render('dashboard', {
collections: collections.map((collection) => collection.serialize()),
activeCollection:
activeCollection?.serialize() || collections[0].serialize(),
});
}
// Create collection form
async showCreatePage({ inertia, auth }: HttpContext) {
const collections = await this.getCollectionsByAuthorId(auth.user!.id);
return inertia.render('collections/create', {
disableHomeLink: collections.length === 0,
});
}
// Create collection form
async showCreatePage({ inertia, auth }: HttpContext) {
const collections = await this.getCollectionsByAuthorId(auth.user!.id);
return inertia.render('collections/create', {
disableHomeLink: collections.length === 0,
});
}
// Method called when creating a collection
async store({ request, response, auth }: HttpContext) {
const payload = await request.validateUsing(createCollectionValidator);
const collection = await Collection.create({
...payload,
authorId: auth.user?.id!,
});
return this.redirectToCollectionId(response, collection.id);
}
// Method called when creating a collection
async store({ request, response, auth }: HttpContext) {
const payload = await request.validateUsing(createCollectionValidator);
const collection = await Collection.create({
...payload,
authorId: auth.user?.id!,
});
return this.redirectToCollectionId(response, collection.id);
}
async showEditPage({ auth, request, inertia, response }: HttpContext) {
const collectionId = request.qs()?.collectionId;
if (!collectionId) {
return response.redirectToNamedRoute('dashboard');
}
async showEditPage({ auth, request, inertia, response }: HttpContext) {
const collectionId = request.qs()?.collectionId;
if (!collectionId) {
return response.redirectToNamedRoute('dashboard');
}
const collection = await this.getCollectionById(
collectionId,
auth.user!.id
);
return inertia.render('collections/edit', {
collection,
});
}
const collection = await this.getCollectionById(
collectionId,
auth.user!.id
);
return inertia.render('collections/edit', {
collection,
});
}
async update({ request, auth, response }: HttpContext) {
const { params, ...payload } = await request.validateUsing(
updateCollectionValidator
);
async update({ request, auth, response }: HttpContext) {
const { params, ...payload } = await request.validateUsing(
updateCollectionValidator
);
// Cant use validator (vinejs) custom rule 'cause its too generic,
// because we have to find a collection by identifier and
// check whether the current user is the author.
// https://vinejs.dev/docs/extend/custom_rules
await this.getCollectionById(params.id, auth.user!.id);
// Cant use validator (vinejs) custom rule 'cause its too generic,
// because we have to find a collection by identifier and
// check whether the current user is the author.
// https://vinejs.dev/docs/extend/custom_rules
await this.getCollectionById(params.id, auth.user!.id);
await Collection.updateOrCreate(
{
id: params.id,
},
payload
);
return this.redirectToCollectionId(response, params.id);
}
await Collection.updateOrCreate(
{
id: params.id,
},
payload
);
return this.redirectToCollectionId(response, params.id);
}
async showDeletePage({ auth, request, inertia, response }: HttpContext) {
const collectionId = request.qs()?.collectionId;
if (!collectionId) {
return response.redirectToNamedRoute('dashboard');
}
async showDeletePage({ auth, request, inertia, response }: HttpContext) {
const collectionId = request.qs()?.collectionId;
if (!collectionId) {
return response.redirectToNamedRoute('dashboard');
}
const collection = await this.getCollectionById(
collectionId,
auth.user!.id
);
return inertia.render('collections/delete', {
collection,
});
}
const collection = await this.getCollectionById(
collectionId,
auth.user!.id
);
return inertia.render('collections/delete', {
collection,
});
}
async delete({ request, auth, response }: HttpContext) {
const { params } = await request.validateUsing(deleteCollectionValidator);
const collection = await this.getCollectionById(params.id, auth.user!.id);
await collection.delete();
return response.redirectToNamedRoute('dashboard');
}
async delete({ request, auth, response }: HttpContext) {
const { params } = await request.validateUsing(deleteCollectionValidator);
const collection = await this.getCollectionById(params.id, auth.user!.id);
await collection.delete();
return response.redirectToNamedRoute('dashboard');
}
async getTotalCollectionsCount() {
const totalCount = await db.from('collections').count('* as total');
return Number(totalCount[0].total);
}
async getTotalCollectionsCount() {
const totalCount = await db.from('collections').count('* as total');
return Number(totalCount[0].total);
}
/**
* Get collection by id.
*
* /!\ Only return private collection (create by the current user)
*/
async getCollectionById(id: Collection['id'], userId: User['id']) {
return await Collection.query()
.where('id', id)
.andWhere('author_id', userId)
.firstOrFail();
}
/**
* Get collection by id.
*
* /!\ Only return private collection (create by the current user)
*/
async getCollectionById(id: Collection['id'], userId: User['id']) {
return await Collection.query()
.where('id', id)
.andWhere('author_id', userId)
.firstOrFail();
}
async getCollectionsByAuthorId(authorId: User['id']) {
return await Collection.query()
.where('author_id', authorId)
.orderBy('created_at')
.preload('links');
}
async getCollectionsByAuthorId(authorId: User['id']) {
return await Collection.query()
.where('author_id', authorId)
.orderBy('created_at')
.preload('links');
}
redirectToCollectionId(
response: HttpContext['response'],
collectionId: Collection['id']
) {
return response.redirectToNamedRoute('dashboard', {
qs: { collectionId },
});
}
redirectToCollectionId(
response: HttpContext['response'],
collectionId: Collection['id']
) {
return response.redirectToNamedRoute('dashboard', {
qs: { collectionId },
});
}
}

View File

@@ -5,156 +5,156 @@ import logger from '@adonisjs/core/services/logger';
import { parse } from 'node-html-parser';
interface Favicon {
buffer: Buffer;
url: string;
type: string;
size: number;
buffer: Buffer;
url: string;
type: string;
size: number;
}
export default class FaviconsController {
private userAgent =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0';
private relList = [
'icon',
'shortcut icon',
'apple-touch-icon',
'apple-touch-icon-precomposed',
'apple-touch-startup-image',
'mask-icon',
'fluid-icon',
];
private userAgent =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0';
private relList = [
'icon',
'shortcut icon',
'apple-touch-icon',
'apple-touch-icon-precomposed',
'apple-touch-startup-image',
'mask-icon',
'fluid-icon',
];
async index(ctx: HttpContext) {
const url = ctx.request.qs()?.url;
if (!url) {
throw new Error('Missing URL');
}
async index(ctx: HttpContext) {
const url = ctx.request.qs()?.url;
if (!url) {
throw new Error('Missing URL');
}
const cacheNs = cache.namespace('favicon');
const favicon = await cacheNs.getOrSet({
key: url,
ttl: '1h',
factory: () => this.tryGetFavicon(url),
});
return this.sendImage(ctx, favicon);
}
const cacheNs = cache.namespace('favicon');
const favicon = await cacheNs.getOrSet({
key: url,
ttl: '1h',
factory: () => this.tryGetFavicon(url),
});
return this.sendImage(ctx, favicon);
}
private async tryGetFavicon(url: string): Promise<Favicon> {
const faviconUrl = this.buildFaviconUrl(url, '/favicon.ico');
try {
return await this.fetchFavicon(faviconUrl);
} catch {
logger.debug(`Unable to retrieve favicon from ${faviconUrl}`);
}
private async tryGetFavicon(url: string): Promise<Favicon> {
const faviconUrl = this.buildFaviconUrl(url, '/favicon.ico');
try {
return await this.fetchFavicon(faviconUrl);
} catch {
logger.debug(`Unable to retrieve favicon from ${faviconUrl}`);
}
const documentText = await this.fetchDocumentText(url);
const faviconPath = this.extractFaviconPath(documentText);
const documentText = await this.fetchDocumentText(url);
const faviconPath = this.extractFaviconPath(documentText);
if (!faviconPath) {
throw new FaviconNotFoundException(`No favicon path found in ${url}`);
}
if (!faviconPath) {
throw new FaviconNotFoundException(`No favicon path found in ${url}`);
}
if (faviconPath.startsWith('http')) {
try {
return await this.fetchFavicon(faviconPath);
} catch {
logger.debug(`Unable to retrieve favicon from ${faviconPath}`);
}
}
if (faviconPath.startsWith('http')) {
try {
return await this.fetchFavicon(faviconPath);
} catch {
logger.debug(`Unable to retrieve favicon from ${faviconPath}`);
}
}
return this.fetchFaviconFromPath(url, faviconPath);
}
return this.fetchFaviconFromPath(url, faviconPath);
}
private async fetchFavicon(url: string): Promise<Favicon> {
const response = await this.fetchWithUserAgent(url);
if (!response.ok) {
throw new FaviconNotFoundException(`Request to favicon ${url} failed`);
}
private async fetchFavicon(url: string): Promise<Favicon> {
const response = await this.fetchWithUserAgent(url);
if (!response.ok) {
throw new FaviconNotFoundException(`Request to favicon ${url} failed`);
}
const blob = await response.blob();
if (!this.isImage(blob.type) || blob.size === 0) {
throw new FaviconNotFoundException(`Invalid image at ${url}`);
}
const blob = await response.blob();
if (!this.isImage(blob.type) || blob.size === 0) {
throw new FaviconNotFoundException(`Invalid image at ${url}`);
}
return {
buffer: Buffer.from(await blob.arrayBuffer()),
url: response.url,
type: blob.type,
size: blob.size,
};
}
return {
buffer: Buffer.from(await blob.arrayBuffer()),
url: response.url,
type: blob.type,
size: blob.size,
};
}
private async fetchDocumentText(url: string): Promise<string> {
const response = await this.fetchWithUserAgent(url);
if (!response.ok) {
throw new FaviconNotFoundException(`Request to ${url} failed`);
}
private async fetchDocumentText(url: string): Promise<string> {
const response = await this.fetchWithUserAgent(url);
if (!response.ok) {
throw new FaviconNotFoundException(`Request to ${url} failed`);
}
return await response.text();
}
return await response.text();
}
private extractFaviconPath(html: string): string | undefined {
const document = parse(html);
const link = document
.getElementsByTagName('link')
.find((element) => this.relList.includes(element.getAttribute('rel')!));
return link?.getAttribute('href');
}
private extractFaviconPath(html: string): string | undefined {
const document = parse(html);
const link = document
.getElementsByTagName('link')
.find((element) => this.relList.includes(element.getAttribute('rel')!));
return link?.getAttribute('href');
}
private async fetchFaviconFromPath(
baseUrl: string,
path: string
): Promise<Favicon> {
if (this.isBase64Image(path)) {
const buffer = this.convertBase64ToBuffer(path);
return {
buffer,
type: 'image/x-icon',
size: buffer.length,
url: path,
};
}
private async fetchFaviconFromPath(
baseUrl: string,
path: string
): Promise<Favicon> {
if (this.isBase64Image(path)) {
const buffer = this.convertBase64ToBuffer(path);
return {
buffer,
type: 'image/x-icon',
size: buffer.length,
url: path,
};
}
const faviconUrl = this.buildFaviconUrl(baseUrl, path);
return this.fetchFavicon(faviconUrl);
}
const faviconUrl = this.buildFaviconUrl(baseUrl, path);
return this.fetchFavicon(faviconUrl);
}
private buildFaviconUrl(base: string, path: string): string {
const { origin } = new URL(base);
if (path.startsWith('/')) {
return origin + path;
}
private buildFaviconUrl(base: string, path: string): string {
const { origin } = new URL(base);
if (path.startsWith('/')) {
return origin + path;
}
const basePath = this.urlWithoutSearchParams(base);
const baseUrl = basePath.endsWith('/') ? basePath.slice(0, -1) : basePath;
return `${baseUrl}/${path}`;
}
const basePath = this.urlWithoutSearchParams(base);
const baseUrl = basePath.endsWith('/') ? basePath.slice(0, -1) : basePath;
return `${baseUrl}/${path}`;
}
private urlWithoutSearchParams(url: string): string {
const { protocol, host, pathname } = new URL(url);
return `${protocol}//${host}${pathname}`;
}
private urlWithoutSearchParams(url: string): string {
const { protocol, host, pathname } = new URL(url);
return `${protocol}//${host}${pathname}`;
}
private isImage(type: string): boolean {
return type.startsWith('image/');
}
private isImage(type: string): boolean {
return type.startsWith('image/');
}
private isBase64Image(data: string): boolean {
return data.startsWith('data:image/');
}
private isBase64Image(data: string): boolean {
return data.startsWith('data:image/');
}
private convertBase64ToBuffer(base64: string): Buffer {
return Buffer.from(base64.split(',')[1], 'base64');
}
private convertBase64ToBuffer(base64: string): Buffer {
return Buffer.from(base64.split(',')[1], 'base64');
}
private async fetchWithUserAgent(url: string): Promise<Response> {
const headers = new Headers({ 'User-Agent': this.userAgent });
return fetch(url, { headers });
}
private async fetchWithUserAgent(url: string): Promise<Response> {
const headers = new Headers({ 'User-Agent': this.userAgent });
return fetch(url, { headers });
}
private sendImage(ctx: HttpContext, { buffer, type, size }: Favicon) {
ctx.response.header('Content-Type', type);
ctx.response.header('Content-Length', size.toString());
ctx.response.send(buffer, true);
}
private sendImage(ctx: HttpContext, { buffer, type, size }: Favicon) {
ctx.response.header('Content-Type', type);
ctx.response.header('Content-Length', size.toString());
ctx.response.send(buffer, true);
}
}

View File

@@ -1,10 +1,10 @@
import CollectionsController from '#controllers/collections_controller';
import Link from '#models/link';
import {
createLinkValidator,
deleteLinkValidator,
updateLinkFavoriteStatusValidator,
updateLinkValidator,
createLinkValidator,
deleteLinkValidator,
updateLinkFavoriteStatusValidator,
updateLinkValidator,
} from '#validators/link';
import { inject } from '@adonisjs/core';
import type { HttpContext } from '@adonisjs/core/http';
@@ -12,120 +12,120 @@ import db from '@adonisjs/lucid/services/db';
@inject()
export default class LinksController {
constructor(protected collectionsController: CollectionsController) {}
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 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);
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
);
}
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');
}
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);
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 });
}
return inertia.render('links/edit', { collections, link });
}
async update({ request, auth, response }: HttpContext) {
const { params, ...payload } =
await request.validateUsing(updateLinkValidator);
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);
// Throw if invalid link id provided
await this.getLinkById(params.id, auth.user!.id);
await Link.updateOrCreate(
{
id: params.id,
},
payload
);
await Link.updateOrCreate(
{
id: params.id,
},
payload
);
return response.redirectToNamedRoute('dashboard', {
qs: { collectionId: payload.collectionId },
});
}
return response.redirectToNamedRoute('dashboard', {
qs: { collectionId: payload.collectionId },
});
}
async toggleFavorite({ request, auth, response }: HttpContext) {
const { params, favorite } = await request.validateUsing(
updateLinkFavoriteStatusValidator
);
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);
// Throw if invalid link id provided
await this.getLinkById(params.id, auth.user!.id);
await Link.updateOrCreate(
{
id: params.id,
},
{ favorite }
);
await Link.updateOrCreate(
{
id: params.id,
},
{ favorite }
);
return response.json({ status: 'ok' });
}
return response.json({ status: 'ok' });
}
async showDeletePage({ auth, inertia, request, response }: HttpContext) {
const linkId = request.qs()?.linkId;
if (!linkId) {
return response.redirectToNamedRoute('dashboard');
}
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 });
}
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);
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();
const link = await this.getLinkById(params.id, auth.user!.id);
await link.delete();
return response.redirectToNamedRoute('dashboard', {
qs: { collectionId: link.id },
});
}
return response.redirectToNamedRoute('dashboard', {
qs: { collectionId: link.id },
});
}
async getTotalLinksCount() {
const totalCount = await db.from('links').count('* as total');
return Number(totalCount[0].total);
}
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();
}
/**
* 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();
}
}

View File

@@ -2,17 +2,17 @@ import type { HttpContext } from '@adonisjs/core/http';
import db from '@adonisjs/lucid/services/db';
export default class SearchesController {
async search({ request, auth }: HttpContext) {
const term = request.qs()?.term;
if (!term) {
console.warn('qs term null');
return { error: 'missing "term" query param' };
}
async search({ request, auth }: HttpContext) {
const term = request.qs()?.term;
if (!term) {
console.warn('qs term null');
return { error: 'missing "term" query param' };
}
const { rows } = await db.rawQuery('SELECT * FROM search_text(?, ?)', [
term,
auth.user!.id,
]);
return { results: rows };
}
const { rows } = await db.rawQuery('SELECT * FROM search_text(?, ?)', [
term,
auth.user!.id,
]);
return { results: rows };
}
}

View File

@@ -4,21 +4,21 @@ import { getSharedCollectionValidator } from '#validators/shared_collection';
import type { HttpContext } from '@adonisjs/core/http';
export default class SharedCollectionsController {
async index({ request, inertia }: HttpContext) {
const { params } = await request.validateUsing(
getSharedCollectionValidator
);
async index({ request, inertia }: HttpContext) {
const { params } = await request.validateUsing(
getSharedCollectionValidator
);
const collection = await this.getSharedCollectionById(params.id);
return inertia.render('shared', { collection });
}
const collection = await this.getSharedCollectionById(params.id);
return inertia.render('shared', { collection });
}
private async getSharedCollectionById(id: Collection['id']) {
return await Collection.query()
.where('id', id)
.andWhere('visibility', Visibility.PUBLIC)
.preload('links')
.preload('author')
.firstOrFail();
}
private async getSharedCollectionById(id: Collection['id']) {
return await Collection.query()
.where('id', id)
.andWhere('visibility', Visibility.PUBLIC)
.preload('links')
.preload('author')
.firstOrFail();
}
}

View File

@@ -5,74 +5,74 @@ import db from '@adonisjs/lucid/services/db';
import { RouteName } from '@izzyjs/route/types';
export default class UsersController {
private redirectTo: RouteName = 'auth.login';
private redirectTo: RouteName = 'auth.login';
login({ inertia }: HttpContext) {
return inertia.render('login');
}
login({ inertia }: HttpContext) {
return inertia.render('login');
}
google = ({ ally }: HttpContext) => ally.use('google').redirect();
google = ({ ally }: HttpContext) => ally.use('google').redirect();
async callbackAuth({ ally, auth, response, session }: HttpContext) {
const google = ally.use('google');
if (google.accessDenied()) {
// TODO: translate error messages + show them in UI
session.flash('flash', 'Access was denied');
return response.redirectToNamedRoute(this.redirectTo);
}
async callbackAuth({ ally, auth, response, session }: HttpContext) {
const google = ally.use('google');
if (google.accessDenied()) {
// TODO: translate error messages + show them in UI
session.flash('flash', 'Access was denied');
return response.redirectToNamedRoute(this.redirectTo);
}
if (google.stateMisMatch()) {
session.flash('flash', 'Request expired. Retry again');
return response.redirectToNamedRoute(this.redirectTo);
}
if (google.stateMisMatch()) {
session.flash('flash', 'Request expired. Retry again');
return response.redirectToNamedRoute(this.redirectTo);
}
if (google.hasError()) {
session.flash('flash', google.getError() || 'Something went wrong');
return response.redirectToNamedRoute(this.redirectTo);
}
if (google.hasError()) {
session.flash('flash', google.getError() || 'Something went wrong');
return response.redirectToNamedRoute(this.redirectTo);
}
const userCount = await db.from('users').count('* as total');
const {
email,
id: providerId,
name,
nickName,
avatarUrl,
token,
} = await google.user();
const user = await User.updateOrCreate(
{
email,
},
{
email,
providerId,
name,
nickName,
avatarUrl,
token,
providerType: 'google',
isAdmin: userCount[0].total === '0' ? true : undefined,
}
);
const userCount = await db.from('users').count('* as total');
const {
email,
id: providerId,
name,
nickName,
avatarUrl,
token,
} = await google.user();
const user = await User.updateOrCreate(
{
email,
},
{
email,
providerId,
name,
nickName,
avatarUrl,
token,
providerType: 'google',
isAdmin: userCount[0].total === '0' ? true : undefined,
}
);
await auth.use('web').login(user);
session.flash('flash', 'Successfully authenticated');
logger.info(`[${user.email}] auth success`);
await auth.use('web').login(user);
session.flash('flash', 'Successfully authenticated');
logger.info(`[${user.email}] auth success`);
response.redirectToNamedRoute('dashboard');
}
response.redirectToNamedRoute('dashboard');
}
async logout({ auth, response, session }: HttpContext) {
await auth.use('web').logout();
session.flash('flash', 'Successfully disconnected');
logger.info(`[${auth.user?.email}] disconnected successfully`);
response.redirectToNamedRoute(this.redirectTo);
}
async logout({ auth, response, session }: HttpContext) {
await auth.use('web').logout();
session.flash('flash', 'Successfully disconnected');
logger.info(`[${auth.user?.email}] disconnected successfully`);
response.redirectToNamedRoute(this.redirectTo);
}
async getAllUsersWithTotalRelations() {
return User.query()
.withCount('collections', (q) => q.as('totalCollections'))
.withCount('links', (q) => q.as('totalLinks'));
}
async getAllUsersWithTotalRelations() {
return User.query()
.withCount('collections', (q) => q.as('totalCollections'))
.withCount('links', (q) => q.as('totalLinks'));
}
}

View File

@@ -1,4 +1,4 @@
export enum Visibility {
PUBLIC = 'PUBLIC',
PRIVATE = 'PRIVATE',
PUBLIC = 'PUBLIC',
PRIVATE = 'PRIVATE',
}

View File

@@ -5,16 +5,16 @@ import { createReadStream } from 'node:fs';
import { resolve } from 'node:path';
export default class FaviconNotFoundException extends Exception {
static status = 404;
static code = 'E_FAVICON_NOT_FOUND';
static status = 404;
static code = 'E_FAVICON_NOT_FOUND';
async handle(error: this, ctx: HttpContext) {
const readStream = createReadStream(
resolve(process.cwd(), './public/empty-image.png')
);
async handle(error: this, ctx: HttpContext) {
const readStream = createReadStream(
resolve(process.cwd(), './public/empty-image.png')
);
ctx.response.header('Content-Type', 'image/png');
ctx.response.stream(readStream);
logger.debug(error.message);
}
ctx.response.header('Content-Type', 'image/png');
ctx.response.stream(readStream);
logger.debug(error.message);
}
}

View File

@@ -1,54 +1,54 @@
import { ExceptionHandler, HttpContext } from '@adonisjs/core/http';
import app from '@adonisjs/core/services/app';
import type {
StatusPageRange,
StatusPageRenderer,
StatusPageRange,
StatusPageRenderer,
} from '@adonisjs/core/types/http';
import { errors } from '@adonisjs/lucid';
export default class HttpExceptionHandler extends ExceptionHandler {
/**
* In debug mode, the exception handler will display verbose errors
* with pretty printed stack traces.
*/
protected debug = !app.inProduction;
/**
* In debug mode, the exception handler will display verbose errors
* with pretty printed stack traces.
*/
protected debug = !app.inProduction;
/**
* Status pages are used to display a custom HTML pages for certain error
* codes. You might want to enable them in production only, but feel
* free to enable them in development as well.
*/
protected renderStatusPages = app.inProduction;
/**
* Status pages are used to display a custom HTML pages for certain error
* codes. You might want to enable them in production only, but feel
* free to enable them in development as well.
*/
protected renderStatusPages = app.inProduction;
/**
* Status pages is a collection of error code range and a callback
* to return the HTML contents to send as a response.
*/
protected statusPages: Record<StatusPageRange, StatusPageRenderer> = {
'404': (error, { inertia }) =>
inertia.render('errors/not_found', { error }),
'500..599': (error, { inertia }) =>
inertia.render('errors/server_error', { error }),
};
/**
* Status pages is a collection of error code range and a callback
* to return the HTML contents to send as a response.
*/
protected statusPages: Record<StatusPageRange, StatusPageRenderer> = {
'404': (error, { inertia }) =>
inertia.render('errors/not_found', { error }),
'500..599': (error, { inertia }) =>
inertia.render('errors/server_error', { error }),
};
/**
* The method is used for handling errors and returning
* response to the client
*/
async handle(error: unknown, ctx: HttpContext) {
if (error instanceof errors.E_ROW_NOT_FOUND) {
return ctx.response.redirectToNamedRoute('dashboard');
}
return super.handle(error, ctx);
}
/**
* The method is used for handling errors and returning
* response to the client
*/
async handle(error: unknown, ctx: HttpContext) {
if (error instanceof errors.E_ROW_NOT_FOUND) {
return ctx.response.redirectToNamedRoute('dashboard');
}
return super.handle(error, ctx);
}
/**
* The method is used to report error to the logging service or
* the a third party error monitoring service.
*
* @note You should not attempt to send a response from this method.
*/
async report(error: unknown, ctx: HttpContext) {
return super.report(error, ctx);
}
/**
* The method is used to report error to the logging service or
* the a third party error monitoring service.
*
* @note You should not attempt to send a response from this method.
*/
async report(error: unknown, ctx: HttpContext) {
return super.report(error, ctx);
}
}

View File

@@ -2,9 +2,9 @@ import { BentoCache, bentostore } from 'bentocache';
import { memoryDriver } from 'bentocache/drivers/memory';
export const cache = new BentoCache({
default: 'cache',
default: 'cache',
stores: {
cache: bentostore().useL1Layer(memoryDriver({ maxSize: 10_000 })),
},
stores: {
cache: bentostore().useL1Layer(memoryDriver({ maxSize: 10_000 })),
},
});

View File

@@ -2,10 +2,10 @@ import type { HttpContext } from '@adonisjs/core/http';
import type { NextFn } from '@adonisjs/core/types/http';
export default class AdminMiddleware {
async handle(ctx: HttpContext, next: NextFn) {
if (!ctx.auth.user?.isAdmin) {
return ctx.response.redirectToNamedRoute('dashboard');
}
return next();
}
async handle(ctx: HttpContext, next: NextFn) {
if (!ctx.auth.user?.isAdmin) {
return ctx.response.redirectToNamedRoute('dashboard');
}
return next();
}
}

View File

@@ -8,21 +8,21 @@ import { route } from '@izzyjs/route/client';
* access to unauthenticated users.
*/
export default class AuthMiddleware {
/**
* The URL to redirect to, when authentication fails
*/
redirectTo = route('auth.login').url;
/**
* The URL to redirect to, when authentication fails
*/
redirectTo = route('auth.login').url;
async handle(
ctx: HttpContext,
next: NextFn,
options: {
guards?: (keyof Authenticators)[];
} = {}
) {
await ctx.auth.authenticateUsing(options.guards, {
loginRoute: this.redirectTo,
});
return next();
}
async handle(
ctx: HttpContext,
next: NextFn,
options: {
guards?: (keyof Authenticators)[];
} = {}
) {
await ctx.auth.authenticateUsing(options.guards, {
loginRoute: this.redirectTo,
});
return next();
}
}

View File

@@ -10,10 +10,10 @@ import { NextFn } from '@adonisjs/core/types/http';
* - And bind "Logger" class to the "ctx.logger" object
*/
export default class ContainerBindingsMiddleware {
handle(ctx: HttpContext, next: NextFn) {
ctx.containerResolver.bindValue(HttpContext, ctx);
ctx.containerResolver.bindValue(Logger, ctx.logger);
handle(ctx: HttpContext, next: NextFn) {
ctx.containerResolver.bindValue(HttpContext, ctx);
ctx.containerResolver.bindValue(Logger, ctx.logger);
return next();
}
return next();
}
}

View File

@@ -10,22 +10,22 @@ import type { Authenticators } from '@adonisjs/auth/types';
* is already logged-in
*/
export default class GuestMiddleware {
/**
* The URL to redirect to when user is logged-in
*/
redirectTo = '/';
/**
* The URL to redirect to when user is logged-in
*/
redirectTo = '/';
async handle(
ctx: HttpContext,
next: NextFn,
options: { guards?: (keyof Authenticators)[] } = {}
) {
for (let guard of options.guards || [ctx.auth.defaultGuard]) {
if (await ctx.auth.use(guard).check()) {
return ctx.response.redirect(this.redirectTo, true);
}
}
async handle(
ctx: HttpContext,
next: NextFn,
options: { guards?: (keyof Authenticators)[] } = {}
) {
for (let guard of options.guards || [ctx.auth.defaultGuard]) {
if (await ctx.auth.use(guard).check()) {
return ctx.response.redirect(this.redirectTo, true);
}
}
return next();
}
return next();
}
}

View File

@@ -2,16 +2,16 @@ import { HttpContext } from '@adonisjs/core/http';
import logger from '@adonisjs/core/services/logger';
export default class LogRequest {
async handle({ request }: HttpContext, next: () => Promise<void>) {
if (
!request.url().startsWith('/node_modules') &&
!request.url().startsWith('/inertia') &&
!request.url().startsWith('/@vite') &&
!request.url().startsWith('/@react-refresh') &&
!request.url().includes('.ts')
) {
logger.debug(`[${request.method()}]: ${request.url()}`);
}
await next();
}
async handle({ request }: HttpContext, next: () => Promise<void>) {
if (
!request.url().startsWith('/node_modules') &&
!request.url().startsWith('/inertia') &&
!request.url().startsWith('/@vite') &&
!request.url().startsWith('/@react-refresh') &&
!request.url().includes('.ts')
) {
logger.debug(`[${request.method()}]: ${request.url()}`);
}
await next();
}
}

View File

@@ -1,25 +1,25 @@
import {
BaseModel,
CamelCaseNamingStrategy,
column,
BaseModel,
CamelCaseNamingStrategy,
column,
} from '@adonisjs/lucid/orm';
import { DateTime } from 'luxon';
export default class AppBaseModel extends BaseModel {
static namingStrategy = new CamelCaseNamingStrategy();
serializeExtras = true;
static namingStrategy = new CamelCaseNamingStrategy();
serializeExtras = true;
@column({ isPrimary: true })
declare id: number;
@column({ isPrimary: true })
declare id: number;
@column.dateTime({
autoCreate: true,
})
declare createdAt: DateTime;
@column.dateTime({
autoCreate: true,
})
declare createdAt: DateTime;
@column.dateTime({
autoCreate: true,
autoUpdate: true,
})
declare updatedAt: DateTime;
@column.dateTime({
autoCreate: true,
autoUpdate: true,
})
declare updatedAt: DateTime;
}

View File

@@ -6,24 +6,24 @@ import type { BelongsTo, HasMany } from '@adonisjs/lucid/types/relations';
import { Visibility } from '#enums/visibility';
export default class Collection extends AppBaseModel {
@column()
declare name: string;
@column()
declare name: string;
@column()
declare description: string | null;
@column()
declare description: string | null;
@column()
declare visibility: Visibility;
@column()
declare visibility: Visibility;
@column()
declare nextId: number;
@column()
declare nextId: number;
@column()
declare authorId: number;
@column()
declare authorId: number;
@belongsTo(() => User, { foreignKey: 'authorId' })
declare author: BelongsTo<typeof User>;
@belongsTo(() => User, { foreignKey: 'authorId' })
declare author: BelongsTo<typeof User>;
@hasMany(() => Link)
declare links: HasMany<typeof Link>;
@hasMany(() => Link)
declare links: HasMany<typeof Link>;
}

View File

@@ -5,27 +5,27 @@ import { belongsTo, column } from '@adonisjs/lucid/orm';
import type { BelongsTo } from '@adonisjs/lucid/types/relations';
export default class Link extends AppBaseModel {
@column()
declare name: string;
@column()
declare name: string;
@column()
declare description: string | null;
@column()
declare description: string | null;
@column()
declare url: string;
@column()
declare url: string;
@column()
declare favorite: boolean;
@column()
declare favorite: boolean;
@column()
declare collectionId: number;
@column()
declare collectionId: number;
@belongsTo(() => Collection, { foreignKey: 'collectionId' })
declare collection: BelongsTo<typeof Collection>;
@belongsTo(() => Collection, { foreignKey: 'collectionId' })
declare collection: BelongsTo<typeof Collection>;
@column()
declare authorId: number;
@column()
declare authorId: number;
@belongsTo(() => User, { foreignKey: 'authorId' })
declare author: BelongsTo<typeof User>;
@belongsTo(() => User, { foreignKey: 'authorId' })
declare author: BelongsTo<typeof User>;
}

View File

@@ -6,42 +6,42 @@ import type { HasMany } from '@adonisjs/lucid/types/relations';
import AppBaseModel from './app_base_model.js';
export default class User extends AppBaseModel {
@column()
declare email: string;
@column()
declare email: string;
@column()
declare name: string;
@column()
declare name: string;
@column()
declare nickName: string; // public username
@column()
declare nickName: string; // public username
@column()
declare avatarUrl: string;
@column()
declare avatarUrl: string;
@column()
declare isAdmin: boolean;
@column()
declare isAdmin: boolean;
@column({ serializeAs: null })
declare token?: GoogleToken;
@column({ serializeAs: null })
declare token?: GoogleToken;
@column({ serializeAs: null })
declare providerId: number;
@column({ serializeAs: null })
declare providerId: number;
@column({ serializeAs: null })
declare providerType: 'google';
@column({ serializeAs: null })
declare providerType: 'google';
@hasMany(() => Collection, {
foreignKey: 'authorId',
})
declare collections: HasMany<typeof Collection>;
@hasMany(() => Collection, {
foreignKey: 'authorId',
})
declare collections: HasMany<typeof Collection>;
@hasMany(() => Link, {
foreignKey: 'authorId',
})
declare links: HasMany<typeof Link>;
@hasMany(() => Link, {
foreignKey: 'authorId',
})
declare links: HasMany<typeof Link>;
@computed()
get fullname() {
return this.nickName || this.name;
}
@computed()
get fullname() {
return this.nickName || this.name;
}
}

View File

@@ -2,36 +2,36 @@ import { Visibility } from '#enums/visibility';
import vine, { SimpleMessagesProvider } from '@vinejs/vine';
const params = vine.object({
id: vine.number(),
id: vine.number(),
});
export const createCollectionValidator = vine.compile(
vine.object({
name: vine.string().trim().minLength(1).maxLength(254),
description: vine.string().trim().maxLength(254).nullable(),
visibility: vine.enum(Visibility),
nextId: vine.number().optional(),
})
vine.object({
name: vine.string().trim().minLength(1).maxLength(254),
description: vine.string().trim().maxLength(254).nullable(),
visibility: vine.enum(Visibility),
nextId: vine.number().optional(),
})
);
export const updateCollectionValidator = vine.compile(
vine.object({
name: vine.string().trim().minLength(1).maxLength(254),
description: vine.string().trim().maxLength(254).nullable(),
visibility: vine.enum(Visibility),
nextId: vine.number().optional(),
vine.object({
name: vine.string().trim().minLength(1).maxLength(254),
description: vine.string().trim().maxLength(254).nullable(),
visibility: vine.enum(Visibility),
nextId: vine.number().optional(),
params,
})
params,
})
);
export const deleteCollectionValidator = vine.compile(
vine.object({
params,
})
vine.object({
params,
})
);
createCollectionValidator.messagesProvider = new SimpleMessagesProvider({
name: 'Collection name is required',
'visibility.required': 'Collection visibiliy is required',
name: 'Collection name is required',
'visibility.required': 'Collection visibiliy is required',
});

View File

@@ -1,43 +1,43 @@
import vine from '@vinejs/vine';
const params = vine.object({
id: vine.number(),
id: vine.number(),
});
export const createLinkValidator = vine.compile(
vine.object({
name: vine.string().trim().minLength(1).maxLength(254),
description: vine.string().trim().maxLength(300).optional(),
url: vine.string().trim(),
favorite: vine.boolean(),
collectionId: vine.number(),
})
vine.object({
name: vine.string().trim().minLength(1).maxLength(254),
description: vine.string().trim().maxLength(300).optional(),
url: vine.string().trim(),
favorite: vine.boolean(),
collectionId: vine.number(),
})
);
export const updateLinkValidator = vine.compile(
vine.object({
name: vine.string().trim().minLength(1).maxLength(254),
description: vine.string().trim().maxLength(300).optional(),
url: vine.string().trim(),
favorite: vine.boolean(),
collectionId: vine.number(),
vine.object({
name: vine.string().trim().minLength(1).maxLength(254),
description: vine.string().trim().maxLength(300).optional(),
url: vine.string().trim(),
favorite: vine.boolean(),
collectionId: vine.number(),
params,
})
params,
})
);
export const deleteLinkValidator = vine.compile(
vine.object({
params,
})
vine.object({
params,
})
);
export const updateLinkFavoriteStatusValidator = vine.compile(
vine.object({
favorite: vine.boolean(),
vine.object({
favorite: vine.boolean(),
params: vine.object({
id: vine.number(),
}),
})
params: vine.object({
id: vine.number(),
}),
})
);

View File

@@ -1,11 +1,11 @@
import vine from '@vinejs/vine';
const params = vine.object({
id: vine.number(),
id: vine.number(),
});
export const getSharedCollectionValidator = vine.compile(
vine.object({
params,
})
vine.object({
params,
})
);

View File

@@ -1,7 +1,7 @@
import vine from '@vinejs/vine';
export const updateUserThemeValidator = vine.compile(
vine.object({
preferDarkTheme: vine.boolean(),
})
vine.object({
preferDarkTheme: vine.boolean(),
})
);

View File

@@ -25,23 +25,23 @@ const APP_ROOT = new URL('../', import.meta.url);
* application.
*/
const IMPORTER = (filePath: string) => {
if (filePath.startsWith('./') || filePath.startsWith('../')) {
return import(new URL(filePath, APP_ROOT).href);
}
return import(filePath);
if (filePath.startsWith('./') || filePath.startsWith('../')) {
return import(new URL(filePath, APP_ROOT).href);
}
return import(filePath);
};
new Ignitor(APP_ROOT, { importer: IMPORTER })
.tap((app) => {
app.booting(async () => {
await import('#start/env');
});
app.listen('SIGTERM', () => app.terminate());
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate());
})
.ace()
.handle(process.argv.splice(2))
.catch((error) => {
process.exitCode = 1;
prettyPrintError(error);
});
.tap((app) => {
app.booting(async () => {
await import('#start/env');
});
app.listen('SIGTERM', () => app.terminate());
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate());
})
.ace()
.handle(process.argv.splice(2))
.catch((error) => {
process.exitCode = 1;
prettyPrintError(error);
});

View File

@@ -23,23 +23,23 @@ const APP_ROOT = new URL('../', import.meta.url);
* application.
*/
const IMPORTER = (filePath: string) => {
if (filePath.startsWith('./') || filePath.startsWith('../')) {
return import(new URL(filePath, APP_ROOT).href);
}
return import(filePath);
if (filePath.startsWith('./') || filePath.startsWith('../')) {
return import(new URL(filePath, APP_ROOT).href);
}
return import(filePath);
};
new Ignitor(APP_ROOT, { importer: IMPORTER })
.tap((app) => {
app.booting(async () => {
await import('#start/env');
});
app.listen('SIGTERM', () => app.terminate());
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate());
})
.httpServer()
.start()
.catch((error) => {
process.exitCode = 1;
prettyPrintError(error);
});
.tap((app) => {
app.booting(async () => {
await import('#start/env');
});
app.listen('SIGTERM', () => app.terminate());
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate());
})
.httpServer()
.start()
.catch((error) => {
process.exitCode = 1;
prettyPrintError(error);
});

View File

@@ -27,36 +27,36 @@ const APP_ROOT = new URL('../', import.meta.url);
* application.
*/
const IMPORTER = (filePath: string) => {
if (filePath.startsWith('./') || filePath.startsWith('../')) {
return import(new URL(filePath, APP_ROOT).href);
}
return import(filePath);
if (filePath.startsWith('./') || filePath.startsWith('../')) {
return import(new URL(filePath, APP_ROOT).href);
}
return import(filePath);
};
new Ignitor(APP_ROOT, { importer: IMPORTER })
.tap((app) => {
app.booting(async () => {
await import('#start/env');
});
app.listen('SIGTERM', () => app.terminate());
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate());
})
.testRunner()
.configure(async (app) => {
const { runnerHooks, ...config } = await import('../tests/bootstrap.js');
.tap((app) => {
app.booting(async () => {
await import('#start/env');
});
app.listen('SIGTERM', () => app.terminate());
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate());
})
.testRunner()
.configure(async (app) => {
const { runnerHooks, ...config } = await import('../tests/bootstrap.js');
processCLIArgs(process.argv.splice(2));
configure({
...app.rcFile.tests,
...config,
...{
setup: runnerHooks.setup,
teardown: runnerHooks.teardown.concat([() => app.terminate()]),
},
});
})
.run(() => run())
.catch((error) => {
process.exitCode = 1;
prettyPrintError(error);
});
processCLIArgs(process.argv.splice(2));
configure({
...app.rcFile.tests,
...config,
...{
setup: runnerHooks.setup,
teardown: runnerHooks.teardown.concat([() => app.terminate()]),
},
});
})
.run(() => run())
.catch((error) => {
process.exitCode = 1;
prettyPrintError(error);
});

View File

@@ -2,18 +2,18 @@ import env from '#start/env';
import { defineConfig, services } from '@adonisjs/ally';
const allyConfig = defineConfig({
google: services.google({
clientId: env.get('GOOGLE_CLIENT_ID'),
clientSecret: env.get('GOOGLE_CLIENT_SECRET'),
callbackUrl: env.get('GOOGLE_CLIENT_CALLBACK_URL'),
prompt: 'select_account',
display: 'page',
scopes: ['userinfo.email', 'userinfo.profile'],
}),
google: services.google({
clientId: env.get('GOOGLE_CLIENT_ID'),
clientSecret: env.get('GOOGLE_CLIENT_SECRET'),
callbackUrl: env.get('GOOGLE_CLIENT_CALLBACK_URL'),
prompt: 'select_account',
display: 'page',
scopes: ['userinfo.email', 'userinfo.profile'],
}),
});
export default allyConfig;
declare module '@adonisjs/ally/types' {
interface SocialProviders extends InferSocialProviders<typeof allyConfig> {}
interface SocialProviders extends InferSocialProviders<typeof allyConfig> {}
}

View File

@@ -16,25 +16,25 @@ export const appKey = new Secret(env.get('APP_KEY'));
* The configuration settings used by the HTTP server
*/
export const http = defineConfig({
generateRequestId: true,
allowMethodSpoofing: false,
generateRequestId: true,
allowMethodSpoofing: false,
/**
* Enabling async local storage will let you access HTTP context
* from anywhere inside your application.
*/
useAsyncLocalStorage: false,
/**
* Enabling async local storage will let you access HTTP context
* from anywhere inside your application.
*/
useAsyncLocalStorage: false,
/**
* Manage cookies configuration. The settings for the session id cookie are
* defined inside the "config/session.ts" file.
*/
cookie: {
domain: '',
path: '/',
maxAge: '2h',
httpOnly: true,
secure: app.inProduction,
sameSite: 'lax',
},
/**
* Manage cookies configuration. The settings for the session id cookie are
* defined inside the "config/session.ts" file.
*/
cookie: {
domain: '',
path: '/',
maxAge: '2h',
httpOnly: true,
secure: app.inProduction,
sameSite: 'lax',
},
});

View File

@@ -3,15 +3,15 @@ import { InferAuthEvents, Authenticators } from '@adonisjs/auth/types';
import { sessionGuard, sessionUserProvider } from '@adonisjs/auth/session';
const authConfig = defineConfig({
default: 'web',
guards: {
web: sessionGuard({
useRememberMeTokens: false,
provider: sessionUserProvider({
model: () => import('#models/user'),
}),
}),
},
default: 'web',
guards: {
web: sessionGuard({
useRememberMeTokens: false,
provider: sessionUserProvider({
model: () => import('#models/user'),
}),
}),
},
});
export default authConfig;
@@ -21,8 +21,8 @@ export default authConfig;
* guards.
*/
declare module '@adonisjs/auth/types' {
interface Authenticators extends InferAuthenticators<typeof authConfig> {}
interface Authenticators extends InferAuthenticators<typeof authConfig> {}
}
declare module '@adonisjs/core/types' {
interface EventsList extends InferAuthEvents<Authenticators> {}
interface EventsList extends InferAuthEvents<Authenticators> {}
}

View File

@@ -1,55 +1,55 @@
import { defineConfig } from '@adonisjs/core/bodyparser';
const bodyParserConfig = defineConfig({
/**
* The bodyparser middleware will parse the request body
* for the following HTTP methods.
*/
allowedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'],
/**
* The bodyparser middleware will parse the request body
* for the following HTTP methods.
*/
allowedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'],
/**
* Config for the "application/x-www-form-urlencoded"
* content-type parser
*/
form: {
convertEmptyStringsToNull: true,
types: ['application/x-www-form-urlencoded'],
},
/**
* Config for the "application/x-www-form-urlencoded"
* content-type parser
*/
form: {
convertEmptyStringsToNull: true,
types: ['application/x-www-form-urlencoded'],
},
/**
* Config for the JSON parser
*/
json: {
convertEmptyStringsToNull: true,
types: [
'application/json',
'application/json-patch+json',
'application/vnd.api+json',
'application/csp-report',
],
},
/**
* Config for the JSON parser
*/
json: {
convertEmptyStringsToNull: true,
types: [
'application/json',
'application/json-patch+json',
'application/vnd.api+json',
'application/csp-report',
],
},
/**
* Config for the "multipart/form-data" content-type parser.
* File uploads are handled by the multipart parser.
*/
multipart: {
/**
* Enabling auto process allows bodyparser middleware to
* move all uploaded files inside the tmp folder of your
* operating system
*/
autoProcess: true,
convertEmptyStringsToNull: true,
processManually: [],
/**
* Config for the "multipart/form-data" content-type parser.
* File uploads are handled by the multipart parser.
*/
multipart: {
/**
* Enabling auto process allows bodyparser middleware to
* move all uploaded files inside the tmp folder of your
* operating system
*/
autoProcess: true,
convertEmptyStringsToNull: true,
processManually: [],
/**
* Maximum limit of data to parse including all files
* and fields
*/
limit: '20mb',
types: ['multipart/form-data'],
},
/**
* Maximum limit of data to parse including all files
* and fields
*/
limit: '20mb',
types: ['multipart/form-data'],
},
});
export default bodyParserConfig;

View File

@@ -7,13 +7,13 @@ import { defineConfig } from '@adonisjs/cors';
* https://docs.adonisjs.com/guides/security/cors
*/
const corsConfig = defineConfig({
enabled: true,
origin: [],
methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
headers: true,
exposeHeaders: [],
credentials: true,
maxAge: 90,
enabled: true,
origin: [],
methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
headers: true,
exposeHeaders: [],
credentials: true,
maxAge: 90,
});
export default corsConfig;

View File

@@ -2,26 +2,26 @@ import env from '#start/env';
import { defineConfig } from '@adonisjs/lucid';
const dbConfig = defineConfig({
connection: 'postgres',
connections: {
postgres: {
client: 'pg',
connection: {
host: env.get('DB_HOST'),
port: env.get('DB_PORT'),
user: env.get('DB_USER'),
password: env.get('DB_PASSWORD'),
database: env.get('DB_DATABASE'),
},
migrations: {
naturalSort: true,
paths: ['database/migrations'],
},
seeders: {
paths: ['./database/seeders/main'],
},
},
},
connection: 'postgres',
connections: {
postgres: {
client: 'pg',
connection: {
host: env.get('DB_HOST'),
port: env.get('DB_PORT'),
user: env.get('DB_USER'),
password: env.get('DB_PASSWORD'),
database: env.get('DB_DATABASE'),
},
migrations: {
naturalSort: true,
paths: ['database/migrations'],
},
seeders: {
paths: ['./database/seeders/main'],
},
},
},
});
export default dbConfig;

View File

@@ -1,16 +1,16 @@
import { defineConfig, drivers } from '@adonisjs/core/hash';
const hashConfig = defineConfig({
default: 'scrypt',
default: 'scrypt',
list: {
scrypt: drivers.scrypt({
cost: 16384,
blockSize: 8,
parallelization: 1,
maxMemory: 33554432,
}),
},
list: {
scrypt: drivers.scrypt({
cost: 16384,
blockSize: 8,
parallelization: 1,
maxMemory: 33554432,
}),
},
});
export default hashConfig;
@@ -20,5 +20,5 @@ export default hashConfig;
* in your application.
*/
declare module '@adonisjs/core/types' {
export interface HashersList extends InferHashers<typeof hashConfig> {}
export interface HashersList extends InferHashers<typeof hashConfig> {}
}

View File

@@ -1,36 +1,36 @@
import {
DARK_THEME_DEFAULT_VALUE,
PREFER_DARK_THEME,
DARK_THEME_DEFAULT_VALUE,
PREFER_DARK_THEME,
} from '#constants/session';
import { defineConfig } from '@adonisjs/inertia';
export default defineConfig({
/**
* Path to the Edge view that will be used as the root view for Inertia responses
*/
rootView: 'inertia_layout',
/**
* Path to the Edge view that will be used as the root view for Inertia responses
*/
rootView: 'inertia_layout',
/**
* Data that should be shared with all rendered pages
*/
sharedData: {
errors: (ctx) => ctx.session?.flashMessages.get('errors'),
preferDarkTheme: (ctx) =>
ctx.session?.get(PREFER_DARK_THEME, DARK_THEME_DEFAULT_VALUE),
auth: async (ctx) => {
await ctx.auth?.check();
return {
user: ctx.auth?.user || null,
isAuthenticated: ctx.auth?.isAuthenticated || false,
};
},
},
/**
* Data that should be shared with all rendered pages
*/
sharedData: {
errors: (ctx) => ctx.session?.flashMessages.get('errors'),
preferDarkTheme: (ctx) =>
ctx.session?.get(PREFER_DARK_THEME, DARK_THEME_DEFAULT_VALUE),
auth: async (ctx) => {
await ctx.auth?.check();
return {
user: ctx.auth?.user || null,
isAuthenticated: ctx.auth?.isAuthenticated || false,
};
},
},
/**
* Options for the server-side rendering
*/
ssr: {
enabled: true,
entrypoint: 'inertia/app/ssr.tsx',
},
/**
* Options for the server-side rendering
*/
ssr: {
enabled: true,
entrypoint: 'inertia/app/ssr.tsx',
},
});

View File

@@ -3,25 +3,25 @@ import app from '@adonisjs/core/services/app';
import { defineConfig, targets } from '@adonisjs/core/logger';
const loggerConfig = defineConfig({
default: 'app',
default: 'app',
/**
* The loggers object can be used to define multiple loggers.
* By default, we configure only one logger (named "app").
*/
loggers: {
app: {
enabled: true,
name: env.get('APP_NAME'),
level: env.get('LOG_LEVEL'),
transport: {
targets: targets()
.pushIf(!app.inProduction, targets.pretty())
.pushIf(app.inProduction, targets.file({ destination: 1 }))
.toArray(),
},
},
},
/**
* The loggers object can be used to define multiple loggers.
* By default, we configure only one logger (named "app").
*/
loggers: {
app: {
enabled: true,
name: env.get('APP_NAME'),
level: env.get('LOG_LEVEL'),
transport: {
targets: targets()
.pushIf(!app.inProduction, targets.pretty())
.pushIf(app.inProduction, targets.file({ destination: 1 }))
.toArray(),
},
},
},
});
export default loggerConfig;
@@ -31,5 +31,5 @@ export default loggerConfig;
* in your application.
*/
declare module '@adonisjs/core/types' {
export interface LoggersList extends InferLoggers<typeof loggerConfig> {}
export interface LoggersList extends InferLoggers<typeof loggerConfig> {}
}

View File

@@ -2,48 +2,48 @@ import env from '#start/env';
import { defineConfig, stores } from '@adonisjs/session';
const sessionConfig = defineConfig({
enabled: true,
cookieName: 'adonis-session',
enabled: true,
cookieName: 'adonis-session',
/**
* When set to true, the session id cookie will be deleted
* once the user closes the browser.
*/
clearWithBrowser: false,
/**
* When set to true, the session id cookie will be deleted
* once the user closes the browser.
*/
clearWithBrowser: false,
/**
* Define how long to keep the session data alive without
* any activity.
*/
age: '7d',
/**
* Define how long to keep the session data alive without
* any activity.
*/
age: '7d',
/**
* Configuration for session cookie and the
* cookie store
*/
cookie: {
path: '/',
httpOnly: true,
secure: true,
/**
* Configuration for session cookie and the
* cookie store
*/
cookie: {
path: '/',
httpOnly: true,
secure: true,
// TODO: set this to lax and found a solution to keep auth when using extension
sameSite: 'none',
},
// TODO: set this to lax and found a solution to keep auth when using extension
sameSite: 'none',
},
/**
* The store to use. Make sure to validate the environment
* variable in order to infer the store name without any
* errors.
*/
store: env.get('SESSION_DRIVER'),
/**
* The store to use. Make sure to validate the environment
* variable in order to infer the store name without any
* errors.
*/
store: env.get('SESSION_DRIVER'),
/**
* List of configured stores. Refer documentation to see
* list of available stores and their config.
*/
stores: {
cookie: stores.cookie(),
},
/**
* List of configured stores. Refer documentation to see
* list of available stores and their config.
*/
stores: {
cookie: stores.cookie(),
},
});
export default sessionConfig;

View File

@@ -1,50 +1,50 @@
import { defineConfig } from '@adonisjs/shield';
const shieldConfig = defineConfig({
/**
* Configure CSP policies for your app. Refer documentation
* to learn more
*/
csp: {
enabled: false,
directives: {},
reportOnly: false,
},
/**
* Configure CSP policies for your app. Refer documentation
* to learn more
*/
csp: {
enabled: false,
directives: {},
reportOnly: false,
},
/**
* Configure CSRF protection options. Refer documentation
* to learn more
*/
csrf: {
enabled: false,
exceptRoutes: [],
enableXsrfCookie: true,
methods: ['POST', 'PUT', 'PATCH', 'DELETE'],
},
/**
* Configure CSRF protection options. Refer documentation
* to learn more
*/
csrf: {
enabled: false,
exceptRoutes: [],
enableXsrfCookie: true,
methods: ['POST', 'PUT', 'PATCH', 'DELETE'],
},
/**
* Control how your website should be embedded inside
* iFrames
*/
xFrame: {
enabled: false,
},
/**
* Control how your website should be embedded inside
* iFrames
*/
xFrame: {
enabled: false,
},
/**
* Force browser to always use HTTPS
*/
hsts: {
enabled: true,
maxAge: '180 days',
},
/**
* Force browser to always use HTTPS
*/
hsts: {
enabled: true,
maxAge: '180 days',
},
/**
* Disable browsers from sniffing the content type of a
* response and always rely on the "content-type" header.
*/
contentTypeSniffing: {
enabled: true,
},
/**
* Disable browsers from sniffing the content type of a
* response and always rely on the "content-type" header.
*/
contentTypeSniffing: {
enabled: true,
},
});
export default shieldConfig;

View File

@@ -8,10 +8,10 @@ import { defineConfig } from '@adonisjs/static';
* https://docs.adonisjs.com/guides/static-assets
*/
const staticServerConfig = defineConfig({
enabled: true,
etag: true,
lastModified: true,
dotFiles: 'ignore',
enabled: true,
etag: true,
lastModified: true,
dotFiles: 'ignore',
});
export default staticServerConfig;

View File

@@ -1,28 +1,28 @@
import { defineConfig } from '@adonisjs/vite';
const viteBackendConfig = defineConfig({
/**
* The output of vite will be written inside this
* directory. The path should be relative from
* the application root.
*/
buildDirectory: 'public/assets',
/**
* The output of vite will be written inside this
* directory. The path should be relative from
* the application root.
*/
buildDirectory: 'public/assets',
/**
* The path to the manifest file generated by the
* "vite build" command.
*/
manifestFile: 'public/assets/.vite/manifest.json',
/**
* The path to the manifest file generated by the
* "vite build" command.
*/
manifestFile: 'public/assets/.vite/manifest.json',
/**
* Feel free to change the value of the "assetsUrl" to
* point to a CDN in production.
*/
assetsUrl: '/assets',
/**
* Feel free to change the value of the "assetsUrl" to
* point to a CDN in production.
*/
assetsUrl: '/assets',
scriptAttributes: {
defer: true,
},
scriptAttributes: {
defer: true,
},
});
export default viteBackendConfig;

View File

@@ -1,8 +1,8 @@
import { Knex } from 'knex';
export function defaultTableFields(table: Knex.CreateTableBuilder) {
table.increments('id').primary().first().unique().notNullable();
table.increments('id').primary().first().unique().notNullable();
table.timestamp('created_at').notNullable();
table.timestamp('updated_at').nullable();
table.timestamp('created_at').notNullable();
table.timestamp('updated_at').nullable();
}

View File

@@ -2,25 +2,25 @@ import { defaultTableFields } from '#database/default_table_fields';
import { BaseSchema } from '@adonisjs/lucid/schema';
export default class CreateUsersTable extends BaseSchema {
static tableName = 'users';
static tableName = 'users';
async up() {
this.schema.createTableIfNotExists(CreateUsersTable.tableName, (table) => {
table.string('email', 254).notNullable().unique();
table.string('name', 254).notNullable();
table.string('nick_name', 254).nullable();
table.text('avatar_url').notNullable();
table.boolean('is_admin').defaultTo(0).notNullable();
async up() {
this.schema.createTableIfNotExists(CreateUsersTable.tableName, (table) => {
table.string('email', 254).notNullable().unique();
table.string('name', 254).notNullable();
table.string('nick_name', 254).nullable();
table.text('avatar_url').notNullable();
table.boolean('is_admin').defaultTo(0).notNullable();
table.json('token').nullable();
table.string('provider_id').notNullable();
table.enum('provider_type', ['google']).notNullable().defaultTo('google');
table.json('token').nullable();
table.string('provider_id').notNullable();
table.enum('provider_type', ['google']).notNullable().defaultTo('google');
defaultTableFields(table);
});
}
defaultTableFields(table);
});
}
async down() {
this.schema.dropTable(CreateUsersTable.tableName);
}
async down() {
this.schema.dropTable(CreateUsersTable.tableName);
}
}

View File

@@ -3,42 +3,42 @@ import { Visibility } from '#enums/visibility';
import { BaseSchema } from '@adonisjs/lucid/schema';
export default class CreateCollectionTable extends BaseSchema {
static tableName = 'collections';
private visibilityEnumName = 'collection_visibility';
static tableName = 'collections';
private visibilityEnumName = 'collection_visibility';
async up() {
this.schema.raw(`DROP TYPE IF EXISTS ${this.visibilityEnumName}`);
this.schema.createTableIfNotExists(
CreateCollectionTable.tableName,
(table) => {
table.string('name', 254).notNullable();
table.string('description', 254).nullable();
table
.enum('visibility', Object.values(Visibility), {
useNative: true,
enumName: this.visibilityEnumName,
existingType: false,
})
.nullable()
.defaultTo(Visibility.PRIVATE);
table
.integer('next_id')
.references('id')
.inTable('collections')
.defaultTo(null);
table
.integer('author_id')
.references('id')
.inTable('users')
.onDelete('CASCADE');
async up() {
this.schema.raw(`DROP TYPE IF EXISTS ${this.visibilityEnumName}`);
this.schema.createTableIfNotExists(
CreateCollectionTable.tableName,
(table) => {
table.string('name', 254).notNullable();
table.string('description', 254).nullable();
table
.enum('visibility', Object.values(Visibility), {
useNative: true,
enumName: this.visibilityEnumName,
existingType: false,
})
.nullable()
.defaultTo(Visibility.PRIVATE);
table
.integer('next_id')
.references('id')
.inTable('collections')
.defaultTo(null);
table
.integer('author_id')
.references('id')
.inTable('users')
.onDelete('CASCADE');
defaultTableFields(table);
}
);
}
defaultTableFields(table);
}
);
}
async down() {
this.schema.raw(`DROP TYPE IF EXISTS ${this.visibilityEnumName}`);
this.schema.dropTable(CreateCollectionTable.tableName);
}
async down() {
this.schema.raw(`DROP TYPE IF EXISTS ${this.visibilityEnumName}`);
this.schema.dropTable(CreateCollectionTable.tableName);
}
}

View File

@@ -2,30 +2,30 @@ import { defaultTableFields } from '#database/default_table_fields';
import { BaseSchema } from '@adonisjs/lucid/schema';
export default class CreateLinksTable extends BaseSchema {
static tableName = 'links';
static tableName = 'links';
async up() {
this.schema.createTableIfNotExists(CreateLinksTable.tableName, (table) => {
table.string('name', 254).notNullable();
table.string('description', 254).nullable();
table.text('url').notNullable();
table.boolean('favorite').notNullable().defaultTo(0);
table
.integer('collection_id')
.references('id')
.inTable('collections')
.onDelete('CASCADE');
table
.integer('author_id')
.references('id')
.inTable('users')
.onDelete('CASCADE');
async up() {
this.schema.createTableIfNotExists(CreateLinksTable.tableName, (table) => {
table.string('name', 254).notNullable();
table.string('description', 254).nullable();
table.text('url').notNullable();
table.boolean('favorite').notNullable().defaultTo(0);
table
.integer('collection_id')
.references('id')
.inTable('collections')
.onDelete('CASCADE');
table
.integer('author_id')
.references('id')
.inTable('users')
.onDelete('CASCADE');
defaultTableFields(table);
});
}
defaultTableFields(table);
});
}
async down() {
this.schema.dropTable(CreateLinksTable.tableName);
}
async down() {
this.schema.dropTable(CreateLinksTable.tableName);
}
}

View File

@@ -1,18 +1,18 @@
import { BaseSchema } from '@adonisjs/lucid/schema';
export default class extends BaseSchema {
async up() {
this.schema.raw(`
async up() {
this.schema.raw(`
CREATE EXTENSION IF NOT EXISTS unaccent;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
`);
this.schema.raw(`
this.schema.raw(`
CREATE INDEX ON links USING gin(to_tsvector('english', name));
CREATE INDEX ON collections USING gin(to_tsvector('english', name));
CREATE INDEX ON links USING gin(to_tsvector('french', name));
CREATE INDEX ON collections USING gin(to_tsvector('french', name));
`);
this.schema.raw(`
this.schema.raw(`
CREATE OR REPLACE FUNCTION search_text(search_query TEXT, p_author_id INTEGER)
RETURNS TABLE (
id INTEGER,
@@ -45,9 +45,9 @@ export default class extends BaseSchema {
$$
LANGUAGE plpgsql;
`);
}
}
async down() {
this.schema.raw('DROP FUNCTION IF EXISTS search_text');
}
async down() {
this.schema.raw('DROP FUNCTION IF EXISTS search_text');
}
}

View File

@@ -5,36 +5,36 @@ import { BaseSeeder } from '@adonisjs/lucid/seeders';
import { faker } from '@faker-js/faker';
export default class extends BaseSeeder {
static environment = ['development', 'testing'];
static environment = ['development', 'testing'];
async run() {
const users = await getUserIds();
async run() {
const users = await getUserIds();
const collections = faker.helpers.multiple(
() => createRandomCollection(users),
{
count: 50,
}
);
await Collection.createMany(collections);
}
const collections = faker.helpers.multiple(
() => createRandomCollection(users),
{
count: 50,
}
);
await Collection.createMany(collections);
}
}
export async function getUserIds() {
const users = await User.all();
return users.map(({ id }) => id);
const users = await User.all();
return users.map(({ id }) => id);
}
let collectionId = 0;
function createRandomCollection(userIds: User['id'][]) {
const authorId = faker.helpers.arrayElements(userIds, 1).at(0);
collectionId++;
return {
id: collectionId,
name: faker.string.alphanumeric({ length: { min: 5, max: 25 } }),
description: faker.string.alphanumeric({ length: { min: 0, max: 254 } }),
visibility: Visibility.PRIVATE,
nextId: collectionId + 1,
authorId,
};
const authorId = faker.helpers.arrayElements(userIds, 1).at(0);
collectionId++;
return {
id: collectionId,
name: faker.string.alphanumeric({ length: { min: 5, max: 25 } }),
description: faker.string.alphanumeric({ length: { min: 0, max: 254 } }),
visibility: Visibility.PRIVATE,
nextId: collectionId + 1,
authorId,
};
}

View File

@@ -6,41 +6,41 @@ import { BaseSeeder } from '@adonisjs/lucid/seeders';
import { faker } from '@faker-js/faker';
export default class extends BaseSeeder {
static environment = ['development', 'testing'];
static environment = ['development', 'testing'];
async run() {
const users = await getUserIds();
async run() {
const users = await getUserIds();
const links = await Promise.all(
faker.helpers.multiple(async () => createRandomLink(users), {
count: 500,
})
);
await Link.createMany(links.filter((a) => typeof a !== 'undefined') as any);
}
const links = await Promise.all(
faker.helpers.multiple(async () => createRandomLink(users), {
count: 500,
})
);
await Link.createMany(links.filter((a) => typeof a !== 'undefined') as any);
}
}
async function getCollectionIds(authorId: User['id']) {
const collection = await Collection.findManyBy('author_id', authorId);
return collection.map(({ id }) => id);
const collection = await Collection.findManyBy('author_id', authorId);
return collection.map(({ id }) => id);
}
async function createRandomLink(userIds: User['id'][]) {
const authorId = faker.helpers.arrayElements(userIds, 1).at(0)!;
const collections = await getCollectionIds(authorId);
const authorId = faker.helpers.arrayElements(userIds, 1).at(0)!;
const collections = await getCollectionIds(authorId);
const collectionId = faker.helpers.arrayElements(collections, 1).at(0);
if (!collectionId) {
return undefined;
}
const collectionId = faker.helpers.arrayElements(collections, 1).at(0);
if (!collectionId) {
return undefined;
}
return {
id: faker.string.uuid(),
name: faker.string.alphanumeric({ length: { min: 5, max: 25 } }),
description: faker.string.alphanumeric({ length: { min: 0, max: 254 } }),
url: faker.internet.url(),
favorite: faker.number.int({ min: 0, max: 1 }),
authorId,
collectionId,
};
return {
id: faker.string.uuid(),
name: faker.string.alphanumeric({ length: { min: 5, max: 25 } }),
description: faker.string.alphanumeric({ length: { min: 0, max: 254 } }),
url: faker.internet.url(),
favorite: faker.number.int({ min: 0, max: 1 }),
authorId,
collectionId,
};
}

View File

@@ -3,31 +3,31 @@ import logger from '@adonisjs/core/services/logger';
import { BaseSeeder } from '@adonisjs/lucid/seeders';
export default class IndexSeeder extends BaseSeeder {
private async seed(Seeder: { default: typeof BaseSeeder }) {
/**
* Do not run when not in a environment specified in Seeder
*/
if (
!Seeder.default.environment ||
(!Seeder.default.environment.includes('development') && app.inDev) ||
(!Seeder.default.environment.includes('testing') && app.inTest) ||
(!Seeder.default.environment.includes('production') && app.inProduction)
) {
return;
}
private async seed(Seeder: { default: typeof BaseSeeder }) {
/**
* Do not run when not in a environment specified in Seeder
*/
if (
!Seeder.default.environment ||
(!Seeder.default.environment.includes('development') && app.inDev) ||
(!Seeder.default.environment.includes('testing') && app.inTest) ||
(!Seeder.default.environment.includes('production') && app.inProduction)
) {
return;
}
await new Seeder.default(this.client).run();
}
await new Seeder.default(this.client).run();
}
async run() {
logger.info('Start user seed');
await this.seed(await import('#database/seeders/user_seeder'));
logger.info('User seed done');
logger.info('Collection user seed');
await this.seed(await import('#database/seeders/collection_seeder'));
logger.info('Collection seed done');
logger.info('Link user seed');
await this.seed(await import('#database/seeders/link_seeder'));
logger.info('Link seed done');
}
async run() {
logger.info('Start user seed');
await this.seed(await import('#database/seeders/user_seeder'));
logger.info('User seed done');
logger.info('Collection user seed');
await this.seed(await import('#database/seeders/collection_seeder'));
logger.info('Collection seed done');
logger.info('Link user seed');
await this.seed(await import('#database/seeders/link_seeder'));
logger.info('Link seed done');
}
}

View File

@@ -4,26 +4,26 @@ import { BaseSeeder } from '@adonisjs/lucid/seeders';
import { faker } from '@faker-js/faker';
export default class extends BaseSeeder {
static environment = ['development', 'testing'];
static environment = ['development', 'testing'];
async run() {
const users = faker.helpers.multiple(createRandomUser, {
count: 25,
});
await User.createMany(users);
}
async run() {
const users = faker.helpers.multiple(createRandomUser, {
count: 25,
});
await User.createMany(users);
}
}
export function createRandomUser() {
return {
id: faker.number.int(),
email: faker.internet.email(),
name: faker.internet.userName(),
nickName: faker.internet.displayName(),
avatarUrl: faker.image.avatar(),
isAdmin: false,
providerId: faker.number.int(),
providerType: 'google' as const,
token: {} as GoogleToken,
};
return {
id: faker.number.int(),
email: faker.internet.email(),
name: faker.internet.userName(),
nickName: faker.internet.displayName(),
avatarUrl: faker.image.avatar(),
isAdmin: false,
providerId: faker.number.int(),
providerType: 'google' as const,
token: {} as GoogleToken,
};
}

View File

@@ -10,18 +10,18 @@ import '../i18n/index';
const appName = import.meta.env.VITE_APP_NAME || 'MyLinks';
createInertiaApp({
progress: { color: primaryColor },
progress: { color: primaryColor },
title: (title) => `${appName}${title && ` - ${title}`}`,
title: (title) => `${appName}${title && ` - ${title}`}`,
resolve: (name) => {
return resolvePageComponent(
`../pages/${name}.tsx`,
import.meta.glob('../pages/**/*.tsx')
);
},
resolve: (name) => {
return resolvePageComponent(
`../pages/${name}.tsx`,
import.meta.glob('../pages/**/*.tsx')
);
},
setup({ el, App, props }) {
hydrateRoot(el, <App {...props} />);
},
setup({ el, App, props }) {
hydrateRoot(el, <App {...props} />);
},
});

View File

@@ -2,13 +2,13 @@ import { createInertiaApp } from '@inertiajs/react';
import ReactDOMServer from 'react-dom/server';
export default function render(page: any) {
return createInertiaApp({
page,
render: ReactDOMServer.renderToString,
resolve: (name) => {
const pages = import.meta.glob('../pages/**/*.tsx', { eager: true });
return pages[`../pages/${name}.tsx`];
},
setup: ({ App, props }) => <App {...props} />,
});
return createInertiaApp({
page,
render: ReactDOMServer.renderToString,
resolve: (name) => {
const pages = import.meta.glob('../pages/**/*.tsx', { eager: true });
return pages[`../pages/${name}.tsx`];
},
setup: ({ App, props }) => <App {...props} />,
});
}

View File

@@ -7,58 +7,58 @@ import useToggle from '~/hooks/use_modal';
import useShortcut from '~/hooks/use_shortcut';
const DropdownStyle = styled.div<{ opened: boolean; svgSize?: number }>(
({ opened, theme, svgSize = 24 }) => ({
cursor: 'pointer',
userSelect: 'none',
position: 'relative',
minWidth: 'fit-content',
width: 'fit-content',
maxWidth: '250px',
backgroundColor: opened ? theme.colors.secondary : theme.colors.background,
padding: '4px',
borderRadius: theme.border.radius,
({ opened, theme, svgSize = 24 }) => ({
cursor: 'pointer',
userSelect: 'none',
position: 'relative',
minWidth: 'fit-content',
width: 'fit-content',
maxWidth: '250px',
backgroundColor: opened ? theme.colors.secondary : theme.colors.background,
padding: '4px',
borderRadius: theme.border.radius,
'&:hover': {
backgroundColor: theme.colors.secondary,
},
'&:hover': {
backgroundColor: theme.colors.secondary,
},
'& svg': {
height: `${svgSize}px`,
width: `${svgSize}px`,
},
})
'& svg': {
height: `${svgSize}px`,
width: `${svgSize}px`,
},
})
);
export default function Dropdown({
children,
label,
className,
svgSize,
onClick,
children,
label,
className,
svgSize,
onClick,
}: HtmlHTMLAttributes<HTMLDivElement> & {
label: ReactNode | string;
className?: string;
svgSize?: number;
label: ReactNode | string;
className?: string;
svgSize?: number;
}) {
const dropdownRef = useRef<HTMLDivElement>(null);
const { isShowing, toggle, close } = useToggle();
const dropdownRef = useRef<HTMLDivElement>(null);
const { isShowing, toggle, close } = useToggle();
useClickOutside(dropdownRef, close);
useShortcut('ESCAPE_KEY', close, { disableGlobalCheck: true });
useClickOutside(dropdownRef, close);
useShortcut('ESCAPE_KEY', close, { disableGlobalCheck: true });
return (
<DropdownStyle
opened={isShowing}
onClick={(event) => {
onClick?.(event);
toggle();
}}
ref={dropdownRef}
className={className}
svgSize={svgSize}
>
<DropdownLabel>{label}</DropdownLabel>
<DropdownContainer show={isShowing}>{children}</DropdownContainer>
</DropdownStyle>
);
return (
<DropdownStyle
opened={isShowing}
onClick={(event) => {
onClick?.(event);
toggle();
}}
ref={dropdownRef}
className={className}
svgSize={svgSize}
>
<DropdownLabel>{label}</DropdownLabel>
<DropdownContainer show={isShowing}>{children}</DropdownContainer>
</DropdownStyle>
);
}

View File

@@ -2,20 +2,20 @@ import styled from '@emotion/styled';
import TransitionLayout from '~/components/layouts/_transition_layout';
const DropdownContainer = styled(TransitionLayout)<{ show: boolean }>(
({ show, theme }) => ({
zIndex: 99,
position: 'absolute',
top: 'calc(100% + 0.5em)',
right: 0,
minWidth: '175px',
backgroundColor: show ? theme.colors.secondary : theme.colors.background,
border: `2px solid ${theme.colors.secondary}`,
borderRadius: theme.border.radius,
boxShadow: theme.colors.boxShadow,
display: show ? 'flex' : 'none',
flexDirection: 'column',
overflow: 'hidden',
})
({ show, theme }) => ({
zIndex: 99,
position: 'absolute',
top: 'calc(100% + 0.5em)',
right: 0,
minWidth: '175px',
backgroundColor: show ? theme.colors.secondary : theme.colors.background,
border: `2px solid ${theme.colors.secondary}`,
borderRadius: theme.border.radius,
boxShadow: theme.colors.boxShadow,
display: show ? 'flex' : 'none',
flexDirection: 'column',
overflow: 'hidden',
})
);
export default DropdownContainer;

View File

@@ -2,30 +2,30 @@ import styled from '@emotion/styled';
import { Link } from '@inertiajs/react';
const DropdownItemBase = styled('div', {
shouldForwardProp: (propName) => propName !== 'danger',
shouldForwardProp: (propName) => propName !== 'danger',
})<{ danger?: boolean }>(({ theme, danger }) => ({
fontSize: '14px',
whiteSpace: 'nowrap',
color: danger ? theme.colors.lightRed : theme.colors.primary,
padding: '8px 12px',
borderRadius: theme.border.radius,
fontSize: '14px',
whiteSpace: 'nowrap',
color: danger ? theme.colors.lightRed : theme.colors.primary,
padding: '8px 12px',
borderRadius: theme.border.radius,
'&:hover': {
backgroundColor: theme.colors.background,
},
'&:hover': {
backgroundColor: theme.colors.background,
},
}));
const DropdownItemButton = styled(DropdownItemBase)({
display: 'flex',
gap: '0.75em',
alignItems: 'center',
display: 'flex',
gap: '0.75em',
alignItems: 'center',
});
const DropdownItemLink = styled(DropdownItemBase.withComponent(Link))({
width: '100%',
display: 'flex',
gap: '0.75em',
alignItems: 'center',
width: '100%',
display: 'flex',
gap: '0.75em',
alignItems: 'center',
});
export { DropdownItemButton, DropdownItemLink };

View File

@@ -1,11 +1,11 @@
import styled from '@emotion/styled';
const DropdownLabel = styled.div(({ theme }) => ({
height: 'auto',
width: 'auto',
color: theme.colors.font,
display: 'flex',
gap: '0.35em',
height: 'auto',
width: 'auto',
color: theme.colors.font,
display: 'flex',
gap: '0.35em',
}));
export default DropdownLabel;

View File

@@ -1,18 +1,18 @@
import { AnchorHTMLAttributes, CSSProperties, ReactNode } from 'react';
export default function ExternalLink({
children,
title,
...props
children,
title,
...props
}: AnchorHTMLAttributes<HTMLAnchorElement> & {
children: ReactNode;
style?: CSSProperties;
title?: string;
className?: string;
children: ReactNode;
style?: CSSProperties;
title?: string;
className?: string;
}) {
return (
<a target="_blank" rel="noreferrer" title={title} {...props}>
{children}
</a>
);
return (
<a target="_blank" rel="noreferrer" title={title} {...props}>
{children}
</a>
);
}

View File

@@ -1,31 +1,31 @@
import styled from '@emotion/styled';
const Button = styled.button<{ danger?: boolean }>(({ theme, danger }) => {
const btnColor = !danger ? theme.colors.primary : theme.colors.lightRed;
const btnDarkColor = !danger ? theme.colors.darkBlue : theme.colors.lightRed;
return {
cursor: 'pointer',
width: '100%',
textTransform: 'uppercase',
fontSize: '14px',
color: theme.colors.white,
background: btnColor,
padding: '0.75em',
border: `1px solid ${btnColor}`,
borderRadius: theme.border.radius,
transition: theme.transition.delay,
const btnColor = !danger ? theme.colors.primary : theme.colors.lightRed;
const btnDarkColor = !danger ? theme.colors.darkBlue : theme.colors.lightRed;
return {
cursor: 'pointer',
width: '100%',
textTransform: 'uppercase',
fontSize: '14px',
color: theme.colors.white,
background: btnColor,
padding: '0.75em',
border: `1px solid ${btnColor}`,
borderRadius: theme.border.radius,
transition: theme.transition.delay,
'&:disabled': {
cursor: 'not-allowed',
opacity: '0.5',
},
'&:disabled': {
cursor: 'not-allowed',
opacity: '0.5',
},
'&:not(:disabled):hover': {
boxShadow: `${btnDarkColor} 0 0 3px 1px`,
background: btnDarkColor,
color: theme.colors.white,
},
};
'&:not(:disabled):hover': {
boxShadow: `${btnDarkColor} 0 0 3px 1px`,
background: btnDarkColor,
color: theme.colors.white,
},
};
});
export default Button;

View File

@@ -1,10 +1,10 @@
import styled from '@emotion/styled';
const Form = styled.form({
width: '100%',
display: 'flex',
gap: '1em',
flexDirection: 'column',
width: '100%',
display: 'flex',
gap: '1em',
flexDirection: 'column',
});
export default Form;

View File

@@ -1,25 +1,25 @@
import styled from '@emotion/styled';
const FormField = styled('div', {
shouldForwardProp: (propName) => propName !== 'required',
shouldForwardProp: (propName) => propName !== 'required',
})<{ required?: boolean }>(({ required, theme }) => ({
display: 'flex',
gap: '0.25em',
flexDirection: 'column',
display: 'flex',
gap: '0.25em',
flexDirection: 'column',
'& label': {
position: 'relative',
userSelect: 'none',
width: 'fit-content',
},
'& label': {
position: 'relative',
userSelect: 'none',
width: 'fit-content',
},
'& label::after': {
position: 'absolute',
top: 0,
right: '-0.75em',
color: theme.colors.lightRed,
content: (required ? '"*"' : '""') as any,
},
'& label::after': {
position: 'absolute',
top: 0,
right: '-0.75em',
color: theme.colors.lightRed,
content: (required ? '"*"' : '""') as any,
},
}));
export default FormField;

View File

@@ -2,8 +2,8 @@ import styled from '@emotion/styled';
// TODO: create a global style variable (fontSize)
const FormFieldError = styled.p(({ theme }) => ({
fontSize: '12px',
color: theme.colors.lightRed,
fontSize: '12px',
color: theme.colors.lightRed,
}));
export default FormFieldError;

View File

@@ -1,27 +1,27 @@
import styled from '@emotion/styled';
const Input = styled.input(({ theme }) => ({
width: '100%',
color: theme.colors.font,
backgroundColor: theme.colors.secondary,
padding: '0.75em',
border: `1px solid ${theme.colors.lightGrey}`,
borderBottom: `2px solid ${theme.colors.lightGrey}`,
borderRadius: theme.border.radius,
transition: theme.transition.delay,
width: '100%',
color: theme.colors.font,
backgroundColor: theme.colors.secondary,
padding: '0.75em',
border: `1px solid ${theme.colors.lightGrey}`,
borderBottom: `2px solid ${theme.colors.lightGrey}`,
borderRadius: theme.border.radius,
transition: theme.transition.delay,
'&:focus': {
borderBottom: `2px solid ${theme.colors.primary}`,
},
'&:focus': {
borderBottom: `2px solid ${theme.colors.primary}`,
},
'&:disabled': {
opacity: 0.85,
},
'&:disabled': {
opacity: 0.85,
},
'&::placeholder': {
fontStyle: 'italic',
color: theme.colors.grey,
},
'&::placeholder': {
fontStyle: 'italic',
color: theme.colors.grey,
},
}));
export default Input;

View File

@@ -4,52 +4,52 @@ import FormField from '~/components/common/form/_form_field';
import FormFieldError from '~/components/common/form/_form_field_error';
interface InputProps
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
label: string;
name: string;
checked: boolean;
errors?: string[];
onChange?: (name: string, checked: boolean) => void;
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
label: string;
name: string;
checked: boolean;
errors?: string[];
onChange?: (name: string, checked: boolean) => void;
}
export default function Checkbox({
name,
label,
checked = false,
errors = [],
onChange,
required = false,
...props
name,
label,
checked = false,
errors = [],
onChange,
required = false,
...props
}: InputProps): JSX.Element {
const [checkboxChecked, setCheckboxChecked] = useState<boolean>(checked);
const [checkboxChecked, setCheckboxChecked] = useState<boolean>(checked);
if (typeof window === 'undefined') return <Fragment />;
if (typeof window === 'undefined') return <Fragment />;
function _onChange({ target }: ChangeEvent<HTMLInputElement>) {
setCheckboxChecked(target.checked);
if (onChange) {
onChange(target.name, target.checked);
}
}
function _onChange({ target }: ChangeEvent<HTMLInputElement>) {
setCheckboxChecked(target.checked);
if (onChange) {
onChange(target.name, target.checked);
}
}
return (
<FormField
css={{ alignItems: 'center', gap: '1em', flexDirection: 'row' }}
required={required}
>
<label htmlFor={name} title={label}>
{label}
</label>
<Toggle
{...props}
onChange={_onChange}
checked={checkboxChecked}
placeholder={props.placeholder ?? 'Type something...'}
name={name}
id={name}
/>
{errors.length > 0 &&
errors.map((error) => <FormFieldError>{error}</FormFieldError>)}
</FormField>
);
return (
<FormField
css={{ alignItems: 'center', gap: '1em', flexDirection: 'row' }}
required={required}
>
<label htmlFor={name} title={label}>
{label}
</label>
<Toggle
{...props}
onChange={_onChange}
checked={checkboxChecked}
placeholder={props.placeholder ?? 'Type something...'}
name={name}
id={name}
/>
{errors.length > 0 &&
errors.map((error) => <FormFieldError>{error}</FormFieldError>)}
</FormField>
);
}

View File

@@ -1,79 +1,79 @@
import { useTheme } from '@emotion/react';
import { InputHTMLAttributes, ReactNode, useEffect, useState } from 'react';
import Select, {
FormatOptionLabelMeta,
GroupBase,
OptionsOrGroups,
FormatOptionLabelMeta,
GroupBase,
OptionsOrGroups,
} from 'react-select';
import FormField from '~/components/common/form/_form_field';
type Option = { label: string | number; value: string | number };
interface SelectorProps
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
label: string;
name: string;
errors?: string[];
options: OptionsOrGroups<Option, GroupBase<Option>>;
value: number | string;
onChangeCallback?: (value: number | string) => void;
formatOptionLabel?: (
data: Option,
formatOptionLabelMeta: FormatOptionLabelMeta<Option>
) => ReactNode;
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
label: string;
name: string;
errors?: string[];
options: OptionsOrGroups<Option, GroupBase<Option>>;
value: number | string;
onChangeCallback?: (value: number | string) => void;
formatOptionLabel?: (
data: Option,
formatOptionLabelMeta: FormatOptionLabelMeta<Option>
) => ReactNode;
}
export default function Selector({
name,
label,
value,
errors = [],
options,
onChangeCallback,
formatOptionLabel,
required = false,
...props
name,
label,
value,
errors = [],
options,
onChangeCallback,
formatOptionLabel,
required = false,
...props
}: SelectorProps): JSX.Element {
const theme = useTheme();
const [selectorValue, setSelectorValue] = useState<Option>();
const theme = useTheme();
const [selectorValue, setSelectorValue] = useState<Option>();
useEffect(() => {
if (options.length === 0) return;
useEffect(() => {
if (options.length === 0) return;
const option = options.find((o: any) => o.value === value);
if (option) {
setSelectorValue(option as Option);
}
}, [options, value]);
const option = options.find((o: any) => o.value === value);
if (option) {
setSelectorValue(option as Option);
}
}, [options, value]);
const handleChange = (selectedOption: Option) => {
setSelectorValue(selectedOption);
if (onChangeCallback) {
onChangeCallback(selectedOption.value);
}
};
const handleChange = (selectedOption: Option) => {
setSelectorValue(selectedOption);
if (onChangeCallback) {
onChangeCallback(selectedOption.value);
}
};
return (
<FormField required={required}>
{label && (
<label htmlFor={name} title={`${name} field`}>
{label}
</label>
)}
<Select
value={selectorValue}
onChange={(newValue) => handleChange(newValue as Option)}
options={options}
isDisabled={props.disabled}
menuPlacement="auto"
formatOptionLabel={
formatOptionLabel
? (val, formatOptionLabelMeta) =>
formatOptionLabel(val, formatOptionLabelMeta)
: undefined
}
css={{ color: theme.colors.black }}
/>
</FormField>
);
return (
<FormField required={required}>
{label && (
<label htmlFor={name} title={`${name} field`}>
{label}
</label>
)}
<Select
value={selectorValue}
onChange={(newValue) => handleChange(newValue as Option)}
options={options}
isDisabled={props.disabled}
menuPlacement="auto"
formatOptionLabel={
formatOptionLabel
? (val, formatOptionLabelMeta) =>
formatOptionLabel(val, formatOptionLabelMeta)
: undefined
}
css={{ color: theme.colors.black }}
/>
</FormField>
);
}

View File

@@ -4,46 +4,46 @@ import FormFieldError from '~/components/common/form/_form_field_error';
import Input from '~/components/common/form/_input';
interface InputProps
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
label: string;
name: string;
value?: string;
errors?: string[];
onChange?: (name: string, value: string) => void;
extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
label: string;
name: string;
value?: string;
errors?: string[];
onChange?: (name: string, value: string) => void;
}
export default function TextBox({
name,
label,
value = '',
errors = [],
onChange,
required = false,
...props
name,
label,
value = '',
errors = [],
onChange,
required = false,
...props
}: InputProps): JSX.Element {
const [inputValue, setInputValue] = useState<string>(value);
const [inputValue, setInputValue] = useState<string>(value);
function _onChange({ target }: ChangeEvent<HTMLInputElement>) {
setInputValue(target.value);
if (onChange) {
onChange(target.name, target.value);
}
}
function _onChange({ target }: ChangeEvent<HTMLInputElement>) {
setInputValue(target.value);
if (onChange) {
onChange(target.name, target.value);
}
}
return (
<FormField required={required}>
<label htmlFor={name} title={label}>
{label}
</label>
<Input
{...props}
name={name}
onChange={_onChange}
value={inputValue}
placeholder={props.placeholder ?? 'Type something...'}
/>
{errors.length > 0 &&
errors.map((error) => <FormFieldError>{error}</FormFieldError>)}
</FormField>
);
return (
<FormField required={required}>
<label htmlFor={name} title={label}>
{label}
</label>
<Input
{...props}
name={name}
onChange={_onChange}
value={inputValue}
placeholder={props.placeholder ?? 'Type something...'}
/>
{errors.length > 0 &&
errors.map((error) => <FormFieldError>{error}</FormFieldError>)}
</FormField>
);
}

View File

@@ -1,22 +1,22 @@
import styled from '@emotion/styled';
const IconButton = styled.button(({ theme }) => ({
cursor: 'pointer',
height: '2rem',
width: '2rem',
fontSize: '1rem',
color: theme.colors.font,
backgroundColor: theme.colors.grey,
borderRadius: '50%',
border: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
cursor: 'pointer',
height: '2rem',
width: '2rem',
fontSize: '1rem',
color: theme.colors.font,
backgroundColor: theme.colors.grey,
borderRadius: '50%',
border: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
'&:disabled': {
cursor: 'not-allowed',
opacity: 0.15,
},
'&:disabled': {
cursor: 'not-allowed',
opacity: 0.15,
},
}));
export default IconButton;

View File

@@ -1,8 +1,8 @@
import styled from '@emotion/styled';
const Legend = styled.span(({ theme }) => ({
fontSize: '13px',
color: theme.colors.grey,
fontSize: '13px',
color: theme.colors.grey,
}));
export default Legend;

View File

@@ -1,11 +1,11 @@
import styled from '@emotion/styled';
const ModalBody = styled.div({
width: '100%',
display: 'flex',
flex: 1,
alignItems: 'center',
flexDirection: 'column',
width: '100%',
display: 'flex',
flex: 1,
alignItems: 'center',
flexDirection: 'column',
});
export default ModalBody;

View File

@@ -2,23 +2,23 @@ import styled from '@emotion/styled';
import TransitionLayout from '~/components/layouts/_transition_layout';
const ModalContainer = styled(TransitionLayout)(({ theme }) => ({
minWidth: '500px',
background: theme.colors.background,
padding: '1em',
borderRadius: theme.border.radius,
marginTop: '6em',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
boxShadow: theme.colors.boxShadow,
minWidth: '500px',
background: theme.colors.background,
padding: '1em',
borderRadius: theme.border.radius,
marginTop: '6em',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
boxShadow: theme.colors.boxShadow,
[`@media (max-width: ${theme.media.mobile})`]: {
maxHeight: 'calc(100% - 2em)',
width: 'calc(100% - 2em)',
minWidth: 'unset',
marginTop: '1em',
},
[`@media (max-width: ${theme.media.mobile})`]: {
maxHeight: 'calc(100% - 2em)',
width: 'calc(100% - 2em)',
minWidth: 'unset',
marginTop: '1em',
},
}));
export default ModalContainer;

View File

@@ -1,20 +1,20 @@
import styled from '@emotion/styled';
const ModalHeader = styled.h3({
width: '100%',
marginBottom: '0.75em',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
width: '100%',
marginBottom: '0.75em',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
});
const ModalCloseBtn = styled.button(({ theme }) => ({
cursor: 'pointer',
color: theme.colors.primary,
backgroundColor: 'transparent',
border: 0,
padding: 0,
margin: 0,
cursor: 'pointer',
color: theme.colors.primary,
backgroundColor: 'transparent',
border: 0,
padding: 0,
margin: 0,
}));
export { ModalHeader, ModalCloseBtn };

View File

@@ -2,18 +2,18 @@ import styled from '@emotion/styled';
import { rgba } from '~/lib/color';
const ModalWrapper = styled.div(({ theme }) => ({
zIndex: 9999,
position: 'absolute',
top: 0,
left: 0,
height: '100%',
width: '100%',
background: rgba(theme.colors.black, 0.35),
backdropFilter: 'blur(0.1em)',
display: 'flex',
alignItems: 'center',
flexDirection: 'column',
transition: theme.transition.delay,
zIndex: 9999,
position: 'absolute',
top: 0,
left: 0,
height: '100%',
width: '100%',
background: rgba(theme.colors.black, 0.35),
backdropFilter: 'blur(0.1em)',
display: 'flex',
alignItems: 'center',
flexDirection: 'column',
transition: theme.transition.delay,
}));
export default ModalWrapper;

View File

@@ -4,8 +4,8 @@ import { IoClose } from 'react-icons/io5';
import ModalBody from '~/components/common/modal/_modal_body';
import ModalContainer from '~/components/common/modal/_modal_container';
import {
ModalCloseBtn,
ModalHeader,
ModalCloseBtn,
ModalHeader,
} from '~/components/common/modal/_modal_header';
import ModalWrapper from '~/components/common/modal/_modal_wrapper';
import TextEllipsis from '~/components/common/text_ellipsis';
@@ -14,54 +14,54 @@ import useGlobalHotkeys from '~/hooks/use_global_hotkeys';
import useShortcut from '~/hooks/use_shortcut';
interface ModalProps {
title?: string;
children: ReactNode;
opened: boolean;
hideCloseBtn?: boolean;
className?: string;
title?: string;
children: ReactNode;
opened: boolean;
hideCloseBtn?: boolean;
className?: string;
close: () => void;
close: () => void;
}
export default function Modal({
title,
children,
opened = true,
hideCloseBtn = false,
className,
close,
title,
children,
opened = true,
hideCloseBtn = false,
className,
close,
}: ModalProps) {
const modalRef = useRef<HTMLDivElement>(null);
const { setGlobalHotkeysEnabled } = useGlobalHotkeys();
const modalRef = useRef<HTMLDivElement>(null);
const { setGlobalHotkeysEnabled } = useGlobalHotkeys();
useClickOutside(modalRef, close);
useShortcut('ESCAPE_KEY', close, { disableGlobalCheck: true });
useClickOutside(modalRef, close);
useShortcut('ESCAPE_KEY', close, { disableGlobalCheck: true });
useEffect(() => setGlobalHotkeysEnabled(!opened), [opened]);
useEffect(() => setGlobalHotkeysEnabled(!opened), [opened]);
if (typeof window === 'undefined') {
return <Fragment />;
}
if (typeof window === 'undefined') {
return <Fragment />;
}
return (
opened &&
createPortal(
<ModalWrapper>
<ModalContainer className={className} ref={modalRef}>
{(!hideCloseBtn || title) && (
<ModalHeader>
{title && <TextEllipsis>{title}</TextEllipsis>}
{!hideCloseBtn && (
<ModalCloseBtn onClick={close}>
<IoClose size={20} />
</ModalCloseBtn>
)}
</ModalHeader>
)}
<ModalBody>{children}</ModalBody>
</ModalContainer>
</ModalWrapper>,
document.body
)
);
return (
opened &&
createPortal(
<ModalWrapper>
<ModalContainer className={className} ref={modalRef}>
{(!hideCloseBtn || title) && (
<ModalHeader>
{title && <TextEllipsis>{title}</TextEllipsis>}
{!hideCloseBtn && (
<ModalCloseBtn onClick={close}>
<IoClose size={20} />
</ModalCloseBtn>
)}
</ModalHeader>
)}
<ModalBody>{children}</ModalBody>
</ModalContainer>
</ModalWrapper>,
document.body
)
);
}

View File

@@ -6,12 +6,12 @@ import useShortcut from '~/hooks/use_shortcut';
import { appendCollectionId } from '~/lib/navigation';
export default function BackToDashboard({ children }: { children: ReactNode }) {
const collectionId = Number(useSearchParam('collectionId'));
useShortcut(
'ESCAPE_KEY',
() =>
router.visit(appendCollectionId(route('dashboard').url, collectionId)),
{ disableGlobalCheck: true }
);
return <>{children}</>;
const collectionId = Number(useSearchParam('collectionId'));
useShortcut(
'ESCAPE_KEY',
() =>
router.visit(appendCollectionId(route('dashboard').url, collectionId)),
{ disableGlobalCheck: true }
);
return <>{children}</>;
}

View File

@@ -2,14 +2,14 @@ import styled from '@emotion/styled';
import { rgba } from '~/lib/color';
const RoundedImage = styled.img(({ theme }) => {
const transparentBlack = rgba(theme.colors.black, 0.1);
return {
borderRadius: '50%',
const transparentBlack = rgba(theme.colors.black, 0.1);
return {
borderRadius: '50%',
'&:hover': {
boxShadow: `0 1px 3px 0 ${transparentBlack}, 0 1px 2px -1px ${transparentBlack}`,
},
};
'&:hover': {
boxShadow: `0 1px 3px 0 ${transparentBlack}, 0 1px 2px -1px ${transparentBlack}`,
},
};
});
export default RoundedImage;

View File

@@ -1,218 +1,218 @@
import styled from '@emotion/styled';
import {
ColumnDef,
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
PaginationState,
useReactTable,
ColumnDef,
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
PaginationState,
useReactTable,
} from '@tanstack/react-table';
import { useState } from 'react';
import IconButton from '~/components/common/icon_button';
import {
MdKeyboardArrowLeft,
MdKeyboardArrowRight,
MdKeyboardDoubleArrowLeft,
MdKeyboardDoubleArrowRight,
MdKeyboardArrowLeft,
MdKeyboardArrowRight,
MdKeyboardDoubleArrowLeft,
MdKeyboardDoubleArrowRight,
} from 'react-icons/md';
import Input from '~/components/common/form/_input';
const TablePageFooter = styled.div({
display: 'flex',
gap: '1em',
alignItems: 'center',
display: 'flex',
gap: '1em',
alignItems: 'center',
});
const Box = styled(TablePageFooter)({
gap: '0.35em',
gap: '0.35em',
});
const Resizer = styled.div<{ isResizing: boolean }>(
({ theme, isResizing }) => ({
cursor: 'col-resize',
userSelect: 'none',
touchAction: 'none',
position: 'absolute',
right: 0,
top: 0,
height: '100%',
width: '5px',
opacity: !isResizing ? 0 : 1,
background: !isResizing ? theme.colors.white : theme.colors.primary,
'&:hover': {
opacity: 0.5,
},
})
({ theme, isResizing }) => ({
cursor: 'col-resize',
userSelect: 'none',
touchAction: 'none',
position: 'absolute',
right: 0,
top: 0,
height: '100%',
width: '5px',
opacity: !isResizing ? 0 : 1,
background: !isResizing ? theme.colors.white : theme.colors.primary,
'&:hover': {
opacity: 0.5,
},
})
);
type TableProps<T> = {
columns: ColumnDef<T>[];
data: T[];
columns: ColumnDef<T>[];
data: T[];
};
export default function Table<T>({ columns, data }: TableProps<T>) {
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});
const table = useReactTable({
data,
columns,
enableColumnResizing: true,
columnResizeMode: 'onChange',
state: {
pagination,
},
onPaginationChange: setPagination,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
debugTable: true,
});
const table = useReactTable({
data,
columns,
enableColumnResizing: true,
columnResizeMode: 'onChange',
state: {
pagination,
},
onPaginationChange: setPagination,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
debugTable: true,
});
return (
<div css={{ fontSize: '0.9rem', paddingBlock: '1em' }}>
<div
css={{
maxWidth: '100%',
marginBottom: '1em',
display: 'block',
overflowX: 'auto',
overflowY: 'hidden',
}}
>
<table>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th
key={header.id}
style={{
width: header.getSize(),
}}
css={{
position: 'relative',
userSelect: 'none',
// resizer
'&:hover > div > div': {
opacity: 0.5,
},
}}
colSpan={header.colSpan}
>
{header.isPlaceholder ? null : (
<div
css={{
cursor: header.column.getCanSort()
? 'pointer'
: 'default',
}}
onClick={header.column.getToggleSortingHandler()}
title={
header.column.getCanSort()
? header.column.getNextSortingOrder() === 'asc'
? 'Sort ascending'
: header.column.getNextSortingOrder() === 'desc'
? 'Sort descending'
: 'Clear sort'
: undefined
}
>
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
{{
asc: ' 🔼',
desc: ' 🔽',
}[header.column.getIsSorted() as string] ?? null}
{header.column.getCanResize() && (
<Resizer
onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()}
isResizing={header.column.getIsResizing()}
/>
)}
</div>
)}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table
.getRowModel()
.rows.slice(0, 10)
.map((row) => (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} style={{ width: cell.column.getSize() }}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
{table.getPageCount() > 1 && (
<TablePageFooter>
<Box>
<IconButton
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<MdKeyboardDoubleArrowLeft />
</IconButton>
<IconButton
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<MdKeyboardArrowLeft />
</IconButton>
<IconButton
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<MdKeyboardArrowRight />
</IconButton>
<IconButton
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<MdKeyboardDoubleArrowRight />
</IconButton>
</Box>
<Box>
<span>Page</span>
<strong>
{table.getState().pagination.pageIndex + 1} of{' '}
{table.getPageCount()}
</strong>
</Box>
<Box>
Go to page
<Input
type="number"
min="1"
max={table.getPageCount()}
defaultValue={table.getState().pagination.pageIndex + 1}
onChange={(e) => {
const page = e.target.value ? Number(e.target.value) - 1 : 0;
table.setPageIndex(page);
}}
/>
</Box>
</TablePageFooter>
)}
</div>
);
return (
<div css={{ fontSize: '0.9rem', paddingBlock: '1em' }}>
<div
css={{
maxWidth: '100%',
marginBottom: '1em',
display: 'block',
overflowX: 'auto',
overflowY: 'hidden',
}}
>
<table>
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th
key={header.id}
style={{
width: header.getSize(),
}}
css={{
position: 'relative',
userSelect: 'none',
// resizer
'&:hover > div > div': {
opacity: 0.5,
},
}}
colSpan={header.colSpan}
>
{header.isPlaceholder ? null : (
<div
css={{
cursor: header.column.getCanSort()
? 'pointer'
: 'default',
}}
onClick={header.column.getToggleSortingHandler()}
title={
header.column.getCanSort()
? header.column.getNextSortingOrder() === 'asc'
? 'Sort ascending'
: header.column.getNextSortingOrder() === 'desc'
? 'Sort descending'
: 'Clear sort'
: undefined
}
>
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
{{
asc: ' 🔼',
desc: ' 🔽',
}[header.column.getIsSorted() as string] ?? null}
{header.column.getCanResize() && (
<Resizer
onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()}
isResizing={header.column.getIsResizing()}
/>
)}
</div>
)}
</th>
))}
</tr>
))}
</thead>
<tbody>
{table
.getRowModel()
.rows.slice(0, 10)
.map((row) => (
<tr key={row.id}>
{row.getVisibleCells().map((cell) => (
<td key={cell.id} style={{ width: cell.column.getSize() }}>
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
{table.getPageCount() > 1 && (
<TablePageFooter>
<Box>
<IconButton
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
>
<MdKeyboardDoubleArrowLeft />
</IconButton>
<IconButton
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<MdKeyboardArrowLeft />
</IconButton>
<IconButton
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<MdKeyboardArrowRight />
</IconButton>
<IconButton
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
>
<MdKeyboardDoubleArrowRight />
</IconButton>
</Box>
<Box>
<span>Page</span>
<strong>
{table.getState().pagination.pageIndex + 1} of{' '}
{table.getPageCount()}
</strong>
</Box>
<Box>
Go to page
<Input
type="number"
min="1"
max={table.getPageCount()}
defaultValue={table.getState().pagination.pageIndex + 1}
onChange={(e) => {
const page = e.target.value ? Number(e.target.value) - 1 : 0;
table.setPageIndex(page);
}}
/>
</Box>
</TablePageFooter>
)}
</div>
);
}

View File

@@ -2,23 +2,23 @@ import styled from '@emotion/styled';
import { rgba } from '~/lib/color';
const TabItem = styled.li<{ active?: boolean; danger?: boolean }>(
({ theme, active, danger }) => {
const activeColor = !danger ? theme.colors.primary : theme.colors.lightRed;
return {
userSelect: 'none',
cursor: 'pointer',
backgroundColor: active
? rgba(activeColor, 0.15)
: theme.colors.secondary,
padding: '10px 20px',
border: `1px solid ${active ? rgba(activeColor, 0.1) : theme.colors.secondary}`,
borderBottom: `1px solid ${active ? rgba(activeColor, 0.25) : theme.colors.secondary}`,
display: 'flex',
gap: '0.35em',
alignItems: 'center',
transition: '.075s',
};
}
({ theme, active, danger }) => {
const activeColor = !danger ? theme.colors.primary : theme.colors.lightRed;
return {
userSelect: 'none',
cursor: 'pointer',
backgroundColor: active
? rgba(activeColor, 0.15)
: theme.colors.secondary,
padding: '10px 20px',
border: `1px solid ${active ? rgba(activeColor, 0.1) : theme.colors.secondary}`,
borderBottom: `1px solid ${active ? rgba(activeColor, 0.25) : theme.colors.secondary}`,
display: 'flex',
gap: '0.35em',
alignItems: 'center',
transition: '.075s',
};
}
);
export default TabItem;

View File

@@ -1,10 +1,10 @@
import styled from '@emotion/styled';
const TabList = styled.ul({
padding: 0,
margin: 0,
display: 'flex',
listStyle: 'none',
padding: 0,
margin: 0,
display: 'flex',
listStyle: 'none',
});
export default TabList;

View File

@@ -2,11 +2,11 @@ import styled from '@emotion/styled';
import { rgba } from '~/lib/color';
const TabPanel = styled.div(({ theme }) => ({
zIndex: 1,
position: 'relative',
border: `1px solid ${rgba(theme.colors.primary, 0.25)}`,
padding: '20px',
marginTop: '-1px',
zIndex: 1,
position: 'relative',
border: `1px solid ${rgba(theme.colors.primary, 0.25)}`,
padding: '20px',
marginTop: '-1px',
}));
export default TabPanel;

View File

@@ -6,37 +6,37 @@ import TabPanel from '~/components/common/tabs/tab_panel';
import TransitionLayout from '~/components/layouts/_transition_layout';
export interface Tab {
title: string;
content: ReactNode;
icon?: IconType;
danger?: boolean;
title: string;
content: ReactNode;
icon?: IconType;
danger?: boolean;
}
export default function Tabs({ tabs }: { tabs: Tab[] }) {
const [activeTabIndex, setActiveTabIndex] = useState<number>(0);
const [activeTabIndex, setActiveTabIndex] = useState<number>(0);
const handleTabClick = (index: number) => {
setActiveTabIndex(index);
};
const handleTabClick = (index: number) => {
setActiveTabIndex(index);
};
return (
<div css={{ width: '100%' }}>
<TabList>
{tabs.map(({ title, icon: Icon, danger }, index) => (
<TabItem
key={index}
active={index === activeTabIndex}
onClick={() => handleTabClick(index)}
danger={danger ?? false}
>
{!!Icon && <Icon size={20} />}
{title}
</TabItem>
))}
</TabList>
<TabPanel key={tabs[activeTabIndex].title}>
<TransitionLayout>{tabs[activeTabIndex].content}</TransitionLayout>
</TabPanel>
</div>
);
return (
<div css={{ width: '100%' }}>
<TabList>
{tabs.map(({ title, icon: Icon, danger }, index) => (
<TabItem
key={index}
active={index === activeTabIndex}
onClick={() => handleTabClick(index)}
danger={danger ?? false}
>
{!!Icon && <Icon size={20} />}
{title}
</TabItem>
))}
</TabList>
<TabPanel key={tabs[activeTabIndex].title}>
<TransitionLayout>{tabs[activeTabIndex].content}</TransitionLayout>
</TabPanel>
</div>
);
}

View File

@@ -1,20 +1,20 @@
import styled from '@emotion/styled';
const TextEllipsis = styled.p<{ lines?: number }>(({ lines = 1 }) => {
if (lines > 1) {
return {
overflow: 'hidden',
display: '-webkit-box',
WebkitLineClamp: lines,
WebkitBoxOrient: 'vertical',
};
}
if (lines > 1) {
return {
overflow: 'hidden',
display: '-webkit-box',
WebkitLineClamp: lines,
WebkitBoxOrient: 'vertical',
};
}
return {
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
};
return {
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
};
});
export default TextEllipsis;

View File

@@ -1,12 +1,12 @@
import styled from '@emotion/styled';
const UnstyledList = styled.ul({
'&, & li': {
listStyleType: 'none',
margin: 0,
padding: 0,
border: 0,
},
'&, & li': {
listStyleType: 'none',
margin: 0,
padding: 0,
border: 0,
},
});
export default UnstyledList;

View File

@@ -7,33 +7,33 @@ import Footer from '~/components/footer/footer';
import useActiveCollection from '~/hooks/use_active_collection';
export interface CollectionHeaderProps {
showButtons: boolean;
showControls?: boolean;
openNavigationItem?: ReactNode;
openCollectionItem?: ReactNode;
showButtons: boolean;
showControls?: boolean;
openNavigationItem?: ReactNode;
openCollectionItem?: ReactNode;
}
const CollectionContainerStyle = styled.div({
height: '100%',
minWidth: 0,
padding: '0.5em 0.5em 0',
display: 'flex',
flex: 1,
flexDirection: 'column',
height: '100%',
minWidth: 0,
padding: '0.5em 0.5em 0',
display: 'flex',
flex: 1,
flexDirection: 'column',
});
export default function CollectionContainer(props: CollectionHeaderProps) {
const { activeCollection } = useActiveCollection();
const { activeCollection } = useActiveCollection();
if (activeCollection === null) {
return <NoCollection />;
}
if (activeCollection === null) {
return <NoCollection />;
}
return (
<CollectionContainerStyle>
<CollectionHeader {...props} />
<LinkList links={activeCollection.links} />
<Footer css={{ paddingBottom: 0 }} />
</CollectionContainerStyle>
);
return (
<CollectionContainerStyle>
<CollectionHeader {...props} />
<LinkList links={activeCollection.links} />
<Footer css={{ paddingBottom: 0 }} />
</CollectionContainerStyle>
);
}

View File

@@ -10,33 +10,33 @@ import { appendCollectionId } from '~/lib/navigation';
import { Collection } from '~/types/app';
export default function CollectionControls({
collectionId,
collectionId,
}: {
collectionId: Collection['id'];
collectionId: Collection['id'];
}) {
const { t } = useTranslation('common');
return (
<Dropdown label={<BsThreeDotsVertical />} svgSize={18}>
<DropdownItemLink href={route('link.create-form').url}>
<IoIosAddCircleOutline /> {t('link.create')}
</DropdownItemLink>
<DropdownItemLink
href={appendCollectionId(
route('collection.edit-form').url,
collectionId
)}
>
<GoPencil /> {t('collection.edit')}
</DropdownItemLink>
<DropdownItemLink
href={appendCollectionId(
route('collection.delete-form').url,
collectionId
)}
danger
>
<IoTrashOutline /> {t('collection.delete')}
</DropdownItemLink>
</Dropdown>
);
const { t } = useTranslation('common');
return (
<Dropdown label={<BsThreeDotsVertical />} svgSize={18}>
<DropdownItemLink href={route('link.create-form').url}>
<IoIosAddCircleOutline /> {t('link.create')}
</DropdownItemLink>
<DropdownItemLink
href={appendCollectionId(
route('collection.edit-form').url,
collectionId
)}
>
<GoPencil /> {t('collection.edit')}
</DropdownItemLink>
<DropdownItemLink
href={appendCollectionId(
route('collection.delete-form').url,
collectionId
)}
danger
>
<IoTrashOutline /> {t('collection.delete')}
</DropdownItemLink>
</Dropdown>
);
}

View File

@@ -3,16 +3,16 @@ import TextEllipsis from '~/components/common/text_ellipsis';
import useActiveCollection from '~/hooks/use_active_collection';
const CollectionDescriptionStyle = styled.div({
width: '100%',
fontSize: '0.85rem',
marginBottom: '0.5rem',
width: '100%',
fontSize: '0.85rem',
marginBottom: '0.5rem',
});
export default function CollectionDescription() {
const { activeCollection } = useActiveCollection();
return (
<CollectionDescriptionStyle>
<TextEllipsis lines={3}>{activeCollection!.description}</TextEllipsis>
</CollectionDescriptionStyle>
);
const { activeCollection } = useActiveCollection();
return (
<CollectionDescriptionStyle>
<TextEllipsis lines={3}>{activeCollection!.description}</TextEllipsis>
</CollectionDescriptionStyle>
);
}

View File

@@ -12,76 +12,76 @@ const paddingLeft = '1.25em';
const paddingRight = '1.65em';
const CollectionHeaderWrapper = styled.div(({ theme }) => ({
minWidth: 0,
width: '100%',
paddingInline: `${paddingLeft} ${paddingRight}`,
marginBottom: '0.5em',
minWidth: 0,
width: '100%',
paddingInline: `${paddingLeft} ${paddingRight}`,
marginBottom: '0.5em',
[`@media (max-width: ${theme.media.tablet})`]: {
paddingInline: 0,
marginBottom: '1rem',
},
[`@media (max-width: ${theme.media.tablet})`]: {
paddingInline: 0,
marginBottom: '1rem',
},
}));
const CollectionHeaderStyle = styled.div({
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
'& > svg': {
display: 'flex',
},
'& > svg': {
display: 'flex',
},
});
const CollectionName = styled.h2(({ theme }) => ({
width: `calc(100% - (${paddingLeft} + ${paddingRight}))`,
color: theme.colors.primary,
display: 'flex',
gap: '0.35em',
alignItems: 'center',
width: `calc(100% - (${paddingLeft} + ${paddingRight}))`,
color: theme.colors.primary,
display: 'flex',
gap: '0.35em',
alignItems: 'center',
[`@media (max-width: ${theme.media.tablet})`]: {
width: `calc(100% - (${paddingLeft} + ${paddingRight} + 1.75em))`,
},
[`@media (max-width: ${theme.media.tablet})`]: {
width: `calc(100% - (${paddingLeft} + ${paddingRight} + 1.75em))`,
},
}));
const LinksCount = styled.div(({ theme }) => ({
minWidth: 'fit-content',
fontWeight: 300,
fontSize: '0.8em',
color: theme.colors.grey,
minWidth: 'fit-content',
fontWeight: 300,
fontSize: '0.8em',
color: theme.colors.grey,
}));
export default function CollectionHeader({
showButtons,
showControls = true,
openNavigationItem,
openCollectionItem,
showButtons,
showControls = true,
openNavigationItem,
openCollectionItem,
}: CollectionHeaderProps) {
const { t } = useTranslation('common');
const { activeCollection } = useActiveCollection();
const { t } = useTranslation('common');
const { activeCollection } = useActiveCollection();
if (!activeCollection) return <Fragment />;
if (!activeCollection) return <Fragment />;
const { name, links, visibility } = activeCollection;
return (
<CollectionHeaderWrapper>
<CollectionHeaderStyle>
{showButtons && openNavigationItem && openNavigationItem}
<CollectionName title={name}>
<TextEllipsis>{name}</TextEllipsis>
{links.length > 0 && <LinksCount> {links.length}</LinksCount>}
<VisibilityBadge
label={t('collection.visibility')}
visibility={visibility}
/>
</CollectionName>
{showControls && (
<CollectionControls collectionId={activeCollection.id} />
)}
{showButtons && openCollectionItem && openCollectionItem}
</CollectionHeaderStyle>
{activeCollection.description && <CollectionDescription />}
</CollectionHeaderWrapper>
);
const { name, links, visibility } = activeCollection;
return (
<CollectionHeaderWrapper>
<CollectionHeaderStyle>
{showButtons && openNavigationItem && openNavigationItem}
<CollectionName title={name}>
<TextEllipsis>{name}</TextEllipsis>
{links.length > 0 && <LinksCount> {links.length}</LinksCount>}
<VisibilityBadge
label={t('collection.visibility')}
visibility={visibility}
/>
</CollectionName>
{showControls && (
<CollectionControls collectionId={activeCollection.id} />
)}
{showButtons && openCollectionItem && openCollectionItem}
</CollectionHeaderStyle>
{activeCollection.description && <CollectionDescription />}
</CollectionHeaderWrapper>
);
}

View File

@@ -10,48 +10,48 @@ import { appendCollectionId } from '~/lib/navigation';
import { CollectionWithLinks } from '~/types/app';
const CollectionItemStyle = styled(Item, {
shouldForwardProp: (propName) => propName !== 'isActive',
shouldForwardProp: (propName) => propName !== 'isActive',
})<{ isActive: boolean }>(({ theme, isActive }) => ({
cursor: 'pointer',
color: isActive ? theme.colors.primary : theme.colors.font,
backgroundColor: theme.colors.secondary,
cursor: 'pointer',
color: isActive ? theme.colors.primary : theme.colors.font,
backgroundColor: theme.colors.secondary,
}));
const CollectionItemLink = CollectionItemStyle.withComponent(Link);
const LinksCount = styled.div(({ theme }) => ({
minWidth: 'fit-content',
fontWeight: 300,
fontSize: '0.9rem',
color: theme.colors.grey,
minWidth: 'fit-content',
fontWeight: 300,
fontSize: '0.9rem',
color: theme.colors.grey,
}));
export default function CollectionItem({
collection,
collection,
}: {
collection: CollectionWithLinks;
collection: CollectionWithLinks;
}) {
const itemRef = useRef<HTMLDivElement>(null);
const { activeCollection } = useActiveCollection();
const isActiveCollection = collection.id === activeCollection?.id;
const FolderIcon = isActiveCollection ? AiFillFolderOpen : AiOutlineFolder;
const itemRef = useRef<HTMLDivElement>(null);
const { activeCollection } = useActiveCollection();
const isActiveCollection = collection.id === activeCollection?.id;
const FolderIcon = isActiveCollection ? AiFillFolderOpen : AiOutlineFolder;
useEffect(() => {
if (collection.id === activeCollection?.id) {
itemRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
}, [collection.id, activeCollection?.id]);
useEffect(() => {
if (collection.id === activeCollection?.id) {
itemRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
}, [collection.id, activeCollection?.id]);
return (
<CollectionItemLink
href={appendCollectionId(route('dashboard').url, collection.id)}
isActive={isActiveCollection}
ref={itemRef}
>
<FolderIcon css={{ minWidth: '24px' }} size={24} />
<TextEllipsis>{collection.name}</TextEllipsis>
{collection.links.length > 0 && (
<LinksCount> {collection.links.length}</LinksCount>
)}
</CollectionItemLink>
);
return (
<CollectionItemLink
href={appendCollectionId(route('dashboard').url, collection.id)}
isActive={isActiveCollection}
ref={itemRef}
>
<FolderIcon css={{ minWidth: '24px' }} size={24} />
<TextEllipsis>{collection.name}</TextEllipsis>
{collection.links.length > 0 && (
<LinksCount> {collection.links.length}</LinksCount>
)}
</CollectionItemLink>
);
}

View File

@@ -7,76 +7,76 @@ import useCollections from '~/hooks/use_collections';
import useShortcut from '~/hooks/use_shortcut';
const SideMenu = styled.nav(({ theme }) => ({
height: '100%',
width: '300px',
backgroundColor: theme.colors.background,
paddingLeft: '10px',
marginLeft: '5px',
borderLeft: `1px solid ${theme.colors.lightGrey}`,
display: 'flex',
gap: '.35em',
flexDirection: 'column',
height: '100%',
width: '300px',
backgroundColor: theme.colors.background,
paddingLeft: '10px',
marginLeft: '5px',
borderLeft: `1px solid ${theme.colors.lightGrey}`,
display: 'flex',
gap: '.35em',
flexDirection: 'column',
}));
const CollectionLabel = styled.p(({ theme }) => ({
color: theme.colors.grey,
marginBlock: '0.35em',
paddingInline: '15px',
color: theme.colors.grey,
marginBlock: '0.35em',
paddingInline: '15px',
}));
const CollectionListStyle = styled.div({
padding: '1px',
paddingRight: '5px',
display: 'flex',
flex: 1,
gap: '.35em',
flexDirection: 'column',
overflow: 'auto',
padding: '1px',
paddingRight: '5px',
display: 'flex',
flex: 1,
gap: '.35em',
flexDirection: 'column',
overflow: 'auto',
});
export default function CollectionList() {
const { t } = useTranslation('common');
const { collections } = useCollections();
const { activeCollection, setActiveCollection } = useActiveCollection();
const { t } = useTranslation('common');
const { collections } = useCollections();
const { activeCollection, setActiveCollection } = useActiveCollection();
const goToPreviousCollection = () => {
const currentCategoryIndex = collections.findIndex(
({ id }) => id === activeCollection?.id
);
if (currentCategoryIndex === -1 || currentCategoryIndex === 0) return;
const goToPreviousCollection = () => {
const currentCategoryIndex = collections.findIndex(
({ id }) => id === activeCollection?.id
);
if (currentCategoryIndex === -1 || currentCategoryIndex === 0) return;
setActiveCollection(collections[currentCategoryIndex - 1]);
};
setActiveCollection(collections[currentCategoryIndex - 1]);
};
const goToNextCollection = () => {
const currentCategoryIndex = collections.findIndex(
({ id }) => id === activeCollection?.id
);
if (
currentCategoryIndex === -1 ||
currentCategoryIndex === collections.length - 1
)
return;
const goToNextCollection = () => {
const currentCategoryIndex = collections.findIndex(
({ id }) => id === activeCollection?.id
);
if (
currentCategoryIndex === -1 ||
currentCategoryIndex === collections.length - 1
)
return;
setActiveCollection(collections[currentCategoryIndex + 1]);
};
setActiveCollection(collections[currentCategoryIndex + 1]);
};
useShortcut('ARROW_UP', goToPreviousCollection);
useShortcut('ARROW_DOWN', goToNextCollection);
useShortcut('ARROW_UP', goToPreviousCollection);
useShortcut('ARROW_DOWN', goToNextCollection);
return (
<SideMenu>
<CollectionListContainer>
<CollectionLabel>
{t('collection.collections', { count: collections.length })} {' '}
{collections.length}
</CollectionLabel>
<CollectionListStyle>
{collections.map((collection) => (
<CollectionItem collection={collection} key={collection.id} />
))}
</CollectionListStyle>
</CollectionListContainer>
</SideMenu>
);
return (
<SideMenu>
<CollectionListContainer>
<CollectionLabel>
{t('collection.collections', { count: collections.length })} {' '}
{collections.length}
</CollectionLabel>
<CollectionListStyle>
{collections.map((collection) => (
<CollectionItem collection={collection} key={collection.id} />
))}
</CollectionListStyle>
</CollectionListContainer>
</SideMenu>
);
}

View File

@@ -1,11 +1,11 @@
import styled from '@emotion/styled';
const CollectionListContainer = styled.div({
height: '100%',
minHeight: 0,
paddingInline: '10px',
display: 'flex',
flexDirection: 'column',
height: '100%',
minHeight: 0,
paddingInline: '10px',
display: 'flex',
flexDirection: 'column',
});
export default CollectionListContainer;

View File

@@ -10,86 +10,86 @@ import { appendCollectionId } from '~/lib/navigation';
import { CollectionWithLinks, LinkWithCollection } from '~/types/app';
export default function DashboardProviders(
props: Readonly<{
children: ReactNode;
collections: CollectionWithLinks[];
activeCollection: CollectionWithLinks;
}>
props: Readonly<{
children: ReactNode;
collections: CollectionWithLinks[];
activeCollection: CollectionWithLinks;
}>
) {
const [globalHotkeysEnabled, setGlobalHotkeysEnabled] =
useState<boolean>(true);
const [collections, setCollections] = useState<CollectionWithLinks[]>(
props.collections
);
const [activeCollection, setActiveCollection] =
useState<CollectionWithLinks | null>(
props.activeCollection || collections?.[0]
);
const [globalHotkeysEnabled, setGlobalHotkeysEnabled] =
useState<boolean>(true);
const [collections, setCollections] = useState<CollectionWithLinks[]>(
props.collections
);
const [activeCollection, setActiveCollection] =
useState<CollectionWithLinks | null>(
props.activeCollection || collections?.[0]
);
const handleChangeCollection = (collection: CollectionWithLinks) => {
setActiveCollection(collection);
router.visit(appendCollectionId(route('dashboard').url, collection.id));
};
const handleChangeCollection = (collection: CollectionWithLinks) => {
setActiveCollection(collection);
router.visit(appendCollectionId(route('dashboard').url, collection.id));
};
// TODO: compute this in controller
const favorites = useMemo<LinkWithCollection[]>(
() =>
collections.reduce((acc, collection) => {
collection.links.forEach((link) => {
if (link.favorite) {
const newLink: LinkWithCollection = { ...link, collection };
acc.push(newLink);
}
});
return acc;
}, [] as LinkWithCollection[]),
[collections]
);
// TODO: compute this in controller
const favorites = useMemo<LinkWithCollection[]>(
() =>
collections.reduce((acc, collection) => {
collection.links.forEach((link) => {
if (link.favorite) {
const newLink: LinkWithCollection = { ...link, collection };
acc.push(newLink);
}
});
return acc;
}, [] as LinkWithCollection[]),
[collections]
);
const collectionsContextValue = useMemo(
() => ({ collections, setCollections }),
[collections]
);
const activeCollectionContextValue = useMemo(
() => ({ activeCollection, setActiveCollection: handleChangeCollection }),
[activeCollection, handleChangeCollection]
);
const favoritesContextValue = useMemo(() => ({ favorites }), [favorites]);
const globalHotkeysContextValue = useMemo(
() => ({
globalHotkeysEnabled,
setGlobalHotkeysEnabled,
}),
[globalHotkeysEnabled]
);
const collectionsContextValue = useMemo(
() => ({ collections, setCollections }),
[collections]
);
const activeCollectionContextValue = useMemo(
() => ({ activeCollection, setActiveCollection: handleChangeCollection }),
[activeCollection, handleChangeCollection]
);
const favoritesContextValue = useMemo(() => ({ favorites }), [favorites]);
const globalHotkeysContextValue = useMemo(
() => ({
globalHotkeysEnabled,
setGlobalHotkeysEnabled,
}),
[globalHotkeysEnabled]
);
useShortcut(
'OPEN_CREATE_LINK_KEY',
() =>
router.visit(
appendCollectionId(route('link.create-form').url, activeCollection?.id)
),
{
enabled: globalHotkeysEnabled,
}
);
useShortcut(
'OPEN_CREATE_COLLECTION_KEY',
() => router.visit(route('collection.create-form').url),
{
enabled: globalHotkeysEnabled,
}
);
useShortcut(
'OPEN_CREATE_LINK_KEY',
() =>
router.visit(
appendCollectionId(route('link.create-form').url, activeCollection?.id)
),
{
enabled: globalHotkeysEnabled,
}
);
useShortcut(
'OPEN_CREATE_COLLECTION_KEY',
() => router.visit(route('collection.create-form').url),
{
enabled: globalHotkeysEnabled,
}
);
return (
<CollectionsContext.Provider value={collectionsContextValue}>
<ActiveCollectionContext.Provider value={activeCollectionContextValue}>
<FavoritesContext.Provider value={favoritesContextValue}>
<GlobalHotkeysContext.Provider value={globalHotkeysContextValue}>
{props.children}
</GlobalHotkeysContext.Provider>
</FavoritesContext.Provider>
</ActiveCollectionContext.Provider>
</CollectionsContext.Provider>
);
return (
<CollectionsContext.Provider value={collectionsContextValue}>
<ActiveCollectionContext.Provider value={activeCollectionContextValue}>
<FavoritesContext.Provider value={favoritesContextValue}>
<GlobalHotkeysContext.Provider value={globalHotkeysContextValue}>
{props.children}
</GlobalHotkeysContext.Provider>
</FavoritesContext.Provider>
</ActiveCollectionContext.Provider>
</CollectionsContext.Provider>
);
}

View File

@@ -11,27 +11,27 @@ import { appendLinkId } from '~/lib/navigation';
import { Link } from '~/types/app';
export default function LinkControls({ link }: { link: Link }) {
const theme = useTheme();
const { t } = useTranslation('common');
const theme = useTheme();
const { t } = useTranslation('common');
return (
<Dropdown
label={<BsThreeDotsVertical css={{ color: theme.colors.grey }} />}
css={{ backgroundColor: theme.colors.secondary }}
svgSize={18}
>
<FavoriteDropdownItem link={link} />
<DropdownItemLink
href={appendLinkId(route('link.edit-form').url, link.id)}
>
<GoPencil /> {t('link.edit')}
</DropdownItemLink>
<DropdownItemLink
href={appendLinkId(route('link.delete-form').url, link.id)}
danger
>
<IoTrashOutline /> {t('link.delete')}
</DropdownItemLink>
</Dropdown>
);
return (
<Dropdown
label={<BsThreeDotsVertical css={{ color: theme.colors.grey }} />}
css={{ backgroundColor: theme.colors.secondary }}
svgSize={18}
>
<FavoriteDropdownItem link={link} />
<DropdownItemLink
href={appendLinkId(route('link.edit-form').url, link.id)}
>
<GoPencil /> {t('link.edit')}
</DropdownItemLink>
<DropdownItemLink
href={appendLinkId(route('link.delete-form').url, link.id)}
danger
>
<IoTrashOutline /> {t('link.delete')}
</DropdownItemLink>
</Dropdown>
);
}

View File

@@ -7,76 +7,76 @@ import { rotate } from '~/styles/keyframes';
const IMG_LOAD_TIMEOUT = 7_500;
interface LinkFaviconProps {
url: string;
size?: number;
url: string;
size?: number;
}
const Favicon = styled.div({
position: 'relative',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
position: 'relative',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
});
const FaviconLoader = styled.div(({ theme }) => ({
position: 'absolute',
top: 0,
left: 0,
color: theme.colors.font,
backgroundColor: theme.colors.secondary,
position: 'absolute',
top: 0,
left: 0,
color: theme.colors.font,
backgroundColor: theme.colors.secondary,
'& > *': {
animation: `${rotate} 1s both reverse infinite linear`,
},
'& > *': {
animation: `${rotate} 1s both reverse infinite linear`,
},
}));
// The Favicon API should always return an image, so it's not really useful to keep the loader nor placeholder icon,
// but for slow connections and other random stuff, I'll keep this
export default function LinkFavicon({ url, size = 32 }: LinkFaviconProps) {
const imgRef = useRef<HTMLImageElement>(null);
const imgRef = useRef<HTMLImageElement>(null);
const [isFailed, setFailed] = useState<boolean>(false);
const [isLoading, setLoading] = useState<boolean>(true);
const [isFailed, setFailed] = useState<boolean>(false);
const [isLoading, setLoading] = useState<boolean>(true);
const setFallbackFavicon = () => setFailed(true);
const handleStopLoading = () => setLoading(false);
const setFallbackFavicon = () => setFailed(true);
const handleStopLoading = () => setLoading(false);
const handleErrorLoading = () => {
setFallbackFavicon();
handleStopLoading();
};
const handleErrorLoading = () => {
setFallbackFavicon();
handleStopLoading();
};
useEffect(() => {
// Ugly hack, onLoad cb not triggered on first load when SSR
if (imgRef.current?.complete) {
handleStopLoading();
return;
}
const id = setTimeout(() => handleErrorLoading(), IMG_LOAD_TIMEOUT);
return () => clearTimeout(id);
}, [isLoading]);
useEffect(() => {
// Ugly hack, onLoad cb not triggered on first load when SSR
if (imgRef.current?.complete) {
handleStopLoading();
return;
}
const id = setTimeout(() => handleErrorLoading(), IMG_LOAD_TIMEOUT);
return () => clearTimeout(id);
}, [isLoading]);
return (
<Favicon>
{!isFailed ? (
<img
src={`/favicon?url=${url}`}
onError={handleErrorLoading}
onLoad={handleStopLoading}
height={size}
width={size}
alt="icon"
ref={imgRef}
decoding="async"
/>
) : (
<TfiWorld size={size} />
)}
{isLoading && (
<FaviconLoader style={{ height: `${size}px`, width: `${size}px` }}>
<TbLoader3 size={size} />
</FaviconLoader>
)}
</Favicon>
);
return (
<Favicon>
{!isFailed ? (
<img
src={`/favicon?url=${url}`}
onError={handleErrorLoading}
onLoad={handleStopLoading}
height={size}
width={size}
alt="icon"
ref={imgRef}
decoding="async"
/>
) : (
<TfiWorld size={size} />
)}
{isLoading && (
<FaviconLoader style={{ height: `${size}px`, width: `${size}px` }}>
<TbLoader3 size={size} />
</FaviconLoader>
)}
</Favicon>
);
}

View File

@@ -6,121 +6,121 @@ import LinkFavicon from '~/components/dashboard/link/link_favicon';
import { Link } from '~/types/app';
const LinkWrapper = styled.li(({ theme }) => ({
userSelect: 'none',
cursor: 'pointer',
height: 'fit-content',
width: '100%',
color: theme.colors.primary,
backgroundColor: theme.colors.secondary,
padding: '0.75em 1em',
borderRadius: theme.border.radius,
userSelect: 'none',
cursor: 'pointer',
height: 'fit-content',
width: '100%',
color: theme.colors.primary,
backgroundColor: theme.colors.secondary,
padding: '0.75em 1em',
borderRadius: theme.border.radius,
'&:hover': {
outlineWidth: '1px',
outlineStyle: 'solid',
},
'&:hover': {
outlineWidth: '1px',
outlineStyle: 'solid',
},
}));
const LinkHeader = styled.div(({ theme }) => ({
display: 'flex',
gap: '1em',
alignItems: 'center',
display: 'flex',
gap: '1em',
alignItems: 'center',
'& > a': {
height: '100%',
maxWidth: 'calc(100% - 75px)', // TODO: fix this, it is ugly af :(
textDecoration: 'none',
display: 'flex',
flex: 1,
flexDirection: 'column',
transition: theme.transition.delay,
'& > a': {
height: '100%',
maxWidth: 'calc(100% - 75px)', // TODO: fix this, it is ugly af :(
textDecoration: 'none',
display: 'flex',
flex: 1,
flexDirection: 'column',
transition: theme.transition.delay,
'&, &:hover': {
border: 0,
},
},
'&, &:hover': {
border: 0,
},
},
}));
const LinkName = styled.div({
width: '100%',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
width: '100%',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
});
const LinkDescription = styled.div(({ theme }) => ({
marginTop: '0.5em',
color: theme.colors.font,
fontSize: '0.8em',
wordWrap: 'break-word',
marginTop: '0.5em',
color: theme.colors.font,
fontSize: '0.8em',
wordWrap: 'break-word',
}));
const LinkUrl = styled.span(({ theme }) => ({
width: '100%',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
color: theme.colors.grey,
fontSize: '0.8em',
width: '100%',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
color: theme.colors.grey,
fontSize: '0.8em',
}));
const StarIcon = styled(AiFillStar)(({ theme }) => ({
color: theme.colors.yellow,
color: theme.colors.yellow,
}));
const LinkUrlPathname = styled.span({
opacity: 0,
opacity: 0,
});
export default function LinkItem({
link,
showUserControls = false,
link,
showUserControls = false,
}: {
link: Link;
showUserControls: boolean;
link: Link;
showUserControls: boolean;
}) {
const { id, name, url, description, favorite } = link;
return (
<LinkWrapper key={id} title={name}>
<LinkHeader>
<LinkFavicon url={url} />
<ExternalLink href={url} className="reset">
<LinkName>
{name} {showUserControls && favorite && <StarIcon />}
</LinkName>
<LinkItemURL url={url} />
</ExternalLink>
{showUserControls && <LinkControls link={link} />}
</LinkHeader>
{description && <LinkDescription>{description}</LinkDescription>}
</LinkWrapper>
);
const { id, name, url, description, favorite } = link;
return (
<LinkWrapper key={id} title={name}>
<LinkHeader>
<LinkFavicon url={url} />
<ExternalLink href={url} className="reset">
<LinkName>
{name} {showUserControls && favorite && <StarIcon />}
</LinkName>
<LinkItemURL url={url} />
</ExternalLink>
{showUserControls && <LinkControls link={link} />}
</LinkHeader>
{description && <LinkDescription>{description}</LinkDescription>}
</LinkWrapper>
);
}
function LinkItemURL({ url }: { url: Link['url'] }) {
try {
const { origin, pathname, search } = new URL(url);
let text = '';
try {
const { origin, pathname, search } = new URL(url);
let text = '';
if (pathname !== '/') {
text += pathname;
}
if (pathname !== '/') {
text += pathname;
}
if (search !== '') {
if (text === '') {
text += '/';
}
text += search;
}
if (search !== '') {
if (text === '') {
text += '/';
}
text += search;
}
return (
<LinkUrl>
{origin}
<LinkUrlPathname>{text}</LinkUrlPathname>
</LinkUrl>
);
} catch (error) {
console.error('error', error);
return <LinkUrl>{url}</LinkUrl>;
}
return (
<LinkUrl>
{origin}
<LinkUrlPathname>{text}</LinkUrlPathname>
</LinkUrl>
);
} catch (error) {
console.error('error', error);
return <LinkUrl>{url}</LinkUrl>;
}
}

View File

@@ -5,34 +5,34 @@ import { sortByCreationDate } from '~/lib/array';
import { Link } from '~/types/app';
const LinkListStyle = styled.ul({
height: '100%',
width: '100%',
minWidth: 0,
display: 'flex',
flex: 1,
gap: '0.5em',
padding: '3px',
flexDirection: 'column',
overflowX: 'hidden',
overflowY: 'scroll',
height: '100%',
width: '100%',
minWidth: 0,
display: 'flex',
flex: 1,
gap: '0.5em',
padding: '3px',
flexDirection: 'column',
overflowX: 'hidden',
overflowY: 'scroll',
});
export default function LinkList({
links,
showControls = true,
links,
showControls = true,
}: {
links: Link[];
showControls?: boolean;
links: Link[];
showControls?: boolean;
}) {
if (links.length === 0) {
return <NoLink />;
}
if (links.length === 0) {
return <NoLink />;
}
return (
<LinkListStyle>
{sortByCreationDate(links).map((link) => (
<LinkItem link={link} key={link.id} showUserControls={showControls} />
))}
</LinkListStyle>
);
return (
<LinkListStyle>
{sortByCreationDate(links).map((link) => (
<LinkItem link={link} key={link.id} showUserControls={showControls} />
))}
</LinkListStyle>
);
}

View File

@@ -7,60 +7,60 @@ import { appendCollectionId } from '~/lib/navigation';
import { fadeIn } from '~/styles/keyframes';
const NoCollectionStyle = styled.div({
minWidth: 0,
display: 'flex',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
animation: `${fadeIn} 0.3s both`,
minWidth: 0,
display: 'flex',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
animation: `${fadeIn} 0.3s both`,
});
const Text = styled.p({
minWidth: 0,
width: '100%',
textAlign: 'center',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
minWidth: 0,
width: '100%',
textAlign: 'center',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
});
export function NoCollection() {
const { t } = useTranslation('home');
return (
<NoCollectionStyle>
<Text>{t('select-collection')}</Text>
<Link href={route('collection.create-form').url}>
{t('or-create-one')}
</Link>
</NoCollectionStyle>
);
const { t } = useTranslation('home');
return (
<NoCollectionStyle>
<Text>{t('select-collection')}</Text>
<Link href={route('collection.create-form').url}>
{t('or-create-one')}
</Link>
</NoCollectionStyle>
);
}
export function NoLink() {
const { t } = useTranslation('common');
const { activeCollection } = useActiveCollection();
return (
<NoCollectionStyle>
<Text
dangerouslySetInnerHTML={{
__html: t(
'home:no-link',
{ name: activeCollection?.name ?? '' } as any,
{
interpolation: { escapeValue: false },
}
),
}}
/>
<Link
href={appendCollectionId(
route('link.create-form').url,
activeCollection?.id
)}
>
{t('link.create')}
</Link>
</NoCollectionStyle>
);
const { t } = useTranslation('common');
const { activeCollection } = useActiveCollection();
return (
<NoCollectionStyle>
<Text
dangerouslySetInnerHTML={{
__html: t(
'home:no-link',
{ name: activeCollection?.name ?? '' } as any,
{
interpolation: { escapeValue: false },
}
),
}}
/>
<Link
href={appendCollectionId(
route('link.create-form').url,
activeCollection?.id
)}
>
{t('link.create')}
</Link>
</NoCollectionStyle>
);
}

View File

@@ -3,27 +3,27 @@ import { useTranslation } from 'react-i18next';
import { FcGoogle } from 'react-icons/fc';
const NoSearchResultStyle = styled.i({
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '0.25em',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '0.25em',
'& > span': {
display: 'flex',
alignItems: 'center',
},
'& > span': {
display: 'flex',
alignItems: 'center',
},
});
export default function NoSearchResult() {
const { t } = useTranslation('common');
return (
<NoSearchResultStyle>
{t('search-with')}
{''}
<span>
<FcGoogle size={20} />
oogle
</span>
</NoSearchResultStyle>
);
const { t } = useTranslation('common');
return (
<NoSearchResultStyle>
{t('search-with')}
{''}
<span>
<FcGoogle size={20} />
oogle
</span>
</NoSearchResultStyle>
);
}

View File

@@ -15,142 +15,142 @@ import { makeRequest } from '~/lib/request';
import { SearchResult } from '~/types/search';
const SearchInput = styled.input(({ theme }) => ({
width: '100%',
fontSize: '20px',
color: theme.colors.font,
backgroundColor: 'transparent',
paddingLeft: 0,
border: '1px solid transparent',
width: '100%',
fontSize: '20px',
color: theme.colors.font,
backgroundColor: 'transparent',
paddingLeft: 0,
border: '1px solid transparent',
}));
interface SearchModalProps {
openItem: any;
openItem: any;
}
function SearchModal({ openItem: OpenItem }: SearchModalProps) {
const { t } = useTranslation();
const { collections } = useCollections();
const { setActiveCollection } = useActiveCollection();
const { t } = useTranslation();
const { collections } = useCollections();
const { setActiveCollection } = useActiveCollection();
const [searchTerm, setSearchTerm] = useState<string>('');
const [results, setResults] = useState<SearchResult[]>([]);
const [selectedItem, setSelectedItem] = useState<SearchResult | null>(null);
const [searchTerm, setSearchTerm] = useState<string>('');
const [results, setResults] = useState<SearchResult[]>([]);
const [selectedItem, setSelectedItem] = useState<SearchResult | null>(null);
const searchModal = useToggle(!!searchTerm);
const searchModal = useToggle(!!searchTerm);
const handleCloseModal = useCallback(() => {
searchModal.close();
setSearchTerm('');
}, [searchModal]);
const handleCloseModal = useCallback(() => {
searchModal.close();
setSearchTerm('');
}, [searchModal]);
const handleSearchInputChange = (value: string) => setSearchTerm(value);
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
handleCloseModal();
const handleSearchInputChange = (value: string) => setSearchTerm(value);
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
handleCloseModal();
if (results.length === 0) {
return window.open(GOOGLE_SEARCH_URL + encodeURI(searchTerm.trim()));
}
if (results.length === 0) {
return window.open(GOOGLE_SEARCH_URL + encodeURI(searchTerm.trim()));
}
if (!selectedItem) return;
if (!selectedItem) return;
if (selectedItem.type === 'collection') {
const collection = collections.find((c) => c.id === selectedItem.id);
if (collection) {
setActiveCollection(collection);
}
return;
}
if (selectedItem.type === 'collection') {
const collection = collections.find((c) => c.id === selectedItem.id);
if (collection) {
setActiveCollection(collection);
}
return;
}
window.open(selectedItem.url);
};
window.open(selectedItem.url);
};
useShortcut('OPEN_SEARCH_KEY', searchModal.open, {
enabled: !searchModal.isShowing,
});
useShortcut('ESCAPE_KEY', handleCloseModal, {
enabled: searchModal.isShowing,
disableGlobalCheck: true,
});
useShortcut('OPEN_SEARCH_KEY', searchModal.open, {
enabled: !searchModal.isShowing,
});
useShortcut('ESCAPE_KEY', handleCloseModal, {
enabled: searchModal.isShowing,
disableGlobalCheck: true,
});
useEffect(() => {
if (searchTerm.trim() === '') {
return setResults([]);
}
useEffect(() => {
if (searchTerm.trim() === '') {
return setResults([]);
}
const controller = new AbortController();
const { url, method } = route('search', { qs: { term: searchTerm } });
makeRequest({
method,
url,
controller,
}).then(({ results: _results }) => {
setResults(_results);
setSelectedItem(_results?.[0]);
});
const controller = new AbortController();
const { url, method } = route('search', { qs: { term: searchTerm } });
makeRequest({
method,
url,
controller,
}).then(({ results: _results }) => {
setResults(_results);
setSelectedItem(_results?.[0]);
});
return () => controller.abort();
}, [searchTerm]);
return () => controller.abort();
}, [searchTerm]);
return (
<>
<OpenItem onClick={searchModal.open}>
<IoIosSearch /> {t('common:search')}
</OpenItem>
<Modal
close={handleCloseModal}
opened={searchModal.isShowing}
hideCloseBtn
css={{ width: '650px' }}
>
<form
onSubmit={handleSubmit}
css={{
width: '100%',
display: 'flex',
gap: '0.5em',
flexDirection: 'column',
}}
>
<div
css={{
display: 'flex',
gap: '0.35em',
alignItems: 'center',
justifyContent: 'center',
}}
>
<label htmlFor="search" css={{ display: 'flex' }}>
<IoIosSearch size={24} />
</label>
<SearchInput
name="search"
id="search"
onChange={({ target }) => handleSearchInputChange(target.value)}
value={searchTerm}
placeholder={t('common:search')}
autoFocus
/>
</div>
{results.length > 0 && selectedItem && (
<SearchResultList
results={results}
selectedItem={selectedItem}
setSelectedItem={setSelectedItem}
/>
)}
{results.length === 0 && !!searchTerm.trim() && <NoSearchResult />}
<button
type="submit"
disabled={searchTerm.length === 0}
style={{ display: 'none' }}
>
{t('common:confirm')}
</button>
</form>
</Modal>
</>
);
return (
<>
<OpenItem onClick={searchModal.open}>
<IoIosSearch /> {t('common:search')}
</OpenItem>
<Modal
close={handleCloseModal}
opened={searchModal.isShowing}
hideCloseBtn
css={{ width: '650px' }}
>
<form
onSubmit={handleSubmit}
css={{
width: '100%',
display: 'flex',
gap: '0.5em',
flexDirection: 'column',
}}
>
<div
css={{
display: 'flex',
gap: '0.35em',
alignItems: 'center',
justifyContent: 'center',
}}
>
<label htmlFor="search" css={{ display: 'flex' }}>
<IoIosSearch size={24} />
</label>
<SearchInput
name="search"
id="search"
onChange={({ target }) => handleSearchInputChange(target.value)}
value={searchTerm}
placeholder={t('common:search')}
autoFocus
/>
</div>
{results.length > 0 && selectedItem && (
<SearchResultList
results={results}
selectedItem={selectedItem}
setSelectedItem={setSelectedItem}
/>
)}
{results.length === 0 && !!searchTerm.trim() && <NoSearchResult />}
<button
type="submit"
disabled={searchTerm.length === 0}
style={{ display: 'none' }}
>
{t('common:confirm')}
</button>
</form>
</Modal>
</>
);
}
export default SearchModal;

Some files were not shown because too many files have changed in this diff Show More