refactor: migrate from @izzyjs/route to @tuyau

This commit is contained in:
Sonny
2024-10-28 01:05:45 +01:00
parent 05c867f44f
commit c308262ee0
44 changed files with 294 additions and 235 deletions

View File

@@ -21,3 +21,4 @@ docker-compose*
# App specific
database/seeders
.adonisjs

1
.gitignore vendored
View File

@@ -22,3 +22,4 @@ yarn-error.log
# Platform specific
.DS_Store
.adonisjs

View File

@@ -37,8 +37,7 @@ ENV DB_DATABASE=db_db
ENV GOOGLE_CLIENT_ID=client_id
ENV GOOGLE_CLIENT_SECRET=client_secret
ENV GOOGLE_CLIENT_CALLBACK_URL=http://localhost:3333/auth/callback
RUN node ace izzy:routes
RUN node ace tuyau:generate
RUN node ace build
# Production stage
@@ -53,6 +52,7 @@ ENV PORT=$PORT
WORKDIR /app
COPY --from=production-deps /app/node_modules /app/node_modules
COPY --from=build /app/build /app
COPY --from=build /app/.adonisjs /app/.adonisjs
# Expose port
EXPOSE $PORT

View File

@@ -2,29 +2,29 @@ import { defineConfig } from '@adonisjs/core/app';
export default defineConfig({
/*
|--------------------------------------------------------------------------
| Commands
|--------------------------------------------------------------------------
|
| List of ace commands to register from packages. The application commands
| will be scanned automatically from the "./commands" directory.
|
*/
|--------------------------------------------------------------------------
| Commands
|--------------------------------------------------------------------------
|
| List of ace commands to register from packages. The application commands
| will be scanned automatically from the "./commands" directory.
|
*/
commands: [
() => import('@adonisjs/core/commands'),
() => import('@adonisjs/lucid/commands'),
() => import('@izzyjs/route/commands'),
() => import('@tuyau/core/commands'),
],
/*
|--------------------------------------------------------------------------
| Service providers
|--------------------------------------------------------------------------
|
| List of service providers to import and register when booting the
| application
|
*/
|--------------------------------------------------------------------------
| Service providers
|--------------------------------------------------------------------------
|
| List of service providers to import and register when booting the
| application
|
*/
providers: [
() => import('@adonisjs/core/providers/app_provider'),
() => import('@adonisjs/core/providers/hash_provider'),
@@ -43,29 +43,29 @@ export default defineConfig({
() => import('@adonisjs/auth/auth_provider'),
() => import('@adonisjs/inertia/inertia_provider'),
() => import('@adonisjs/ally/ally_provider'),
() => import('@izzyjs/route/izzy_provider'),
() => import('#providers/route_provider'),
() => import('@tuyau/core/tuyau_provider'),
],
/*
|--------------------------------------------------------------------------
| Preloads
|--------------------------------------------------------------------------
|
| List of modules to import before starting the application.
|
*/
|--------------------------------------------------------------------------
| Preloads
|--------------------------------------------------------------------------
|
| List of modules to import before starting the application.
|
*/
preloads: [() => import('#start/routes'), () => import('#start/kernel')],
/*
|--------------------------------------------------------------------------
| Tests
|--------------------------------------------------------------------------
|
| List of test suites to organize tests by their type. Feel free to remove
| and add additional suites.
|
*/
|--------------------------------------------------------------------------
| Tests
|--------------------------------------------------------------------------
|
| List of test suites to organize tests by their type. Feel free to remove
| and add additional suites.
|
*/
tests: {
suites: [
{
@@ -83,14 +83,14 @@ export default defineConfig({
},
/*
|--------------------------------------------------------------------------
| Metafiles
|--------------------------------------------------------------------------
|
| A collection of files you want to copy to the build folder when creating
| the production build.
|
*/
|--------------------------------------------------------------------------
| Metafiles
|--------------------------------------------------------------------------
|
| A collection of files you want to copy to the build folder when creating
| the production build.
|
*/
metaFiles: [
{
pattern: 'resources/views/**/*.edge',
@@ -105,6 +105,5 @@ export default defineConfig({
assetsBundler: false,
unstable_assembler: {
onBuildStarting: [() => import('@adonisjs/vite/build_hook')],
onDevServerStarted: [() => import('@izzyjs/route/dev_hook')],
},
});

View File

@@ -1,16 +1,12 @@
import { searchTermValidator } from '#validators/search_term';
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' };
}
const { searchTerm } = await request.validateUsing(searchTermValidator);
const { rows } = await db.rawQuery('SELECT * FROM search_text(?, ?)', [
term,
searchTerm,
auth.user!.id,
]);
return { results: rows };

View File

@@ -1,8 +1,8 @@
import User from '#models/user';
import { RouteName } from '#types/tuyau';
import type { HttpContext } from '@adonisjs/core/http';
import logger from '@adonisjs/core/services/logger';
import db from '@adonisjs/lucid/services/db';
import { RouteName } from '@izzyjs/route/types';
export default class UsersController {
private redirectTo: RouteName = 'auth.login';

22
app/lib/tuyau.ts Normal file
View File

@@ -0,0 +1,22 @@
import { api } from '#adonisjs/api';
import { QueryParams } from '#types/query_params';
import { RouteName } from '#types/tuyau';
export const getRoute = (routeName: RouteName, options?: QueryParams) => {
const current = api.routes.find((route) => route.name === routeName);
if (!current) {
throw new Error(`Route ${routeName} not found`);
}
if (options?.qs) {
const searchParams = new URLSearchParams(options?.qs);
return { ...current, path: `${current.path}?${searchParams.toString()}` };
}
return current;
};
export function getPath(routeName: RouteName, options?: QueryParams) {
const current = getRoute(routeName, options);
return current.path;
}

View File

@@ -1,7 +1,7 @@
import { getPath } from '#lib/tuyau';
import type { Authenticators } from '@adonisjs/auth/types';
import type { HttpContext } from '@adonisjs/core/http';
import type { NextFn } from '@adonisjs/core/types/http';
import { route } from '@izzyjs/route/client';
/**
* Auth middleware is used authenticate HTTP requests and deny
@@ -11,7 +11,7 @@ export default class AuthMiddleware {
/**
* The URL to redirect to, when authentication fails
*/
redirectTo = route('auth.login').url;
redirectTo = getPath('auth.login');
async handle(
ctx: HttpContext,

View File

@@ -0,0 +1 @@
export type QueryParams = { qs?: Record<string, any> };

4
app/types/tuyau.ts Normal file
View File

@@ -0,0 +1,4 @@
import { api } from '#adonisjs/api';
export type RouteName = (typeof api)['routes'][number]['name'];
export type RouteParams = (typeof api)['routes'][number]['params'];

View File

@@ -0,0 +1,7 @@
import vine from '@vinejs/vine';
export const searchTermValidator = vine.compile(
vine.object({
searchTerm: vine.string().trim().minLength(1).maxLength(255),
})
);

17
config/tuyau.ts Normal file
View File

@@ -0,0 +1,17 @@
import { defineConfig } from '@tuyau/core'
const tuyauConfig = defineConfig({
codegen: {
/**
* Filters the definitions and named routes to be generated
*/
// definitions: {
// only: [],
// }
// routes: {
// only: [],
// }
}
})
export default tuyauConfig

View File

@@ -1,16 +1,14 @@
import { router } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { ReactNode } from 'react';
import useSearchParam from '~/hooks/use_search_param';
import useShortcut from '~/hooks/use_shortcut';
import { appendCollectionId } from '~/lib/navigation';
import { routeWithCollectionId } 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)),
() => router.visit(routeWithCollectionId('dashboard', collectionId)),
{ disableGlobalCheck: true }
);
return <>{children}</>;

View File

@@ -1,4 +1,3 @@
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import { BsThreeDotsVertical } from 'react-icons/bs';
import { GoPencil } from 'react-icons/go';
@@ -6,7 +5,7 @@ import { IoIosAddCircleOutline } from 'react-icons/io';
import { IoTrashOutline } from 'react-icons/io5';
import Dropdown from '~/components/common/dropdown/dropdown';
import { DropdownItemLink } from '~/components/common/dropdown/dropdown_item';
import { appendCollectionId } from '~/lib/navigation';
import { getPath, routeWithCollectionId } from '~/lib/navigation';
import { Collection } from '~/types/app';
export default function CollectionControls({
@@ -17,22 +16,16 @@ export default function CollectionControls({
const { t } = useTranslation('common');
return (
<Dropdown label={<BsThreeDotsVertical />} svgSize={18}>
<DropdownItemLink href={route('link.create-form').url}>
<DropdownItemLink href={getPath('link.create-form')}>
<IoIosAddCircleOutline /> {t('link.create')}
</DropdownItemLink>
<DropdownItemLink
href={appendCollectionId(
route('collection.edit-form').url,
collectionId
)}
href={routeWithCollectionId('collection.edit-form', collectionId)}
>
<GoPencil /> {t('collection.edit')}
</DropdownItemLink>
<DropdownItemLink
href={appendCollectionId(
route('collection.delete-form').url,
collectionId
)}
href={routeWithCollectionId('collection.delete-form', collectionId)}
danger
>
<IoTrashOutline /> {t('collection.delete')}

View File

@@ -1,12 +1,11 @@
import styled from '@emotion/styled';
import { Link } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useEffect, useRef } from 'react';
import { AiFillFolderOpen, AiOutlineFolder } from 'react-icons/ai';
import TextEllipsis from '~/components/common/text_ellipsis';
import { Item } from '~/components/dashboard/side_nav/nav_item';
import useActiveCollection from '~/hooks/use_active_collection';
import { appendCollectionId } from '~/lib/navigation';
import { routeWithCollectionId } from '~/lib/navigation';
import { CollectionWithLinks } from '~/types/app';
const CollectionItemStyle = styled(Item, {
@@ -43,7 +42,7 @@ export default function CollectionItem({
return (
<CollectionItemLink
href={appendCollectionId(route('dashboard').url, collection.id)}
href={routeWithCollectionId('dashboard', collection.id)}
isActive={isActiveCollection}
ref={itemRef}
>

View File

@@ -1,12 +1,11 @@
import { router } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { ReactNode, useMemo, useState } from 'react';
import { ActiveCollectionContext } from '~/contexts/active_collection_context';
import CollectionsContext from '~/contexts/collections_context';
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 { routeWithCollectionId } from '~/lib/navigation';
import { CollectionWithLinks, LinkWithCollection } from '~/types/app';
export default function DashboardProviders(
@@ -28,7 +27,7 @@ export default function DashboardProviders(
const handleChangeCollection = (collection: CollectionWithLinks) => {
setActiveCollection(collection);
router.visit(appendCollectionId(route('dashboard').url, collection.id));
router.visit(routeWithCollectionId('dashboard', collection.id));
};
// TODO: compute this in controller
@@ -67,7 +66,7 @@ export default function DashboardProviders(
'OPEN_CREATE_LINK_KEY',
() =>
router.visit(
appendCollectionId(route('link.create-form').url, activeCollection?.id)
routeWithCollectionId('link.create-form', activeCollection?.id)
),
{
enabled: globalHotkeysEnabled,
@@ -75,7 +74,7 @@ export default function DashboardProviders(
);
useShortcut(
'OPEN_CREATE_COLLECTION_KEY',
() => router.visit(route('collection.create-form').url),
() => router.visit('collection.create-form'),
{
enabled: globalHotkeysEnabled,
}

View File

@@ -1,5 +1,4 @@
import { useTheme } from '@emotion/react';
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import { BsThreeDotsVertical } from 'react-icons/bs';
import { GoPencil } from 'react-icons/go';
@@ -7,7 +6,7 @@ import { IoTrashOutline } from 'react-icons/io5';
import Dropdown from '~/components/common/dropdown/dropdown';
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 { routeWithLinkId } from '~/lib/navigation';
import { Link } from '~/types/app';
export default function LinkControls({ link }: { link: Link }) {
@@ -21,13 +20,11 @@ export default function LinkControls({ link }: { link: Link }) {
svgSize={18}
>
<FavoriteDropdownItem link={link} />
<DropdownItemLink
href={appendLinkId(route('link.edit-form').url, link.id)}
>
<DropdownItemLink href={routeWithLinkId('link.edit-form', link.id)}>
<GoPencil /> {t('link.edit')}
</DropdownItemLink>
<DropdownItemLink
href={appendLinkId(route('link.delete-form').url, link.id)}
href={routeWithLinkId('link.delete-form', link.id)}
danger
>
<IoTrashOutline /> {t('link.delete')}

View File

@@ -1,9 +1,8 @@
import styled from '@emotion/styled';
import { Link } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import useActiveCollection from '~/hooks/use_active_collection';
import { appendCollectionId } from '~/lib/navigation';
import { routeWithCollectionId } from '~/lib/navigation';
import { fadeIn } from '~/styles/keyframes';
const NoCollectionStyle = styled.div({
@@ -30,9 +29,7 @@ export function NoCollection() {
return (
<NoCollectionStyle>
<Text>{t('select-collection')}</Text>
<Link href={route('collection.create-form').url}>
{t('or-create-one')}
</Link>
<Link href={'collection.create-form'}>{t('or-create-one')}</Link>
</NoCollectionStyle>
);
}
@@ -54,10 +51,7 @@ export function NoLink() {
}}
/>
<Link
href={appendCollectionId(
route('link.create-form').url,
activeCollection?.id
)}
href={routeWithCollectionId('link.create-form', activeCollection?.id)}
>
{t('link.create')}
</Link>

View File

@@ -1,5 +1,4 @@
import styled from '@emotion/styled';
import { route } from '@izzyjs/route/client';
import { FormEvent, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { IoIosSearch } from 'react-icons/io';
@@ -11,7 +10,7 @@ import useActiveCollection from '~/hooks/use_active_collection';
import useCollections from '~/hooks/use_collections';
import useToggle from '~/hooks/use_modal';
import useShortcut from '~/hooks/use_shortcut';
import { makeRequest } from '~/lib/request';
import { tuyau, tuyauAbortController } from '~/lib/tuyau';
import { SearchResult } from '~/types/search';
const SearchInput = styled.input(({ theme }) => ({
@@ -78,18 +77,14 @@ function SearchModal({ openItem: OpenItem }: SearchModalProps) {
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]);
tuyau.search.$get({ query: { searchTerm } }).then(({ error, data }) => {
if (error?.status === 404) return setResults([]);
const results = data?.results || [];
setResults(results);
setSelectedItem(results?.[0]);
});
return () => controller.abort();
return () => tuyauAbortController.abort();
}, [searchTerm]);
return (

View File

@@ -1,5 +1,4 @@
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';
@@ -12,7 +11,7 @@ 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 { routeWithCollectionId, routeWithLinkId } from '~/lib/navigation';
import { LinkWithCollection } from '~/types/app';
const FavoriteItemStyle = styled(ItemExternalLink)(({ theme }) => ({
@@ -47,18 +46,16 @@ export default function FavoriteItem({ link }: { link: LinkWithCollection }) {
svgSize={18}
>
<DropdownItemLink
href={appendCollectionId(route('dashboard').url, link.collection.id)}
href={routeWithCollectionId('dashboard', link.collection.id)}
>
<FaRegEye /> {t('go-to-collection')}
</DropdownItemLink>
<FavoriteDropdownItem link={link} />
<DropdownItemLink
href={appendLinkId(route('link.edit-form').url, link.id)}
>
<DropdownItemLink href={routeWithLinkId('link.edit-form', link.id)}>
<GoPencil /> {t('link.edit')}
</DropdownItemLink>
<DropdownItemLink
href={appendLinkId(route('link.delete-form').url, link.id)}
href={routeWithLinkId('link.delete-form', link.id)}
danger
>
<IoTrashOutline /> {t('link.delete')}

View File

@@ -1,5 +1,4 @@
import styled from '@emotion/styled';
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import { AiOutlineFolderAdd } from 'react-icons/ai';
import { IoAdd, IoShieldHalfSharp } from 'react-icons/io5';
@@ -11,7 +10,7 @@ import ModalSettings from '~/components/settings/settings_modal';
import useActiveCollection from '~/hooks/use_active_collection';
import useUser from '~/hooks/use_user';
import { rgba } from '~/lib/color';
import { appendCollectionId } from '~/lib/navigation';
import { getPath, routeWithCollectionId } from '~/lib/navigation';
const SideMenu = styled.nav(({ theme }) => ({
height: '100%',
@@ -56,21 +55,18 @@ export default function SideNavigation() {
<div css={{ paddingInline: '10px' }}>
<UserCard />
{user!.isAdmin && (
<AdminButton href={route('admin.dashboard').url}>
<AdminButton href={getPath('admin.dashboard')}>
<IoShieldHalfSharp /> {t('admin')}
</AdminButton>
)}
<ModalSettings openItem={SettingsButton} />
<SearchModal openItem={SearchButton} />
<AddButton
href={appendCollectionId(
route('link.create-form').url,
activeCollection?.id
)}
href={routeWithCollectionId('link.create-form', activeCollection?.id)}
>
<IoAdd /> {t('link.create')}
</AddButton>
<AddButton href={route('collection.create-form').url}>
<AddButton href={getPath('collection.create-form')}>
<AiOutlineFolderAdd /> {t('collection.create')}
</AddButton>
</div>

View File

@@ -1,9 +1,9 @@
import PATHS from '#constants/paths';
import styled from '@emotion/styled';
import { Link } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import ExternalLink from '~/components/common/external_link';
import { getPath } from '~/lib/navigation';
import packageJson from '../../../package.json';
const FooterStyle = styled.footer(({ theme }) => ({
@@ -22,9 +22,9 @@ export default function Footer({ className }: { className?: string }) {
return (
<FooterStyle className={className}>
<div className="row">
<Link href={route('privacy').url}>{t('privacy')}</Link>
<Link href={getPath('privacy')}>{t('privacy')}</Link>
{' • '}
<Link href={route('terms').url}>{t('terms')}</Link>
<Link href={getPath('terms')}>{t('terms')}</Link>
{' • '}
<ExternalLink href={PATHS.EXTENSION}>Extension</ExternalLink>
</div>

View File

@@ -1,8 +1,8 @@
import styled from '@emotion/styled';
import { Link } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import Quotes from '~/components/quotes';
import { getPath } from '~/lib/navigation';
const HeroStyle = styled.header(({ theme }) => ({
height: '250px',
@@ -46,9 +46,7 @@ export default function HeroHeader() {
<HeroStyle>
<HeroTitle>{t('about:hero.title')}</HeroTitle>
<HeroQuote>{t('common:slogan')}</HeroQuote>
<LinkButton href={route('dashboard').url}>
{t('about:hero.cta')}
</LinkButton>
<LinkButton href={getPath('dashboard')}>{t('about:hero.cta')}</LinkButton>
</HeroStyle>
);
}

View File

@@ -1,13 +1,12 @@
import styled from '@emotion/styled';
import { Head, Link } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { FormEvent, ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import Button from '~/components/common/form/_button';
import Form from '~/components/common/form/_form';
import TransitionLayout from '~/components/layouts/_transition_layout';
import i18n from '~/i18n';
import { appendCollectionId } from '~/lib/navigation';
import { routeWithCollectionId } from '~/lib/navigation';
import BaseLayout from './_base_layout';
const FormLayoutStyle = styled(TransitionLayout)(({ theme }) => ({
@@ -59,7 +58,7 @@ export default function FormLayout({
</Button>
</Form>
{!disableHomeLink && (
<Link href={appendCollectionId(route('dashboard').url, collectionId)}>
<Link href={routeWithCollectionId('dashboard', collectionId)}>
{t('back-home')}
</Link>
)}

View File

@@ -1,7 +1,6 @@
import PATHS from '#constants/paths';
import styled from '@emotion/styled';
import { Link } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import { IoIosLogOut } from 'react-icons/io';
import Dropdown from '~/components/common/dropdown/dropdown';
@@ -14,6 +13,7 @@ import RoundedImage from '~/components/common/rounded_image';
import UnstyledList from '~/components/common/unstyled/unstyled_list';
import ModalSettings from '~/components/settings/settings_modal';
import useUser from '~/hooks/use_user';
import { getPath } from '~/lib/navigation';
type NavbarListDirection = {
right?: boolean;
@@ -66,7 +66,7 @@ export default function Navbar() {
<Nav>
<NavList>
<li>
<Link href={route('home').url} css={{ fontSize: '24px' }}>
<Link href={getPath('home')} css={{ fontSize: '24px' }}>
MyLinks
</Link>
</li>
@@ -79,13 +79,13 @@ export default function Navbar() {
<>
{user.isAdmin && (
<li>
<AdminLink href={route('admin.dashboard').url}>
<AdminLink href={getPath('admin.dashboard')}>
{t('admin')}
</AdminLink>
</li>
)}
<li>
<Link href={route('dashboard').url}>Dashboard</Link>
<Link href={getPath('dashboard')}>Dashboard</Link>
</li>
<li>
<ProfileDropdown />
@@ -97,7 +97,7 @@ export default function Navbar() {
<ModalSettings openItem={DropdownItemButtonWithPadding} />
</li>
<li>
<Link href={route('auth.login').url}>{t('login')}</Link>
<Link href={getPath('auth.login')}>{t('login')}</Link>
</li>
</>
)}
@@ -124,7 +124,7 @@ function ProfileDropdown() {
}
>
<ModalSettings openItem={DropdownItemButton} />
<DropdownItemLink href={route('auth.logout').url} danger>
<DropdownItemLink href={getPath('auth.logout')} danger>
<IoIosLogOut /> {t('logout')}
</DropdownItemLink>
</Dropdown>

View File

@@ -1,6 +1,5 @@
import styled from '@emotion/styled';
import { Link } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import dayjs from 'dayjs';
import { Fragment } from 'react';
import { useTranslation } from 'react-i18next';
@@ -8,6 +7,7 @@ import RoundedImage from '~/components/common/rounded_image';
import UnstyledList from '~/components/common/unstyled/unstyled_list';
import { DATE_FORMAT } from '~/constants';
import useUser from '~/hooks/use_user';
import { getPath } from '~/lib/navigation';
const ProfileStyle = styled(UnstyledList)({
display: 'flex',
@@ -47,7 +47,7 @@ export default function Profile() {
alt={avatarLabel}
title={avatarLabel}
/>
<Link href={route('auth.logout').url}>{t('logout')}</Link>
<Link href={getPath('auth.logout')}>{t('logout')}</Link>
</Column>
<Column>
<Field>

View File

@@ -1,7 +1,6 @@
import { usePage } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { ReactNode, createContext, useEffect, useState } from 'react';
import { makeRequest } from '~/lib/request';
import { tuyau } from '~/lib/tuyau';
const LS_KEY = 'dark_theme';
@@ -19,13 +18,8 @@ export default function DarkThemeContextProvider({
const [isDarkTheme, setDarkTheme] = useState<boolean>(preferDarkTheme);
const toggleDarkTheme = (value: boolean) => {
setDarkTheme(value);
const { method, url } = route('user.theme');
makeRequest({
method,
url,
body: {
preferDarkTheme: value,
},
tuyau.user.theme.$post({
preferDarkTheme: value,
});
};

View File

@@ -1,5 +1,4 @@
import { route } from '@izzyjs/route/client';
import { makeRequest } from '~/lib/request';
import { tuyau } from '~/lib/tuyau';
import { Link } from '~/types/app';
export const onFavorite = (
@@ -7,16 +6,14 @@ export const onFavorite = (
isFavorite: boolean,
cb: () => void
) => {
const { url, method } = route('link.toggle-favorite', {
params: { id: linkId.toString() },
});
makeRequest({
url,
method,
body: {
tuyau
.$route('link.toggle-favorite', {
id: linkId.toString(),
})
.$put({
favorite: isFavorite,
},
})
params: { id: linkId.toString() },
})
.then(() => cb())
.catch(console.error);
};

View File

@@ -1,19 +1,43 @@
import { tuyau } from '~/lib/tuyau';
import { Collection, Link } from '~/types/app';
import { RouteName } from '~/types/tuyau';
export const appendCollectionId = (
url: string,
export const routeWithCollectionId = (
routeName: RouteName,
collectionId?: Collection['id'] | null | undefined
) => `${url}${collectionId ? `?collectionId=${collectionId}` : ''}`;
) =>
buildUrlWithQueryParams(routeName, {
collectionId,
});
export const appendLinkId = (
url: string,
export const routeWithLinkId = (
routeName: RouteName,
linkId?: Link['id'] | null | undefined
) => `${url}${linkId ? `?linkId=${linkId}` : ''}`;
) => buildUrlWithQueryParams(routeName, { linkId });
export const appendResourceId = (
url: string,
export const routeWithResourceId = (
routeName: RouteName,
resourceId?: Collection['id'] | Link['id']
) => `${url}${resourceId ? `/${resourceId}` : ''}`;
) => `${routeName}${resourceId ? `/${resourceId}` : ''}`;
export function buildUrlWithQueryParams(
routeName: RouteName,
queryParam: Record<string, string | number | null | undefined>
) {
const path = tuyau.$route(routeName).path;
const [key, value] = Object.entries(queryParam)[0];
if (!value) {
return path;
}
const searchParams = new URLSearchParams({
[key]: value.toString(),
});
return `${path}?${searchParams}`;
}
export const getRoute = (routeName: RouteName) => tuyau.$route(routeName);
export const getPath = (routeName: RouteName) => getRoute(routeName).path;
export function isValidHttpUrl(urlParam: string) {
let url;

11
inertia/lib/tuyau.ts Normal file
View File

@@ -0,0 +1,11 @@
/// <reference path="../../adonisrc.ts" />
import { api } from '#adonisjs/api';
import { createTuyau } from '@tuyau/client';
export const tuyauAbortController = new AbortController();
export const tuyau = createTuyau({
api,
baseUrl: 'http://localhost:3333',
signal: tuyauAbortController.signal,
});

View File

@@ -1,11 +1,11 @@
import { Visibility } from '#enums/visibility';
import { useForm } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import FormCollection, {
FormCollectionData,
} from '~/components/form/form_collection';
import { getRoute } from '~/lib/navigation';
export default function CreateCollectionPage({
disableHomeLink,
@@ -24,8 +24,8 @@ export default function CreateCollectionPage({
);
const handleSubmit = () => {
const { method, url } = route('collection.create');
submit(method, url);
const { method, path } = getRoute('collection.create');
submit(method.at(0) as any, path);
};
return (

View File

@@ -1,9 +1,9 @@
import { useForm } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import FormCollection, {
FormCollectionData,
} from '~/components/form/form_collection';
import { tuyau } from '~/lib/tuyau';
import { Collection } from '~/types/app';
export default function DeleteCollectionPage({
@@ -20,10 +20,10 @@ export default function DeleteCollectionPage({
});
const handleSubmit = () => {
const { method, url } = route('collection.delete', {
params: { id: collection.id.toString() },
const { method, path } = tuyau.$route('collection.delete', {
id: collection.id.toString(),
});
submit(method, url);
submit(method.at(0) as any, path);
};
return (

View File

@@ -1,10 +1,10 @@
import { useForm } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import FormCollection, {
FormCollectionData,
} from '~/components/form/form_collection';
import { tuyau } from '~/lib/tuyau';
import { Collection } from '~/types/app';
export default function EditCollectionPage({
@@ -30,10 +30,10 @@ export default function EditCollectionPage({
}, [data, collection]);
const handleSubmit = () => {
const { method, url } = route('collection.edit', {
params: { id: collection.id.toString() },
const { method, path } = tuyau.$route('collection.edit', {
id: collection.id.toString(),
});
submit(method, url);
submit(method.at(0) as any, path);
};
return (

View File

@@ -1,10 +1,10 @@
import { useForm } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import FormLink from '~/components/form/form_link';
import useSearchParam from '~/hooks/use_search_param';
import { isValidHttpUrl } from '~/lib/navigation';
import { tuyau } from '~/lib/tuyau';
import { Collection } from '~/types/app';
export default function CreateLinkPage({
@@ -33,8 +33,8 @@ export default function CreateLinkPage({
);
const handleSubmit = () => {
const { method, url } = route('link.create');
submit(method, url);
const { method, path } = tuyau.$route('link.create');
submit(method.at(0) as any, path);
};
return (

View File

@@ -1,7 +1,7 @@
import { useForm } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useTranslation } from 'react-i18next';
import FormLink from '~/components/form/form_link';
import { tuyau } from '~/lib/tuyau';
import { LinkWithCollection } from '~/types/app';
export default function DeleteLinkPage({ link }: { link: LinkWithCollection }) {
@@ -15,10 +15,10 @@ export default function DeleteLinkPage({ link }: { link: LinkWithCollection }) {
});
const handleSubmit = () => {
const { method, url } = route('link.delete', {
params: { id: link.id.toString() },
const { method, path } = tuyau.$route('link.delete', {
id: link.id.toString(),
});
submit(method, url);
submit(method.at(0) as any, path);
};
return (

View File

@@ -1,9 +1,9 @@
import { useForm } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import FormLink from '~/components/form/form_link';
import { isValidHttpUrl } from '~/lib/navigation';
import { tuyau } from '~/lib/tuyau';
import { Collection, Link } from '~/types/app';
export default function EditLinkPage({
@@ -39,10 +39,10 @@ export default function EditLinkPage({
}, [data, processing]);
const handleSubmit = () => {
const { method, url } = route('link.edit', {
params: { id: link.id.toString() },
const { method, path } = tuyau.$route('link.edit', {
id: link.id.toString(),
});
submit(method, url);
submit(method.at(0) as any, path);
};
return (

View File

@@ -1,12 +1,12 @@
import styled from '@emotion/styled';
import { Head, Link } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { FcGoogle } from 'react-icons/fc';
import Button from '~/components/common/form/_button';
import ContentLayout from '~/components/layouts/content_layout';
import Quotes from '~/components/quotes';
import { getPath } from '~/lib/navigation';
const LoginContainer = styled.div({
width: '100%',
@@ -70,14 +70,14 @@ function LoginPage() {
<FormWrapper>
<h1>{t('login:title')}</h1>
<InformativeText>{t('login:informative-text')}</InformativeText>
<ButtonLink href={route('auth.google').url}>
<ButtonLink href={getPath('auth.google')}>
<FcGoogle size="1.5em" />{' '}
{t('login:continue-with', { provider: 'Google' })}
</ButtonLink>
</FormWrapper>
<AgreementText>
{t('login:accept-terms')}{' '}
<Link href={route('terms').url}>{t('common:terms')}</Link>
<Link href={getPath('terms')}>{t('common:terms')}</Link>
</AgreementText>
</LoginContainer>
);

View File

@@ -1,8 +1,8 @@
import { Link } from '@inertiajs/react';
import { route } from '@izzyjs/route/client';
import { ReactNode } from 'react';
import { Trans, useTranslation } from 'react-i18next';
import LegalContentLayout from '~/components/layouts/legal_content_layout';
import { getPath } from '~/lib/navigation';
function TermsPage() {
const { t } = useTranslation('terms');
@@ -30,7 +30,7 @@ function TermsPage() {
<p>
<Trans
i18nKey="personal_data.collect.description"
components={{ a: <Link href={route('privacy').url} /> }}
components={{ a: <Link href={getPath('privacy')} /> }}
/>
</p>

3
inertia/types/tuyau.ts Normal file
View File

@@ -0,0 +1,3 @@
import { api } from '#adonisjs/api';
export type RouteName = (typeof api)['routes'][number]['name'];

View File

@@ -33,7 +33,9 @@
"#tests/*": "./tests/*.js",
"#start/*": "./start/*.js",
"#config/*": "./config/*.js",
"#lib/*": "./app/lib/*.js"
"#lib/*": "./app/lib/*.js",
"#types/*": "./app/types/*.js",
"#adonisjs/*": "./.adonisjs/*.js"
},
"devDependencies": {
"@adonisjs/assembler": "^7.8.2",
@@ -78,8 +80,10 @@
"@emotion/react": "11.12.0",
"@emotion/styled": "^11.13.0",
"@inertiajs/react": "^1.2.0",
"@izzyjs/route": "^1.2.0",
"@tanstack/react-table": "^8.20.5",
"@tuyau/client": "^0.1.3",
"@tuyau/core": "^0.2.1",
"@tuyau/utils": "^0.0.4",
"@vinejs/vine": "^2.1.0",
"bentocache": "^1.0.0-beta.9",
"dayjs": "^1.11.13",

55
pnpm-lock.yaml generated
View File

@@ -47,12 +47,18 @@ importers:
'@inertiajs/react':
specifier: ^1.2.0
version: 1.2.0(react@18.3.1)
'@izzyjs/route':
specifier: ^1.2.0
version: 1.2.0(@adonisjs/core@6.14.1(@adonisjs/assembler@7.8.2(babel-plugin-macros@3.1.0)(typescript@5.5.4))(@vinejs/vine@2.1.0)(edge.js@6.2.0))(edge.js@6.2.0)
'@tanstack/react-table':
specifier: ^8.20.5
version: 8.20.5(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
'@tuyau/client':
specifier: ^0.1.3
version: 0.1.3
'@tuyau/core':
specifier: ^0.2.1
version: 0.2.1(@adonisjs/core@6.14.1(@adonisjs/assembler@7.8.2(babel-plugin-macros@3.1.0)(typescript@5.5.4))(@vinejs/vine@2.1.0)(edge.js@6.2.0))
'@tuyau/utils':
specifier: ^0.0.4
version: 0.0.4
'@vinejs/vine':
specifier: ^2.1.0
version: 2.1.0
@@ -933,13 +939,6 @@ packages:
resolution: {integrity: sha512-ErXXzENMH5pJt5/ssXV0DfWUZqly8nGzf0UcBV9xTnP+KyffE2mqyxIMBrZ8ijQck2nU0TQm40EQB53YreyWHw==}
engines: {node: '>=18'}
'@izzyjs/route@1.2.0':
resolution: {integrity: sha512-GOc2tf4xNrFMZK3SGK7XSweUfxNskJX6vrdhx9M8mDOgkRONnpuIzaVM/N7AgRjCft8f97d5t2oOXyk5Sq92hA==}
engines: {node: '>=20.6.0'}
peerDependencies:
'@adonisjs/core': ^6.2.0
edge.js: ^6.0.2
'@japa/assert@3.0.0':
resolution: {integrity: sha512-4Uvixj78PBpRGeNTqO1GN/qYyl4EeWmIwt/cKiQSLLsoZQpQfe8tvF4PO2Z+zteUi3Zv7WR6pluKYbLQrn3vjg==}
engines: {node: '>=18.16.0'}
@@ -1395,6 +1394,15 @@ packages:
'@tsconfig/node16@1.0.4':
resolution: {integrity: sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==}
'@tuyau/client@0.1.3':
resolution: {integrity: sha512-00IqAkbae7a154bpcavuJYcv1oRQW4nfSVND2jZn/ZACHPEcFVWoBmgM9Gl0wdELoHotsQSQ2eC+nDqfDvanAQ==}
'@tuyau/core@0.2.1':
resolution: {integrity: sha512-CUA1bfEoqVOLFEzSQ8cTHBu+Z+Sbv8CFArr0iKctuApbQ+YJVuY8sAW4J0KgjfoTFOC+wVYtU2Dcp90ZVBZj8g==}
engines: {node: '>=20.6.0'}
peerDependencies:
'@adonisjs/core': ^6.2.0
'@tuyau/utils@0.0.4':
resolution: {integrity: sha512-ex6CAJNLiTuOvx7nUrgs8FwNG/t88Mi8QTLSO3muHbB6vBSpYimZ6iSUkk4cjEFd4XDy0y+24GDgXKoBfGf4ag==}
@@ -3306,6 +3314,10 @@ packages:
resolution: {integrity: sha512-KJ/IXXkFhTDqxcN8wKqMXk1/UoOpc0UnOB6H7QcqlPInh/M2B5Mlj+i9exez1w4RSwJhNFmHiUDPriAYFwb5VA==}
engines: {node: '>=18'}
ky@1.7.2:
resolution: {integrity: sha512-OzIvbHKKDpi60TnF9t7UUVAF1B4mcqc02z5PIvrm08Wyb+yOcz63GRvEuVxNT18a9E1SrNouhB4W2NNLeD7Ykg==}
engines: {node: '>=18'}
latest-version@9.0.0:
resolution: {integrity: sha512-7W0vV3rqv5tokqkBAFV1LbR7HPOWzXQDpDgEuib/aJ1jsZZx6x3c2mBI+TJhJzOhkGeaLbCKEHXEXLfirtG2JA==}
engines: {node: '>=18'}
@@ -3607,6 +3619,9 @@ packages:
resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}
engines: {node: '>= 0.4'}
object-to-formdata@4.5.1:
resolution: {integrity: sha512-QiM9D0NiU5jV6J6tjE1g7b4Z2tcUnKs1OPUi4iMb2zH+7jwlcUrASghgkFk9GtzqNNq8rTQJtT8AzjBAvLoNMw==}
object.assign@4.1.5:
resolution: {integrity: sha512-byy+U7gp+FVwmyzKPYhW2h5l3crpmGsxl7X2s8y43IgxvG4g3QZ6CffDtsNQy1WsmZpQbO+ybo0AlW7TY6DcBQ==}
engines: {node: '>= 0.4'}
@@ -5736,11 +5751,6 @@ snapshots:
'@inquirer/figures@1.0.3': {}
'@izzyjs/route@1.2.0(@adonisjs/core@6.14.1(@adonisjs/assembler@7.8.2(babel-plugin-macros@3.1.0)(typescript@5.5.4))(@vinejs/vine@2.1.0)(edge.js@6.2.0))(edge.js@6.2.0)':
dependencies:
'@adonisjs/core': 6.14.1(@adonisjs/assembler@7.8.2(babel-plugin-macros@3.1.0)(typescript@5.5.4))(@vinejs/vine@2.1.0)(edge.js@6.2.0)
edge.js: 6.2.0
'@japa/assert@3.0.0(@japa/runner@3.1.4)(openapi-types@1.3.4)':
dependencies:
'@japa/runner': 3.1.4
@@ -6180,6 +6190,17 @@ snapshots:
'@tsconfig/node16@1.0.4': {}
'@tuyau/client@0.1.3':
dependencies:
'@poppinss/matchit': 3.1.2
ky: 1.7.2
object-to-formdata: 4.5.1
'@tuyau/core@0.2.1(@adonisjs/core@6.14.1(@adonisjs/assembler@7.8.2(babel-plugin-macros@3.1.0)(typescript@5.5.4))(@vinejs/vine@2.1.0)(edge.js@6.2.0))':
dependencies:
'@adonisjs/core': 6.14.1(@adonisjs/assembler@7.8.2(babel-plugin-macros@3.1.0)(typescript@5.5.4))(@vinejs/vine@2.1.0)(edge.js@6.2.0)
ts-morph: 23.0.0
'@tuyau/utils@0.0.4': {}
'@types/babel__core@7.20.5':
@@ -8196,6 +8217,8 @@ snapshots:
ky@1.7.1: {}
ky@1.7.2: {}
latest-version@9.0.0:
dependencies:
package-json: 10.0.1
@@ -8456,6 +8479,8 @@ snapshots:
object-keys@1.1.1: {}
object-to-formdata@4.5.1: {}
object.assign@4.1.5:
dependencies:
call-bind: 1.0.7

View File

@@ -1,18 +1,17 @@
import { getRoute } from '#lib/tuyau';
import { QueryParams } from '#types/query_params';
import { RouteName, RouteParams } from '#types/tuyau';
import { Response } from '@adonisjs/core/http';
import { route } from '@izzyjs/route/client';
import { RouteName } from '@izzyjs/route/types';
type IzzyRouteOptions = {
params?: Record<string, any>; //Params<Name>;
qs?: Record<string, any>;
prefix?: string;
};
type RouteOptions = {
params?: RouteParams;
} & QueryParams;
declare module '@adonisjs/core/http' {
export interface Response {
redirectToNamedRoute: (
routeName: RouteName,
options?: IzzyRouteOptions
options?: RouteOptions
) => void;
}
}
@@ -20,12 +19,7 @@ declare module '@adonisjs/core/http' {
Response.macro(
'redirectToNamedRoute',
function (this: Response, routeName, options) {
// TODO: fix this
// @ts-ignore
const current = route(routeName, options);
this.redirect().toRoute(current.url, current.params, {
qs: current.qs,
disableRouteLookup: true,
});
const route = getRoute(routeName, options);
this.redirect().toRoute(route.path, route.params, options);
}
);

View File

@@ -29,7 +29,6 @@ server.use([
() => import('@adonisjs/cors/cors_middleware'),
() => import('@adonisjs/vite/vite_middleware'),
() => import('@adonisjs/inertia/inertia_middleware'),
() => import('@izzyjs/route/izzy_middleware'),
]);
/**

View File

@@ -1,9 +1,8 @@
import { assert } from '@japa/assert';
import app from '@adonisjs/core/services/app';
import type { Config } from '@japa/runner/types';
import { pluginAdonisJS } from '@japa/plugin-adonisjs';
import testUtils from '@adonisjs/core/services/test_utils';
import { izzyRoutePlugin } from '@izzyjs/route/plugins/japa';
import { assert } from '@japa/assert';
import { pluginAdonisJS } from '@japa/plugin-adonisjs';
import type { Config } from '@japa/runner/types';
/**
* This file is imported by the "bin/test.ts" entrypoint file
@@ -13,11 +12,7 @@ import { izzyRoutePlugin } from '@izzyjs/route/plugins/japa';
* Configure Japa plugins in the plugins array.
* Learn more - https://japa.dev/docs/runner-config#plugins-optional
*/
export const plugins: Config['plugins'] = [
assert(),
pluginAdonisJS(app),
izzyRoutePlugin(),
];
export const plugins: Config['plugins'] = [assert(), pluginAdonisJS(app)];
/**
* Configure lifecycle function to run before and after all the