@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,57 @@
1
+ import { useEffect } from 'react';
2
+ import { useBrowserState } from './hooks';
3
+ import type { Theme } from './api';
4
+
5
+ const key = 'larakit:mode';
6
+ const saved = () => { try { return typeof localStorage === 'undefined' ? null : localStorage.getItem(key); } catch { return null; } };
7
+ // Asked when the page draws, not when the module loads: a server that draws the page first has no matchMedia.
8
+ const system = () => (typeof matchMedia === 'undefined' ? null : matchMedia('(prefers-color-scheme: dark)'));
9
+
10
+ /** Black or white, whichever reads better on a color. */
11
+ function readable(color: string): string | undefined {
12
+ if (!CSS.supports('color', color)) return;
13
+ const canvas = document.createElement('canvas');
14
+ canvas.width = canvas.height = 1;
15
+ const c = canvas.getContext('2d');
16
+ if (!c) return;
17
+ c.fillStyle = color;
18
+ c.fillRect(0, 0, 1, 1);
19
+ const [r, g, b] = [...c.getImageData(0, 0, 1, 1).data].map((v) => (v / 255 <= 0.04045 ? v / 255 / 12.92 : ((v / 255 + 0.055) / 1.055) ** 2.4));
20
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b > 0.179 ? '#000' : '#fff';
21
+ }
22
+
23
+ /** Applies the panel's theme and lets the visitor switch light and dark. */
24
+ export function useTheme(theme?: Theme): ['light' | 'dark', (choice: 'light' | 'dark' | 'system') => void, 'light' | 'dark' | 'system'] {
25
+ const [choice, setChoice] = useBrowserState<string | null>(null, saved);
26
+ const [dark, setDark] = useBrowserState(false, () => system()?.matches ?? false);
27
+ useEffect(() => {
28
+ const query = system();
29
+ if (!query) return;
30
+ const change = () => setDark(query.matches);
31
+ query.addEventListener('change', change);
32
+ return () => query.removeEventListener('change', change);
33
+ }, []);
34
+ const wanted = theme && theme.mode !== 'system' ? theme.mode : choice;
35
+ const mode = wanted === 'light' || wanted === 'dark' ? wanted : dark ? 'dark' : 'light';
36
+ useEffect(() => {
37
+ const el = document.documentElement;
38
+ el.dataset.lkMode = mode;
39
+ if (!theme) return;
40
+ el.dataset.lkPreset = theme.preset;
41
+ const own = { ...theme.tokens, ...theme[mode] };
42
+ // A new primary color also needs readable text on it, unless the theme says which.
43
+ if (own.primary && !own['on-primary']) own['on-primary'] = readable(own.primary) ?? own['on-primary'];
44
+ // Charts follow a new primary color too.
45
+ if (own.primary && !own.chart) own.chart = own.primary;
46
+ // Focus rings follow a new primary color unless customized.
47
+ if (own.primary && !own.ring) own.ring = `color-mix(in srgb, ${own.primary} 55%, transparent)`;
48
+ for (const name of new Set(['on-primary', 'chart', 'ring', ...Object.keys(theme.tokens), ...Object.keys(theme.light), ...Object.keys(theme.dark)])) {
49
+ if (own[name] === undefined) el.style.removeProperty('--lk-' + name);
50
+ else el.style.setProperty('--lk-' + name, own[name]);
51
+ }
52
+ }, [theme, mode]);
53
+ return [mode, (next) => {
54
+ try { localStorage.setItem(key, next); } catch { /* private window */ }
55
+ setChoice(next);
56
+ }, choice === 'light' || choice === 'dark' ? choice : 'system'];
57
+ }
@@ -0,0 +1,159 @@
1
+ // Every part of the layout that the protocol lists (protocol/conformance/parts.json, panel.schema.json's
2
+ // layoutPart) can be drawn by the application's own component: @larakit/react draws it through LayoutPart, exports
3
+ // its props type, and gives the component `data`, `partKey` and `Default`. A part added to the protocol and not
4
+ // here, or drawn without LayoutPart, fails this test.
5
+ import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
6
+ import { act, cleanup, render } from '@testing-library/react';
7
+ import { createInertiaApp } from '@inertiajs/react';
8
+ import type { IndexProps, LayoutPart as PartName, Panel } from '@larakit/core';
9
+ import { larakit, type Customizable } from './components';
10
+ import { kitFor, LarakitProvider } from './context';
11
+ import { Dashboard } from './Dashboard';
12
+ import { panel, screen } from './fixtures';
13
+ import { ErrorView } from './PanelPages';
14
+ import { ResourceIndex } from './pages';
15
+
16
+ afterEach(cleanup);
17
+
18
+ /** React's warnings while the parts draw: a wrapped Default must not put props on an element that it can't take. */
19
+ const warned: string[] = [];
20
+ const error = console.error;
21
+ beforeAll(() => { console.error = (...args: unknown[]) => { warned.push(args.map(String).join(' ')); }; });
22
+ afterAll(() => { console.error = error; });
23
+
24
+ declare global {
25
+ interface ImportMeta {
26
+ glob(pattern: string | string[], options: { query: '?raw'; import: 'default'; eager: true }): Record<string, string>;
27
+ }
28
+ }
29
+
30
+ // Vite reads the files when it loads the test, as text.
31
+ const files = import.meta.glob(['./*.ts', './*.tsx', './kit/*.tsx', '!./*.test.*', '../../../../protocol/conformance/parts.json'], { query: '?raw', import: 'default', eager: true });
32
+ const text = (end: string) => Object.entries(files).find(([path]) => path.endsWith(end))?.[1] ?? '';
33
+ const listed: PartName[] = JSON.parse(text('/parts.json')).parts;
34
+ const sources = Object.entries(files).filter(([path]) => !path.endsWith('.json')).map(([, source]) => source).join('\n');
35
+ // The kit's parts go through LayoutPart by their names, in kit/bridge.tsx.
36
+ const bridged = text('/kit/bridge.tsx');
37
+ const index = text('/index.ts');
38
+ const pascal = (part: string) => part[0].toUpperCase() + part.slice(1);
39
+
40
+ /** What each application component saw, by its part: once for every time it was drawn. */
41
+ const seen = new Map<string, { data: unknown; partKey: string; hasDefault: boolean }[]>();
42
+
43
+ /** An application's component for a part: it notes what it got and wraps Larakit's drawing in one line. */
44
+ function own(part: string) {
45
+ return function Own(props: Customizable<Record<string, unknown>, Record<string, unknown>>) {
46
+ seen.set(part, [...(seen.get(part) ?? []), { data: props.data, partKey: props.partKey, hasDefault: typeof props.Default === 'function' }]);
47
+ return <span data-own={part} style={{ display: 'contents' }}><props.Default {...props} /></span>;
48
+ };
49
+ }
50
+
51
+ function everyPartOwn(): Panel['parts'] {
52
+ larakit({ components: Object.fromEntries(listed.map((p) => [`./larakit/components/own/${p}.tsx`, { default: own(p) }])) });
53
+ return Object.fromEntries(listed.map((p) => [p, `own/${p}`]));
54
+ }
55
+
56
+ function page(parts: Panel['parts'], rows: number): IndexProps {
57
+ const larakit = { ...panel('Shop', [
58
+ { name: 'dashboard', label: 'Dashboard', icon: '', group: '', href: '/admin' },
59
+ { name: 'orders', label: 'Orders', icon: '', group: 'Sales', href: '/admin/orders' },
60
+ ]), parts, tenancy: { enabled: true, tenants: [{ id: 'a', name: 'Acme', active: true }, { id: 'b', name: 'Beta' }] } };
61
+ return {
62
+ path: '/admin', errors: {}, larakit,
63
+ screen: screen({
64
+ name: 'orders', label: 'Orders', canCreate: true,
65
+ columns: [
66
+ { key: 'number', label: 'Number', type: 'text', sortable: true, searchable: true, props: { icon: 'hash' } },
67
+ { key: 'status', label: 'Status', type: 'badge', sortable: false, searchable: false, look: { colors: { paid: 'success' } } },
68
+ ],
69
+ tabs: [{ name: 'all', label: 'All' }, { name: 'paid', label: 'Paid' }],
70
+ filters: [{ key: 'status', label: 'Status', type: 'select', options: [{ value: 'paid', label: 'Paid' }] }],
71
+ fields: [{ key: 'number', label: 'Number', type: 'text', props: { hint: 'ORD-' } }, { key: 'note', label: 'Note', type: 'text' }],
72
+ form: { items: [
73
+ { type: 'section', heading: 'Order', items: [{ field: 'number' }] },
74
+ { type: 'tabs', items: [{ type: 'tab', heading: 'More', items: [{ field: 'note' }] }] },
75
+ ] },
76
+ }),
77
+ table: { data: Array.from({ length: rows }, (_, i) => ({ id: String(i + 1), cells: { number: 'ORD-' + (i + 1), status: 'paid' }, can: { update: true, actions: [] } })), total: rows, page: 1, lastPage: 1, tabCounts: { all: rows, paid: rows } },
78
+ query: { filters: {} },
79
+ modal: { mode: 'create' },
80
+ } as IndexProps;
81
+ }
82
+
83
+ async function visit(props: IndexProps) {
84
+ const at = { component: 'larakit/Resource/Index', props, url: '/admin/orders/create', version: '1', flash: { larakit: { type: 'success', message: 'Saved.' } } };
85
+ await act(async () => {
86
+ await createInertiaApp({ page: at as never, resolve: () => ResourceIndex as never, setup: ({ App, props }) => { render(<App {...props} />); } });
87
+ });
88
+ }
89
+
90
+ describe('every part of the layout', () => {
91
+ it('is listed by the protocol', () => {
92
+ expect(listed).toHaveLength(24);
93
+ });
94
+
95
+ it('has a props type that @larakit/react exports', () => {
96
+ const missing = listed.filter((p) => !new RegExp(`\\btype ${pascal(p)}Props\\b`).test(index));
97
+ expect(missing).toEqual([]);
98
+ });
99
+
100
+ it('has no space around Larakit\'s drawing, so an app component that wraps Default lines up', () => {
101
+ // Margins belong to the place that draws a part. On the part's own outer element they move it away from the
102
+ // application's elements next to <props.Default />, as a breadcrumb with mb-2 beside the app's own text.
103
+ const margin = /(^|\s)-?m[xytbselr]?-/;
104
+ const spaced: string[] = [];
105
+ for (const [path, source] of Object.entries(files)) {
106
+ if (!path.includes('/kit/')) continue;
107
+ for (const found of source.matchAll(/function (Default\w+)\(/g)) {
108
+ const outer = /return\s*\(?\s*<\w+([^>]*)>/.exec(source.slice(found.index, found.index + 3000));
109
+ const cls = outer && /className=["{']([^"'}]*)/.exec(outer[1]);
110
+ if (cls && margin.test(cls[1])) spaced.push(`${found[1]}: ${cls[1]}`);
111
+ }
112
+ }
113
+ expect(spaced).toEqual([]);
114
+ });
115
+
116
+ it('is drawn through LayoutPart', () => {
117
+ const missing = listed.filter((p) => !sources.includes(`part="${p}"`) && !bridged.includes(`case '${p}':`));
118
+ expect(missing).toEqual([]);
119
+ });
120
+
121
+ it('can be drawn by the application\'s component, which gets data, partKey and Default', async () => {
122
+ seen.clear();
123
+ const parts = everyPartOwn();
124
+ await visit(page(parts, 2));
125
+ cleanup();
126
+ await visit(page(parts, 0));
127
+ cleanup();
128
+ render(
129
+ <LarakitProvider value={kitFor({ ...panel('Shop'), parts }, '/admin')}>
130
+ <Dashboard widgets={[
131
+ { name: 'sales', label: 'Sales', type: 'stats', wide: false, poll: 0 },
132
+ { name: 'later', label: 'Later', type: 'stats', wide: false, poll: 0 },
133
+ ]} data={{ sales: { stats: [{ label: 'Revenue', value: 12, screen: 'orders' }] } }} />
134
+ </LarakitProvider>,
135
+ );
136
+ cleanup();
137
+ await act(async () => {
138
+ await createInertiaApp({
139
+ page: { component: 'larakit/Error', props: { path: '/admin', errors: {}, larakit: { ...panel('Shop'), parts }, status: 500 }, url: '/admin/nope', version: '1' } as never,
140
+ resolve: () => ErrorView as never, setup: ({ App, props }) => { render(<App {...props} />); },
141
+ });
142
+ });
143
+ expect(listed.filter((p) => !seen.has(p))).toEqual([]);
144
+ expect(warned).toEqual([]);
145
+ for (const [part, all] of seen) {
146
+ for (const got of all) {
147
+ expect(got.hasDefault, part).toBe(true);
148
+ expect(typeof got.data, part).toBe('object');
149
+ expect(got.partKey, part).toBeTruthy();
150
+ }
151
+ }
152
+ // A part of the panel gets its own name as its key; a cell, a field and a section get their item's
153
+ // .props(...) and key, as the item's own .component(...) would.
154
+ expect(seen.get('brand')?.[0]).toMatchObject({ partKey: 'brand', data: {} });
155
+ expect(seen.get('cell')).toContainEqual({ partKey: 'number', data: { icon: 'hash' }, hasDefault: true });
156
+ expect(seen.get('field')).toContainEqual({ partKey: 'number', data: { hint: 'ORD-' }, hasDefault: true });
157
+ expect(seen.get('section')).toContainEqual({ partKey: 'Order', data: {}, hasDefault: true });
158
+ });
159
+ });
@@ -0,0 +1,7 @@
1
+ // The pages the app's thin files under resources/js/pages/larakit/ show, such as
2
+ // `export { ResourceIndex as default } from '@larakit/react/pages';`.
3
+ export { ResourceIndex } from '../ResourceIndex';
4
+ export {
5
+ DashboardPage as Dashboard, PanelPage as Page, ProfileView as Profile, ErrorView as Error,
6
+ LoginPage as Login, ForgotPasswordPage as ForgotPassword, ResetPasswordPage as ResetPassword,
7
+ } from '../PanelPages';
@@ -0,0 +1,56 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { act, cleanup, render, screen } from '@testing-library/react';
3
+ import { larakit, larakitReady, Part, type ColumnCellProps } from './components';
4
+
5
+ afterEach(cleanup);
6
+
7
+ /** Larakit's drawing of a part, as `Default`. */
8
+ function Plain({ value, partKey }: { value: string; partKey?: string }) {
9
+ return <span data-key={partKey}>{value}</span>;
10
+ }
11
+
12
+ /** An application's component that wraps Larakit's drawing in one line. */
13
+ function Wrapped(props: ColumnCellProps<{ icon: string }, string>) {
14
+ return <b title={props.data.icon}><props.Default {...props} /></b>;
15
+ }
16
+
17
+ describe('a part', () => {
18
+ it('is Larakit\'s drawing without a component', () => {
19
+ render(<Part partKey="orders.status" props={{ value: 'paid' }} Default={Plain} />);
20
+ expect(screen.getByText('paid').dataset.key).toBe('orders.status');
21
+ });
22
+
23
+ it('is the application\'s component, which gets data and the default', () => {
24
+ larakit({ components: { './larakit/components/Wrapped.tsx': { default: Wrapped } } });
25
+ render(<Part name="Wrapped" data={{ icon: 'truck' }} partKey="orders.status" props={{ value: 'paid' }} Default={Plain} />);
26
+ const own = screen.getByTitle('truck');
27
+ expect(own.tagName).toBe('B');
28
+ expect(own.textContent).toBe('paid');
29
+ expect(screen.getByText('paid').dataset.key).toBe('orders.status');
30
+ });
31
+
32
+ it('says plainly when the application has no such file', () => {
33
+ render(<Part name="Nope" partKey="x" props={{ value: 'paid' }} Default={Plain} />);
34
+ expect(screen.getByRole('alert').textContent).toContain('resources/js/larakit/components/Nope.tsx');
35
+ });
36
+
37
+ it('loads the application\'s lazy components as soon as app.tsx names them, in the browser too', async () => {
38
+ let loads = 0;
39
+ larakit({ components: { './larakit/components/Early.tsx': () => { loads++; return Promise.resolve({ default: Wrapped }); } } });
40
+ expect(loads).toBe(1);
41
+ await act(() => larakitReady());
42
+ // Drawn on a later click, it is there at once: no frame with Larakit's own drawing in its place.
43
+ render(<Part name="Early" data={{ icon: 'bolt' }} partKey="x" props={{ value: 'paid' }} Default={Plain} />);
44
+ expect(screen.getByTitle('bolt').textContent).toBe('paid');
45
+ });
46
+
47
+ it('never shows Larakit\'s drawing while the application\'s component is still loading', async () => {
48
+ let done!: (m: { default: typeof Wrapped }) => void;
49
+ const slow = new Promise<{ default: typeof Wrapped }>((r) => { done = r; });
50
+ larakit({ components: { './larakit/components/Slow.tsx': () => slow } });
51
+ render(<Part name="Slow" data={{ icon: 'clock' }} partKey="x" props={{ value: 'paid' }} Default={Plain} />);
52
+ expect(screen.queryByText('paid')).toBeNull();
53
+ await act(async () => { done({ default: Wrapped }); await slow; });
54
+ expect((await screen.findByTitle('clock')).textContent).toBe('paid');
55
+ });
56
+ });
@@ -0,0 +1,159 @@
1
+ // Plugins 2 (LA-322): a plugin's ui, which the application copies to resources/js/larakit/plugins/{id}, draws its
2
+ // page, columns, fields, widgets, bars, hooks and the parts it replaces, after the application passes it to
3
+ // larakit({ plugins }) in app.tsx. The server lists the panel's plugins in the larakit prop; a plugin the panel
4
+ // doesn't have draws nothing, and the order of larakit({ plugins }) says which one draws a part that several replace.
5
+ import { afterEach, describe, expect, it, vi } from 'vitest';
6
+ import { act, cleanup, render } from '@testing-library/react';
7
+ import { hydrateRoot, type Root } from 'react-dom/client';
8
+ import { renderToString } from 'react-dom/server';
9
+ import { createInertiaApp } from '@inertiajs/react';
10
+ import type { Panel, PanelPageProps, PanelPlugin } from '@larakit/core';
11
+ import { larakit, type EmptyProps } from './components';
12
+ import { panel, screen } from './fixtures';
13
+ import { definePlugin, pluginApi, type PluginPageProps } from './plugins';
14
+ import { Page, ResourceIndex } from './pages';
15
+
16
+ afterEach(() => { cleanup(); larakit({}); vi.unstubAllGlobals(); });
17
+
18
+ const listed = (id: string, more: Partial<PanelPlugin> = {}): PanelPlugin =>
19
+ ({ id, name: id[0].toUpperCase() + id.slice(1), version: '1.0.0', ui: true, replaces: [], bars: [], hooks: [], ...more });
20
+
21
+ function Ratings({ data, path, href }: PluginPageProps) {
22
+ return <div data-test="ratings">{String(data.average)} of {String(data.max)} at [{path}] <a href={href('about')}>About</a></div>;
23
+ }
24
+
25
+ const stars = definePlugin({ id: 'stars', pages: { ratings: Ratings } });
26
+
27
+ function pluginPage(plugins: PanelPlugin[], rest = ''): { component: string; props: PanelPageProps; url: string; version: string; flash: object } {
28
+ return {
29
+ component: 'larakit/Page', url: '/admin/stars/ratings' + (rest ? '/' + rest : ''), version: '1', flash: {},
30
+ props: {
31
+ path: '/admin', errors: {}, larakit: { ...panel('Shop', [{ name: 'stars/ratings', label: 'Ratings', icon: 'star', group: '', href: '/admin/stars/ratings' }]), plugins },
32
+ page: { type: 'stars/ratings', label: 'Ratings', icon: 'star', group: '' }, at: 'plugins/stars/ratings', data: { average: 3.5, max: 5 }, rest,
33
+ } as PanelPageProps,
34
+ };
35
+ }
36
+
37
+ describe("a plugin's page", () => {
38
+ it('is drawn on the server with its data, and the browser takes it over without a mismatch', async () => {
39
+ larakit({ plugins: [stars] });
40
+ const at = pluginPage([listed('stars')], '42');
41
+ let html = '';
42
+ await createInertiaApp({ page: at as never, resolve: () => Page as never, setup: ({ App, props }) => { html = renderToString(<App {...props} />); } });
43
+ expect(html).toContain('3.5<!-- --> of <!-- -->5<!-- --> at [<!-- -->42<!-- -->]');
44
+ expect(html).toContain('href="/admin/stars/ratings/about"');
45
+ const el = document.body.appendChild(document.createElement('div'));
46
+ el.innerHTML = html;
47
+ const mismatch = vi.fn();
48
+ let root: Root | undefined;
49
+ await act(async () => {
50
+ await createInertiaApp({ page: at as never, resolve: () => Page as never, setup: ({ App, props }) => { root = hydrateRoot(el, <App {...props} />, { onRecoverableError: mismatch }); } });
51
+ });
52
+ expect(mismatch).not.toHaveBeenCalled();
53
+ expect(el.querySelector('[data-test="ratings"]')).not.toBeNull();
54
+ act(() => root?.unmount());
55
+ el.remove();
56
+ });
57
+
58
+ it('says which ui is missing when app.tsx does not pass it', async () => {
59
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {});
60
+ await act(async () => {
61
+ await createInertiaApp({ page: pluginPage([listed('stars')]) as never, resolve: () => Page as never, setup: ({ App, props }) => { render(<App {...props} />); } });
62
+ });
63
+ expect(document.querySelector('[data-lk="missing-plugin"]')?.textContent).toContain('resources/js/larakit/plugins/stars');
64
+ expect(said.mock.calls.flat().join(' ')).toContain('larakit({ plugins }) in app.tsx');
65
+ said.mockRestore();
66
+ });
67
+
68
+ it("asks only the plugin's own routes", async () => {
69
+ const asked: string[] = [];
70
+ vi.stubGlobal('fetch', vi.fn(async (url: string) => { asked.push(String(url)); return new Response('{"name":"Stars"}', { status: 200, headers: { 'content-type': 'application/json' } }); }));
71
+ await expect(pluginApi('stars')('/about')).resolves.toEqual({ name: 'Stars' });
72
+ await expect(pluginApi('stars')('/../../posts')).rejects.toThrow('stays below the plugin');
73
+ expect(asked).toEqual([expect.stringMatching(/\/api\/plugins\/stars\/about$/)]);
74
+ });
75
+ });
76
+
77
+ function listPage(larakitProp: Panel) {
78
+ return {
79
+ component: 'larakit/Resource/Index', url: '/admin/orders', version: '1', flash: {},
80
+ props: {
81
+ path: '/admin', errors: {}, larakit: larakitProp,
82
+ screen: screen({ name: 'orders', label: 'Orders', columns: [
83
+ { key: 'number', label: 'Number', type: 'text', sortable: false, searchable: false },
84
+ { key: 'rating', label: 'Rating', type: 'stars/stars', sortable: false, searchable: false, props: { max: 3 } },
85
+ ] }),
86
+ table: { data: [{ id: '1', cells: { number: 'ORD-1', rating: 2 }, can: { update: false, actions: [] } }], total: 1, page: 1, lastPage: 1 },
87
+ query: { filters: {} }, modal: null,
88
+ },
89
+ };
90
+ }
91
+
92
+ async function draw(larakitProp: Panel, rows = true) {
93
+ const at = listPage(larakitProp);
94
+ if (!rows) at.props.table = { data: [], total: 0, page: 1, lastPage: 1 };
95
+ await act(async () => {
96
+ await createInertiaApp({ page: at as never, resolve: () => ResourceIndex as never, setup: ({ App, props }) => { render(<App {...props} />); } });
97
+ });
98
+ }
99
+
100
+ const menu = [{ name: 'orders', label: 'Orders', icon: '', group: '', href: '/admin/orders' }];
101
+
102
+ describe("a plugin's components", () => {
103
+ it("draw its column, its bar and its hook in a panel that has the plugin", async () => {
104
+ larakit({ plugins: [definePlugin({
105
+ id: 'stars',
106
+ columns: { stars: ({ value, props }) => <span data-test="stars">{'★'.repeat(Number(value))} / {String(props.max)}</span> },
107
+ bars: { ratings: ({ place }) => <a data-test="bar" href="/admin/stars/ratings">{place}</a>, unlisted: () => <b data-test="unlisted" /> },
108
+ hooks: { 'table.before': () => <p data-test="hook">hooked</p> },
109
+ })] });
110
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {});
111
+ await draw({ ...panel('Shop', menu), plugins: [listed('stars', { bars: ['ratings'], hooks: ['table.before'] })] });
112
+ expect(document.querySelector('[data-test="stars"]')?.textContent).toBe('★★ / 3');
113
+ expect(document.querySelector('[data-test="bar"]')?.textContent).toBe('topbar');
114
+ expect(document.querySelector('[data-test="hook"]')).not.toBeNull();
115
+ expect(document.querySelector('[data-test="unlisted"]')).toBeNull();
116
+ expect(said.mock.calls.flat().join(' ')).toContain('does not list "unlisted" in bars');
117
+ said.mockRestore();
118
+ });
119
+
120
+ it("draw nothing in a panel that doesn't have the plugin", async () => {
121
+ larakit({ plugins: [definePlugin({ id: 'stars', bars: { ratings: () => <a data-test="bar" /> }, hooks: { 'table.before': () => <p data-test="hook" /> } })] });
122
+ await draw({ ...panel('Shop', menu), plugins: [] });
123
+ expect(document.querySelector('[data-test="bar"]')).toBeNull();
124
+ expect(document.querySelector('[data-test="hook"]')).toBeNull();
125
+ });
126
+ });
127
+
128
+ /** A part that names who drew it, around what its Default draws. */
129
+ const marked = (who: string) => function Marked(props: EmptyProps) {
130
+ return <span data-by={who}><props.Default {...props} /></span>;
131
+ };
132
+ const order = () => [...document.querySelectorAll('[data-by]')].map((e) => e.getAttribute('data-by'));
133
+
134
+ describe('a part that several replace', () => {
135
+ it('is drawn by the later plugin, then the application, then the server, each around the one under it', async () => {
136
+ larakit({
137
+ components: { './larakit/components/ServerEmpty.tsx': { default: marked('server') } },
138
+ parts: { empty: marked('app') },
139
+ plugins: [definePlugin({ id: 'a', parts: { empty: marked('a') } }), definePlugin({ id: 'b', parts: { empty: marked('b') } })],
140
+ });
141
+ await draw({ ...panel('Shop', menu), parts: { empty: 'ServerEmpty' }, plugins: [listed('b', { replaces: ['empty'] }), listed('a', { replaces: ['empty'] })] }, false);
142
+ // The order of larakit({ plugins }) counts, not the server's.
143
+ expect(order()).toEqual(['server', 'app', 'b', 'a']);
144
+ expect(document.querySelector('[data-by="a"]')?.textContent).not.toBe('');
145
+ });
146
+
147
+ it("leaves out a plugin that doesn't list the part, and one that breaks", async () => {
148
+ const said = vi.spyOn(console, 'error').mockImplementation(() => {});
149
+ larakit({ plugins: [
150
+ definePlugin({ id: 'a', parts: { empty: marked('a') } }),
151
+ definePlugin({ id: 'b', parts: { empty: () => { throw new Error('broken'); } } }),
152
+ definePlugin({ id: 'c', parts: { empty: marked('c') } }),
153
+ ] });
154
+ await draw({ ...panel('Shop', menu), plugins: [listed('a', { replaces: ['empty'] }), listed('b', { replaces: ['empty'] }), listed('c')] }, false);
155
+ expect(order()).toEqual(['a']);
156
+ expect(said.mock.calls.flat().join(' ')).toContain('does not list "empty" in replaces');
157
+ said.mockRestore();
158
+ });
159
+ });