-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFieldTreeRow.tsx
More file actions
276 lines (253 loc) · 8.36 KB
/
Copy pathFieldTreeRow.tsx
File metadata and controls
276 lines (253 loc) · 8.36 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
/**
* A recursive tree row rendering one `FieldApi`, via
* {@linkcode FieldTreeRow}.
*
* @module
*/
import { type CSSProperties, type ReactNode, useState } from "react";
import { useNodeVersion } from "./useNodeVersion.ts";
import { colors, monoFont } from "./styles.ts";
import type { AnyNode } from "./types.ts";
/** Props for {@linkcode FieldTreeRow}. */
export type FieldTreeRowProps = {
node: AnyNode;
/** Nesting depth, for indentation; `0` for the tree's root. */
depth: number;
};
// A node's `children` keys are dotted paths *relative to that node* and can
// be any depth (e.g. "items.0.label"), not just a direct child name; see
// `FieldApi.field`'s `DeepKey` typing. `Map` iteration order also doesn't
// track current array order: `swapItems`/`moveItem` re-key existing entries
// in place without reordering the `Map` itself. So for an array-valued node,
// sort by the numeric first segment of each key instead of trusting
// iteration order; a non-array node's registration order is stable and left
// alone.
function sortedFields(node: AnyNode): AnyNode[] {
const entries = [...node.children.entries()];
if (!Array.isArray(node.value)) {
return entries.map(([, field]) => field);
}
return entries
.map(([key, field], i) => ({ field, index: Number(key.split(".")[0]), i }))
.sort((a, b) =>
Number.isNaN(a.index) || Number.isNaN(b.index)
? a.i - b.i
: a.index - b.index
)
.map((e) => e.field);
}
function formatValue(value: unknown): string {
if (value === undefined) return "undefined";
if (value instanceof File) return `File(${value.name})`;
if (value instanceof Date) return value.toISOString();
try {
const json = JSON.stringify(value);
return json.length > 60 ? json.slice(0, 60) + "…" : json;
} catch {
return String(value);
}
}
// Hoisted module-level constants, not object literals inline in JSX: built
// once, not re-allocated on every render. `rowBaseStyle` holds everything
// that doesn't vary per row; `depth`'s indentation is the one thing that
// does, so it's spread in at the callsite instead of living here.
const rowBaseStyle: CSSProperties = {
display: "flex",
alignItems: "center",
gap: 4,
padding: "2px 8px",
fontFamily: monoFont,
fontSize: 12,
lineHeight: "20px",
whiteSpace: "nowrap",
};
const disclosureStyle: CSSProperties = {
background: "none",
border: "none",
color: colors.textDim,
cursor: "pointer",
padding: 0,
width: 20,
fontSize: 20,
lineHeight: 1,
};
const disclosureSpacerStyle: CSSProperties = { width: 20 };
const nameStyle: CSSProperties = { color: colors.accent };
const valueStyle: CSSProperties = {
color: colors.text,
overflow: "hidden",
textOverflow: "ellipsis",
};
const errorStyle: CSSProperties = { color: colors.invalid };
const detailsToggleStyle: CSSProperties = {
background: "none",
border: "none",
color: colors.textDim,
cursor: "pointer",
padding: 0,
fontFamily: monoFont,
fontSize: 11,
};
const detailsListStyle: CSSProperties = {
display: "flex",
flexDirection: "column",
gap: 2,
padding: "2px 8px",
fontFamily: monoFont,
fontSize: 11,
lineHeight: "16px",
color: colors.textDim,
};
const detailRowStyle: CSSProperties = {
display: "flex",
gap: 6,
whiteSpace: "normal",
wordBreak: "break-word",
};
const detailLabelStyle: CSSProperties = { flexShrink: 0 };
const detailValueStyle: CSSProperties = { color: colors.text };
const badgeColor = {
touched: colors.touched,
validating: colors.validating,
invalid: colors.invalid,
dirty: colors.dirty,
} as const;
function Badge({
label,
kind,
}: {
label: string;
kind: "touched" | "validating" | "invalid" | "dirty";
}): ReactNode {
const color = badgeColor[kind];
return (
<span
style={{
color,
border: `1px solid ${color}`,
borderRadius: 4,
fontSize: 10,
padding: "0 4px",
lineHeight: "16px",
}}
>
{label}
</span>
);
}
/**
* One row per `FieldApi`, recursing into a node's own
* {@linkcode sortedFields} for its children, deliberately built the same
* way real Kin Form UI is: each row subscribes only to its own node via
* {@linkcode useNodeVersion}, so an edit to one field re-renders that row
* (and whichever ancestors' aggregate flags it flips), not the whole tree.
*
* Whether a row renders as expandable is decided by `children.size`, not a
* type check: a node whose value happens to be an object/array but hasn't
* had `field()` called on any of its sub-paths yet (e.g. its inputs haven't
* rendered) shows as a leaf until something registers into it, matching
* "leaf vs. decomposed is a usage choice, not a data-shape fact."
*/
export function FieldTreeRow({ node, depth }: FieldTreeRowProps): ReactNode {
useNodeVersion(node);
const [expanded, setExpanded] = useState(true);
const [detailsOpen, setDetailsOpen] = useState(false);
const hasChildren = node.children.size > 0;
return (
<>
<div style={{ ...rowBaseStyle, paddingLeft: 8 + depth * 24 }}>
{hasChildren
? (
<button
type="button"
onClick={() => setExpanded((e) => !e)}
style={disclosureStyle}
aria-label={expanded ? "Collapse" : "Expand"}
>
{expanded ? "▾" : "▸"}
</button>
)
: <span style={disclosureSpacerStyle} />}
<span style={nameStyle}>{node.name || "(root)"}</span>
{!hasChildren && (
<span style={valueStyle}>{formatValue(node.value)}</span>
)}
{node.touched && <Badge label="touched" kind="touched" />}
{node.dirty && <Badge label="dirty" kind="dirty" />}
{node.validating && <Badge label="validating" kind="validating" />}
{node.invalid && <Badge label="invalid" kind="invalid" />}
{node.error || node.schemaError
? (
<span style={errorStyle}>
{String(node.error ?? node.schemaError)}
</span>
)
: null}
<button
type="button"
onClick={() => setDetailsOpen((o) => !o)}
style={detailsToggleStyle}
aria-label={detailsOpen ? "Hide details" : "Show details"}
>
{detailsOpen ? "▾ details" : "▸ details"}
</button>
</div>
{detailsOpen && <NodeDetails node={node} depth={depth} />}
{hasChildren && expanded && (
<div>
{sortedFields(node).map((field) => (
<FieldTreeRow key={field.id} node={field} depth={depth + 1} />
))}
</div>
)}
</>
);
}
// The expanded state a node's "▸ details" toggle reveals: every property
// `FieldTreeRow`'s own compact row doesn't already surface as a badge or
// inline preview. Kept as a separate disclosure from `expanded` (which
// governs `children`) so inspecting one node's full state doesn't force
// every descendant's rows to grow too.
function NodeDetails(
{ node, depth }: { node: AnyNode; depth: number },
): ReactNode {
const schemaErrorEntries = node.schemaErrorMap
? Object.entries(node.schemaErrorMap)
: null;
return (
<div
style={{ ...detailsListStyle, paddingLeft: 8 + depth * 24 + 24 }}
>
<div style={detailRowStyle}>
<span style={detailLabelStyle}>value:</span>
<span style={detailValueStyle}>{formatValue(node.value)}</span>
</div>
<div style={detailRowStyle}>
<span style={detailLabelStyle}>error:</span>
<span style={detailValueStyle}>{String(node.error)}</span>
</div>
<div style={detailRowStyle}>
<span style={detailLabelStyle}>schemaError:</span>
<span style={detailValueStyle}>{String(node.schemaError)}</span>
</div>
<div style={detailRowStyle}>
<span style={detailLabelStyle}>schemaErrorMap:</span>
<span style={detailValueStyle}>
{schemaErrorEntries
? schemaErrorEntries
.map(([path, message]) => `${path || "(self)"}: ${message}`)
.join(", ")
: "null"}
</span>
</div>
<div style={detailRowStyle}>
<span style={detailLabelStyle}>validators:</span>
<span style={detailValueStyle}>{node.validators.length}</span>
</div>
<div style={detailRowStyle}>
<span style={detailLabelStyle}>children:</span>
<span style={detailValueStyle}>{node.children.size}</span>
</div>
</div>
);
}