@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,435 @@
1
+ import { lazy, Suspense, useContext, type ButtonHTMLAttributes, type ComponentType, type ReactNode } from 'react';
2
+ import type { Action, Column, Field, FormMode, Group, LayoutPart as PartName, Row, Stat, TenantInfo, Widget } from '@larakit/core';
3
+ import { Context } from './context';
4
+ import { Guard, partLayers, takePlugins, type AppParts, type LarakitPlugin } from './plugins';
5
+
6
+ /**
7
+ * What every customizable part gets, besides its own props: `data` is what the server gave with `.props(...)`,
8
+ * `partKey` its key in the page, and `Default` Larakit's own drawing of the part, so that wrapping it is one line:
9
+ * `<props.Default {...props} />`.
10
+ */
11
+ export type Customizable<P, D> = P & {
12
+ /** What the server gave with `.props(...)`. */
13
+ data: D;
14
+ /** The part's `data-key`: `.part_key(...)` / `.PartKey(...)`, or its own key or name. */
15
+ partKey: string;
16
+ /** Larakit's own drawing of the part. */
17
+ Default: ComponentType<P & { data?: unknown; partKey?: string }>;
18
+ };
19
+
20
+ type Data = Record<string, unknown>;
21
+
22
+ /** A section, fieldset, tab, grid or other group of a form: `.component(...)` on the group. */
23
+ export type SectionProps<D = Data> = Customizable<{
24
+ heading?: ReactNode;
25
+ description?: ReactNode;
26
+ /** The group's fields, drawn by Larakit. */
27
+ children: ReactNode;
28
+ /** The group as the server describes it. */
29
+ place: Group;
30
+ }, D>;
31
+
32
+ /** The cell of a table column: `.component(...)` on the column. */
33
+ export type ColumnCellProps<D = Data, V = unknown> = Customizable<{
34
+ value: V;
35
+ /** The whole row, with the other cells in `row.cells`. */
36
+ row: Row;
37
+ column: Column;
38
+ }, D>;
39
+
40
+ /** The input of a form field: `.component(...)` on the field. Larakit keeps its label, helper and error. */
41
+ export type FieldInputProps<D = Data, V = unknown> = Customizable<{
42
+ value: V;
43
+ /** Changes the value that the form sends. */
44
+ set: (value: unknown) => void;
45
+ field: Field;
46
+ /** The input's id, which the label points to. */
47
+ id: string;
48
+ invalid: boolean;
49
+ /** The id of the error text, for `aria-describedby`. */
50
+ describedBy?: string;
51
+ required?: boolean;
52
+ disabled?: boolean;
53
+ /** Where a select that asks the server gets its options. */
54
+ options?: string;
55
+ /**
56
+ * The screen's JSON endpoints, `/admin/api/orders`: options, `uploads/{field}` and `files/{field}`. In an action's
57
+ * form it is the action's address, such as `/admin/api/orders/7/actions/ship`, which takes the same `uploads/{field}`
58
+ * and `files/{field}`.
59
+ */
60
+ api?: string;
61
+ /** The record the form edits, if it edits one. */
62
+ record?: string;
63
+ /** Every error of the form, by its place: `items.0.sku` for a field of a repeater row. */
64
+ errors?: Record<string, string>;
65
+ /** The field's place in the form's errors: its key, or `items.0.sku` inside a repeater. */
66
+ path?: string;
67
+ }, D>;
68
+
69
+ /** The button of a row action: `.component(...)` on the action. */
70
+ export type ActionButtonProps<D = Data> = Customizable<{
71
+ action: Action;
72
+ row: Row;
73
+ /** Runs the action, asking first when it has a question or a form. */
74
+ run: () => void;
75
+ }, D>;
76
+
77
+ /** The panel's name or logo at the top of the menu: `part("brand", ...)`. */
78
+ export type BrandProps = Customizable<{
79
+ name: string; logo?: string; href: string;
80
+ /** The side menu is narrowed to its icons: there is room for a small picture, not the name. */
81
+ rail?: boolean;
82
+ }, Data>;
83
+
84
+ /** One entry of the menu: a screen, a page or the dashboard. */
85
+ export type NavItem = { name: string; label: string; href: string; current: boolean; icon?: string; group?: string };
86
+ /** The menu of screens: `part("nav", ...)`. A menu of the application's own has no narrow form. */
87
+ export type NavProps = Customizable<{ items: NavItem[] }, Data>;
88
+
89
+ /** The bar above the page: `part("topbar", ...)`. */
90
+ export type TopbarProps = Customizable<{ title: string; user?: { name: string; email?: string } }, Data>;
91
+
92
+ /** The choice of tenant, under the brand, when the panel has tenancy: `part("tenantSwitcher", ...)`. */
93
+ export type TenantSwitcherProps = Customizable<{
94
+ tenants: TenantInfo[];
95
+ /** The tenant the pages show, as the server marks it. */
96
+ active?: TenantInfo;
97
+ /** Switches to a tenant. */
98
+ choose: (tenant: TenantInfo) => void;
99
+ /** The side menu is narrowed to its icons. */
100
+ rail?: boolean;
101
+ }, Data>;
102
+
103
+ /** The heading of a screen with its buttons: `part("header", ...)`. */
104
+ export type HeaderProps = Customizable<{ title: string; actions?: ReactNode }, Data>;
105
+
106
+ /** Where the page is in the panel, above its heading: `part("breadcrumb", ...)`. The last item is the page itself. */
107
+ export type BreadcrumbProps = Customizable<{ items: { label: string; href?: string }[] }, Data>;
108
+
109
+ /** The table of a screen's list: `part("table", ...)`. Its own component can draw the rows any way it likes. */
110
+ export type TableProps = Customizable<{
111
+ /** The columns the table shows. */
112
+ columns: Column[];
113
+ rows: Row[];
114
+ /** `total` or `-total`, as in the address. */
115
+ sort?: string;
116
+ /** Sorts by a column, or turns its sorting around. */
117
+ sortBy: (column: string) => void;
118
+ /** Larakit's cell, which draws `.component(...)` and `part("cell", ...)` too. */
119
+ Cell: ComponentType<{ column: Column; row: Row }>;
120
+ /** The row's buttons: edit and its actions. */
121
+ Actions: ComponentType<{ row: Row }>;
122
+ }, Data>;
123
+
124
+ /** Every cell of a table: `part("cell", ...)`. A column's own `.component(...)` comes first. `data` is the column's `.props(...)`. */
125
+ export type CellProps<D = Data, V = unknown> = ColumnCellProps<D, V>;
126
+
127
+ /** A small colored label, such as a status or a count: `part("badge", ...)`. */
128
+ export type BadgeProps = Customizable<{ color?: string; children: ReactNode }, Data>;
129
+
130
+ /** What a table without rows shows: `part("empty", ...)`. */
131
+ export type EmptyProps = Customizable<{ text: string }, Data>;
132
+
133
+ /** The pages under a table: `part("pagination", ...)`. */
134
+ export type PaginationProps = Customizable<{ page: number; lastPage: number; total: number; from: number; to: number; go: (page: number) => void }, Data>;
135
+
136
+ /** The filters above a table: `part("filters", ...)`. */
137
+ export type FiltersProps = Customizable<{
138
+ filters: Field[];
139
+ /** What each filter holds now, by its key, as in the address. */
140
+ values: Record<string, string | string[] | undefined>;
141
+ /** Changes a filter, which reloads the table. */
142
+ set: (filter: string, value: string | string[]) => void;
143
+ /** Larakit's input of one filter. */
144
+ Filter: ComponentType<{ filter: Field }>;
145
+ }, Data>;
146
+
147
+ /** A record's form, with every field in its layout: `part("form", ...)`. */
148
+ export type FormProps = Customizable<{
149
+ fields: Field[];
150
+ mode: FormMode;
151
+ values: Record<string, unknown>;
152
+ errors: Record<string, string>;
153
+ /** The fields in the screen's layout: sections, grids and tabs. */
154
+ children: ReactNode;
155
+ /** One field, by its key, with its label, input and error. */
156
+ Field: ComponentType<{ name: string }>;
157
+ }, Data>;
158
+
159
+ /** Every field of a form, with its label, helper and error around the input: `part("field", ...)`. `data` is the field's `.props(...)`. */
160
+ export type FieldProps<D = Data> = Customizable<{
161
+ field: Field;
162
+ /** The input's id, which the label points to. */
163
+ id: string;
164
+ /** The field's place in the form's errors: its key, or `items.0.sku` inside a repeater. */
165
+ path: string;
166
+ error?: string;
167
+ required?: boolean;
168
+ disabled?: boolean;
169
+ /** The input: Larakit's, or the field's own `.component(...)`. */
170
+ children: ReactNode;
171
+ }, D>;
172
+
173
+ /** Every button Larakit draws: `part("button", ...)`. */
174
+ export type ButtonProps = Customizable<ButtonHTMLAttributes<HTMLButtonElement> & {
175
+ /** primary for a solid button, danger for one that destroys, plain for the rest. */
176
+ tone?: 'primary' | 'plain' | 'danger';
177
+ /** The color the server or Larakit gave it: gray, primary, info, success, warning, danger, indigo, ... */
178
+ color?: string;
179
+ variant?: 'solid' | 'soft' | 'outline' | 'ghost' | 'link';
180
+ size?: 'xs' | 'sm' | 'md' | 'lg';
181
+ icon?: string;
182
+ /** Only the icon is shown, with the text as its tooltip. */
183
+ iconOnly?: boolean;
184
+ /** Which button it is, such as `save`, `cancel` or `action-publish`, as Larakit's own button has in data-lk. */
185
+ 'data-lk'?: string;
186
+ }, Data>;
187
+
188
+ /** A row of tabs: the list's tabs, and the tabs of a form, `part("tabs", ...)`. */
189
+ export type TabsProps = Customizable<{
190
+ tabs: { name: string; label: string; badge?: number | string; color?: string; wrong?: boolean }[];
191
+ /** The name of the tab that is open. */
192
+ active: string;
193
+ select: (name: string) => void;
194
+ /** What the open tab shows. The list's tabs have none: they filter the table under them. */
195
+ children?: ReactNode;
196
+ }, Data>;
197
+
198
+ /** A dialog over the page: a record's form, an action's question, `part("modal", ...)`. */
199
+ export type ModalProps = Customizable<{
200
+ title: ReactNode;
201
+ width: 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'full';
202
+ close: () => void;
203
+ /** The buttons under it. */
204
+ footer?: ReactNode;
205
+ children: ReactNode;
206
+ }, Data>;
207
+
208
+ /** The dashboard's widgets: `part("dashboard", ...)`. */
209
+ export type DashboardProps = Customizable<{
210
+ widgets: Widget[];
211
+ /** Larakit's widget, with what it shows. */
212
+ Widget: ComponentType<{ widget: Widget }>;
213
+ }, Data>;
214
+
215
+ /** One widget of the dashboard, around what it shows: `part("widget", ...)`. */
216
+ export type WidgetProps = Customizable<{
217
+ widget: Widget;
218
+ /** What the widget shows, drawn by Larakit: its numbers, chart or list. */
219
+ children: ReactNode;
220
+ }, Data>;
221
+
222
+ /** One number of a stats widget: `part("stat", ...)`. */
223
+ export type StatProps = Customizable<{ stat: Stat; href?: string }, Data>;
224
+
225
+ /** The message after a save or an action: `part("toast", ...)`. */
226
+ export type ToastProps = Customizable<{ type: 'success' | 'danger'; message: string; close: () => void }, Data>;
227
+
228
+ /** What shows while a part waits for the server: `part("loading", ...)`. */
229
+ export type LoadingProps = Customizable<{ kind: 'page' | 'table' | 'form' | 'widget' }, Data>;
230
+
231
+ /**
232
+ * The body of `larakit/Error`, a page of the panel that is forbidden (403), not found (404) or failed (500), inside the
233
+ * panel's menu: `part("error", ...)`. A 403 reads as a 404, so nobody learns what they may not open. `retry` is there
234
+ * only when the page failed.
235
+ */
236
+ export type ErrorProps = Customizable<{ status: number; title: string; message: string; home: string; retry?: () => void }, Data>;
237
+
238
+ /** The props of each part of the layout that `part(...)` can give to the application: one for every `LayoutPart`. */
239
+ export type LayoutPartProps = {
240
+ brand: BrandProps; nav: NavProps; topbar: TopbarProps; tenantSwitcher: TenantSwitcherProps; header: HeaderProps;
241
+ breadcrumb: BreadcrumbProps; table: TableProps; cell: CellProps; badge: BadgeProps; empty: EmptyProps;
242
+ pagination: PaginationProps; filters: FiltersProps; form: FormProps; field: FieldProps; button: ButtonProps;
243
+ section: SectionProps; tabs: TabsProps; modal: ModalProps; dashboard: DashboardProps; widget: WidgetProps;
244
+ stat: StatProps; toast: ToastProps; loading: LoadingProps; error: ErrorProps;
245
+ };
246
+
247
+ // Every part of the protocol has its props, and nothing else does.
248
+ type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;
249
+ const everyPart: Same<keyof LayoutPartProps, PartName> = true;
250
+ void everyPart;
251
+
252
+ /** A part's own props, without what `Part` adds: what Larakit's drawing of it takes. */
253
+ export type PartOwn<P> = Omit<P, 'data' | 'partKey' | 'Default'> & { partKey?: string };
254
+
255
+ type Module = { default: ComponentType<any> };
256
+ /** What `import.meta.glob` gives for a file: the module, or a function that loads it. */
257
+ type Found = unknown;
258
+
259
+ export type Setup = {
260
+ /**
261
+ * The application's components, as `import.meta.glob('./larakit/components/**\/*.tsx')` gives them. The glob
262
+ * has to be in the application's code: Vite finds its files from the file the glob is written in.
263
+ */
264
+ components?: Record<string, Found>;
265
+ /**
266
+ * The panel's plugins, from their ui that the application copies to `resources/js/larakit/plugins/{id}`:
267
+ * `plugins: [stars()]`. A part that several replace is drawn by the one
268
+ * later in the list; its `Default` draws the one before it.
269
+ */
270
+ plugins?: LarakitPlugin[];
271
+ /**
272
+ * The application's own components for parts of the layout, in every panel: `parts: { section: MySection }`. They
273
+ * come after every plugin's, and the server's `part(...)` comes after them.
274
+ */
275
+ parts?: AppParts;
276
+ };
277
+
278
+ const found = new Map<string, Found>();
279
+ const drawn = new Map<string, ComponentType<any>>();
280
+ const folder = 'larakit/components/';
281
+
282
+ /** The name that `.component(...)` gives to a file: `./larakit/components/orders/Header.tsx` is `orders/Header`. */
283
+ export function componentName(path: string): string {
284
+ const at = path.lastIndexOf(folder);
285
+ return (at < 0 ? path.replace(/^\.\//, '') : path.slice(at + folder.length)).replace(/\.[jt]sx?$/, '');
286
+ }
287
+
288
+ /** Tells Larakit about the application's own components. Call it once, in the application's `app.tsx`. */
289
+ export function larakit(setup: Setup): void {
290
+ for (const [path, module] of Object.entries(setup.components ?? {})) found.set(componentName(path), module);
291
+ takePlugins(setup.plugins, setup.parts);
292
+ drawn.clear();
293
+ // Start loading them all now. The server draws a page in one go and can't wait for a component that is still
294
+ // loading ("Switched to client rendering"); the browser would otherwise load one only when it is first drawn, such
295
+ // as a modal on the first click.
296
+ void larakitReady();
297
+ }
298
+
299
+ /**
300
+ * Loads every component that `larakit(...)` was given as a function, as `import.meta.glob` without `eager` gives
301
+ * them. A component that has loaded is drawn at once, also on the server. The server starts this by itself; an SSR
302
+ * entry that awaits it before the first page is drawn never draws a part with Larakit's own drawing instead.
303
+ */
304
+ export function larakitReady(): Promise<void> {
305
+ return Promise.all([...found].map(([name, module]) => typeof module !== 'function' ? undefined
306
+ : (module as () => Promise<Module>)().then((loaded) => {
307
+ // A component already drawn stays the same one, so React keeps what it shows.
308
+ if (loaded.default && found.get(name) === module && !drawn.has(name)) drawn.set(name, loaded.default);
309
+ }, () => {}))).then(() => {});
310
+ }
311
+
312
+ /** The component that `.component(name)` names, or null when the application doesn't have it. */
313
+ export function component(name: string): ComponentType<any> | null {
314
+ const known = drawn.get(name);
315
+ if (known) return known;
316
+ const module = found.get(name);
317
+ if (!module) return null;
318
+ const made = typeof module === 'function' ? lazy(module as () => Promise<Module>) : (module as Partial<Module>).default;
319
+ if (!made) return null;
320
+ drawn.set(name, made);
321
+ return made;
322
+ }
323
+
324
+ type Layer = { component: ComponentType<any>; plugin?: string };
325
+
326
+ type PartArgs<P> = {
327
+ /** The application's component, from `.component(...)`; Larakit's drawing without one. */
328
+ name?: string;
329
+ /**
330
+ * Who draws the part between Larakit and `name`, from the bottom: plugins, the application's `parts`, the
331
+ * server's `part(...)`. `name` replaces them all.
332
+ */
333
+ layers?: (Layer | string)[];
334
+ data?: unknown;
335
+ partKey: string;
336
+ props: P;
337
+ Default: ComponentType<P & { data?: unknown; partKey?: string }>;
338
+ };
339
+
340
+ const plain = new WeakMap<ComponentType<any>, ComponentType<any>>();
341
+
342
+ /**
343
+ * Larakit's drawing as the application's component gets it: `<props.Default {...props} />` passes the component's
344
+ * own `data` and `Default` along, which Larakit's drawing doesn't take and must not put on an element.
345
+ */
346
+ function forApp(Default: ComponentType<any>): ComponentType<any> {
347
+ let made = plain.get(Default);
348
+ if (!made) {
349
+ const Inner = Default;
350
+ // A layer under it is someone's component, which takes data too.
351
+ made = stacked.has(Inner)
352
+ ? function LarakitDefault({ Default: _d, ...rest }: Record<string, unknown>) { return <Inner {...rest} />; }
353
+ : function LarakitDefault({ Default: _d, data: _data, ...rest }: Record<string, unknown>) { return <Inner {...rest} />; };
354
+ plain.set(Default, made);
355
+ }
356
+ return made;
357
+ }
358
+
359
+ const stacked = new WeakSet<ComponentType<any>>();
360
+ const stacks = new WeakMap<ComponentType<any>, WeakMap<ComponentType<any>, ComponentType<any>>>();
361
+
362
+ /**
363
+ * `Upper` drawn over `Lower`: its `Default` draws `Lower` with the same props. The same pair is the same component
364
+ * from one drawing to the next, so React keeps what it shows. A plugin's component that breaks shows `Lower`.
365
+ */
366
+ function stack(Upper: ComponentType<any>, Lower: ComponentType<any>, plugin: boolean): ComponentType<any> {
367
+ let under = stacks.get(Upper);
368
+ if (!under) stacks.set(Upper, (under = new WeakMap()));
369
+ let made = under.get(Lower);
370
+ if (!made) {
371
+ const Default = forApp(Lower);
372
+ made = function LarakitLayer({ Default: _d, ...props }: Record<string, unknown>) {
373
+ const drawn = <Upper {...props} data={props.data ?? {}} Default={Default} />;
374
+ return plugin ? <Guard fallback={<Default {...props} />}>{drawn}</Guard> : drawn;
375
+ };
376
+ stacked.add(made);
377
+ under.set(Lower, made);
378
+ }
379
+ return made;
380
+ }
381
+
382
+ /** Says that the application has no component by this name. */
383
+ export function Missing({ name }: { name: string }) {
384
+ return (
385
+ <span data-lk="missing-component" role="alert" className="block rounded-(--lk-radius) p-2 text-xs ring-1 ring-(--lk-danger) text-(--lk-danger)">
386
+ Larakit: there is no resources/js/larakit/components/{name}.tsx, or app.tsx doesn't pass it to larakit(&#123; components &#125;). Run larakit:doctor.
387
+ </span>
388
+ );
389
+ }
390
+
391
+ /** Draws a part with the application's component when the server names one, and with Larakit's otherwise. */
392
+ export function Part<P extends object>({ name, layers, data, partKey, props, Default }: PartArgs<P>) {
393
+ let Drawn: ComponentType<any> = Default;
394
+ if (name) {
395
+ const Found = component(name);
396
+ if (!Found) return <Missing name={name} />;
397
+ Drawn = stack(Found, Default, false);
398
+ } else {
399
+ for (const layer of layers ?? []) {
400
+ const Found = typeof layer === 'string' ? component(layer) : layer.component;
401
+ if (!Found) return <Missing name={layer as string} />;
402
+ Drawn = stack(Found, Drawn, typeof layer !== 'string' && !!layer.plugin);
403
+ }
404
+ }
405
+ if (Drawn === Default) return <Default {...props} partKey={partKey} />;
406
+ return (
407
+ // While the application's component is still loading, draw nothing rather than Larakit's own part: the visitor
408
+ // would see Larakit's drawing turn into the application's (a centered dialog becoming a drawer).
409
+ <Suspense fallback={null}>
410
+ <Drawn {...props} data={data ?? {}} partKey={partKey} />
411
+ </Suspense>
412
+ );
413
+ }
414
+
415
+ /**
416
+ * Draws a part of the layout with the application's component that `part(...)` names, or with Larakit's.
417
+ * `name` is an item's own `.component(...)`, which comes first; `data` and `partKey` are the item's, when it has them.
418
+ * Without it, the part is drawn by, from the top: the server's `part(...)`, the application's `larakit({ parts })`,
419
+ * then the panel's plugins that replace it, the later one in `larakit({ plugins })` first; each one's `Default`
420
+ * draws the one under it, down to Larakit's. Outside a Larakit page there is no panel, and the part is Larakit's.
421
+ */
422
+ export function LayoutPart<K extends keyof LayoutPartProps>({ part, props, Default, name, data, partKey }: {
423
+ part: K;
424
+ props: Omit<LayoutPartProps[K], 'data' | 'partKey' | 'Default'>;
425
+ Default: ComponentType<any>;
426
+ name?: string;
427
+ data?: unknown;
428
+ partKey?: string;
429
+ }) {
430
+ const kit = useContext(Context);
431
+ const server = kit?.panel.parts?.[part];
432
+ const layers: (Layer | string)[] = kit ? partLayers(part, kit.panel.plugins) : [];
433
+ if (server) layers.push(server);
434
+ return <Part name={name} layers={layers} data={data} partKey={partKey ?? part} props={props} Default={Default} />;
435
+ }
@@ -0,0 +1,68 @@
1
+ // A question asked before an action (`.confirm(...)`) must be answerable when the application draws its own
2
+ // `modal` part without a <dialog>, as a drawer of plain elements does.
3
+ import { afterEach, describe, expect, it } from 'vitest';
4
+ import { act, cleanup, fireEvent, render, screen as find } from '@testing-library/react';
5
+ import { createInertiaApp } from '@inertiajs/react';
6
+ import type { IndexProps } from '@larakit/core';
7
+ import { larakit, type ModalProps } from './components';
8
+ import { panel, screen } from './fixtures';
9
+ import { sure } from './kit/notice';
10
+ import { ResourceIndex } from './pages';
11
+
12
+ afterEach(cleanup);
13
+
14
+ /** A drawer made of plain elements: no <dialog>, so it never takes Larakit's dialog ref. */
15
+ function Drawer({ title, close, children }: ModalProps) {
16
+ return <div data-app="drawer"><h2>{title}</h2><button type="button" onClick={close}>Close drawer</button>{children}</div>;
17
+ }
18
+
19
+ async function visit(parts: Record<string, string>) {
20
+ larakit({ components: { './larakit/components/parts/Drawer.tsx': { default: Drawer } } });
21
+ const props = {
22
+ path: '/admin', errors: {},
23
+ larakit: { ...panel('Shop', [{ name: 'orders', label: 'Orders', icon: '', group: '', href: '/admin/orders' }]), parts },
24
+ screen: screen({ name: 'orders', label: 'Orders', columns: [{ key: 'number', label: 'Number', type: 'text', sortable: false, searchable: false }] }),
25
+ table: { data: [], total: 0, page: 1, lastPage: 1 },
26
+ query: { filters: {} },
27
+ modal: null,
28
+ } as unknown as IndexProps;
29
+ await act(async () => {
30
+ await createInertiaApp({
31
+ page: { component: 'larakit/Resource/Index', props, url: '/admin/orders', version: '1', flash: {} } as never,
32
+ resolve: () => ResourceIndex as never, setup: ({ App, props }) => { render(<App {...props} />); },
33
+ });
34
+ });
35
+ }
36
+
37
+ async function ask(click: string | RegExp, drawer = true) {
38
+ let answer!: Promise<boolean>;
39
+ act(() => { answer = sure('Ship the order?', 'Ship', false); });
40
+ const button = await find.findByRole('button', { name: click });
41
+ expect(document.querySelector('[data-app="drawer"]') !== null).toBe(drawer);
42
+ await act(async () => { fireEvent.click(button); });
43
+ const got = await answer;
44
+ expect(document.querySelector('[data-lk="confirm-yes"]')).toBeNull();
45
+ return got;
46
+ }
47
+
48
+ describe('a question in the application\'s own modal part', () => {
49
+ it('answers yes', async () => {
50
+ await visit({ modal: 'parts/Drawer' });
51
+ expect(await ask('Ship')).toBe(true);
52
+ });
53
+
54
+ it('answers no', async () => {
55
+ await visit({ modal: 'parts/Drawer' });
56
+ expect(await ask(/cancel/i)).toBe(false);
57
+ });
58
+
59
+ it('answers no when the drawer is closed its own way', async () => {
60
+ await visit({ modal: 'parts/Drawer' });
61
+ expect(await ask('Close drawer')).toBe(false);
62
+ });
63
+
64
+ it('still answers in Larakit\'s own dialog', async () => {
65
+ await visit({});
66
+ expect(await ask('Ship', false)).toBe(true);
67
+ });
68
+ });
@@ -0,0 +1,19 @@
1
+ import { createContext, useContext } from 'react';
2
+ import { translator, type Panel } from '@larakit/core';
3
+
4
+ export type Larakit = { panel: Panel; path: string; t: ReturnType<typeof translator>; locale?: string };
5
+
6
+ export const Context = createContext<Larakit | null>(null);
7
+
8
+ export const LarakitProvider = Context.Provider;
9
+
10
+ /** The panel the page is in, with its translator. */
11
+ export function useLarakit(): Larakit {
12
+ const kit = useContext(Context);
13
+ if (!kit) throw new Error('Larakit: a Larakit component is drawn outside a Larakit page.');
14
+ return kit;
15
+ }
16
+
17
+ export function kitFor(panel: Panel, path: string): Larakit {
18
+ return { panel, path, t: translator(panel.messages), locale: panel.locale };
19
+ }