Skip to content

Commit

Permalink
Add Link component to @mfng/core/client
Browse files Browse the repository at this point in the history
  • Loading branch information
unstubbable committed Mar 14, 2024
1 parent afce936 commit 6e5669f
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 28 deletions.
23 changes: 0 additions & 23 deletions apps/shared-app/src/client/link.tsx

This file was deleted.

11 changes: 6 additions & 5 deletions apps/shared-app/src/shared/navigation-item.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {Link} from '@mfng/core/client';
import {useRouterLocation} from '@mfng/core/use-router-location';
import * as React from 'react';
import {Link} from '../client/link.js';

export type NavigationItemProps = React.PropsWithChildren<{
readonly pathname: string;
Expand All @@ -21,10 +21,11 @@ export function NavigationItem({
}

return (
<Link pathname={pathname}>
<span className="inline-block rounded-md py-1 px-3 text-zinc-200 hover:bg-zinc-600">
{children}
</span>
<Link
to={{pathname}}
className="inline-block rounded-md py-1 px-3 text-zinc-200 hover:bg-zinc-600"
>
{children}
</Link>
);
}
1 change: 1 addition & 0 deletions packages/core/src/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './hydrate-app.js';
export * from './link.js';
export * from './use-router.js';
41 changes: 41 additions & 0 deletions packages/core/src/client/link.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use client';

import {useRouter} from '@mfng/core/client';
import type {RouterLocation} from '@mfng/core/use-router-location';
import {useRouterLocation} from '@mfng/core/use-router-location';
import * as React from 'react';
import {createUrlPath} from './router-location-utils.js';

export type LinkProps = React.PropsWithChildren<{
readonly to: Partial<RouterLocation>;
readonly action?: 'push' | 'replace';
readonly className?: string;
}>;

export function Link({
children,
to,
action = `push`,
className,
}: LinkProps): React.ReactNode {
const router = useRouter();
const location = useRouterLocation();

const urlPath = createUrlPath({
pathname: to.pathname ?? location.pathname,
search: to.search ?? ``,
});

const handleClick: React.MouseEventHandler<HTMLAnchorElement> = (event) => {
if (!event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) {
event.preventDefault();
router[action](to);
}
};

return (
<a href={urlPath} onClick={handleClick} className={className}>
{children}
</a>
);
}
2 changes: 2 additions & 0 deletions packages/core/src/client/router.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
'use client';

import * as React from 'react';
import type {RouterLocation} from '../use-router-location.js';
import {createUrl, createUrlPath} from './router-location-utils.js';
Expand Down

0 comments on commit 6e5669f

Please sign in to comment.