@larakit/react 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/package.json +30 -4
  2. package/src/Cell.tsx +35 -0
  3. package/src/Dashboard.tsx +79 -0
  4. package/src/Field.tsx +132 -0
  5. package/src/FileInput.tsx +76 -0
  6. package/src/Form.tsx +116 -0
  7. package/src/Layout.tsx +250 -0
  8. package/src/PanelPages.tsx +115 -0
  9. package/src/Repeater.tsx +46 -0
  10. package/src/ResourceIndex.tsx +271 -0
  11. package/src/action-upload.test.tsx +44 -0
  12. package/src/blocks.tsx +26 -0
  13. package/src/button-part.test.tsx +42 -0
  14. package/src/components.test.ts +22 -0
  15. package/src/components.tsx +435 -0
  16. package/src/confirm.test.tsx +68 -0
  17. package/src/context.tsx +19 -0
  18. package/src/custom-pages.test.tsx +177 -0
  19. package/src/errors.test.tsx +95 -0
  20. package/src/fixtures.ts +20 -0
  21. package/src/index.ts +29 -0
  22. package/src/kit/api.ts +305 -0
  23. package/src/kit/auth.tsx +109 -0
  24. package/src/kit/bridge.tsx +142 -0
  25. package/src/kit/button.tsx +396 -0
  26. package/src/kit/cell.tsx +260 -0
  27. package/src/kit/charts.tsx +638 -0
  28. package/src/kit/create.tsx +166 -0
  29. package/src/kit/dashboard.tsx +335 -0
  30. package/src/kit/dates.tsx +62 -0
  31. package/src/kit/entry.tsx +87 -0
  32. package/src/kit/field.tsx +449 -0
  33. package/src/kit/fields/CodeEditor.tsx +157 -0
  34. package/src/kit/fields/KeyValue.tsx +215 -0
  35. package/src/kit/fields/MarkdownEditor.tsx +380 -0
  36. package/src/kit/fields/OneTimeCode.tsx +192 -0
  37. package/src/kit/fields/Repeater.tsx +350 -0
  38. package/src/kit/fields/Slider.tsx +185 -0
  39. package/src/kit/fields/TagsInput.tsx +219 -0
  40. package/src/kit/filters.tsx +214 -0
  41. package/src/kit/form-shared.tsx +62 -0
  42. package/src/kit/form.tsx +253 -0
  43. package/src/kit/hooks.ts +119 -0
  44. package/src/kit/i18n.tsx +67 -0
  45. package/src/kit/icons.tsx +190 -0
  46. package/src/kit/infolist.tsx +452 -0
  47. package/src/kit/kit.test.tsx +2200 -0
  48. package/src/kit/layout.tsx +236 -0
  49. package/src/kit/loading.tsx +120 -0
  50. package/src/kit/notice.tsx +72 -0
  51. package/src/kit/page.tsx +103 -0
  52. package/src/kit/pageform.tsx +75 -0
  53. package/src/kit/picker.tsx +110 -0
  54. package/src/kit/plugins.tsx +206 -0
  55. package/src/kit/profile.tsx +86 -0
  56. package/src/kit/relations.tsx +146 -0
  57. package/src/kit/rich.tsx +276 -0
  58. package/src/kit/search.tsx +92 -0
  59. package/src/kit/select.tsx +244 -0
  60. package/src/kit/shell.tsx +401 -0
  61. package/src/kit/table-extras.tsx +457 -0
  62. package/src/kit/table.tsx +734 -0
  63. package/src/kit/theme.ts +57 -0
  64. package/src/layout-parts.test.tsx +159 -0
  65. package/src/pages/index.ts +7 -0
  66. package/src/part.test.tsx +56 -0
  67. package/src/plugins.test.tsx +159 -0
  68. package/src/plugins.tsx +240 -0
  69. package/src/preview.test.tsx +81 -0
  70. package/src/rail.test.tsx +56 -0
  71. package/src/repeater.test.tsx +48 -0
  72. package/src/resource-pages.test.tsx +119 -0
  73. package/src/screens.test.tsx +121 -0
  74. package/src/ssr.test.tsx +86 -0
  75. package/src/tenant.test.tsx +94 -0
  76. package/src/ui.tsx +100 -0
  77. package/theme.css +467 -0
  78. package/README.md +0 -3
