@larakit/react 0.0.0-stage → 0.5.1

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 +398 -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 +2210 -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,177 @@
1
+ // A page of the panel that the application's own component draws (Go Page.Component, Rust Page::component), like a
2
+ // Filament page and its view: Larakit draws the menu, the heading and the page's buttons; the component gets the
3
+ // page's data, which comes with the page so the server draws it too, and run(), which runs one of the page's actions
4
+ // or calls on the server, shows its message as Larakit's toast and loads the data again.
5
+ import { afterEach, describe, expect, it, vi } from 'vitest';
6
+ import { act, cleanup, fireEvent, render, screen as view } from '@testing-library/react';
7
+ import { hydrateRoot, type Root } from 'react-dom/client';
8
+ import { renderToString } from 'react-dom/server';
9
+ import { createInertiaApp, router } from '@inertiajs/react';
10
+ import type { PanelPageProps } from '@larakit/core';
11
+ import { larakit } from './components';
12
+ import { panel } from './fixtures';
13
+ import { definePlugin, type ComponentWidgetProps, type PageProps, type RunResult } from './plugins';
14
+ import { Dashboard, Page } from './pages';
15
+
16
+ afterEach(() => { cleanup(); larakit({}); vi.unstubAllGlobals(); vi.restoreAllMocks(); document.cookie = 'XSRF-TOKEN=; expires=Thu, 01 Jan 1970 00:00:00 GMT'; });
17
+
18
+ let answered: RunResult | undefined;
19
+
20
+ function Greeting({ data, run, reload, href }: PageProps<{ message: string }>) {
21
+ return (
22
+ <div data-test="greeting">
23
+ <p>{data.message}</p>
24
+ <a href={href()}>Here</a>
25
+ <button type="button" onClick={async () => { answered = await run('greet', { text: 'Ada' }); }}>Greet</button>
26
+ <button type="button" onClick={reload}>Reload</button>
27
+ </div>
28
+ );
29
+ }
30
+
31
+ const components = { './larakit/components/pages/Greeting.tsx': { default: Greeting } };
32
+
33
+ function greetingPage(more: Record<string, unknown> = {}): { component: string; props: PanelPageProps; url: string; version: string; flash: object } {
34
+ return {
35
+ component: 'larakit/Page', url: '/admin/greeting', version: '1', flash: {},
36
+ props: {
37
+ path: '/admin', errors: {}, larakit: panel('Shop', [{ name: 'greeting', label: 'Greeting', icon: 'file', group: '', href: '/admin/greeting' }]),
38
+ page: { name: 'greeting', label: 'Greeting', icon: 'file', group: '', description: 'Says hello.', component: 'pages/Greeting', widgets: [],
39
+ actions: [{ name: 'wave', label: 'Wave', icon: '', confirm: '', danger: false }], ...more },
40
+ at: 'greeting', data: { message: 'Hello from the server' },
41
+ } as PanelPageProps,
42
+ };
43
+ }
44
+
45
+ async function open(page = greetingPage()) {
46
+ await act(async () => {
47
+ await createInertiaApp({ page: page as never, resolve: () => Page as never, setup: ({ App, props }) => { render(<App {...props} />); } });
48
+ });
49
+ }
50
+
51
+ const json = (status: number, body: object) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
52
+
53
+ describe("a page that the application's component draws", () => {
54
+ it('is drawn on the server with its heading, buttons and data, and the browser takes it over without a mismatch', async () => {
55
+ larakit({ components });
56
+ const at = greetingPage();
57
+ let html = '';
58
+ await createInertiaApp({ page: at as never, resolve: () => Page as never, setup: ({ App, props }) => { html = renderToString(<App {...props} />); } });
59
+ expect(html).toContain('Hello from the server');
60
+ expect(html).toContain('Says hello.');
61
+ expect(html).toContain('data-lk="header-wave"');
62
+ expect(html).toContain('href="/admin/greeting"');
63
+ const el = document.body.appendChild(document.createElement('div'));
64
+ el.innerHTML = html;
65
+ const mismatch = vi.fn();
66
+ let root: Root | undefined;
67
+ await act(async () => {
68
+ await createInertiaApp({ page: at as never, resolve: () => Page as never, setup: ({ App, props }) => { root = hydrateRoot(el, <App {...props} />, { onRecoverableError: mismatch }); } });
69
+ });
70
+ expect(mismatch).not.toHaveBeenCalled();
71
+ expect(el.querySelector('[data-test="greeting"]')).not.toBeNull();
72
+ act(() => root?.unmount());
73
+ el.remove();
74
+ });
75
+
76
+ it("runs a call with its payload and the CSRF token, says the message and loads the data again", async () => {
77
+ larakit({ components });
78
+ document.cookie = 'XSRF-TOKEN=tok%3D1';
79
+ const sent: { url: string; init: RequestInit }[] = [];
80
+ vi.stubGlobal('fetch', vi.fn(async (url: string, init: RequestInit) => { sent.push({ url: String(url), init }); return json(200, { message: 'Hello, Ada.' }); }));
81
+ const reload = vi.spyOn(router, 'reload').mockImplementation(() => {});
82
+ await open();
83
+ await act(async () => { fireEvent.click(view.getByText('Greet')); });
84
+ expect(sent).toHaveLength(1);
85
+ expect(sent[0].url).toBe('/admin/api/greeting/actions/greet');
86
+ expect(sent[0].init.method).toBe('POST');
87
+ expect(JSON.parse(String(sent[0].init.body))).toEqual({ text: 'Ada' });
88
+ expect((sent[0].init.headers as Record<string, string>)['X-XSRF-TOKEN']).toBe('tok=1');
89
+ expect(answered).toEqual({ ok: true, message: 'Hello, Ada.' });
90
+ expect(reload).toHaveBeenCalledWith({ only: ['data'] });
91
+ expect(document.querySelector('[data-lk="notice"]')?.textContent).toContain('Hello, Ada.');
92
+ });
93
+
94
+ it('says why a call did not run, gives its errors and keeps the data', async () => {
95
+ larakit({ components });
96
+ vi.stubGlobal('fetch', vi.fn(async () => json(403, { message: 'This is a preview; nothing is saved.' })));
97
+ const reload = vi.spyOn(router, 'reload').mockImplementation(() => {});
98
+ await open();
99
+ await act(async () => { fireEvent.click(view.getByText('Greet')); });
100
+ expect(answered).toEqual({ ok: false, status: 403, message: 'This is a preview; nothing is saved.', errors: {} });
101
+ expect(reload).not.toHaveBeenCalled();
102
+ expect(document.querySelector('[data-lk="notice"][data-bad]')?.textContent).toContain('This is a preview; nothing is saved.');
103
+
104
+ vi.stubGlobal('fetch', vi.fn(async () => json(422, { message: 'The text field is required.', errors: { text: ['The text field is required.'] } })));
105
+ await act(async () => { fireEvent.click(view.getByText('Greet')); });
106
+ expect(answered).toMatchObject({ ok: false, status: 422, errors: { text: ['The text field is required.'] } });
107
+ });
108
+
109
+ it("runs a button of the heading at the page's address and loads the data again", async () => {
110
+ larakit({ components });
111
+ const sent: string[] = [];
112
+ vi.stubGlobal('fetch', vi.fn(async (url: string) => { sent.push(String(url)); return json(200, { message: 'Waved.' }); }));
113
+ const reload = vi.spyOn(router, 'reload').mockImplementation(() => {});
114
+ await open();
115
+ await act(async () => { fireEvent.click(document.querySelector('[data-lk="header-wave"]')!); });
116
+ expect(sent).toEqual(['/admin/api/greeting/actions/wave']);
117
+ expect(reload).toHaveBeenCalledWith({ only: ['data'] });
118
+ });
119
+
120
+ it("reloads only the data", async () => {
121
+ larakit({ components });
122
+ const reload = vi.spyOn(router, 'reload').mockImplementation(() => {});
123
+ await open();
124
+ fireEvent.click(view.getByText('Reload'));
125
+ expect(reload).toHaveBeenCalledWith({ only: ['data'] });
126
+ });
127
+
128
+ it('says which file is missing when the application has no such component', async () => {
129
+ await open(greetingPage({ component: 'pages/Nope' }));
130
+ expect(document.querySelector('[data-lk="missing-component"]')?.textContent).toContain('resources/js/larakit/components/pages/Nope.tsx');
131
+ });
132
+ });
133
+
134
+ describe("a plugin's page", () => {
135
+ it("runs its calls at {p}/api/{plugin}/{page}/actions/{name}", async () => {
136
+ let run: PageProps['run'] | undefined;
137
+ larakit({ plugins: [definePlugin({ id: 'stars', pages: { ratings: (props: PageProps) => { run = props.run; return <p>Ratings</p>; } } })] });
138
+ const sent: string[] = [];
139
+ vi.stubGlobal('fetch', vi.fn(async (url: string) => { sent.push(String(url)); return json(200, { message: 'Thank you' }); }));
140
+ vi.spyOn(router, 'reload').mockImplementation(() => {});
141
+ const page = greetingPage();
142
+ page.url = '/admin/stars/ratings';
143
+ page.props = { ...page.props, larakit: { ...page.props.larakit, plugins: [{ id: 'stars', name: 'Stars', version: '1', ui: true, replaces: [], bars: [], hooks: [] }] },
144
+ page: { type: 'stars/ratings', label: 'Ratings', icon: 'star', group: '', actions: [] }, at: 'plugins/stars/ratings', rest: '' } as PanelPageProps;
145
+ await open(page);
146
+ await act(async () => { await expect(run!('thank')).resolves.toEqual({ ok: true, message: 'Thank you' }); });
147
+ expect(sent).toEqual(['/admin/api/stars/ratings/actions/thank']);
148
+ });
149
+ });
150
+
151
+ describe("a widget that the application's component draws", () => {
152
+ it('gets its data and reload, in Larakit\'s card with its title', async () => {
153
+ let reloadWidget: (() => void) | undefined;
154
+ function Visits({ data, reload }: ComponentWidgetProps<{ today: number }>) {
155
+ reloadWidget = reload;
156
+ return <p data-test="visits">{data.today} today</p>;
157
+ }
158
+ larakit({ components: { './larakit/components/widgets/Visits.tsx': { default: Visits } } });
159
+ let n = 12;
160
+ const sent: string[] = [];
161
+ vi.stubGlobal('fetch', vi.fn(async (url: string) => { sent.push(String(url)); return json(200, { today: n++ }); }));
162
+ const page = {
163
+ component: 'larakit/Dashboard', url: '/admin', version: '1', flash: {},
164
+ props: { path: '/admin', errors: {}, larakit: panel('Shop', []),
165
+ dashboard: [{ name: 'visits', label: 'Visits', type: 'component', component: 'widgets/Visits', wide: true, poll: 0, screen: '', links: [] }] },
166
+ };
167
+ await act(async () => {
168
+ await createInertiaApp({ page: page as never, resolve: () => Dashboard as never, setup: ({ App, props }) => { render(<App {...props} />); } });
169
+ });
170
+ await act(async () => { await new Promise((r) => setTimeout(r, 0)); });
171
+ expect(document.querySelector('[data-lk="widget"][data-type="component"] [data-lk="title"]')?.textContent).toBe('Visits');
172
+ expect(document.querySelector('[data-test="visits"]')?.textContent).toBe('12 today');
173
+ await act(async () => { reloadWidget!(); await new Promise((r) => setTimeout(r, 0)); });
174
+ expect(document.querySelector('[data-test="visits"]')?.textContent).toBe('13 today');
175
+ expect(sent[0]).toMatch(/\/admin\/api\/dashboard\/visits/);
176
+ });
177
+ });
@@ -0,0 +1,95 @@
1
+ // What a failure that doesn't change the page tells the visitor (LA-313): a request of the kit that fails on the
2
+ // server is a toast with the server's failure, and a 419 that a new token doesn't cure is a session that ended, for
3
+ // the kit's JSON requests and for Inertia visits alike. The panel's own 403, 404 and 500 are pages (larakit/Error).
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { act, cleanup, render, screen as view } from '@testing-library/react';
6
+ import { createInertiaApp, router } from '@inertiajs/react';
7
+ import type { IndexProps } from '@larakit/core';
8
+ import { panel, screen } from './fixtures';
9
+ import { ResourceIndex } from './pages';
10
+ import { ApiError, api, setPanelPath } from './kit/api';
11
+ import { setI18n } from './kit/i18n';
12
+
13
+ afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
14
+
15
+ const messages = { 'page.serverError': 'The server failed.', 'page.sessionExpired': 'Your session ended.', 'page.signedOut': 'Sign in again.' };
16
+ const json = (status: number, body: unknown = {}) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
17
+
18
+ describe("the kit's JSON requests", () => {
19
+ it('ask for a new token once on a 419, then say the session ended', async () => {
20
+ setI18n('en', 'ltr', messages);
21
+ setPanelPath('/admin');
22
+ const urls: string[] = [];
23
+ vi.stubGlobal('fetch', vi.fn(async (url: string) => { urls.push(String(url)); return json(String(url).endsWith('/api/panel') ? 200 : 419, { message: 'CSRF token mismatch.' }); }));
24
+ const failed = await api('/orders/1/actions/ship', 'POST', {}).catch((e) => e);
25
+ expect(urls).toEqual(['/admin/api/orders/1/actions/ship', '/admin/api/panel', '/admin/api/orders/1/actions/ship']);
26
+ expect(failed).toBeInstanceOf(ApiError);
27
+ expect(failed).toMatchObject({ status: 419, message: 'Your session ended.' });
28
+ });
29
+
30
+ it("say the server failed on a 5xx, with the failure's words only in debug mode", async () => {
31
+ setI18n('en', 'ltr', messages);
32
+ setPanelPath('/admin');
33
+ vi.stubGlobal('fetch', vi.fn(async () => json(500, { message: 'Server Error' })));
34
+ await expect(api('/orders/1/actions/ship', 'POST', {})).rejects.toMatchObject({ status: 500, message: 'The server failed.' });
35
+ vi.stubGlobal('fetch', vi.fn(async () => json(500, { message: 'the note failed', error: '*errors.errorString' })));
36
+ await expect(api('/orders/1/actions/ship', 'POST', {})).rejects.toMatchObject({ message: 'The server failed. (the note failed)' });
37
+ vi.stubGlobal('fetch', vi.fn(async () => json(401, { message: 'Unauthenticated.' })));
38
+ await expect(api('/orders')).rejects.toMatchObject({ status: 401, message: 'Sign in again.' });
39
+ });
40
+ });
41
+
42
+ function page(): IndexProps {
43
+ return {
44
+ path: '/admin', errors: {},
45
+ larakit: { ...panel('Shop', [{ name: 'orders', label: 'Orders', icon: '', group: '', href: '/admin/orders' }]), messages },
46
+ screen: screen({ name: 'orders', label: 'Orders', columns: [{ key: 'number', label: 'Number', type: 'text', sortable: false, searchable: false }] }),
47
+ table: { data: [], total: 0, page: 1, lastPage: 1 },
48
+ query: { filters: {} },
49
+ modal: null,
50
+ } as never;
51
+ }
52
+
53
+ async function open() {
54
+ await act(async () => {
55
+ await createInertiaApp({
56
+ page: { component: 'larakit/Resource/Index', props: page(), url: '/admin/orders', version: '1', flash: {} } as never,
57
+ resolve: () => ResourceIndex as never, setup: ({ App, props }) => { render(<App {...props} />); },
58
+ });
59
+ });
60
+ }
61
+
62
+ /** Inertia's events, as its router fires them around a visit. */
63
+ const before = (visit: object) => document.dispatchEvent(new CustomEvent('inertia:before', { cancelable: true, detail: { visit } }));
64
+ const exception = (status: number, headers: Record<string, string> = {}) => {
65
+ const event = new CustomEvent('inertia:httpException', { cancelable: true, detail: { response: { status, headers, data: '<html>419</html>' } } });
66
+ document.dispatchEvent(event);
67
+ return event.defaultPrevented;
68
+ };
69
+
70
+ describe('an Inertia visit', () => {
71
+ it('is sent once more with a new token after a 419, then the page says the session ended', async () => {
72
+ const urls: string[] = [];
73
+ vi.stubGlobal('fetch', vi.fn(async (url: string) => { urls.push(String(url)); return json(200); }));
74
+ const visit = vi.spyOn(router, 'visit').mockImplementation(() => {});
75
+ await open();
76
+ before({ url: new URL('http://localhost/admin/orders/1/actions/ship?tab=all'), method: 'post', data: { text: 'hi' }, headers: {} });
77
+ await act(async () => { expect(exception(419)).toBe(true); await new Promise((r) => setTimeout(r, 0)); });
78
+ expect(urls).toEqual(['/admin/api/panel']);
79
+ expect(visit).toHaveBeenCalledWith('/admin/orders/1/actions/ship?tab=all', expect.objectContaining({ method: 'post', data: { text: 'hi' }, headers: { 'X-Larakit-Again': '1' } }));
80
+
81
+ before({ url: new URL('http://localhost/admin/orders/1/actions/ship'), method: 'post', data: {}, headers: { 'X-Larakit-Again': '1' } });
82
+ await act(async () => { expect(exception(419)).toBe(true); });
83
+ expect(view.getByRole('alert').textContent).toContain('Your session ended.');
84
+ expect(visit).toHaveBeenCalledTimes(1);
85
+ });
86
+
87
+ it("leaves every other answer to Inertia: the panel's error pages, and the framework's page in debug mode", async () => {
88
+ vi.stubGlobal('fetch', vi.fn(async () => json(200)));
89
+ await open();
90
+ before({ url: new URL('http://localhost/admin/nope'), method: 'get', data: {}, headers: {} });
91
+ expect(exception(500)).toBe(false);
92
+ expect(exception(404, { 'x-inertia': 'true' })).toBe(false);
93
+ expect(exception(419, { 'x-inertia': 'true' })).toBe(false);
94
+ });
95
+ });
@@ -0,0 +1,20 @@
1
+ // Pages as the server sends them, for the tests.
2
+ import type { Panel, Screen } from '@larakit/core';
3
+
4
+ /** A panel with nothing but its name and menu. */
5
+ export function panel(name: string, menu: Panel['menu'] = []): Panel {
6
+ return {
7
+ protocol: 2, name, logo: '', logoDark: '', icons: {}, locale: 'en', dir: 'ltr', messages: {}, dates: 7,
8
+ theme: { preset: 'ink', mode: 'system', tokens: {}, light: {}, dark: {} },
9
+ layout: { nav: 'side', topbar: 'on', width: 'full', form: 'dialog', groups: 'fixed' },
10
+ parts: {}, user: null, userMenu: [], links: [], plugins: [], menu,
11
+ };
12
+ }
13
+
14
+ /** A screen with the parts a test gives. */
15
+ export function screen(given: Pick<Screen, 'name' | 'label'> & Partial<Screen>): Screen {
16
+ return {
17
+ columns: [], fields: [], form: { items: [] }, actions: [], bulk: [], filters: [], canCreate: false, sort: '', perPage: 25,
18
+ perPages: [10, 25, 50], table: {}, ...given,
19
+ };
20
+ }
package/src/index.ts ADDED
@@ -0,0 +1,29 @@
1
+ export { Cell, CellView } from './Cell';
2
+ export {
3
+ larakit, larakitReady, componentName, Part, LayoutPart,
4
+ type Customizable, type PartOwn, type SectionProps, type ColumnCellProps, type FieldInputProps, type ActionButtonProps,
5
+ type BrandProps, type NavProps, type NavItem, type TopbarProps, type TenantSwitcherProps, type HeaderProps, type BreadcrumbProps,
6
+ type TableProps, type CellProps, type BadgeProps, type EmptyProps, type PaginationProps, type FiltersProps, type FormProps,
7
+ type FieldProps, type ButtonProps, type TabsProps, type ModalProps, type DashboardProps, type WidgetProps, type StatProps,
8
+ type ToastProps, type LoadingProps, type ErrorProps,
9
+ type LayoutPartProps, type Setup,
10
+ } from './components';
11
+ export { useLarakit, LarakitProvider, type Larakit } from './context';
12
+ export {
13
+ definePlugin, pluginApi,
14
+ type LarakitPlugin, type PluginColumnProps, type PluginFieldProps, type PluginWidgetProps, type PluginPageProps,
15
+ type PageProps, type RunResult, type ComponentWidgetProps,
16
+ type PluginBarProps, type PluginHookProps, type AppParts, type PluginParts,
17
+ } from './plugins';
18
+ export { Field, FieldFrame, Control, type FieldArgs, type ControlProps } from './Field';
19
+ export { Form, DefaultForm, Section, type FormArgs } from './Form';
20
+ export { Repeater } from './Repeater';
21
+ export { FileInput } from './FileInput';
22
+ export { PanelLayout, Brand, Nav, Topbar, TenantSwitcher, Toast } from './Layout';
23
+ export {
24
+ ResourceIndex, ActionButton, PageHeader, Breadcrumb, Table, Filters, EmptyText, Pages, type ResourcePageProps, type ResourcePageName,
25
+ } from './ResourceIndex';
26
+ export { Dashboard, DefaultDashboard, DefaultWidget, DefaultStat, type WidgetData } from './Dashboard';
27
+ export { Badge, DefaultBadge, Button, DefaultButton, Dialog, DefaultModal, Tabs, Loading } from './ui';
28
+ // Larakit's building blocks, for a component that draws one of a resource's own pages (ResourcePageProps).
29
+ export { ResourceTable, RecordForm, InfolistView } from './blocks';
package/src/kit/api.ts ADDED
@@ -0,0 +1,305 @@
1
+ import { xsrfToken } from './hooks';
2
+ import { t } from './i18n';
3
+
4
+ export type Look = { format?: 'date' | 'datetime' | 'time' | 'since' | 'number' | 'money'; decimals?: number; currency?: string; cents?: boolean; prefix?: string; suffix?: string; limit?: number; align?: 'center' | 'end'; noWrap?: boolean; copyable?: boolean; description?: boolean; toggleable?: boolean; hidden?: boolean; round?: boolean; size?: number; tooltip?: string; placeholder?: string; colors?: Record<string, string>; labels?: Record<string, string>; icon?: string; iconAfter?: boolean; iconColors?: Record<string, string> };
5
+ export type SummarySpec = {
6
+ kind?: 'sum' | 'avg' | 'min' | 'max' | 'count' | string;
7
+ type?: 'sum' | 'avg' | 'min' | 'max' | 'count' | string;
8
+ label?: string;
9
+ hiddenLabel?: boolean;
10
+ look?: Look;
11
+ format?: Look['format'];
12
+ decimals?: number;
13
+ currency?: string;
14
+ cents?: boolean;
15
+ prefix?: string;
16
+ suffix?: string;
17
+ };
18
+ export type SummaryResult = { kind?: string; type?: string; label?: string; value: unknown; hiddenLabel?: boolean; look?: Look; format?: Look['format']; decimals?: number; currency?: string; cents?: boolean; prefix?: string; suffix?: string };
19
+ export type ColumnSummaries = SummaryResult[] | Record<string, unknown>;
20
+ export type ColumnEditable = { type: 'toggle' | 'select' | 'text' | 'number'; options?: Choice[]; placeholder?: string; step?: number | string; min?: number | string; max?: number | string };
21
+ export type Column = { component?: string; partKey?: string; key: string; label: string; type: string; props?: Record<string, unknown>; look?: Look; sortable: boolean; searchable: boolean; summaries?: SummarySpec[]; editable?: ColumnEditable };
22
+ export type TableTab = { name: string; label: string; icon?: string; color?: string; default?: boolean };
23
+ export type GroupOption = { key: string; label: string; collapsible?: boolean };
24
+ export type ImportColumn = { key: string; label: string; required?: boolean };
25
+ export type ImportConfig = { columns?: ImportColumn[]; accept?: string[]; maxSize?: number; sampleUrl?: string };
26
+ export type ImportError = { row: number; message: string; column?: string };
27
+ export type ImportResult = { imported: number; failed: number; errors?: ImportError[]; message?: string };
28
+ export type Choice = { value: string | number | boolean; label: string; group?: string; description?: string; disabled?: boolean; icon?: string };
29
+ export type Choosing = { multiple?: boolean; searchable?: boolean; native?: boolean; clearable?: boolean; remote?: boolean; maxItems?: number; placeholder?: string; create?: { fields: Field[] } };
30
+ export type FileSettings = { accept?: string[]; maxSize: number; multiple?: boolean; maxFiles?: number; image?: boolean };
31
+ export type Field = { component?: string; partKey?: string; key: string; label: string; type: string; file?: FileSettings; props?: Record<string, unknown>; options?: Choice[]; select?: Choosing; default?: unknown; look?: FieldLook; visibleWhen?: Condition[]; requiredWhen?: Condition[]; disabledWhen?: Condition[]; hiddenOn?: string[]; disabledOn?: string[] };
32
+ /** Without values: the field has any. Runs here, so changing a field never asks the server. The server still validates. */
33
+ export type Condition = { field: string; values?: string[]; not?: boolean };
34
+ export type Tone = 'gray' | 'primary' | 'info' | 'success' | 'warning' | 'danger' | 'indigo' | 'purple' | 'rose' | 'orange' | 'teal' | 'cyan';
35
+ export type ButtonVariant = 'solid' | 'soft' | 'outline' | 'ghost' | 'link';
36
+ export type ButtonSize = 'xs' | 'sm' | 'md' | 'lg';
37
+ export type FieldLook = { helper?: string; hint?: string; placeholder?: string; prefix?: string; suffix?: string; hiddenLabel?: boolean; inlineLabel?: boolean; labelAbove?: boolean; autofocus?: boolean; readOnly?: boolean; required?: boolean; input?: string; inputMode?: string; autocomplete?: string; autocapitalize?: string; mask?: string; datalist?: string[]; revealable?: boolean; copyable?: boolean; step?: unknown; min?: unknown; max?: unknown; minLength?: number; maxLength?: number; rows?: number; autosize?: boolean; seconds?: boolean; inline?: boolean; grouped?: boolean; selectAll?: boolean; confirmChanges?: boolean; columns?: number; colors?: Record<string, string>; variant?: 'solid' | 'soft' | 'outline'; size?: ButtonSize; onColor?: string; offColor?: string; span?: number; toolbar?: string[]; minHeight?: number; maxHeight?: number; color?: string; fullWidth?: boolean; separator?: string; suggestions?: string[]; minItems?: number; maxItems?: number; keyLabel?: string; valueLabel?: string; keyPlaceholder?: string; valuePlaceholder?: string; addLabel?: string; editableKeys?: boolean; editableValues?: boolean; reorderable?: boolean; fields?: Field[]; itemLabel?: string; collapsible?: boolean; collapsed?: boolean; cloneable?: boolean; table?: boolean; range?: boolean; marks?: boolean; language?: string; wrap?: boolean; length?: number; numeric?: boolean; submitOnCompletion?: boolean };
38
+ export type Place = { field: string } | Group;
39
+ export type Group = { component?: string; partKey?: string; props?: Record<string, unknown>; type: 'section' | 'fieldset' | 'grid' | 'tabs' | 'tab' | 'callout' | 'wizard' | 'step'; heading?: string; description?: string; columns?: number; span?: number; collapsible?: boolean; collapsed?: boolean; aside?: boolean; compact?: boolean; icon?: string; color?: string; badge?: string; badgeColor?: string; skippable?: boolean; visibleWhen?: Condition[]; items: Place[] };
40
+ export type ModalWidth = 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'full';
41
+ export type FormLayout = { columns?: number; width?: ModalWidth; items: Place[] };
42
+ export type Action = {
43
+ component?: string;
44
+ partKey?: string;
45
+ name: string;
46
+ label: string;
47
+ confirm: string;
48
+ danger: boolean;
49
+ icon?: string;
50
+ form?: Field[];
51
+ color?: string;
52
+ variant?: ButtonVariant;
53
+ size?: ButtonSize;
54
+ iconOnly?: boolean;
55
+ place?: 'menu' | 'row';
56
+ eyebrow?: string;
57
+ description?: string;
58
+ slideOver?: boolean;
59
+ modalWidth?: ModalWidth;
60
+ submitLabel?: string;
61
+ cancelLabel?: string;
62
+ };
63
+ export type InfolistLook = {
64
+ format?: Look['format'];
65
+ decimals?: number;
66
+ currency?: string;
67
+ cents?: boolean;
68
+ prefix?: string;
69
+ suffix?: string;
70
+ limit?: number;
71
+ copyable?: boolean;
72
+ placeholder?: string;
73
+ colors?: Record<string, string>;
74
+ labels?: Record<string, string>;
75
+ icon?: string;
76
+ iconAfter?: boolean;
77
+ iconColors?: Record<string, string>;
78
+ iconColor?: string;
79
+ icons?: Record<string, string>;
80
+ color?: string;
81
+ size?: number;
82
+ round?: boolean;
83
+ bulleted?: boolean;
84
+ span?: number;
85
+ hiddenLabel?: boolean;
86
+ inlineLabel?: boolean;
87
+ helper?: string;
88
+ hint?: string;
89
+ tooltip?: string;
90
+ language?: string;
91
+ wrap?: boolean;
92
+ keyLabel?: string;
93
+ valueLabel?: string;
94
+ fields?: InfolistEntry[];
95
+ columns?: number;
96
+ };
97
+ export type InfolistEntry = {
98
+ key: string;
99
+ label: string;
100
+ type: string;
101
+ look?: InfolistLook;
102
+ props?: Record<string, unknown>;
103
+ visibleWhen?: Condition[];
104
+ };
105
+ export type InfolistPlace = { field: string } | { entry: string } | InfolistGroup;
106
+ export type InfolistGroup = Omit<Group, 'items'> & { items: InfolistPlace[] };
107
+ export type Infolist = {
108
+ columns?: number;
109
+ width?: ModalWidth;
110
+ entries: InfolistEntry[];
111
+ items?: InfolistPlace[];
112
+ };
113
+ /** How a row's View or Edit button looks. */
114
+ export type Button = { label?: string; icon?: string; color?: string; variant?: ButtonVariant; size?: ButtonSize; iconOnly?: boolean; noIcon?: boolean; inMenu?: boolean };
115
+ export type Link = {
116
+ label: string;
117
+ href: string;
118
+ icon?: string;
119
+ post?: boolean;
120
+ color?: string;
121
+ variant?: ButtonVariant;
122
+ size?: ButtonSize;
123
+ badge?: string;
124
+ badgeColor?: string;
125
+ iconOnly?: boolean;
126
+ };
127
+ export type HookName =
128
+ | 'topbar.start'
129
+ | 'topbar.before-search'
130
+ | 'topbar.after-search'
131
+ | 'topbar.end'
132
+ | 'sidebar.header'
133
+ | 'sidebar.nav.start'
134
+ | 'sidebar.nav.end'
135
+ | 'sidebar.footer'
136
+ | 'content.start'
137
+ | 'content.end'
138
+ | 'page.header.actions.before'
139
+ | 'page.header.actions.after'
140
+ | 'table.toolbar.start'
141
+ | 'table.toolbar.end'
142
+ | 'table.before'
143
+ | 'table.after'
144
+ | 'form.before'
145
+ | 'form.after'
146
+ | 'infolist.before'
147
+ | 'infolist.after'
148
+ | 'body.start'
149
+ | 'body.end'
150
+ | (string & {});
151
+ export type HookButtonItem = {
152
+ type?: 'button';
153
+ label: string;
154
+ href: string;
155
+ icon?: string;
156
+ color?: string;
157
+ variant?: ButtonVariant;
158
+ size?: ButtonSize;
159
+ badge?: string;
160
+ badgeColor?: string;
161
+ iconOnly?: boolean;
162
+ post?: boolean;
163
+ };
164
+ export type HookActionItem = { type: 'action'; action: Action };
165
+ export type HookBadgeItem = { type: 'badge'; label: string; icon?: string; color?: string; href?: string };
166
+ export type HookBannerItem = { type: 'banner'; title: string; description?: string; icon?: string; color?: string };
167
+ export type HookTextItem = { type: 'text'; text: string; icon?: string; color?: string };
168
+ export type HookItem = HookButtonItem | HookActionItem | HookBadgeItem | HookBannerItem | HookTextItem;
169
+ export type Notification = { id: string; title: string; body: string; icon: string; color: string; href: string; at: string; read: boolean };
170
+ export type Resource = { name: string; label: string; icon?: string; group?: string; badge?: boolean; pages?: MenuPage[]; globalSearch?: boolean; columns: Column[]; fields: Field[]; actions: Action[]; canCreate: boolean; form?: FormLayout; infolist?: Infolist; relations?: RelationResource[]; view?: boolean; headerActions?: Action[];
171
+ filters?: Field[]; bulk?: Action[]; sort?: string; perPage?: number; perPages?: number[]; tabs?: TableTab[]; groups?: GroupOption[];
172
+ table?: { striped?: boolean; iconActions?: boolean; viewButton?: Button; editButton?: Button; textButtons?: boolean; poll?: number; empty?: string; emptyDescription?: string; defaultGroup?: string; defaultGroupDir?: 'asc' | 'desc'; reorderable?: boolean; exportable?: boolean; importable?: boolean | ImportConfig; deferFilters?: boolean; filtersLayout?: 'popover' | 'above' | 'modal' } };
173
+ export type RelationResource = Resource & { foreignKey?: string; parentResource?: string; relation?: string };
174
+ export type Tokens = Record<string, string>;
175
+ export type Theme = { preset: string; mode: 'system' | 'light' | 'dark'; tokens: Tokens; light: Tokens; dark: Tokens };
176
+ export type Layout = { nav: 'side' | 'top'; topbar?: 'on' | 'off'; width: 'full' | 'narrow'; form: 'dialog' | 'drawer' | 'page'; groups?: 'fixed' | 'collapsible'; loadingDelay?: number };
177
+ export type TenantInfo = { id: string; name: string; slug?: string; avatar?: string; color?: string };
178
+ export type TenancyMeta = { enabled: boolean; tenants: TenantInfo[]; active?: string };
179
+ export type Panel = { profile?: boolean; logo?: string; logoDark?: string; icons?: Record<string, string>; locale?: string; dir?: 'ltr' | 'rtl'; messages?: Record<string, string>; user?: { name: string; detail: string; avatar: string } | null; userMenu?: Link[]; links?: Link[]; topbarActions?: Action[]; hooks?: Partial<Record<HookName, HookItem[]>>; notifications?: { poll: number } | null; tenancy?: TenancyMeta; preview?: { role: string; label: string }; protocol: number; name: string; theme: Theme; layout: Layout; dates: number; dashboard: Widget[]; pages: MenuPage[]; plugins: { id: string; name: string; version: string; script: string; style: string; replaces: string[]; bars?: string[]; hooks?: HookName[] }[]; resources: Resource[] };
180
+ export type PanelMeta = Panel;
181
+ export type PanelInfo = Panel;
182
+ /** A page in the menu: a plugin's, with a type, or the panel's own, with a name, widgets and actions. */
183
+ export type MenuPage = { type?: string; name?: string; component?: string; label: string; icon?: string; group?: string; description?: string; actions?: Action[]; widgets?: Widget[]; form?: { fields: Field[]; items?: Place[]; columns?: number; canSave: boolean } };
184
+ export type WidgetFilter = { name: string; label: string; options: Choice[]; default?: string | number | boolean; placeholder?: string };
185
+ export type WidgetType = 'stats' | 'list' | 'bar' | 'column' | 'line' | 'area' | 'doughnut' | 'pie' | 'component' | (string & {});
186
+ export type Widget = { name: string; label: string; type: WidgetType; component?: string; wide: boolean; poll: number; screen?: string; links?: { label: string; href: string }[]; empty?: string; filters?: WidgetFilter[]; deferFilters?: boolean; assistive?: string };
187
+ export type Stat = { label: string; value: unknown; note: string; screen: string; href?: string; icon?: string; color?: string; chart?: number[] };
188
+ export type Point = { label: string; value: number; href?: string };
189
+ export type Series = { label: string; values: number[] };
190
+ export type Chart = { labels: string[]; series: Series[]; hrefs?: string[] };
191
+ export type ListData = { columns: { key: string; label: string; type: string; props?: Record<string, unknown> | null; look?: Look }[]; rows: { id: string; cells: Record<string, unknown> }[] };
192
+ export type Row = { id: string; cells: Record<string, unknown>; can: { update: boolean; actions: string[]; bulk?: string[]; editColumns?: string[]; preview?: string } };
193
+ export type Page = { data: Row[]; total: number; page: number; lastPage: number; tabCounts?: Record<string, number>; summaries?: Record<string, ColumnSummaries> };
194
+ export type RecordData = { id: string; version: string; values: Record<string, unknown>; infolist?: Record<string, unknown> };
195
+
196
+ export const text = (v: unknown) => (v === null || v === undefined ? '' : String(v));
197
+ /** One value or several, as a list of texts. */
198
+ export const list = (v: unknown): string[] => (Array.isArray(v) ? v.map(String) : v === undefined || v === null || v === '' ? [] : [String(v)]);
199
+ export const fail = (e: unknown) => (e instanceof Error ? e.message : t('page.wentWrong'));
200
+
201
+ export class ApiError extends Error {
202
+ constructor(public status: number, message: string, public errors: Record<string, string[]> = {}, public data?: unknown) { super(message); }
203
+ }
204
+ /** Where the panel lives, such as /admin: the page that draws a part of the panel says it (setPanelPath). */
205
+ let panelPath = '';
206
+ /** The panel's JSON endpoints, such as /admin/api. */
207
+ export let base = '/api';
208
+ /** Tells the panel's pieces where the panel lives. Larakit's pages call it when they draw. */
209
+ export function setPanelPath(path: string) {
210
+ panelPath = path;
211
+ base = path + '/api';
212
+ }
213
+
214
+ export const currentPanelPath = () => panelPath;
215
+
216
+ let delayMs = 150;
217
+
218
+ /** How long (in ms) before a loading placeholder appears. Fast responses show nothing. */
219
+ export const loadingDelay = () => delayMs;
220
+ export function setLoadingDelay(ms?: number) {
221
+ if (typeof ms === 'number' && Number.isFinite(ms) && ms >= 0) delayMs = ms;
222
+ }
223
+
224
+ /** The role whose eyes the panel is seen through: the server keeps it in the session and says it in the panel. */
225
+ export const previewRole = () => '';
226
+ /**
227
+ * Starts or ends seeing the panel as a role. The server keeps it in the session, so a new tab, a reload or a plain
228
+ * link sees the panel the same way; the page is visited again. A role the visitor may not see the panel as is refused
229
+ * (403/404): then nothing changes and the server's message is thrown. No `X-Larakit-As` header is ever sent.
230
+ */
231
+ export async function setPreviewRole(role: string) {
232
+ const token = xsrfToken();
233
+ const res = await fetch(panelPath + '/preview', {
234
+ method: role ? 'POST' : 'DELETE',
235
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...(token ? { 'X-XSRF-TOKEN': token } : {}) },
236
+ body: role ? JSON.stringify({ role }) : undefined,
237
+ });
238
+ if (role && !res.ok) {
239
+ const data = await res.json().catch(() => ({}));
240
+ throw new ApiError(res.status, failure(res.status, data), data.errors, data);
241
+ }
242
+ location.assign(role ? panelPath : location.href);
243
+ }
244
+
245
+ /**
246
+ * Chooses the tenant the panel shows. The server keeps it in the session, so every page and JSON endpoint after it
247
+ * answers for that tenant; the page is then visited again. Refused (403) for a tenant the visitor may not see.
248
+ */
249
+ export async function setTenant(tenant: string) {
250
+ const token = xsrfToken();
251
+ const res = await fetch(panelPath + '/tenant', {
252
+ method: 'POST',
253
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json', ...(token ? { 'X-XSRF-TOKEN': token } : {}) },
254
+ body: JSON.stringify({ tenant }),
255
+ });
256
+ if (!res.ok) {
257
+ const data = await res.json().catch(() => ({}));
258
+ throw new ApiError(res.status, failure(res.status, data), data.errors, data);
259
+ }
260
+ }
261
+
262
+ export async function api<T>(path: string, method = 'GET', body?: unknown, signal?: AbortSignal, version?: string): Promise<T> {
263
+ const send = () => {
264
+ const token = xsrfToken();
265
+ const headers: Record<string, string> = { Accept: 'application/json' };
266
+ const form = body instanceof FormData;
267
+ if (body !== undefined && !form) headers['Content-Type'] = 'application/json';
268
+ if (version) headers['X-Larakit-Version'] = version;
269
+ if (token && method !== 'GET') headers['X-XSRF-TOKEN'] = decodeURIComponent(token);
270
+ return fetch(base + path, { method, headers, signal, body: body === undefined ? undefined : form ? body : JSON.stringify(body) });
271
+ };
272
+ let res = await send();
273
+ // An old token: any answer brings a new one, then it is tried once more.
274
+ if (res.status === 419) {
275
+ await fetch(base + '/panel', { headers: { Accept: 'application/json' }, signal }).catch(() => {});
276
+ res = await send();
277
+ }
278
+ // A login page that the application sent us to is not an answer.
279
+ if (res.redirected && !(res.headers.get('content-type') ?? '').includes('json')) throw new ApiError(401, t('page.signedOut'));
280
+ const data = await res.json().catch(() => ({}));
281
+ if (res.status === 401) throw new ApiError(401, t('page.signedOut'), {}, data);
282
+ if (!res.ok) throw new ApiError(res.status, failure(res.status, data), data.errors, data);
283
+ // Something changed, so the numbers in the menu may have too.
284
+ if (method !== 'GET') dispatchEvent(new Event(changed));
285
+ return data as T;
286
+ }
287
+
288
+ /**
289
+ * What a failed answer tells the visitor. A 419 that a new token didn't cure is a session that ended; a 5xx says the
290
+ * server failed, with the failure's own words only in debug mode, where the answer names the error. Inertia visits
291
+ * that get a 419 say the same (see PanelLayout).
292
+ */
293
+ export function failure(status: number, data: { message?: unknown; error?: unknown }): string {
294
+ const message = typeof data.message === 'string' ? data.message : '';
295
+ if (status === 419) return t('page.sessionExpired');
296
+ if (status >= 500) return t('page.serverError') + (typeof data.error === 'string' && message ? ` (${message})` : '');
297
+ return message || t('form.requestFailed', { status });
298
+ }
299
+
300
+ /** The event after a request that changed something. */
301
+ export const changed = 'larakit:changed';
302
+
303
+
304
+ /** Where to sign in again, when the server said. */
305
+ export const loginOf = (e: unknown) => (e instanceof ApiError && e.status === 401 && typeof (e.data as { login?: unknown })?.login === 'string' ? (e.data as { login: string }).login : '');