-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevtoolsPanel.tsx
More file actions
311 lines (288 loc) · 8.88 KB
/
Copy pathDevtoolsPanel.tsx
File metadata and controls
311 lines (288 loc) · 8.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
/**
* The devtools panel UI, via {@linkcode DevtoolsPanel}: a toggleable,
* dockable overlay showing the selected form's live field tree.
*
* @module
*/
import {
type CSSProperties,
type ReactNode,
useState,
useSyncExternalStore,
} from "react";
import type { FormApi } from "@kintools/form-core";
import type { DevtoolsRegistry } from "./DevtoolsRegistry.ts";
import { FieldTreeRow } from "./FieldTreeRow.tsx";
import { colors, monoFont } from "./styles.ts";
/**
* The 4 corners the panel can be docked to. Exported (re-exported via
* `index.ts`) so `DevtoolsProvider`'s `initialPosition` prop can be typed
* against it.
*/
export type DockPosition =
| "top-left"
| "top-right"
| "bottom-left"
| "bottom-right";
/** Props for {@linkcode DevtoolsPanel}. */
export type DevtoolsPanelProps = {
registry: DevtoolsRegistry;
/**
* Corner to dock into before the user has picked one.
* Defaults to `"bottom-right"`.
*/
initialPosition?: DockPosition;
};
const DOCK_POSITION_STORAGE_KEY = "kin-form-devtools:position";
// `iconX`/`iconY` place the filled corner square within `DockIcon`'s 16x16
// viewBox; order matches reading order.
const DOCK_POSITIONS: readonly {
value: DockPosition;
iconX: number;
iconY: number;
label: string;
}[] = [
{ value: "top-left", iconX: 3, iconY: 3, label: "Dock top-left" },
{ value: "top-right", iconX: 10, iconY: 3, label: "Dock top-right" },
{ value: "bottom-left", iconX: 3, iconY: 10, label: "Dock bottom-left" },
{
value: "bottom-right",
iconX: 10,
iconY: 10,
label: "Dock bottom-right",
},
];
// Small "viewport with a filled corner" glyph indicating which corner a
// button docks to. Uses `currentColor` so it inherits the button's
// active/inactive color.
function DockIcon({ x, y }: { x: number; y: number }): ReactNode {
return (
<svg width={20} height={20} viewBox="0 0 20 20">
<rect
x={1.5}
y={1.5}
width={17}
height={17}
rx={2}
fill="none"
stroke="currentColor"
strokeWidth={1}
/>
<rect x={x} y={y} width={7} height={7} rx={1} fill="currentColor" />
</svg>
);
}
function isDockPosition(value: string | null): value is DockPosition {
return DOCK_POSITIONS.some((p) => p.value === value);
}
// Guards both SSR (no `localStorage`) and privacy-mode browsers, where
// merely *accessing* `localStorage` can throw.
function readStoredPosition(fallback: DockPosition): DockPosition {
try {
const stored = localStorage.getItem(DOCK_POSITION_STORAGE_KEY);
return isDockPosition(stored) ? stored : fallback;
} catch {
return fallback;
}
}
function storePosition(position: DockPosition): void {
try {
localStorage.setItem(DOCK_POSITION_STORAGE_KEY, position);
} catch {
// Ignore write failures (e.g. storage disabled/full).
}
}
// The side each corner anchors to, so the toggle button and panel can be
// offset from the near edges instead of always `bottom`/`right`.
function insetStyle(position: DockPosition, nearOffset: number): CSSProperties {
const [vSide, hSide] = position.split("-") as [
"top" | "bottom",
"left" | "right",
];
return { [vSide]: nearOffset, [hSide]: 12 } as CSSProperties;
}
// Hoisted module-level constants, not object literals inline in JSX: built
// once, not re-allocated on every render. The position-dependent inset
// (`insetStyle`) is merged in at render time since it varies with state.
const toggleBaseStyle: CSSProperties = {
position: "fixed",
zIndex: 2147483647,
background: colors.bg,
color: colors.accent,
border: `1px solid ${colors.border}`,
borderRadius: 4,
fontFamily: monoFont,
fontSize: 13,
lineHeight: "16px",
padding: "4px 8px",
cursor: "pointer",
boxShadow: "0 2px 8px rgba(0, 0, 0, 0.4)",
};
const panelBaseStyle: CSSProperties = {
position: "fixed",
zIndex: 2147483647,
width: 420,
height: 420,
background: colors.bg,
color: colors.text,
border: `1px solid ${colors.border}`,
borderRadius: 4,
display: "flex",
flexDirection: "column",
overflow: "hidden",
boxShadow: "0 4px 16px rgba(0, 0, 0, 0.4)",
};
const headerStyle: CSSProperties = {
display: "flex",
alignItems: "center",
gap: 12,
padding: "8px 12px",
borderBottom: `1px solid ${colors.border}`,
fontFamily: monoFont,
fontSize: 13,
lineHeight: "16px",
};
const selectStyle: CSSProperties = {
background: colors.bgAlt,
color: colors.text,
border: `1px solid ${colors.border}`,
borderRadius: 4,
fontFamily: monoFont,
fontSize: 13,
lineHeight: "16px",
padding: "5px 8px",
flex: 1,
};
const cornerGroupStyle: CSSProperties = {
display: "flex",
gap: 4,
marginLeft: "auto",
};
const cornerButtonBaseStyle: CSSProperties = {
display: "flex",
alignItems: "center",
justifyContent: "center",
background: "transparent",
border: "none",
cursor: "pointer",
padding: 4,
};
const treeStyle: CSSProperties = {
overflow: "auto",
flex: 1,
};
const emptyStyle: CSSProperties = {
padding: 8,
color: colors.textDim,
fontFamily: monoFont,
fontSize: 13,
lineHeight: "16px",
};
function flagLabel(form: FormApi<unknown>): string {
const flags = [form.dirty && "dirty", form.submitting && "submitting"].filter(
Boolean,
);
return flags.length > 0 ? ` (${flags.join(", ")})` : "";
}
/**
* The floating devtools panel. Mounted once by {@linkcode DevtoolsProvider}.
* Subscribes to `registry` for the live set of registered forms, and, only
* for whichever one is currently selected, renders {@linkcode FieldTreeRow}
* for its tree.
*/
export function DevtoolsPanel({
registry,
initialPosition = "bottom-right",
}: DevtoolsPanelProps): ReactNode {
useSyncExternalStore(registry.subscribe, registry.getVersion);
const [open, setOpen] = useState(false);
const [selectedId, setSelectedId] = useState<number | null>(null);
const [position, setPosition] = useState<DockPosition>(() =>
readStoredPosition(initialPosition)
);
const forms = [...registry.forms.values()];
// Falls back to `forms[0]` whenever `selectedId` doesn't resolve to a
// currently-registered form (not just when it's `null`), so selecting a
// form that later unregisters (e.g. its owning component unmounts) lands
// on another registered form instead of a blank "no form" pane while the
// dropdown still lists others.
const selected =
(selectedId != null ? registry.forms.get(selectedId) : null) ??
forms[0] ?? null;
function selectPosition(next: DockPosition) {
setPosition(next);
storePosition(next);
}
return (
<>
<button
type="button"
style={{ ...toggleBaseStyle, ...insetStyle(position, 12) }}
onClick={() => setOpen((o) => !o)}
>
Kin Form ({forms.length})
</button>
{open && (
<div style={{ ...panelBaseStyle, ...insetStyle(position, 48) }}>
<div style={headerStyle}>
<span>Form:</span>
<select
style={selectStyle}
value={selected?.id ?? ""}
onChange={(e) => setSelectedId(Number(e.target.value))}
>
{forms.length === 0 && (
<option value="">(none registered)</option>
)}
{forms.map((form) => (
<option key={form.id} value={form.id}>
{registry.getFormName(form.id) ?? `#${form.id}`}
{flagLabel(form)}
</option>
))}
</select>
<div style={cornerGroupStyle}>
{DOCK_POSITIONS.map((p) => (
<button
key={p.value}
type="button"
title={p.label}
style={{
...cornerButtonBaseStyle,
color: position === p.value
? colors.accent
: colors.textDim,
}}
onClick={() => selectPosition(p.value)}
>
<DockIcon x={p.iconX} y={p.iconY} />
</button>
))}
</div>
</div>
<div style={treeStyle}>
<div style={{ width: "max-content" }}>
{selected
? (
<FieldTreeRow
// A cast, not a structurally-typed pass-through: `FormApi<unknown>`
// is fixed at `TParentValue = never`, and `never` in a
// contravariant (function-parameter) position defeats
// `AnyNode` substitution several layers down through
// `validators`/`handleChange`; see `types.ts`'s comment.
node={selected}
depth={0}
/>
)
: (
<div style={emptyStyle}>
No form has called useFormDevtools yet.
</div>
)}
</div>
</div>
</div>
)}
</>
);
}