20 Commits
2.0.3 ... 2.2.1

Author SHA1 Message Date
Sonny
2fda4aabdd chore: release v2.2.1 2024-10-07 02:48:47 +02:00
Sonny
bc376a72ee fix: error on admin dashboard when user "last seen" is null 2024-10-07 02:48:32 +02:00
Sonny
d360a9044c chore: release v2.2.0 2024-10-07 02:26:00 +02:00
Sonny
8b4e5740d7 refactor: fix lucid warning 2024-10-07 02:24:27 +02:00
Sonny
c8fb5af44d feat: add user last seen field 2024-10-07 02:07:39 +02:00
Sonny
24cea2b0b2 chore: use vscode nesting system 2024-10-07 01:37:39 +02:00
Sonny
eea9732100 refactor: use tabs instead of spaces 2024-10-07 01:33:59 +02:00
Sonny
f425decf2c chore: rename compose files and use major release tag for postgres and pgadmin 2024-10-07 01:30:18 +02:00
Sonny
8b57f6dd47 chore(deps): update deps 2024-10-07 01:19:37 +02:00
Sonny
dda6fc299a chore: release v2.1.3 2024-09-18 17:01:49 +02:00
Sonny
b0e3bfa0f6 fix: favorite link and search result styles 2024-09-17 16:14:25 +02:00
Sonny
9d4eb08bc9 chore: release v2.1.2 2024-09-17 15:24:29 +02:00
Sonny
f8e7e7cd64 chore(deps): revert @emotion/react@11.13.0 update
This version seems to be broken.
In dev mode, styled component theme props's missing only when SSR
2024-09-17 15:23:56 +02:00
Sonny
cda3a89f32 chore: release v2.1.1 2024-09-17 14:55:51 +02:00
Sonny
ed4dbca329 chore(deps): update deps 2024-09-17 14:54:20 +02:00
Sonny
f8a92b7219 chore(deps): replace ts-node by ts-node-maintained + update eslint/prettier" 2024-09-17 14:03:21 +02:00
Sonny
161db362b3 chore: release v2.1.0 2024-08-30 23:39:25 +02:00
Sonny
a5e542a33f chore(deps): update deps 2024-08-30 23:38:39 +02:00
Sonny
f0ec6d6b3d feat: sortable table component 2024-08-30 23:35:05 +02:00
Sonny
442a1003bb feat: add dropdown for favorite items 2024-07-22 12:10:47 +02:00
212 changed files with 6910 additions and 6180 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,4 +1 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npx lint-staged

12
.vscode/settings.json vendored
View File

@@ -1,3 +1,13 @@
{
"typescript.preferences.importModuleSpecifier": "non-relative"
"typescript.preferences.importModuleSpecifier": "non-relative",
/* Prefer tabs over spaces for accessibility */
"editor.insertSpaces": false,
"editor.detectIndentation": false,
/* Explorer */
"explorer.fileNesting.enabled": true,
"explorer.fileNesting.patterns": {
"*.js": "${capture}.js.map, ${capture}.min.js, ${capture}.d.ts",
"package.json": "pnpm-lock.yaml, tsconfig.json, eslint.config.js, .babelrc, vite.config.ts, .editorconfig",
"Makefile": "*compose.yml, Dockerfile, servers_pgadmin.json, .dockerignore"
}
}

View File

@@ -1,11 +1,13 @@
dev:
@docker compose down
@docker compose -f dev.docker-compose.yml up -d --wait
@docker compose -f dev.compose.yml pull
@docker compose -f dev.compose.yml up -d --wait
@node ace migration:fresh
@pnpm run dev
prod:
@docker compose -f dev.docker-compose.yml down
@docker compose -f dev.compose.yml down
@docker compose pull
@docker compose up -d --build --wait
seed:
@@ -13,7 +15,7 @@ seed:
down:
@-docker compose down
@-docker compose -f dev.docker-compose.yml down
@-docker compose -f dev.compose.yml down
release:
@pnpm run release

3
ace.js
View File

