@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.
- package/package.json +30 -4
- package/src/Cell.tsx +35 -0
- package/src/Dashboard.tsx +79 -0
- package/src/Field.tsx +132 -0
- package/src/FileInput.tsx +76 -0
- package/src/Form.tsx +116 -0
- package/src/Layout.tsx +250 -0
- package/src/PanelPages.tsx +115 -0
- package/src/Repeater.tsx +46 -0
- package/src/ResourceIndex.tsx +271 -0
- package/src/action-upload.test.tsx +44 -0
- package/src/blocks.tsx +26 -0
- package/src/button-part.test.tsx +42 -0
- package/src/components.test.ts +22 -0
- package/src/components.tsx +435 -0
- package/src/confirm.test.tsx +68 -0
- package/src/context.tsx +19 -0
- package/src/custom-pages.test.tsx +177 -0
- package/src/errors.test.tsx +95 -0
- package/src/fixtures.ts +20 -0
- package/src/index.ts +29 -0
- package/src/kit/api.ts +305 -0
- package/src/kit/auth.tsx +109 -0
- package/src/kit/bridge.tsx +142 -0
- package/src/kit/button.tsx +396 -0
- package/src/kit/cell.tsx +260 -0
- package/src/kit/charts.tsx +638 -0
- package/src/kit/create.tsx +166 -0
- package/src/kit/dashboard.tsx +335 -0
- package/src/kit/dates.tsx +62 -0
- package/src/kit/entry.tsx +87 -0
- package/src/kit/field.tsx +449 -0
- package/src/kit/fields/CodeEditor.tsx +157 -0
- package/src/kit/fields/KeyValue.tsx +215 -0
- package/src/kit/fields/MarkdownEditor.tsx +380 -0
- package/src/kit/fields/OneTimeCode.tsx +192 -0
- package/src/kit/fields/Repeater.tsx +350 -0
- package/src/kit/fields/Slider.tsx +185 -0
- package/src/kit/fields/TagsInput.tsx +219 -0
- package/src/kit/filters.tsx +214 -0
- package/src/kit/form-shared.tsx +62 -0
- package/src/kit/form.tsx +253 -0
- package/src/kit/hooks.ts +119 -0
- package/src/kit/i18n.tsx +67 -0
- package/src/kit/icons.tsx +190 -0
- package/src/kit/infolist.tsx +452 -0
- package/src/kit/kit.test.tsx +2200 -0
- package/src/kit/layout.tsx +236 -0
- package/src/kit/loading.tsx +120 -0
- package/src/kit/notice.tsx +72 -0
- package/src/kit/page.tsx +103 -0
- package/src/kit/pageform.tsx +75 -0
- package/src/kit/picker.tsx +110 -0
- package/src/kit/plugins.tsx +206 -0
- package/src/kit/profile.tsx +86 -0
- package/src/kit/relations.tsx +146 -0
- package/src/kit/rich.tsx +276 -0
- package/src/kit/search.tsx +92 -0
- package/src/kit/select.tsx +244 -0
- package/src/kit/shell.tsx +401 -0
- package/src/kit/table-extras.tsx +457 -0
- package/src/kit/table.tsx +734 -0
- package/src/kit/theme.ts +57 -0
- package/src/layout-parts.test.tsx +159 -0
- package/src/pages/index.ts +7 -0
- package/src/part.test.tsx +56 -0
- package/src/plugins.test.tsx +159 -0
- package/src/plugins.tsx +240 -0
- package/src/preview.test.tsx +81 -0
- package/src/rail.test.tsx +56 -0
- package/src/repeater.test.tsx +48 -0
- package/src/resource-pages.test.tsx +119 -0
- package/src/screens.test.tsx +121 -0
- package/src/ssr.test.tsx +86 -0
- package/src/tenant.test.tsx +94 -0
- package/src/ui.tsx +100 -0
- package/theme.css +467 -0
- package/README.md +0 -3
package/src/plugins.tsx
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import { Component, type ComponentType, type ReactNode } from 'react';
|
|
2
|
+
import type { HookName, PanelPlugin } from '@larakit/core';
|
|
3
|
+
import type { LayoutPartProps } from './components';
|
|
4
|
+
import { api } from './kit/api';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Plugins 2: a plugin is a Go module or Rust crate (its routes, permissions, pages and widgets) with a `ui` folder of
|
|
8
|
+
* React code that draws it. The application copies that folder to `resources/js/larakit/plugins/{id}` and passes it
|
|
9
|
+
* to `larakit({ plugins: [stars()] })` in `app.tsx`; its Vite builds it with the rest, with HMR and TypeScript.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** A plugin's column type, such as `stars/stars`: the cell of a table or a list widget. */
|
|
13
|
+
export type PluginColumnProps = {
|
|
14
|
+
value: unknown;
|
|
15
|
+
/** The whole row, by column key. */
|
|
16
|
+
row: Record<string, unknown>;
|
|
17
|
+
/** What the column's server code gave with `.props(...)`. */
|
|
18
|
+
props: Record<string, unknown>;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** A plugin's field type: the input of a form field. Larakit keeps the label, helper and error. Values are text. */
|
|
22
|
+
export type PluginFieldProps = {
|
|
23
|
+
/** The input's id, which the label points to. */
|
|
24
|
+
id: string;
|
|
25
|
+
value: string;
|
|
26
|
+
onChange: (value: string) => void;
|
|
27
|
+
invalid: boolean;
|
|
28
|
+
/** The id of the error text, for `aria-describedby`. */
|
|
29
|
+
describedBy?: string;
|
|
30
|
+
props: Record<string, unknown>;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** A plugin's widget type: what its server code answered. Larakit draws the card, title, loading and errors. */
|
|
34
|
+
export type PluginWidgetProps = { data: Record<string, unknown> };
|
|
35
|
+
|
|
36
|
+
/** What `run(name, payload)` of a page answers: the action's message, or why it did not run. */
|
|
37
|
+
export type RunResult =
|
|
38
|
+
| { ok: true; message: string }
|
|
39
|
+
| {
|
|
40
|
+
ok: false;
|
|
41
|
+
/** The HTTP status: 403 when the visitor may not run it (or the panel is a preview), 422 when the payload is invalid. */
|
|
42
|
+
status: number;
|
|
43
|
+
message: string;
|
|
44
|
+
/** The payload's field errors, by field. */
|
|
45
|
+
errors: Record<string, string[]>;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* What a page's component gets: a page of the panel that `.component(...)` (Rust) or `Component(...)` (Go) gives to
|
|
50
|
+
* the application's component under `resources/js/larakit/components`, or a plugin's page at `{p}/{plugin}/{page}`.
|
|
51
|
+
* Larakit draws the menu, the heading and the page's buttons around it.
|
|
52
|
+
*
|
|
53
|
+
* ```tsx
|
|
54
|
+
* export default function Report({ data, run }: PageProps<{ total: number }>) {
|
|
55
|
+
* return <button onClick={() => run('recount')}>{data.total}</button>;
|
|
56
|
+
* }
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export type PageProps<T = Record<string, unknown>> = {
|
|
60
|
+
/** What the page's `Load` (Go) or `load` (Rust) answered. It comes with the page, so the server draws it too. */
|
|
61
|
+
data: T;
|
|
62
|
+
/** What follows a plugin's page in the address, `42` in `/admin/stars/ratings/42`, still encoded; empty otherwise. */
|
|
63
|
+
path: string;
|
|
64
|
+
/** A link to a path below a plugin's page, or to the page itself without one. */
|
|
65
|
+
href: (path?: string) => string;
|
|
66
|
+
/** Loads `data` again (an Inertia partial reload). */
|
|
67
|
+
reload: () => void;
|
|
68
|
+
/**
|
|
69
|
+
* Runs one of the page's actions or calls on the server, `.actions(...)` and `.calls(...)` (Rust) or `Actions` and
|
|
70
|
+
* `Calls` (Go), with `payload` as its JSON body, which a call or an action with a form validates. It sends the
|
|
71
|
+
* CSRF token, shows the answer's message (or the error) as Larakit's toast, and loads `data` again when it ran. It
|
|
72
|
+
* asks no question first: a button's `confirm` is for Larakit's own buttons. It never throws.
|
|
73
|
+
*/
|
|
74
|
+
run: (name: string, payload?: Record<string, unknown>) => Promise<RunResult>;
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* What a widget's component gets: the application's component that `ComponentWidget` (Go) or `component_widget`
|
|
79
|
+
* (Rust) names under `resources/js/larakit/components`. Larakit draws the card, the title, the links, the filters,
|
|
80
|
+
* loading and errors around it, and polls it when the widget polls.
|
|
81
|
+
*/
|
|
82
|
+
export type ComponentWidgetProps<T = Record<string, unknown>> = {
|
|
83
|
+
/** What the widget's load answered, for the dates and filters chosen. */
|
|
84
|
+
data: T;
|
|
85
|
+
/** Loads `data` again. */
|
|
86
|
+
reload: () => void;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
/** A plugin's page, at `{p}/{plugin}/{page}`: the same props as any page's component. */
|
|
90
|
+
export type PluginPageProps<T = Record<string, unknown>> = PageProps<T>;
|
|
91
|
+
|
|
92
|
+
/** A plugin's bar: a button, or anything small, in the topbar, or below the side menu without a topbar. */
|
|
93
|
+
export type PluginBarProps = { place: 'topbar' | 'side' };
|
|
94
|
+
|
|
95
|
+
/** A plugin's component at a render hook, with what the place around it knows. */
|
|
96
|
+
export type PluginHookProps = { hook: HookName; screen: string; place?: 'topbar' | 'side' } & Record<string, unknown>;
|
|
97
|
+
|
|
98
|
+
/** The application's own components for parts of the layout, for every panel: `larakit({ parts: { section: MySection } })`. */
|
|
99
|
+
export type AppParts = { [P in keyof LayoutPartProps]?: ComponentType<LayoutPartProps[P]> };
|
|
100
|
+
|
|
101
|
+
/** The parts a plugin may replace: every part of the layout but the brand and the error page, which are the application's. */
|
|
102
|
+
export type PluginParts = Omit<AppParts, 'brand' | 'error'>;
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* What a plugin's ui gives to `larakit({ plugins })`. Its names are the ones in its `larakit.json`: a
|
|
106
|
+
* column `stars` there is `columns.stars` here, and a screen names it `stars/stars`. This is public API: only add to it.
|
|
107
|
+
*/
|
|
108
|
+
export type LarakitPlugin = {
|
|
109
|
+
/** The plugin's id, as its `larakit.json` has it. */
|
|
110
|
+
id: string;
|
|
111
|
+
columns?: Record<string, ComponentType<PluginColumnProps>>;
|
|
112
|
+
fields?: Record<string, ComponentType<PluginFieldProps>>;
|
|
113
|
+
widgets?: Record<string, ComponentType<PluginWidgetProps>>;
|
|
114
|
+
pages?: Record<string, ComponentType<PluginPageProps>>;
|
|
115
|
+
bars?: Record<string, ComponentType<PluginBarProps>>;
|
|
116
|
+
/** Components at render hooks that `hooks` of its `larakit.json` lists. */
|
|
117
|
+
hooks?: Partial<Record<HookName, ComponentType<PluginHookProps>>>;
|
|
118
|
+
/**
|
|
119
|
+
* The parts of the layout it draws, which `replaces` of its `larakit.json` lists. Each gets the part's props, as an
|
|
120
|
+
* application's `part(...)` does, with `Default`: what would be drawn without it.
|
|
121
|
+
*/
|
|
122
|
+
parts?: PluginParts;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
/** Makes a plugin for `larakit({ plugins })`, with its types checked. */
|
|
126
|
+
export function definePlugin<T extends LarakitPlugin>(plugin: T): T {
|
|
127
|
+
return plugin;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
let plugins: LarakitPlugin[] = [];
|
|
131
|
+
let ownParts: AppParts = {};
|
|
132
|
+
|
|
133
|
+
/** What `larakit(...)` was given: the plugins in their order, and the application's own parts. */
|
|
134
|
+
export function takePlugins(list: LarakitPlugin[] | undefined, parts: AppParts | undefined): void {
|
|
135
|
+
const seen = new Set<string>();
|
|
136
|
+
plugins = [];
|
|
137
|
+
for (const plugin of list ?? []) {
|
|
138
|
+
if (!plugin || typeof plugin.id !== 'string') { console.error('Larakit: larakit({ plugins }) has something that is not a plugin:', plugin); continue; }
|
|
139
|
+
if (seen.has(plugin.id)) { console.error(`Larakit: the plugin ${plugin.id} is in larakit({ plugins }) twice; the first one is used.`); continue; }
|
|
140
|
+
seen.add(plugin.id);
|
|
141
|
+
plugins.push(plugin);
|
|
142
|
+
}
|
|
143
|
+
ownParts = { ...(parts ?? {}) };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** The plugin that `larakit({ plugins })` has with this id. */
|
|
147
|
+
export function registered(id: string): LarakitPlugin | undefined {
|
|
148
|
+
return plugins.find((p) => p.id === id);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
type Kind = 'columns' | 'fields' | 'widgets' | 'pages';
|
|
152
|
+
|
|
153
|
+
/** A plugin's component for a type such as `stars/stars`. */
|
|
154
|
+
export function pluginComponent<K extends Kind>(kind: K, type: string): NonNullable<LarakitPlugin[K]>[string] | undefined {
|
|
155
|
+
const at = type.indexOf('/');
|
|
156
|
+
if (at < 0) return undefined;
|
|
157
|
+
const map = registered(type.slice(0, at))?.[kind] as Record<string, unknown> | undefined;
|
|
158
|
+
return map?.[type.slice(at + 1)] as NonNullable<LarakitPlugin[K]>[string] | undefined;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The plugins of this panel that the application registered, in the application's order. */
|
|
162
|
+
function installed(listed: PanelPlugin[] | undefined): [LarakitPlugin, PanelPlugin][] {
|
|
163
|
+
const out: [LarakitPlugin, PanelPlugin][] = [];
|
|
164
|
+
for (const plugin of plugins) {
|
|
165
|
+
const on = listed?.find((p) => p.id === plugin.id);
|
|
166
|
+
if (on) out.push([plugin, on]);
|
|
167
|
+
}
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const told = new Set<string>();
|
|
172
|
+
const once = (key: string, message: string) => { if (!told.has(key)) { told.add(key); console.error(message); } };
|
|
173
|
+
|
|
174
|
+
/** The bars of this panel's plugins, as `stars/ratings`, that their `larakit.json` lists. */
|
|
175
|
+
export function pluginBars(listed: PanelPlugin[] | undefined): [string, ComponentType<PluginBarProps>][] {
|
|
176
|
+
return installed(listed).flatMap(([plugin, on]) => Object.entries(plugin.bars ?? {})
|
|
177
|
+
.filter(([name]) => on.bars.includes(name) || void once(`${plugin.id} bar ${name}`, `Larakit: larakit.json of the plugin ${plugin.id} does not list "${name}" in bars.`))
|
|
178
|
+
.map(([name, bar]) => [plugin.id + '/' + name, bar] as [string, ComponentType<PluginBarProps>]));
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** The components of this panel's plugins at a render hook, that their `larakit.json` lists. */
|
|
182
|
+
export function pluginHooks(name: string, listed: PanelPlugin[] | undefined): ComponentType<PluginHookProps>[] {
|
|
183
|
+
return installed(listed).flatMap(([plugin, on]) => {
|
|
184
|
+
const hook = plugin.hooks?.[name as HookName];
|
|
185
|
+
if (!hook) return [];
|
|
186
|
+
if (!on.hooks.includes(name as HookName)) { once(`${plugin.id} hook ${name}`, `Larakit: larakit.json of the plugin ${plugin.id} does not list "${name}" in hooks.`); return []; }
|
|
187
|
+
return [hook];
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Who draws a part of the layout under the server's `part(...)`, from the bottom: this panel's plugins that replace
|
|
193
|
+
* it, in the order of `larakit({ plugins })`, then the application's own `larakit({ parts })`. Each one's `Default`
|
|
194
|
+
* draws the one under it, and Larakit's is at the bottom.
|
|
195
|
+
*/
|
|
196
|
+
export function partLayers(part: keyof LayoutPartProps, listed: PanelPlugin[] | undefined): { component: ComponentType<any>; plugin?: string }[] {
|
|
197
|
+
const layers: { component: ComponentType<any>; plugin?: string }[] = [];
|
|
198
|
+
for (const [plugin, on] of installed(listed)) {
|
|
199
|
+
const drawn = (plugin.parts as AppParts | undefined)?.[part];
|
|
200
|
+
if (!drawn) continue;
|
|
201
|
+
if (!(on.replaces as string[]).includes(part)) { once(`${plugin.id} part ${part}`, `Larakit: larakit.json of the plugin ${plugin.id} does not list "${part}" in replaces.`); continue; }
|
|
202
|
+
layers.push({ component: drawn, plugin: plugin.id });
|
|
203
|
+
}
|
|
204
|
+
const own = ownParts[part];
|
|
205
|
+
if (own) layers.push({ component: own });
|
|
206
|
+
return layers;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Whether anything but Larakit draws a part of the layout in this panel. */
|
|
210
|
+
export function replaced(part: keyof LayoutPartProps, listed: PanelPlugin[] | undefined, named?: string): boolean {
|
|
211
|
+
return !!named || partLayers(part, listed).length > 0;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Says, once, which of this panel's plugins have a ui that `larakit({ plugins })` doesn't have. */
|
|
215
|
+
export function missingPlugins(listed: PanelPlugin[] | undefined): PanelPlugin[] {
|
|
216
|
+
const missing = (listed ?? []).filter((p) => p.ui && !registered(p.id));
|
|
217
|
+
for (const p of missing) {
|
|
218
|
+
once(`${p.id} missing`, `Larakit: the plugin ${p.name} draws with its ui, which larakit({ plugins }) in app.tsx doesn't have. Copy it to resources/js/larakit/plugins/${p.id}, pass it there and run larakit:doctor.`);
|
|
219
|
+
}
|
|
220
|
+
return missing;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Asks one of the plugin's own routes, such as `/about` below `{p}/api/plugins/{id}`, with the CSRF token. Fails with `status`, `message` and `errors`. */
|
|
224
|
+
export function pluginApi(id: string) {
|
|
225
|
+
return (path: string, { method, body, signal }: { method?: string; body?: unknown; signal?: AbortSignal } = {}): Promise<unknown> => {
|
|
226
|
+
// A path such as /../../posts would leave the plugin's own routes.
|
|
227
|
+
if (!path.startsWith('/') || !new URL('http://x/plugins/' + id + path).pathname.startsWith('/plugins/' + id + '/')) {
|
|
228
|
+
return Promise.reject(new Error('A path starts with / and stays below the plugin.'));
|
|
229
|
+
}
|
|
230
|
+
return api('/plugins/' + id + path, method, body, signal);
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Shows `fallback` when a plugin's component breaks, so the page around it stays. */
|
|
235
|
+
export class Guard extends Component<{ fallback: ReactNode; children: ReactNode }, { broken: boolean }> {
|
|
236
|
+
state = { broken: false };
|
|
237
|
+
static getDerivedStateFromError() { return { broken: true }; }
|
|
238
|
+
componentDidCatch(e: unknown) { console.error('Larakit plugin component:', e); }
|
|
239
|
+
render() { return this.state.broken ? this.props.fallback : this.props.children; }
|
|
240
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// The role preview is kept in the server's session (POST/DELETE {p}/preview, LA-312): the bar comes from the page's
|
|
2
|
+
// own props, so a page drawn on the server already has it and the browser takes over without a mismatch. The kit
|
|
3
|
+
// never names the role in a header.
|
|
4
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { act, cleanup, fireEvent, render } from '@testing-library/react';
|
|
6
|
+
import { hydrateRoot, type Root } from 'react-dom/client';
|
|
7
|
+
import { renderToString } from 'react-dom/server';
|
|
8
|
+
import { createInertiaApp } from '@inertiajs/react';
|
|
9
|
+
import type { IndexProps } from '@larakit/core';
|
|
10
|
+
import { panel, screen } from './fixtures';
|
|
11
|
+
import { ResourceIndex } from './pages';
|
|
12
|
+
import { setPanelPath, setPreviewRole } from './kit/api';
|
|
13
|
+
|
|
14
|
+
afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
|
|
15
|
+
|
|
16
|
+
function page(preview?: { role: string; label: string }): IndexProps {
|
|
17
|
+
return {
|
|
18
|
+
path: '/admin', errors: {},
|
|
19
|
+
larakit: { ...panel('Shop', [{ name: 'orders', label: 'Orders', icon: '', group: '', href: '/admin/orders' }]), ...(preview ? { preview } : {}) },
|
|
20
|
+
screen: screen({ name: 'orders', label: 'Orders', columns: [{ key: 'number', label: 'Number', type: 'text', sortable: false, searchable: false }] }),
|
|
21
|
+
table: { data: [], total: 0, page: 1, lastPage: 1 },
|
|
22
|
+
query: { filters: {} },
|
|
23
|
+
modal: null,
|
|
24
|
+
} as never;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const at = (preview?: { role: string; label: string }) => ({ component: 'larakit/Resource/Index', props: page(preview), url: '/admin/orders', version: '1', flash: {} });
|
|
28
|
+
const manager = { role: 'manager', label: 'Manager' };
|
|
29
|
+
|
|
30
|
+
describe('the role preview', () => {
|
|
31
|
+
it('draws the bar on the server, and the browser takes over that page without a mismatch', async () => {
|
|
32
|
+
let html = '';
|
|
33
|
+
await createInertiaApp({ page: at(manager) as never, resolve: () => ResourceIndex as never, setup: ({ App, props }) => { html = renderToString(<App {...props} />); } });
|
|
34
|
+
expect(html).toContain('data-lk="preview-bar"');
|
|
35
|
+
expect(html).toContain('roles.previewing');
|
|
36
|
+
const el = document.body.appendChild(document.createElement('div'));
|
|
37
|
+
el.innerHTML = html;
|
|
38
|
+
const mismatch = vi.fn();
|
|
39
|
+
let root: Root | undefined;
|
|
40
|
+
await act(async () => {
|
|
41
|
+
await createInertiaApp({ page: at(manager) as never, resolve: () => ResourceIndex as never, setup: ({ App, props }) => { root = hydrateRoot(el, <App {...props} />, { onRecoverableError: mismatch }); } });
|
|
42
|
+
});
|
|
43
|
+
expect(mismatch).not.toHaveBeenCalled();
|
|
44
|
+
expect(el.querySelector('[data-lk="preview-bar"]')).not.toBeNull();
|
|
45
|
+
act(() => root?.unmount());
|
|
46
|
+
el.remove();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('has no bar when the server says nothing is previewed', async () => {
|
|
50
|
+
let html = '';
|
|
51
|
+
await createInertiaApp({ page: at() as never, resolve: () => ResourceIndex as never, setup: ({ App, props }) => { html = renderToString(<App {...props} />); } });
|
|
52
|
+
expect(html).not.toContain('data-lk="preview-bar"');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('ends the preview in the session, and never sends the role in a header', async () => {
|
|
56
|
+
const calls: { url: string; init?: RequestInit }[] = [];
|
|
57
|
+
vi.stubGlobal('fetch', vi.fn(async (url: string, init?: RequestInit) => {
|
|
58
|
+
calls.push({ url: String(url), init });
|
|
59
|
+
return new Response(String(url).endsWith('/preview') ? null : '{}', { status: String(url).endsWith('/preview') ? 204 : 200, headers: { 'content-type': 'application/json' } });
|
|
60
|
+
}));
|
|
61
|
+
await act(async () => {
|
|
62
|
+
await createInertiaApp({ page: at(manager) as never, resolve: () => ResourceIndex as never, setup: ({ App, props }) => { render(<App {...props} />); } });
|
|
63
|
+
});
|
|
64
|
+
await act(async () => { fireEvent.click(document.querySelector('[data-lk="end-preview"]')!); });
|
|
65
|
+
const ended = calls.find((c) => c.url === '/admin/preview');
|
|
66
|
+
expect(ended?.init?.method).toBe('DELETE');
|
|
67
|
+
expect(calls.length).toBeGreaterThan(0);
|
|
68
|
+
for (const c of calls) expect(new Headers(c.init?.headers).has('X-Larakit-As')).toBe(false);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it('says why when the server refuses the role, and changes nothing', async () => {
|
|
72
|
+
setPanelPath('/admin');
|
|
73
|
+
const fetched = vi.fn(async () => new Response(JSON.stringify({ message: 'Forbidden.' }), { status: 403, headers: { 'content-type': 'application/json' } }));
|
|
74
|
+
vi.stubGlobal('fetch', fetched);
|
|
75
|
+
await expect(setPreviewRole('admin')).rejects.toMatchObject({ status: 403, message: 'Forbidden.' });
|
|
76
|
+
const [url, init] = fetched.mock.calls[0] as unknown as [string, RequestInit];
|
|
77
|
+
expect(url).toBe('/admin/preview');
|
|
78
|
+
expect(init.method).toBe('POST');
|
|
79
|
+
expect(new Headers(init.headers).has('X-Larakit-As')).toBe(false);
|
|
80
|
+
});
|
|
81
|
+
});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// When the side menu is narrowed to its icons, the application's own brand and tenant switcher are told so
|
|
2
|
+
// (`rail`), so a brand can show only its picture there.
|
|
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 BrandProps, type TenantSwitcherProps } from './components';
|
|
8
|
+
import { panel, screen } from './fixtures';
|
|
9
|
+
import { ResourceIndex } from './pages';
|
|
10
|
+
|
|
11
|
+
afterEach(() => { cleanup(); localStorage.clear(); });
|
|
12
|
+
|
|
13
|
+
function Brand({ name, rail }: BrandProps) {
|
|
14
|
+
return <span data-app="brand">{rail ? 'picture' : name}</span>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function Switcher({ active, rail }: TenantSwitcherProps) {
|
|
18
|
+
return <span data-app="switcher">{rail ? 'badge' : active?.name}</span>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function visit() {
|
|
22
|
+
larakit({ components: {
|
|
23
|
+
'./larakit/components/parts/Brand.tsx': { default: Brand },
|
|
24
|
+
'./larakit/components/parts/Switcher.tsx': { default: Switcher },
|
|
25
|
+
} });
|
|
26
|
+
const props = {
|
|
27
|
+
path: '/admin', errors: {},
|
|
28
|
+
larakit: { ...panel('Shop', [{ name: 'orders', label: 'Orders', icon: '', group: '', href: '/admin/orders' }]),
|
|
29
|
+
parts: { brand: 'parts/Brand', tenantSwitcher: 'parts/Switcher' },
|
|
30
|
+
tenancy: { enabled: true, tenants: [{ id: 'a', name: 'Acme', active: true }] } },
|
|
31
|
+
screen: screen({ name: 'orders', label: 'Orders', columns: [{ key: 'number', label: 'Number', type: 'text', sortable: false, searchable: false }] }),
|
|
32
|
+
table: { data: [], total: 0, page: 1, lastPage: 1 },
|
|
33
|
+
query: { filters: {} },
|
|
34
|
+
modal: null,
|
|
35
|
+
} as unknown as IndexProps;
|
|
36
|
+
await act(async () => {
|
|
37
|
+
await createInertiaApp({
|
|
38
|
+
page: { component: 'larakit/Resource/Index', props, url: '/admin/orders', version: '1', flash: {} } as never,
|
|
39
|
+
resolve: () => ResourceIndex as never, setup: ({ App, props }) => { render(<App {...props} />); },
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const text = (app: string) => document.querySelector(`[data-app="${app}"]`)?.textContent;
|
|
45
|
+
|
|
46
|
+
describe('the narrow side menu', () => {
|
|
47
|
+
it('tells the application\'s brand and tenant switcher', async () => {
|
|
48
|
+
await visit();
|
|
49
|
+
expect([text('brand'), text('switcher')]).toEqual(['Shop', 'Acme']);
|
|
50
|
+
const narrow = document.querySelector<HTMLButtonElement>('[data-lk="rail"]');
|
|
51
|
+
expect(narrow).not.toBeNull();
|
|
52
|
+
await act(async () => { fireEvent.click(narrow!); });
|
|
53
|
+
expect([text('brand'), text('switcher')]).toEqual(['picture', 'badge']);
|
|
54
|
+
expect(find.getByRole('button', { name: /widen|genişlet/i })).toBeTruthy();
|
|
55
|
+
});
|
|
56
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
2
|
+
import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
|
|
3
|
+
import { useState } from 'react';
|
|
4
|
+
import type { Field } from '@larakit/core';
|
|
5
|
+
import { kitFor, LarakitProvider } from './context';
|
|
6
|
+
import { panel } from './fixtures';
|
|
7
|
+
import { Form } from './Form';
|
|
8
|
+
|
|
9
|
+
afterEach(cleanup);
|
|
10
|
+
|
|
11
|
+
const items: Field = { key: 'items', label: 'Items', type: 'repeater', look: { addLabel: 'Add line', fields: [
|
|
12
|
+
{ key: 'sku', label: 'SKU', type: 'text', look: { required: true } },
|
|
13
|
+
{ key: 'quantity', label: 'Quantity', type: 'text', look: { input: 'number' } },
|
|
14
|
+
] } };
|
|
15
|
+
|
|
16
|
+
function Order({ errors, start }: { errors: Record<string, string>; start: Record<string, unknown>[] }) {
|
|
17
|
+
const [values, setValues] = useState<Record<string, unknown>>({ items: start });
|
|
18
|
+
return (
|
|
19
|
+
<LarakitProvider value={kitFor(panel('Shop'), '/admin')}>
|
|
20
|
+
<Form fields={[items]} mode="create" values={values} set={(k, v) => setValues((old) => ({ ...old, [k]: v }))} errors={errors} />
|
|
21
|
+
<output data-testid="values">{JSON.stringify(values)}</output>
|
|
22
|
+
</LarakitProvider>
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
describe('a repeater', () => {
|
|
27
|
+
it('shows an error under the field of its own row, as Inertia names it', () => {
|
|
28
|
+
render(<Order start={[{ sku: 'A-1', quantity: '1' }, { sku: '', quantity: '0' }]}
|
|
29
|
+
errors={{ 'items.1.sku': 'The SKU is required.', 'items.1.quantity': 'At least 1.', 'items.1': 'Row two is wrong.' }} />);
|
|
30
|
+
const [first, second] = screen.getAllByRole('group').filter((g) => g.dataset.lk === 'repeater-row');
|
|
31
|
+
expect(within(first).queryByText('The SKU is required.')).toBeNull();
|
|
32
|
+
const sku = within(second).getByLabelText(/SKU/);
|
|
33
|
+
expect(sku.getAttribute('aria-invalid')).toBe('true');
|
|
34
|
+
expect(document.getElementById(sku.getAttribute('aria-describedby')!)?.textContent).toBe('The SKU is required.');
|
|
35
|
+
expect(within(second).getByText('At least 1.')).toBeTruthy();
|
|
36
|
+
expect(within(second).getByText('Row two is wrong.')).toBeTruthy();
|
|
37
|
+
expect(second.querySelector('[data-path="items.1.sku"]')).not.toBeNull();
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('adds and removes rows', () => {
|
|
41
|
+
render(<Order start={[{ sku: 'A-1', quantity: '1' }]} errors={{}} />);
|
|
42
|
+
fireEvent.click(screen.getByText('+ Add line'));
|
|
43
|
+
fireEvent.change(screen.getAllByLabelText(/SKU/)[1], { target: { value: 'B-2' } });
|
|
44
|
+
expect(JSON.parse(screen.getByTestId('values').textContent!).items).toEqual([{ sku: 'A-1', quantity: '1' }, { sku: 'B-2', quantity: '' }]);
|
|
45
|
+
fireEvent.click(screen.getAllByText('Remove')[0]);
|
|
46
|
+
expect(JSON.parse(screen.getByTestId('values').textContent!).items).toEqual([{ sku: 'B-2', quantity: '' }]);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// A resource's own pages, list, create, edit and view, drawn by the application's component (Go PageComponent, Rust
|
|
2
|
+
// .page_component). The component gets what Larakit's page gets and Default, Larakit's own page, to wrap; a custom
|
|
3
|
+
// create, edit or view page is a page of its own, also when the panel's forms are dialogs.
|
|
4
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { act, cleanup, fireEvent, render, screen as view } from '@testing-library/react';
|
|
6
|
+
import { renderToString } from 'react-dom/server';
|
|
7
|
+
import { createInertiaApp, router } from '@inertiajs/react';
|
|
8
|
+
import type { IndexProps } from '@larakit/core';
|
|
9
|
+
import { larakit } from './components';
|
|
10
|
+
import { panel, screen } from './fixtures';
|
|
11
|
+
import { ResourceIndex } from './pages';
|
|
12
|
+
import type { ResourcePageProps } from './ResourceIndex';
|
|
13
|
+
|
|
14
|
+
afterEach(() => { cleanup(); larakit({}); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
|
|
15
|
+
|
|
16
|
+
let got: ResourcePageProps | undefined;
|
|
17
|
+
|
|
18
|
+
function Edit(props: ResourcePageProps) {
|
|
19
|
+
got = props;
|
|
20
|
+
const { record, Default, run } = props;
|
|
21
|
+
return (
|
|
22
|
+
<div data-test="edit">
|
|
23
|
+
<p>Order {record?.id}</p>
|
|
24
|
+
<Default />
|
|
25
|
+
<button type="button" onClick={() => void run('ship', record?.id)}>Ship it</button>
|
|
26
|
+
</div>
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function List(props: ResourcePageProps) {
|
|
31
|
+
got = props;
|
|
32
|
+
return <section data-test="list"><h2>{props.table.total} orders</h2><props.Default /></section>;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const components = {
|
|
36
|
+
'./larakit/components/orders/Edit.tsx': { default: Edit },
|
|
37
|
+
'./larakit/components/orders/List.tsx': { default: List },
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
function props(own: Record<string, string>, modal: IndexProps['modal'] = null): IndexProps {
|
|
41
|
+
return {
|
|
42
|
+
path: '/admin', errors: {},
|
|
43
|
+
larakit: panel('Shop', [{ name: 'orders', label: 'Orders', icon: '', group: '', href: '/admin/orders' }]),
|
|
44
|
+
screen: screen({
|
|
45
|
+
name: 'orders', label: 'Orders', canCreate: true, pageComponents: own,
|
|
46
|
+
actions: [{ name: 'ship', label: 'Ship', icon: '', confirm: '', danger: false }],
|
|
47
|
+
columns: [{ key: 'number', label: 'Number', type: 'text', sortable: false, searchable: false }],
|
|
48
|
+
fields: [{ key: 'number', label: 'Number', type: 'text' }],
|
|
49
|
+
form: { items: [{ field: 'number' }] },
|
|
50
|
+
}),
|
|
51
|
+
table: { data: [{ id: '7', cells: { number: 'ORD-7' }, can: { update: true, actions: ['ship'] } }], total: 1, page: 1, lastPage: 1 },
|
|
52
|
+
query: { filters: {} },
|
|
53
|
+
modal,
|
|
54
|
+
} as unknown as IndexProps;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const editing: IndexProps['modal'] = { mode: 'edit', record: { id: '7', version: 'v1', values: { number: 'ORD-7' }, cells: {}, can: { update: true, actions: ['ship'] } } } as never;
|
|
58
|
+
|
|
59
|
+
async function open(p: IndexProps, url = '/admin/orders') {
|
|
60
|
+
await act(async () => {
|
|
61
|
+
await createInertiaApp({ page: { component: 'larakit/Resource/Index', props: p, url, version: '1', flash: {} } as never, resolve: () => ResourceIndex as never, setup: ({ App, props }) => { render(<App {...props} />); } });
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const json = (status: number, body: object) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
66
|
+
|
|
67
|
+
describe("a resource's page that the application's component draws", () => {
|
|
68
|
+
it("draws an edit page as a page of its own, with the record and Larakit's form as Default", async () => {
|
|
69
|
+
larakit({ components });
|
|
70
|
+
await open(props({ edit: 'orders/Edit' }, editing), '/admin/orders/7/edit');
|
|
71
|
+
expect(document.querySelector('[data-lk="own-page"][data-page="edit"] [data-test="edit"]')).not.toBeNull();
|
|
72
|
+
expect(view.getByText('Order 7')).toBeTruthy();
|
|
73
|
+
expect(got).toMatchObject({ page: 'edit', id: '7', path: '/admin', record: { id: '7', values: { number: 'ORD-7' } } });
|
|
74
|
+
expect(got!.href('/7')).toBe('/admin/orders/7');
|
|
75
|
+
// Default is Larakit's form, as a page: its field has the record's value and nothing opens over a list.
|
|
76
|
+
expect((document.querySelector('#f-number') as HTMLInputElement | null)?.value).toBe('ORD-7');
|
|
77
|
+
expect(document.querySelector('[data-test="edit"] table')).toBeNull();
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('is drawn on the server too', async () => {
|
|
81
|
+
larakit({ components });
|
|
82
|
+
let html = '';
|
|
83
|
+
await createInertiaApp({ page: { component: 'larakit/Resource/Index', props: props({ edit: 'orders/Edit' }, editing), url: '/admin/orders/7/edit', version: '1', flash: {} } as never, resolve: () => ResourceIndex as never, setup: ({ App, props }) => { html = renderToString(<App {...props} />); } });
|
|
84
|
+
expect(html).toContain('data-test="edit"');
|
|
85
|
+
expect(html).toContain('value="ORD-7"');
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it("runs a record's action at its address and loads the page again", async () => {
|
|
89
|
+
larakit({ components });
|
|
90
|
+
const sent: string[] = [];
|
|
91
|
+
vi.stubGlobal('fetch', vi.fn(async (url: string) => { sent.push(String(url)); return json(200, { message: 'Shipped.' }); }));
|
|
92
|
+
const reload = vi.spyOn(router, 'reload').mockImplementation(() => {});
|
|
93
|
+
await open(props({ edit: 'orders/Edit' }, editing), '/admin/orders/7/edit');
|
|
94
|
+
await act(async () => { fireEvent.click(view.getByText('Ship it')); });
|
|
95
|
+
expect(sent).toEqual(['/admin/api/orders/7/actions/ship']);
|
|
96
|
+
expect(reload).toHaveBeenCalled();
|
|
97
|
+
expect(document.querySelector('[data-lk="notice"]')?.textContent).toContain('Shipped.');
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it("draws the list with its rows and Larakit's table as Default", async () => {
|
|
101
|
+
larakit({ components });
|
|
102
|
+
await open(props({ list: 'orders/List' }));
|
|
103
|
+
expect(view.getByText('1 orders')).toBeTruthy();
|
|
104
|
+
expect(got).toMatchObject({ page: 'list', id: null, record: undefined });
|
|
105
|
+
expect(document.querySelector('[data-test="list"]')?.textContent).toContain('ORD-7');
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("keeps Larakit's pages that the application doesn't draw", async () => {
|
|
109
|
+
larakit({ components });
|
|
110
|
+
await open(props({ edit: 'orders/Edit' }));
|
|
111
|
+
expect(document.querySelector('[data-lk="own-page"]')).toBeNull();
|
|
112
|
+
expect(view.getAllByText('ORD-7').length).toBeGreaterThan(0);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it('says which file is missing', async () => {
|
|
116
|
+
await open(props({ edit: 'orders/Nope' }, editing), '/admin/orders/7/edit');
|
|
117
|
+
expect(document.querySelector('[data-lk="missing-component"]')?.textContent).toContain('resources/js/larakit/components/orders/Nope.tsx');
|
|
118
|
+
});
|
|
119
|
+
});
|