@@ -0,0 +1,109 @@
1
+ import { useState, type FormEvent, type ReactNode } from 'react';
2
+ import { setPanelPath, type Theme } from './api';
3
+ import { I18nProvider, setI18n, useT } from './i18n';
4
+ import { Input, Problem, useSend } from './profile';
5
+ import { useTheme } from './theme';
6
+
7
+ /** What the pages of a guest show. */
8
+ export type AuthInfo = { protocol?: number; name: string; logo?: string; logoDark?: string; theme: Theme; locale?: string; dir?: 'ltr' | 'rtl'; messages?: Record<string, string>; login: string; home: string; reset: boolean };
9
+
10
+ /** The card a guest's page is on, with the panel's logo. */
11
+ function Card({ info, mode, title, hint, children }: { info: AuthInfo; mode: string; title: string; hint?: string; children: ReactNode }) {
12
+ const logo = mode === 'dark' ? info.logoDark || info.logo : info.logo;
13
+ return (
14
+ <main data-lk="auth" className="grid min-h-dvh place-items-center p-4">
15
+ <div className="w-full max-w-sm">
16
+ <div className="mb-6 flex justify-center text-xl font-bold">{logo ? <img src={logo} alt={info.name} className="h-10 max-w-full" /> : info.name}</div>
17
+ <div className="card p-6">
18
+ <h1 className="text-lg font-semibold">{title}</h1>
19
+ {hint && <p className="muted mt-1 text-sm">{hint}</p>}
20
+ <div className="mt-5">{children}</div>
21
+ </div>
22
+ </div>
23
+ </main>
24
+ );
25
+ }
26
+
27
+ function SignIn({ info, mode }: { info: AuthInfo; mode: string }) {
28
+ const t = useT(), { errors, busy, problem, send } = useSend();
29
+ const [email, setEmail] = useState(''), [password, setPassword] = useState(''), [remember, setRemember] = useState(false);
30
+ const submit = async (e: FormEvent) => {
31
+ e.preventDefault();
32
+ const done = await send<{ redirect: string }>('/auth/login', { email, password, remember });
33
+ // Back to the page the visitor opened.
34
+ if (done) location.assign(done.redirect);
35
+ };
36
+ return (
37
+ <Card info={info} mode={mode} title={t('auth.signInTo', { name: info.name })}>
38
+ <form className="grid gap-4" onSubmit={submit} noValidate>
39
+ <Problem text={problem} />
40
+ <Input label={t('auth.email')} name="email" type="email" value={email} set={setEmail} errors={errors} auto="username" focus />
41
+ <Input label={t('auth.password')} name="password" type="password" value={password} set={setPassword} errors={errors} auto="current-password" />
42
+ <div className="flex items-center justify-between gap-2 text-sm">
43
+ <label className="flex cursor-pointer items-center gap-2"><input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />{t('auth.remember')}</label>
44
+ {info.reset && <a className="font-medium underline-offset-2 hover:underline" href={info.home + '/forgot-password'}>{t('auth.forgot')}</a>}
45
+ </div>
46
+ <button className="btn primary w-full justify-center" disabled={busy}>{t('auth.signIn')}</button>
47
+ </form>
48
+ </Card>
49
+ );
50
+ }
51
+
52
+ function Forgot({ info, mode }: { info: AuthInfo; mode: string }) {
53
+ const t = useT(), { errors, busy, problem, send } = useSend();
54
+ const [email, setEmail] = useState(''), [sent, setSent] = useState('');
55
+ const submit = async (e: FormEvent) => {
56
+ e.preventDefault();
57
+ const done = await send<{ message: string }>('/auth/forgot', { email });
58
+ if (done) setSent(done.message);
59
+ };
60
+ return (
61
+ <Card info={info} mode={mode} title={t('auth.forgotTitle')} hint={sent ? undefined : t('auth.forgotHint')}>
62
+ {sent ? <p role="status" className="text-sm">{sent}</p> : (
63
+ <form className="grid gap-4" onSubmit={submit} noValidate>
64
+ <Problem text={problem} />
65
+ <Input label={t('auth.email')} name="email" type="email" value={email} set={setEmail} errors={errors} auto="email" focus />
66
+ <button className="btn primary w-full justify-center" disabled={busy}>{t('auth.sendLink')}</button>
67
+ </form>
68
+ )}
69
+ <a className="mt-4 inline-block text-sm font-medium underline-offset-2 hover:underline" href={info.login}>{t('auth.backToSignIn')}</a>
70
+ </Card>
71
+ );
72
+ }
73
+
74
+ function Reset({ info, mode, token, email }: { info: AuthInfo; mode: string; token: string; email: string }) {
75
+ const t = useT(), { errors, busy, problem, send } = useSend();
76
+ const [password, setPassword] = useState(''), [confirmation, setConfirmation] = useState(''), [saved, setSaved] = useState('');
77
+ const submit = async (e: FormEvent) => {
78
+ e.preventDefault();
79
+ const done = await send<{ message: string; redirect: string }>('/auth/reset', { email, token, password, password_confirmation: confirmation });
80
+ if (done) setSaved(done.message);
81
+ };
82
+ return (
83
+ <Card info={info} mode={mode} title={t('auth.resetTitle')} hint={email}>
84
+ {saved ? <p role="status" className="text-sm">{saved}</p> : <form className="grid gap-4" onSubmit={submit} noValidate>
85
+ <Problem text={problem || (errors.email ?? []).join(' ')} />
86
+ <Input label={t('auth.newPassword')} name="password" type="password" value={password} set={setPassword} errors={errors} auto="new-password" focus />
87
+ <Input label={t('auth.confirmPassword')} name="password_confirmation" type="password" value={confirmation} set={setConfirmation} errors={errors} auto="new-password" />
88
+ <button className="btn primary w-full justify-center" disabled={busy}>{t('auth.resetButton')}</button>
89
+ </form>}
90
+ <a className="mt-4 inline-block text-sm font-medium underline-offset-2 hover:underline" href={info.login}>{t('auth.backToSignIn')}</a>
91
+ </Card>
92
+ );
93
+ }
94
+
95
+ export type AuthKind = 'login' | 'forgot' | 'reset';
96
+
97
+ /** The pages of a guest: signing in, and the forms of a forgotten password. The server gives what they show. */
98
+ export function AuthApp({ info, kind, token = '', email = '' }: { info: AuthInfo; kind: AuthKind; token?: string; email?: string }) {
99
+ setPanelPath(info.home);
100
+ setI18n(info.locale ?? 'en', info.dir, info.messages ?? {});
101
+ const [mode] = useTheme(info.theme);
102
+ return (
103
+ <I18nProvider locale={info.locale} dir={info.dir} messages={info.messages}>
104
+ <div className="larakit" dir={info.dir} lang={info.locale}>
105
+ {kind === 'forgot' ? <Forgot info={info} mode={mode} /> : kind === 'reset' ? <Reset info={info} mode={mode} token={token} email={email} /> : <SignIn info={info} mode={mode} />}
106
+ </div>
107
+ </I18nProvider>
108
+ );
109
+ }
@@ -0,0 +1,142 @@
1
+ import { useContext, useMemo, type ComponentType } from 'react';
2
+ import type { Column, Row as CoreRow, Widget as CoreWidget } from '@larakit/core';
3
+ import { LayoutPart, type LayoutPartProps } from '../components';
4
+ import { Context } from '../context';
5
+ import type { Field, Resource } from './api';
6
+ import { Control } from './filters';
7
+ import type { Part, Parts } from './plugins';
8
+
9
+ /**
10
+ * Larakit's own drawing of a part, as `LayoutPart` gets it: the kit's component with the kit's props. Both come
11
+ * along as props, so the component stays the same from one drawing to the next and keeps its state.
12
+ */
13
+ export function KitDefault({ __own: Own, __kit: kit }: { __own: ComponentType<object>; __kit: object }) {
14
+ return <Own {...kit} />;
15
+ }
16
+
17
+ type Mapped = { props: Record<string, unknown>; name?: string; data?: unknown; partKey?: string };
18
+ const words = (v: unknown) => (typeof v === 'string' ? v : '');
19
+
20
+ /**
21
+ * Draws one of the kit's parts through the panel's parts (LA-306/LA-319): the application's component that
22
+ * `part(...)` or an item's `.component(...)` names gets the part's typed props, `data`, `partKey` and `Default`,
23
+ * which draws Larakit's own part.
24
+ */
25
+ export function Bridged<P extends Part>({ part, own, props }: { part: P; own: ComponentType<Parts[P]>; props: Parts[P] }) {
26
+ const kit = useContext(Context);
27
+ const p = props as Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
28
+ // The components a part gets for its rows, cells, filters and widgets, kept the same while the kit's are.
29
+ const cell = p.Cell as ComponentType<{ column: string; row: CoreRow }> | undefined;
30
+ const Cell = useMemo(() => cell && function BridgedCell({ column, row }: { column: Column; row: CoreRow }) {
31
+ const C = cell;
32
+ return <C column={column.key} row={row} />;
33
+ }, [cell]);
34
+ const onEdit = p.onEdit as ((id: string) => void) | undefined, onAction = p.onAction as ((id: string, a: string) => void) | undefined;
35
+ const actions = p.actions as { name: string; label: string }[] | undefined;
36
+ const Actions = useMemo(() => function BridgedActions({ row }: { row: CoreRow }) {
37
+ return (
38
+ <span className="inline-flex gap-1">
39
+ {row.can.update && onEdit && <button type="button" className="row-btn" onClick={() => onEdit(row.id)}>{kit?.t('table.edit', 'Edit')}</button>}
40
+ {(actions ?? []).filter((a) => row.can.actions.includes(a.name)).map((a) => (
41
+ <button key={a.name} type="button" className="row-btn" onClick={() => onAction?.(row.id, a.name)}>{a.label}</button>
42
+ ))}
43
+ </span>
44
+ );
45
+ }, [onEdit, onAction, actions, kit]);
46
+ const widget = p.Widget as ComponentType<{ name: string }> | undefined;
47
+ const Widget = useMemo(() => widget && function BridgedWidget({ widget: w }: { widget: CoreWidget }) {
48
+ const W = widget;
49
+ return <W name={w.name} />;
50
+ }, [widget]);
51
+ // The filters' part gets Larakit's input of one filter, which changes the table as Larakit's own filters do.
52
+ const resource = p.resource as Resource | undefined, baseUrl = p.baseUrl as string | undefined;
53
+ const chosen = p.chosen as Record<string, string[]> | undefined, change = p.onChange as ((c: Record<string, string[]>) => void) | undefined;
54
+ const Filter = useMemo(() => function BridgedFilter({ filter }: { filter: Field }) {
55
+ return resource && change ? <Control resource={resource} baseUrl={baseUrl} field={filter} chosen={chosen ?? {}} onChange={change} /> : null;
56
+ }, [resource, baseUrl, chosen, change]);
57
+ const m = map(part, p, { Cell, Actions, Widget, Filter, user: kit?.panel.user ?? undefined });
58
+ if (!m) return <KitDefault __own={own as ComponentType<object>} __kit={props as object} />;
59
+ return (
60
+ <LayoutPart part={part as keyof LayoutPartProps} name={m.name} data={m.data} partKey={m.partKey}
61
+ props={{ ...m.props, __own: own, __kit: props } as never} Default={KitDefault} />
62
+ );
63
+ }
64
+
65
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
66
+ function map(part: Part, p: Record<string, any>, made: { Cell?: unknown; Actions: unknown; Widget?: unknown; Filter: unknown; user?: { name: string; detail?: string } }): Mapped | null {
67
+ switch (part) {
68
+ case 'nav':
69
+ return { props: { items: p.items } };
70
+ case 'tenantSwitcher':
71
+ return { props: { tenants: p.tenants, active: p.active, choose: p.onChange, rail: p.rail } };
72
+ case 'topbar':
73
+ return { props: { title: '', user: made.user ? { name: made.user.name, email: made.user.detail } : undefined } };
74
+ case 'header':
75
+ return { props: { title: p.title, actions: p.actions ?? null } };
76
+ case 'breadcrumb':
77
+ return { props: { items: (p.items ?? []).map((i: { label: string; href?: string }) => ({ label: i.label, href: i.href })) } };
78
+ case 'table':
79
+ return { props: { columns: p.columns, rows: p.rows, sort: p.sort, sortBy: p.onSort, Cell: made.Cell, Actions: made.Actions } };
80
+ case 'cell': {
81
+ const c = p.column ?? {};
82
+ const row = p.row ?? {};
83
+ return {
84
+ props: { value: p.value, row: { id: words(row.id), cells: row, can: { update: !!p.editable, actions: [] } }, column: c },
85
+ name: c.component, data: c.props ?? {}, partKey: c.partKey ?? c.key,
86
+ };
87
+ }
88
+ case 'badge':
89
+ return { props: { color: p.color, children: p.children ?? p.label } };
90
+ case 'empty':
91
+ return { props: { text: p.heading } };
92
+ case 'pagination':
93
+ return { props: { page: p.page, lastPage: p.lastPage, total: p.total, from: p.from, to: p.to, go: p.onPage } };
94
+ case 'filters': {
95
+ const chosen = (p.chosen ?? {}) as Record<string, string[]>;
96
+ return { props: {
97
+ filters: p.resource?.filters ?? [], values: chosen, Filter: made.Filter,
98
+ set: (key: string, v: string | string[]) => p.onChange({ ...chosen, [key]: Array.isArray(v) ? v : v === '' ? [] : [v] }),
99
+ } };
100
+ }
101
+ case 'form':
102
+ return { props: { fields: p.fields, mode: p.id === null ? 'create' : 'edit', values: p.values ?? {}, errors: p.errors ?? {}, children: null, Field: p.Field } };
103
+ case 'field': {
104
+ const f = p.field ?? {};
105
+ return {
106
+ props: { field: f, id: p.id, path: f.key, error: p.errors?.[0], required: p.required, disabled: p.disabled, children: p.children },
107
+ data: f.props ?? {}, partKey: f.partKey ?? f.key,
108
+ };
109
+ }
110
+ case 'button':
111
+ return { props: {
112
+ type: p.type ?? 'button', disabled: p.disabled, onClick: p.onClick, title: p.title, 'aria-label': p.ariaLabel,
113
+ tone: p.danger ? 'danger' : p.variant === 'solid' ? 'primary' : 'plain', children: p.children ?? p.label,
114
+ color: p.danger ? 'danger' : p.color, variant: p.variant, size: p.size ?? 'md', icon: p.icon, iconOnly: p.iconOnly, 'data-lk': p.dataLk ?? 'button',
115
+ } };
116
+ case 'section': {
117
+ const g = p.group ?? {};
118
+ return { props: { heading: p.heading, description: p.description, children: p.children, place: g }, name: g.component, data: g.props ?? {}, partKey: g.partKey ?? (p.heading || g.type) };
119
+ }
120
+ case 'tabs': {
121
+ // A form's tabs: the group's own `.component()` wins over part("tabs"), as for a section.
122
+ const g = p.group ?? {};
123
+ return { props: {
124
+ tabs: (p.tabs ?? []).map((t: { heading?: string; badge?: string; badgeColor?: string; wrong: boolean }, i: number) => ({ name: String(i), label: t.heading ?? '', badge: t.badge, color: t.badgeColor, wrong: t.wrong })),
125
+ active: String(p.active), select: (name: string) => p.onSelect(Number(name)), children: p.tabs?.[p.active]?.content,
126
+ }, name: g.component, data: g.props ?? {}, partKey: g.partKey ?? 'tabs' };
127
+ }
128
+ case 'modal':
129
+ return { props: { title: p.eyebrow ?? '', width: 'md', close: p.onClose, children: p.children } };
130
+ case 'dashboard':
131
+ return { props: { widgets: p.widgets, Widget: made.Widget } };
132
+ case 'widget':
133
+ return { props: { widget: p.widget, children: p.children } };
134
+ case 'stat':
135
+ return { props: { stat: p.stat, href: p.href } };
136
+ case 'toast':
137
+ return { props: { type: p.bad ? 'danger' : 'success', message: p.text, close: p.onClose } };
138
+ case 'loading':
139
+ return { props: { kind: p.kind === 'panel' || p.kind === 'inline' ? 'page' : p.kind } };
140
+ }
141
+ return null;
142
+ }
@@ -0,0 +1,396 @@
1
+ import { useLayoutEffect, useRef, type ReactNode } from 'react';
2
+ import { createPortal } from 'react-dom';
3
+ import { fail, type ButtonSize, type ButtonVariant, type Link, type ModalWidth } from './api';
4
+ import { TONES, xsrfToken } from './hooks';
5
+ import { t as translate, useT } from './i18n';
6
+ import { Icon } from './icons';
7
+ import { complain, say } from './notice';
8
+ import { RenderHook, Slot, useHasHook, type Parts } from './plugins';
9
+
10
+ const iconSize: Record<ButtonSize, string> = { xs: 'size-3.5', sm: 'size-3.5', md: 'size-4', lg: 'size-4' };
11
+
12
+ /** Submits a POST request to a panel or hook link target with the XSRF header; the session holds the tenant. */
13
+ export async function postLink(href: string) {
14
+ const token = xsrfToken();
15
+ try {
16
+ const r = await fetch(href, {
17
+ method: 'POST',
18
+ headers: {
19
+ Accept: 'text/html, application/json',
20
+ ...(token ? { 'X-XSRF-TOKEN': token } : {}),
21
+ },
22
+ });
23
+ const data = r.headers.get('content-type')?.includes('json') ? await r.json() : {};
24
+ if (!r.ok) throw new Error(data.message || translate('form.requestFailed', { status: r.status }));
25
+ if (r.redirected) location.href = r.url;
26
+ else if (data.message) say(data.message);
27
+ else location.reload();
28
+ } catch (e) {
29
+ complain(fail(e));
30
+ }
31
+ }
32
+
33
+ /** Infer default visual attributes for action/panel buttons without changing explicit props. */
34
+ export function buttonAttrs({
35
+ color,
36
+ variant,
37
+ size,
38
+ danger,
39
+ }: {
40
+ color?: string;
41
+ variant?: ButtonVariant;
42
+ size?: ButtonSize;
43
+ danger?: boolean;
44
+ }) {
45
+ const effectiveColor = color || (danger ? 'danger' : undefined);
46
+ const effectiveVariant = variant ?? (effectiveColor ? 'soft' : undefined);
47
+ return {
48
+ color: effectiveColor,
49
+ variant: effectiveVariant,
50
+ size: size ?? 'md',
51
+ };
52
+ }
53
+
54
+ function DefaultButton({
55
+ label,
56
+ icon,
57
+ color,
58
+ variant,
59
+ size = 'md',
60
+ danger,
61
+ iconOnly,
62
+ disabled,
63
+ type = 'button',
64
+ className = '',
65
+ title,
66
+ ariaLabel,
67
+ dataLk,
68
+ onClick,
69
+ children,
70
+ }: Parts['button']) {
71
+ const attrs = buttonAttrs({ color, variant, size, danger });
72
+ const bare = !!(iconOnly && icon);
73
+ const tip = title ?? (bare && typeof label === 'string' ? label : undefined);
74
+ const aLabel = ariaLabel ?? (bare && typeof label === 'string' ? label : undefined);
75
+ return (
76
+ <button
77
+ type={type}
78
+ disabled={disabled}
79
+ data-lk={dataLk ?? 'button'}
80
+ data-variant={attrs.variant}
81
+ data-color={attrs.color}
82
+ data-size={attrs.size}
83
+ data-icon-only={bare || undefined}
84
+ title={tip}
85
+ aria-label={aLabel}
86
+ className={'btn inline-flex items-center justify-center ' + className}
87
+ onClick={onClick}
88
+ >
89
+ {icon && <Icon name={icon} className={iconSize[attrs.size] + ' shrink-0'} />}
90
+ {!bare && (children ?? label)}
91
+ </button>
92
+ );
93
+ }
94
+
95
+ export function Btn(props: Parts['button']) {
96
+ return <Slot part="button" own={DefaultButton} props={props} />;
97
+ }
98
+
99
+ /** Renders a panel Link or HookButtonItem as either a rich `.btn` or classic `.tool` anchor/post-button. */
100
+ export function LinkBtn({
101
+ link,
102
+ styled = false,
103
+ className = '',
104
+ dataLk,
105
+ defaultSize = 'md',
106
+ }: {
107
+ link: Link;
108
+ styled?: boolean;
109
+ className?: string;
110
+ dataLk?: string;
111
+ defaultSize?: ButtonSize;
112
+ }) {
113
+ const out = !link.post && link.href.startsWith('https://') ? { target: '_blank', rel: 'noreferrer' } : {};
114
+ if (!styled) {
115
+ const cls = className || 'tool';
116
+ const title = link.icon ? link.label : undefined;
117
+ const content = link.icon ? (
118
+ <>
119
+ <Icon name={link.icon} />
120
+ <span className="sr-only">{link.label}</span>
121
+ </>
122
+ ) : (
123
+ link.label
124
+ );
125
+ return link.post ? (
126
+ <button type="button" data-lk={dataLk} className={cls} title={title} onClick={() => void postLink(link.href)}>
127
+ {content}
128
+ </button>
129
+ ) : (
130
+ <a href={link.href} data-lk={dataLk} className={cls} title={title} {...out}>
131
+ {content}
132
+ </a>
133
+ );
134
+ }
135
+ const attrs = buttonAttrs({ color: link.color, variant: link.variant, size: link.size ?? defaultSize });
136
+ const bare = !!(link.iconOnly && link.icon);
137
+ const toneClass = attrs.color && TONES.includes(attrs.color) ? ' tone-' + attrs.color : '';
138
+ const cls = 'btn inline-flex items-center justify-center' + toneClass + (className ? ' ' + className : '');
139
+ const tip = bare ? link.label : undefined;
140
+ const aLabel = bare ? link.label : undefined;
141
+ const content = (
142
+ <>
143
+ {link.icon && <Icon name={link.icon} className={iconSize[attrs.size] + ' shrink-0'} />}
144
+ {!bare && (
145
+ <>
146
+ <span>{link.label}</span>
147
+ {link.badge && <Badge label={link.badge} color={link.badgeColor ?? link.color} />}
148
+ </>
149
+ )}
150
+ </>
151
+ );
152
+ return link.post ? (
153
+ <button
154
+ type="button"
155
+ data-lk={dataLk}
156
+ data-variant={attrs.variant}
157
+ data-color={attrs.color}
158
+ data-size={attrs.size}
159
+ data-icon-only={bare || undefined}
160
+ title={tip}
161
+ aria-label={aLabel}
162
+ className={cls}
163
+ onClick={() => void postLink(link.href)}
164
+ >
165
+ {content}
166
+ </button>
167
+ ) : (
168
+ <a
169
+ href={link.href}
170
+ data-lk={dataLk}
171
+ data-variant={attrs.variant}
172
+ data-color={attrs.color}
173
+ data-size={attrs.size}
174
+ data-icon-only={bare || undefined}
175
+ title={tip}
176
+ aria-label={aLabel}
177
+ className={cls}
178
+ {...out}
179
+ >
180
+ {content}
181
+ </a>
182
+ );
183
+ }
184
+
185
+ function DefaultBadge({ label, color, title, value, className = '', children }: Parts['badge']) {
186
+ return (
187
+ <span
188
+ data-lk="badge"
189
+ data-value={value}
190
+ data-color={color || 'primary'}
191
+ title={title}
192
+ className={'badge inline-flex items-center px-2 py-0.5 text-xs whitespace-nowrap ' + (color ? 'tone-' + color + ' ' : '') + className}
193
+ >
194
+ {children ?? label}
195
+ </span>
196
+ );
197
+ }
198
+
199
+ export function Badge(props: Parts['badge']) {
200
+ return <Slot part="badge" own={DefaultBadge} props={props} />;
201
+ }
202
+
203
+ function DefaultBreadcrumb({ items }: Parts['breadcrumb']) {
204
+ const t = useT();
205
+ if (!items.length) return null;
206
+ return (
207
+ <nav aria-label={t('form.breadcrumb')} data-lk="breadcrumb" className="muted flex flex-wrap items-center gap-1.5 text-sm">
208
+ {items.map((item, i) => (
209
+ <span key={i} className="inline-flex items-center gap-1.5">
210
+ {i > 0 && <Icon name="right" className="size-3.5 rtl:rotate-180" />}
211
+ {item.href !== undefined ? (
212
+ <a
213
+ href={item.href}
214
+ className="hover:underline"
215
+ onClick={
216
+ item.onClick
217
+ ? (e) => {
218
+ e.preventDefault();
219
+ item.onClick!();
220
+ }
221
+ : undefined
222
+ }
223
+ >
224
+ {item.label}
225
+ </a>
226
+ ) : (
227
+ <span aria-current={item.current ? 'page' : undefined}>{item.label}</span>
228
+ )}
229
+ </span>
230
+ ))}
231
+ </nav>
232
+ );
233
+ }
234
+
235
+ export function Breadcrumb(props: Parts['breadcrumb']) {
236
+ return <Slot part="breadcrumb" own={DefaultBreadcrumb} props={props} />;
237
+ }
238
+
239
+ function DefaultHeader({ title, description, breadcrumb, actions, children }: Parts['header']) {
240
+ const hasBefore = useHasHook('page.header.actions.before');
241
+ const hasAfter = useHasHook('page.header.actions.after');
242
+ const showActions = !!actions || hasBefore || hasAfter;
243
+ return (
244
+ <div data-lk="toolbar">
245
+ {breadcrumb && <div className="mb-2">{breadcrumb}</div>}
246
+ <div className="flex flex-wrap items-center gap-3">
247
+ <div className="mr-auto min-w-0">
248
+ <h1 data-lk="title" className="text-2xl font-semibold tracking-[-0.025em] break-words">
249
+ {title}
250
+ </h1>
251
+ {description && (
252
+ <p data-lk="description" className="muted mt-1 text-sm">
253
+ {description}
254
+ </p>
255
+ )}
256
+ </div>
257
+ {showActions && (
258
+ <div data-lk="actions" className="flex flex-wrap items-center gap-2">
259
+ <RenderHook name="page.header.actions.before" />
260
+ {actions}
261
+ <RenderHook name="page.header.actions.after" />
262
+ </div>
263
+ )}
264
+ {children}
265
+ </div>
266
+ </div>
267
+ );
268
+ }
269
+
270
+ // The space around a part is drawn here, not by Larakit's drawing of it: an application's component that wraps
271
+ // `Default` next to its own elements then lines up with them.
272
+ export function PageHeader(props: Parts['header']) {
273
+ return <div className="mb-6"><Slot part="header" own={DefaultHeader} props={props} /></div>;
274
+ }
275
+
276
+ type ModalInternalProps = Parts['modal'] & {
277
+ dialogRef?: React.RefObject<HTMLDialogElement | null>;
278
+ stopCancelPropagation?: boolean;
279
+ };
280
+
281
+ const modalStack: symbol[] = [];
282
+
283
+ /** Maps modal width token + layout mode into a Tailwind max-width utility class. */
284
+ export function modalWidthClass(
285
+ width: ModalWidth | undefined,
286
+ layout: 'dialog' | 'drawer' | 'page' = 'dialog',
287
+ fallback?: string,
288
+ ): string {
289
+ if (!width) return fallback ?? (layout === 'drawer' ? 'max-w-md' : 'max-w-lg');
290
+ if (layout === 'page') {
291
+ return { sm: 'max-w-3xl', md: 'max-w-5xl', lg: 'max-w-7xl', xl: 'max-w-[96rem]', '2xl': 'max-w-[110rem]', full: 'max-w-none' }[width];
292
+ }
293
+ return {
294
+ sm: 'max-w-sm',
295
+ md: layout === 'drawer' ? 'max-w-md' : 'max-w-lg',
296
+ lg: 'max-w-3xl',
297
+ xl: 'max-w-5xl',
298
+ '2xl': 'max-w-7xl',
299
+ full: 'max-w-none',
300
+ }[width];
301
+ }
302
+
303
+ function DefaultModal({
304
+ layout,
305
+ widthClass = 'max-w-lg',
306
+ titleId,
307
+ dataLk = 'modal',
308
+ dataView,
309
+ portal,
310
+ className,
311
+ onClose,
312
+ onCancel,
313
+ onKeyDown,
314
+ dialogRef,
315
+ children,
316
+ }: ModalInternalProps) {
317
+ const localRef = useRef<HTMLDialogElement>(null);
318
+ const ref = dialogRef ?? localRef;
319
+ const stackIdRef = useRef<symbol | null>(null);
320
+ if (!stackIdRef.current) stackIdRef.current = Symbol('modal');
321
+ const stackId = stackIdRef.current;
322
+
323
+ const removeFromStack = () => {
324
+ const idx = modalStack.lastIndexOf(stackId);
325
+ if (idx >= 0) modalStack.splice(idx, 1);
326
+ };
327
+
328
+ useLayoutEffect(() => {
329
+ const d = ref.current;
330
+ if (!d) return;
331
+ if (!modalStack.includes(stackId)) modalStack.push(stackId);
332
+ // A browser without dialogs, such as a test's, opens it as an element.
333
+ if (!d.open) { if (typeof d.showModal === 'function') d.showModal(); else d.setAttribute('open', ''); }
334
+ return () => {
335
+ removeFromStack();
336
+ if (d.open) { if (typeof d.close === 'function') d.close(); else d.removeAttribute('open'); }
337
+ };
338
+ }, []);
339
+
340
+ const isTopModal = () => modalStack[modalStack.length - 1] === stackId;
341
+ const isNativeDialog = typeof HTMLDialogElement !== 'undefined' && /\[native code\]/.test(String(HTMLDialogElement.prototype.showModal));
342
+
343
+ const el = (
344
+ <dialog
345
+ ref={ref}
346
+ data-lk={dataLk}
347
+ data-view={dataView || undefined}
348
+ data-layout={layout}
349
+ aria-labelledby={titleId}
350
+ className={
351
+ className ??
352
+ (layout === 'drawer' ? 'my-0 ms-auto me-0 h-dvh max-h-none overflow-y-auto ' : 'm-auto max-h-[calc(100dvh-2rem)] overflow-y-auto ') +
353
+ widthClass +
354
+ ' w-full surface p-6 backdrop:bg-black/50'
355
+ }
356
+ onClose={(e) => {
357
+ e.stopPropagation();
358
+ removeFromStack();
359
+ onClose();
360
+ }}
361
+ onCancel={(e) => {
362
+ e.stopPropagation();
363
+ if (!isTopModal()) {
364
+ e.preventDefault();
365
+ return;
366
+ }
367
+ if (onCancel) {
368
+ e.preventDefault();
369
+ onCancel();
370
+ }
371
+ }}
372
+ onKeyDown={(e) => {
373
+ onKeyDown?.(e);
374
+ if (e.key === 'Escape') {
375
+ e.stopPropagation();
376
+ if (!e.defaultPrevented && !isNativeDialog && isTopModal()) {
377
+ const d = ref.current;
378
+ if (d) {
379
+ const cancelled = !d.dispatchEvent(new Event('cancel', { cancelable: true }));
380
+ if (!cancelled) d.close();
381
+ }
382
+ }
383
+ }
384
+ }}
385
+ >
386
+ {children}
387
+ </dialog>
388
+ );
389
+ return portal && typeof document !== 'undefined' ? createPortal(el, document.body) : el;
390
+ }
391
+
392
+ export function Modal(props: ModalInternalProps) {
393
+ return <Slot part="modal" own={DefaultModal as React.ComponentType<Parts['modal']>} props={props} />;
394
+ }
395
+
396
+ export type { ReactNode };