@@ -19,8 +19,7 @@
/**
* Register hook to process TypeScript files using ts-node
*/
import { register } from 'node:module';
register('ts-node/esm', import.meta.url);
import 'ts-node-maintained/register/esm';
/**
* Import ace console entrypoint

View File

@@ -14,12 +14,12 @@ class UserWithRelationCountDto {
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),
},
createdAt: this.user.createdAt.toString(),
updatedAt: this.user.updatedAt.toString(),
lastSeenAt:
this.user.lastSeenAt?.toString() ?? this.user.updatedAt.toString(),
linksCount: Number(this.user.$extras.totalLinks),
collectionsCount: Number(this.user.$extras.totalCollections),
});
}

View File

@@ -25,9 +25,11 @@ export default class CollectionsController {
return response.redirectToNamedRoute('dashboard');
}
// TODO: Create DTOs
return inertia.render('dashboard', {
collections,
activeCollection: activeCollection || collections[0],
collections: collections.map((collection) => collection.serialize()),
activeCollection:
activeCollection?.serialize() || collections[0].serialize(),
});
}

View File

@@ -0,0 +1,9 @@
import type { HttpContext } from '@adonisjs/core/http';
import type { NextFn } from '@adonisjs/core/types/http';
export default class SilentAuthMiddleware {
async handle(ctx: HttpContext, next: NextFn) {
await ctx.auth.check();
return next();
}
}

View File

@@ -0,0 +1,16 @@
import type { HttpContext } from '@adonisjs/core/http';
import type { NextFn } from '@adonisjs/core/types/http';
import { DateTime } from 'luxon';
export default class UpdateUserLastSeenMiddleware {
async handle(ctx: HttpContext, next: NextFn) {
const user = ctx.auth.user;
if (user) {
user.lastSeenAt = DateTime.local();
await user.save();
}
const output = await next();
return output;
}
}

View File

@@ -4,6 +4,7 @@ import type { GoogleToken } from '@adonisjs/ally/types';
import { column, computed, hasMany } from '@adonisjs/lucid/orm';
import type { HasMany } from '@adonisjs/lucid/types/relations';
import AppBaseModel from './app_base_model.js';
import { DateTime } from 'luxon';
export default class User extends AppBaseModel {
@column()
@@ -44,4 +45,10 @@ export default class User extends AppBaseModel {
get fullname() {
return this.nickName || this.name;
}
@column.dateTime({
autoCreate: true,
autoUpdate: true,
})
declare lastSeenAt: DateTime;
}

View File

@@ -17,7 +17,7 @@ services:
pgadmin:
container_name: pgadmin
image: dpage/pgadmin4:8.6
image: dpage/pgadmin4:8
restart: always
healthcheck:
test: ['CMD', 'wget', '-O', '-', 'http://localhost:80/misc/ping']

View File

@@ -5,7 +5,14 @@ export default class CreateUsersTable extends BaseSchema {
static tableName = 'users';
async up() {
this.schema.createTableIfNotExists(CreateUsersTable.tableName, (table) => {
const exists = await this.schema.hasTable(CreateUsersTable.tableName);
if (exists) {
return console.warn(
`Table ${CreateUsersTable.tableName} already exists.`
);
}
this.schema.createTable(CreateUsersTable.tableName, (table) => {
table.string('email', 254).notNullable().unique();
table.string('name', 254).notNullable();
table.string('nick_name', 254).nullable();

View File

@@ -8,9 +8,14 @@ export default class CreateCollectionTable extends BaseSchema {
async up() {
this.schema.raw(`DROP TYPE IF EXISTS ${this.visibilityEnumName}`);
this.schema.createTableIfNotExists(
CreateCollectionTable.tableName,
(table) => {
const exists = await this.schema.hasTable(CreateCollectionTable.tableName);
if (exists) {
return console.warn(
`Table ${CreateCollectionTable.tableName} already exists.`
);
}
this.schema.createTable(CreateCollectionTable.tableName, (table) => {
table.string('name', 254).notNullable();
table.string('description', 254).nullable();
table
@@ -33,8 +38,7 @@ export default class CreateCollectionTable extends BaseSchema {
.onDelete('CASCADE');
defaultTableFields(table);
}
);
});
}
async down() {

View File

@@ -5,7 +5,13 @@ export default class CreateLinksTable extends BaseSchema {
static tableName = 'links';
async up() {
this.schema.createTableIfNotExists(CreateLinksTable.tableName, (table) => {
const exists = await this.schema.hasTable(CreateLinksTable.tableName);
if (exists) {
return console.warn(`Table ${CreateLinksTable.tableName} already
exists.`);
}
this.schema.createTable(CreateLinksTable.tableName, (table) => {
table.string('name', 254).notNullable();
table.string('description', 254).nullable();
table.text('url').notNullable();

View File

@@ -0,0 +1,15 @@
import { BaseSchema } from '@adonisjs/lucid/schema';
export default class extends BaseSchema {
protected tableName = 'users';
async up() {
this.schema.alterTable(this.tableName, (table) => {
table.timestamp('last_seen_at');
});
}
async down() {
this.schema.dropTable(this.tableName);
}
}

View File

@@ -17,7 +17,7 @@ services:
pgadmin:
container_name: pgadmin
image: dpage/pgadmin4:8.6
image: dpage/pgadmin4:8
restart: always
environment:
- PGADMIN_DEFAULT_EMAIL=myemail@gmail.com

4
eslint.config.js Normal file
View File

@@ -0,0 +1,4 @@
import { configApp } from '@adonisjs/eslint-config';
export default configApp({
files: ['**/*.ts', '**/*.tsx', '**/*.js', '**/*.jsx'],
});

View File

@@ -1,5 +1,5 @@
import styled from '@emotion/styled';
import { ReactNode, useRef } from 'react';
import { HtmlHTMLAttributes, ReactNode, useRef } from 'react';
import DropdownContainer from '~/components/common/dropdown/dropdown_container';
import DropdownLabel from '~/components/common/dropdown/dropdown_label';
import useClickOutside from '~/hooks/use_click_outside';
@@ -34,8 +34,8 @@ export default function Dropdown({
label,
className,
svgSize,
}: {
children: ReactNode;
onClick,
}: HtmlHTMLAttributes<HTMLDivElement> & {
label: ReactNode | string;
className?: string;
svgSize?: number;
@@ -49,7 +49,10 @@ export default function Dropdown({
return (
<DropdownStyle
opened={isShowing}
onClick={toggle}
onClick={(event) => {
onClick?.(event);
toggle();
}}
ref={dropdownRef}
className={className}
svgSize={svgSize}

View File

@@ -0,0 +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',
'&:disabled': {
cursor: 'not-allowed',
opacity: 0.15,
},
}));
export default IconButton;

View File

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

View File

@@ -0,0 +1,227 @@
import styled from '@emotion/styled';
import {
ColumnDef,
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
PaginationState,
SortingState,
useReactTable,
} from '@tanstack/react-table';
import { useState } from 'react';
import IconButton from '~/components/common/icon_button';
import {
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',
});
const Box = styled(TablePageFooter)({
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,
},
})
);
type TableProps<T> = {
columns: ColumnDef<T>[];
data: T[];
defaultSorting?: SortingState;
};
export default function Table<T>({
columns,
data,
defaultSorting = [],
}: TableProps<T>) {
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});
const [sorting, setSorting] = useState<SortingState>(defaultSorting);
const table = useReactTable({
data,
columns,
enableColumnResizing: true,
columnResizeMode: 'onChange',
state: {
pagination,
sorting,
},
onPaginationChange: setPagination,
getCoreRowModel: getCoreRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getSortedRowModel: getSortedRowModel(),
onSortingChange: setSorting,
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>
);
}

View File

@@ -7,7 +7,7 @@ import FavoritesContext from '~/contexts/favorites_context';
import GlobalHotkeysContext from '~/contexts/global_hotkeys_context';
import useShortcut from '~/hooks/use_shortcut';
import { appendCollectionId } from '~/lib/navigation';
import { CollectionWithLinks, Link } from '~/types/app';
import { CollectionWithLinks, LinkWithCollection } from '~/types/app';
export default function DashboardProviders(
props: Readonly<{
@@ -31,14 +31,18 @@ export default function DashboardProviders(
router.visit(appendCollectionId(route('dashboard').url, collection.id));
};
const favorites = useMemo<Link[]>(
// TODO: compute this in controller
const favorites = useMemo<LinkWithCollection[]>(
() =>
collections.reduce((acc, collection) => {
collection.links.forEach((link) =>
link.favorite ? acc.push(link) : null
);
collection.links.forEach((link) => {
if (link.favorite) {
const newLink: LinkWithCollection = { ...link, collection };
acc.push(newLink);
}
});
return acc;
}, [] as Link[]),
}, [] as LinkWithCollection[]),
[collections]
);
@@ -76,6 +80,7 @@ export default function DashboardProviders(
enabled: globalHotkeysEnabled,
}
);
return (
<CollectionsContext.Provider value={collectionsContextValue}>
<ActiveCollectionContext.Provider value={activeCollectionContextValue}>

View File

@@ -1,71 +1,18 @@
import { useTheme } from '@emotion/react';
import styled from '@emotion/styled';
import { route } from '@izzyjs/route/client';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { AiFillStar, AiOutlineStar } from 'react-icons/ai';
import { BsThreeDotsVertical } from 'react-icons/bs';
import { GoPencil } from 'react-icons/go';
import { IoTrashOutline } from 'react-icons/io5';
import Dropdown from '~/components/common/dropdown/dropdown';
import {
DropdownItemButton,
DropdownItemLink,
} from '~/components/common/dropdown/dropdown_item';
import useActiveCollection from '~/hooks/use_active_collection';
import useCollections from '~/hooks/use_collections';
import { DropdownItemLink } from '~/components/common/dropdown/dropdown_item';
import FavoriteDropdownItem from '~/components/dashboard/side_nav/favorite/favorite_dropdown_item';
import { appendLinkId } from '~/lib/navigation';
import { makeRequest } from '~/lib/request';
import { Link } from '~/types/app';
const StartItem = styled(DropdownItemButton)(({ theme }) => ({
color: theme.colors.yellow,
}));
export default function LinkControls({ link }: { link: Link }) {
const theme = useTheme();
const { t } = useTranslation('common');
const { collections, setCollections } = useCollections();
const { setActiveCollection } = useActiveCollection();
const toggleFavorite = useCallback(
(linkId: Link['id']) => {
let linkIndex = 0;
const collectionIndex = collections.findIndex(({ links }) => {
const lIndex = links.findIndex((l) => l.id === linkId);
if (lIndex !== -1) {
linkIndex = lIndex;
}
return lIndex !== -1;
});
const collectionLink = collections[collectionIndex].links[linkIndex];
const collectionsCopy = [...collections];
collectionsCopy[collectionIndex].links[linkIndex] = {
...collectionLink,
favorite: !collectionLink.favorite,
};
setCollections(collectionsCopy);
setActiveCollection(collectionsCopy[collectionIndex]);
},
[collections, setCollections]
);
const onFavorite = () => {
const { url, method } = route('link.toggle-favorite', {
params: { id: link.id.toString() },
});
makeRequest({
url,
method,
body: {
favorite: !link.favorite,
},
})
.then(() => toggleFavorite(link.id))
.catch(console.error);
};
return (
<Dropdown
@@ -73,17 +20,7 @@ export default function LinkControls({ link }: { link: Link }) {
css={{ backgroundColor: theme.colors.secondary }}
svgSize={18}
>
<StartItem onClick={onFavorite}>
{!link.favorite ? (
<>
<AiFillStar /> {t('add-favorite')}
</>
) : (
<>
<AiOutlineStar /> {t('remove-favorite')}
</>
)}
</StartItem>
<FavoriteDropdownItem link={link} />
<DropdownItemLink
href={appendLinkId(route('link.edit-form').url, link.id)}
>

View File

@@ -1,6 +1,7 @@
import styled from '@emotion/styled';
import { RefObject, useEffect, useRef, useState } from 'react';
import { AiOutlineFolder } from 'react-icons/ai';
import Legend from '~/components/common/legend';
import TextEllipsis from '~/components/common/text_ellipsis';
import LinkFavicon from '~/components/dashboard/link/link_favicon';
import useCollections from '~/hooks/use_collections';
@@ -14,7 +15,7 @@ const SearchItemStyle = styled('li', {
shouldForwardProp: (propName) => propName !== 'isActive',
})<{ isActive: boolean }>(({ theme, isActive }) => ({
fontSize: '16px',
backgroundColor: isActive ? theme.colors.background : 'transparent',
backgroundColor: isActive ? theme.colors.secondary : 'transparent',
display: 'flex',
gap: '0.35em',
alignItems: 'center',
@@ -22,11 +23,6 @@ const SearchItemStyle = styled('li', {
padding: '0.25em 0.35em !important',
}));
const ItemLegeng = styled.span(({ theme }) => ({
fontSize: '13px',
color: theme.colors.grey,
}));
interface CommonResultProps {
innerRef: RefObject<HTMLLIElement>;
isActive: boolean;
@@ -100,7 +96,7 @@ function ResultLink({
__html: result.matched_part ?? result.name,
}}
/>
<ItemLegeng>({collection.name})</ItemLegeng>
<Legend>({collection.name})</Legend>
</SearchItemStyle>
);
}

View File

@@ -0,0 +1,60 @@
import styled from '@emotion/styled';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { AiFillStar, AiOutlineStar } from 'react-icons/ai';
import { DropdownItemButton } from '~/components/common/dropdown/dropdown_item';
import useActiveCollection from '~/hooks/use_active_collection';
import useCollections from '~/hooks/use_collections';
import { onFavorite } from '~/lib/favorite';
import { Link } from '~/types/app';
const StarItem = styled(DropdownItemButton)(({ theme }) => ({
color: theme.colors.yellow,
}));
export default function FavoriteDropdownItem({ link }: { link: Link }) {
const { collections, setCollections } = useCollections();
const { setActiveCollection } = useActiveCollection();
const { t } = useTranslation();
const toggleFavorite = useCallback(
(linkId: Link['id']) => {
let linkIndex = 0;
const collectionIndex = collections.findIndex(({ links }) => {
const lIndex = links.findIndex((l) => l.id === linkId);
if (lIndex !== -1) {
linkIndex = lIndex;
}
return lIndex !== -1;
});
const collectionLink = collections[collectionIndex].links[linkIndex];
const collectionsCopy = [...collections];
collectionsCopy[collectionIndex].links[linkIndex] = {
...collectionLink,
favorite: !collectionLink.favorite,
};
setCollections(collectionsCopy);
setActiveCollection(collectionsCopy[collectionIndex]);
},
[collections, setCollections]
);
const onFavoriteCallback = () => toggleFavorite(link.id);
return (
<StarItem
onClick={() => onFavorite(link.id, !link.favorite, onFavoriteCallback)}
>
{!link.favorite ? (
<>
<AiFillStar /> {t('add-favorite')}
</>
) : (
<>
<AiOutlineStar /> {t('remove-favorite')}
</>
)}
</StarItem>
);
}

View File

@@ -1,8 +1,69 @@
import styled from '@emotion/styled';
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import { BsThreeDotsVertical } from 'react-icons/bs';
import { FaRegEye } from 'react-icons/fa';
import { GoPencil } from 'react-icons/go';
import { IoTrashOutline } from 'react-icons/io5';
import Dropdown from '~/components/common/dropdown/dropdown';
import { DropdownItemLink } from '~/components/common/dropdown/dropdown_item';
import Legend from '~/components/common/legend';
import TextEllipsis from '~/components/common/text_ellipsis';
import LinkFavicon from '~/components/dashboard/link/link_favicon';
import FavoriteDropdownItem from '~/components/dashboard/side_nav/favorite/favorite_dropdown_item';
import { ItemExternalLink } from '~/components/dashboard/side_nav/nav_item';
import { appendCollectionId, appendLinkId } from '~/lib/navigation';
import { LinkWithCollection } from '~/types/app';
const FavoriteItem = styled(ItemExternalLink)(({ theme }) => ({
const FavoriteItemStyle = styled(ItemExternalLink)(({ theme }) => ({
height: 'auto',
backgroundColor: theme.colors.secondary,
}));
export default FavoriteItem;
const FavoriteDropdown = styled(Dropdown)(({ theme }) => ({
backgroundColor: theme.colors.secondary,
}));
const FavoriteContainer = styled.div({
flex: 1,
lineHeight: '1.1rem',
});
export default function FavoriteItem({ link }: { link: LinkWithCollection }) {
const { t } = useTranslation();
return (
<FavoriteItemStyle href={link.url}>
<LinkFavicon url={link.url} size={24} />
<FavoriteContainer>
<TextEllipsis>{link.name}</TextEllipsis>
<Legend>{link.collection.name}</Legend>
</FavoriteContainer>
<FavoriteDropdown
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
}}
label={<BsThreeDotsVertical />}
svgSize={18}
>
<DropdownItemLink
href={appendCollectionId(route('dashboard').url, link.collection.id)}
>
<FaRegEye /> {t('go-to-collection')}
</DropdownItemLink>
<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>
</FavoriteDropdown>
</FavoriteItemStyle>
);
}

View File

@@ -1,7 +1,5 @@
import styled from '@emotion/styled';
import { useTranslation } from 'react-i18next';
import TextEllipsis from '~/components/common/text_ellipsis';
import LinkFavicon from '~/components/dashboard/link/link_favicon';
import FavoriteListContainer from '~/components/dashboard/side_nav/favorite/favorite_container';
import FavoriteItem from '~/components/dashboard/side_nav/favorite/favorite_item';
import useFavorites from '~/hooks/use_favorites';
@@ -44,11 +42,8 @@ export default function FavoriteList() {
{t('favorite')} {favorites.length}
</FavoriteLabel>
<FavoriteListStyle>
{favorites.map(({ id, name, url }) => (
<FavoriteItem href={url} key={id}>
<LinkFavicon url={url} size={24} />
<TextEllipsis>{name}</TextEllipsis>
</FavoriteItem>
{favorites.map((link) => (
<FavoriteItem link={link} key={link.id} />
))}
</FavoriteListStyle>
</FavoriteListContainer>

View File

@@ -131,7 +131,9 @@ function GlobalStyles() {
},
'th, td': {
whiteSpace: 'nowrap',
whiteSspace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
},
'tr:nth-of-type(even)': {

View File

@@ -14,7 +14,7 @@ const ProfileStyle = styled(UnstyledList)({
gap: '1.25em',
});
const Column = styled.li({
const Column = styled.div({
display: 'flex',
gap: '1rem',
flexDirection: 'column',

View File

@@ -1,12 +1,12 @@
import { createContext } from 'react';
import { Link } from '~/types/app';
import { LinkWithCollection } from '~/types/app';
type FavoritesContextType = {
favorites: Link[];
favorites: LinkWithCollection[];
};
const iFavoritesContextState = {
favorites: [] as Link[],
favorites: [] as LinkWithCollection[],
};
const FavoritesContext = createContext<FavoritesContextType>(

View File

@@ -1,7 +1,7 @@
{
"role": "Role",
"created_at": "Created at",
"updated_at": "Updated at",
"last_seen_at": "Last seen at",
"admin": "Administrator",
"user": "User",
"users": "Users",

View File

@@ -32,6 +32,7 @@
"add-favorite": "Add to favorites",
"remove-favorite": "Remove from favorites",
"favorites-appears-here": "Your favorites will appear here",
"go-to-collection": "Go to collection",
"no-item-found": "No item found",
"admin": "Administrator",
"search": "Search",

View File

@@ -1,7 +1,7 @@
{
"role": "Rôle",
"created_at": "Création",
"updated_at": "Mise à jour",
"last_seen_at": "Dernière connexion",
"admin": "Administrateur",
"user": "Utilisateur",
"users": "Utilisateurs",

View File

@@ -32,6 +32,7 @@
"add-favorite": "Ajouter aux favoris",
"remove-favorite": "Retirer des favoris",
"favorites-appears-here": "Vos favoris apparaîtront ici",
"go-to-collection": "Voir la collection",
"no-item-found": "Aucun élément trouvé",
"admin": "Administrateur",
"search": "Rechercher",

22
inertia/lib/favorite.ts Normal file
View File

@@ -0,0 +1,22 @@
import { route } from '@izzyjs/route/client';
import { makeRequest } from '~/lib/request';
import { Link } from '~/types/app';
export const onFavorite = (
linkId: Link['id'],
isFavorite: boolean,
cb: () => void
) => {
const { url, method } = route('link.toggle-favorite', {
params: { id: linkId.toString() },
});
makeRequest({
url,
method,
body: {
favorite: isFavorite,
},
})
.then(() => cb())
.catch(console.error);
};

View File

@@ -1,14 +1,13 @@
import { useTheme } from '@emotion/react';
import styled from '@emotion/styled';
import { ColumnDef } from '@tanstack/react-table';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import { ReactNode } from 'react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import RoundedImage from '~/components/common/rounded_image';
import TextEllipsis from '~/components/common/text_ellipsis';
import Table from '~/components/common/table';
import ContentLayout from '~/components/layouts/content_layout';
import { DATE_FORMAT } from '~/constants';
import { sortByCreationDate } from '~/lib/array';
import { UserWithRelationCount } from '~/types/app';
dayjs.extend(relativeTime);
@@ -19,15 +18,18 @@ interface AdminDashboardProps {
totalLinks: number;
}
const Cell = styled.div<{ column?: boolean; fixed?: boolean }>(
({ column, fixed }) => ({
width: '100%',
const CenteredCell = styled.div({
display: 'flex',
alignItems: 'center',
justifyContent: fixed ? 'unset' : 'center',
gap: column ? 0 : '0.35em',
flexDirection: column ? 'column' : 'row',
})
justifyContent: 'center',
flexDirection: 'column',
});
const RenderDateCell = (info: any) => (
<CenteredCell>
<span>{dayjs(info.getValue().toString()).fromNow()}</span>
<span>{dayjs(info.getValue().toString()).format(DATE_FORMAT)}</span>
</CenteredCell>
);
const ThemeProvider = (props: AdminDashboardProps) => (
@@ -44,95 +46,87 @@ function AdminDashboard({
}: AdminDashboardProps) {
const { t } = useTranslation();
const theme = useTheme();
return (
<div style={{ overflow: 'auto', marginTop: '1em' }}>
<table>
<thead>
<tr>
<TableCell type="th">#</TableCell>
<TableCell type="th">{t('common:name')}</TableCell>
<TableCell type="th">{t('common:email')}</TableCell>
<TableCell type="th">
const columns = useMemo(
() =>
[
{
accessorKey: 'id',
header: () => (
<>
# <span css={{ color: theme.colors.grey }}>({users.length})</span>
</>
),
cell: (info) => info.getValue(),
},
{
accessorKey: 'fullname',
header: t('common:name'),
cell: (info) => info.getValue(),
},
{
accessorKey: 'email',
header: t('common:email'),
cell: (info) => info.getValue(),
},
{
accessorKey: 'collectionsCount',
header: () => (
<>
{t('common:collection.collections', { count: totalCollections })}{' '}
<span css={{ color: theme.colors.grey }}>
({totalCollections})
</span>
</TableCell>
<TableCell type="th">
</>
),
cell: (info) => info.getValue(),
},
{
accessorKey: 'linksCount',
header: () => (
<>
{t('common:link.links', { count: totalLinks })}{' '}
<span css={{ color: theme.colors.grey }}>({totalLinks})</span>
</TableCell>
<TableCell type="th">{t('admin:role')}</TableCell>
<TableCell type="th">{t('admin:created_at')}</TableCell>
<TableCell type="th">{t('admin:updated_at')}</TableCell>
</tr>
</thead>
<tbody>
{users.length !== 0 &&
sortByCreationDate(users).map((user) => (
<TableUserRow user={user} key={user.id} />
))}
</tbody>
</table>
</div>
);
}
function TableUserRow({ user }: { user: UserWithRelationCount }) {
const { t } = useTranslation();
const theme = useTheme();
const { id, fullname, avatarUrl, email, isAdmin, createdAt, updatedAt } =
user;
return (
<tr>
<TableCell type="td">{id}</TableCell>
<TableCell type="td" fixed>
{avatarUrl && (
<RoundedImage
src={avatarUrl}
width={24}
height={24}
alt={fullname}
title={fullname}
referrerPolicy="no-referrer"
/>
)}
<TextEllipsis>{fullname ?? '-'}</TextEllipsis>
</TableCell>
<TableCell type="td">
<TextEllipsis>{email}</TextEllipsis>
</TableCell>
<TableCell type="td">{user.count.collection}</TableCell>
<TableCell type="td">{user.count.link}</TableCell>
<TableCell type="td">
{isAdmin ? (
</>
),
cell: (info: any) => info.getValue(),
},
{
accessorKey: 'isAdmin',
header: t('admin:role'),
cell: (info) =>
info.getValue() ? (
<span style={{ color: theme.colors.lightRed }}>
{t('admin:admin')}
</span>
) : (
<span style={{ color: theme.colors.green }}>{t('admin:user')}</span>
)}
</TableCell>
<TableCell type="td" column>
<span>{dayjs(createdAt.toString()).fromNow()}</span>
<span>{dayjs(createdAt.toString()).format(DATE_FORMAT)}</span>
</TableCell>
<TableCell type="td" column>
<span>{dayjs(updatedAt.toString()).fromNow()}</span>
<span>{dayjs(updatedAt.toString()).format(DATE_FORMAT)}</span>
</TableCell>
</tr>
<span style={{ color: theme.colors.green }}>
{t('admin:user')}
</span>
),
},
{
accessorKey: 'createdAt',
header: t('admin:created_at'),
cell: RenderDateCell,
},
{
accessorKey: 'lastSeenAt',
header: t('admin:last_seen_at'),
cell: RenderDateCell,
},
] satisfies ColumnDef<UserWithRelationCount>[],
[]
);
return (
<Table
columns={columns}
data={users}
defaultSorting={[
{
id: 'lastSeenAt',
desc: true,
},
]}
/>
);
}
type TableItem = {
children: ReactNode;
type: 'td' | 'th';
fixed?: boolean;
column?: boolean;
};
function TableCell({ children, type, ...props }: TableItem) {
const child = <Cell {...props}>{children}</Cell>;
return type === 'td' ? <td>{child}</td> : <th>{child}</th>;
}

View File

@@ -24,10 +24,9 @@ type UserWithRelationCount = CommonBase & {
fullname: string;
avatarUrl: string;
isAdmin: string;
count: {
link: number;
collection: number;
};
linksCount: number;
collectionsCount: number;
lastSeenAt: string;
};
type Link = CommonBase & {

View File

@@ -1,6 +1,6 @@
{
"name": "my-links",
"version": "2.0.3",
"version": "2.2.1",
"type": "module",
"license": "UNLICENSED",
"scripts": {
@@ -8,7 +8,7 @@
"build": "node ace build",
"dev": "node ace serve --watch",
"test": "node ace test",
"lint": "eslint . --ext .ts,.tsx --report-unused-disable-directives --max-warnings 0",
"lint": "eslint . --report-unused-disable-directives --max-warnings 0",
"format": "prettier --write --parser typescript '**/*.{ts,tsx}'",
"typecheck": "tsc --noEmit",
"prepare": "husky",
@@ -36,66 +36,68 @@
"#lib/*": "./app/lib/*.js"
},
"devDependencies": {
"@adonisjs/assembler": "^7.7.0",
"@adonisjs/eslint-config": "^1.3.0",
"@adonisjs/tsconfig": "^1.3.0",
"@emotion/babel-plugin": "^11.11.0",
"@faker-js/faker": "^8.4.1",
"@adonisjs/assembler": "^7.8.2",
"@adonisjs/eslint-config": "2.0.0-beta.6",
"@adonisjs/prettier-config": "^1.4.0",
"@adonisjs/tsconfig": "^1.4.0",
"@emotion/babel-plugin": "^11.12.0",
"@faker-js/faker": "^9.0.3",
"@japa/assert": "^3.0.0",
"@japa/plugin-adonisjs": "^3.0.1",
"@japa/runner": "^3.1.4",
"@swc/core": "^1.6.13",
"@swc/core": "^1.7.26",
"@types/luxon": "^3.4.2",
"@types/node": "^20.14.10",
"@types/react": "^18.3.3",
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.0",
"@types/react-toggle": "^4.0.5",
"@typescript-eslint/eslint-plugin": "^7.15.0",
"@vitejs/plugin-react": "^4.3.1",
"eslint": "^8.57.0",
"hot-hook": "^0.2.6",
"husky": "^9.0.11",
"lint-staged": "^15.2.7",
"pino-pretty": "^11.2.1",
"prettier": "^3.3.2",
"release-it": "^17.4.1",
"ts-node": "^10.9.2",
"typescript": "~5.4.5",
"vite": "^5.3.3"
"@typescript-eslint/eslint-plugin": "^8.8.0",
"@vitejs/plugin-react": "^4.3.2",
"eslint": "^9.12.0",
"hot-hook": "^0.3.0",
"husky": "^9.1.6",
"lint-staged": "^15.2.10",
"pino-pretty": "^11.2.2",
"prettier": "^3.3.3",
"release-it": "^17.7.0",
"ts-node-maintained": "^10.9.4",
"typescript": "~5.5.4",
"vite": "^5.4.8"
},
"dependencies": {
"@adonisjs/ally": "^5.0.2",
"@adonisjs/auth": "^9.2.3",
"@adonisjs/core": "^6.12.1",
"@adonisjs/core": "^6.14.0",
"@adonisjs/cors": "^2.2.1",
"@adonisjs/inertia": "^1.1.0",
"@adonisjs/lucid": "^21.1.0",
"@adonisjs/session": "^7.4.2",
"@adonisjs/inertia": "^1.2.2",
"@adonisjs/lucid": "^21.2.0",
"@adonisjs/session": "^7.5.0",
"@adonisjs/shield": "^8.1.1",
"@adonisjs/static": "^1.1.1",
"@adonisjs/vite": "^3.0.0",
"@emotion/react": "^11.11.4",
"@emotion/styled": "^11.11.5",
"@emotion/react": "11.12.0",
"@emotion/styled": "^11.13.0",
"@inertiajs/react": "^1.2.0",
"@izzyjs/route": "^1.1.0-0",
"@izzyjs/route": "^1.2.0",
"@tanstack/react-table": "^8.20.5",
"@vinejs/vine": "^2.1.0",
"bentocache": "^1.0.0-beta.9",
"dayjs": "^1.11.11",
"edge.js": "^6.0.2",
"dayjs": "^1.11.13",
"edge.js": "^6.2.0",
"hex-rgb": "^5.0.0",
"i18next": "^23.11.5",
"i18next": "^23.15.2",
"knex": "^3.1.0",
"luxon": "^3.4.4",
"luxon": "^3.5.0",
"node-html-parser": "^6.1.13",
"pg": "^8.12.0",
"pg": "^8.13.0",
"react": "^18.3.1",
"react-dnd": "^16.0.1",
"react-dnd-html5-backend": "^16.0.1",
"react-dom": "^18.3.1",
"react-hotkeys-hook": "^4.5.0",
"react-i18next": "^14.1.2",
"react-icons": "^5.2.1",
"react-select": "^5.8.0",
"react-hotkeys-hook": "^4.5.1",
"react-i18next": "^15.0.2",
"react-icons": "^5.3.0",
"react-select": "^5.8.1",
"react-swipeable": "^7.0.1",
"react-toggle": "^4.1.3",
"reflect-metadata": "^0.2.2"
@@ -106,14 +108,11 @@
"./app/middleware/*.ts"
]
},
"eslintConfig": {
"extends": "@adonisjs/eslint-config/app"
},
"prettier": {
"trailingComma": "es5",
"semi": true,
"singleQuote": true,
"useTabs": false,
"useTabs": true,
"quoteProps": "as-needed",
"bracketSpacing": true,
"arrowParens": "always",

2867
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -41,6 +41,8 @@ router.use([
() => import('@adonisjs/session/session_middleware'),
() => import('@adonisjs/shield/shield_middleware'),
() => import('@adonisjs/auth/initialize_auth_middleware'),
() => import('#middleware/silent_auth_middleware'),
() => import('#middleware/update_user_last_seen_middleware'),
]);
/**