-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathuseDatasetFields.ts
More file actions
359 lines (331 loc) · 13.4 KB
/
Copy pathuseDatasetFields.ts
File metadata and controls
359 lines (331 loc) · 13.4 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
/**
* useDatasetFields — metadata-driven catalogs for the DatasetDefaultInspector
* pickers (ADR-0021). Turns the dataset designer's three free-text inputs
* (base object, included relationships, dimension/measure `field`) into
* dropdowns of the real object graph, so an author picks instead of recalling
* exact API names.
*
* • {@link useObjectOptions} — every object (Base object picker).
* • {@link useDatasetFieldCatalog} — the base object's relationships
* (join allowlist) + a flat `field` / `relationship.field` option list,
* fetching each included relationship's target object on demand.
* • {@link useDatasetUsage} — reverse lineage: how many reports /
* dashboards bind this dataset (shown before a breaking edit).
*
* The hooks are defensive (a 404 / transport error resolves to an empty
* catalog so the inspector falls back to free-text entry) and the heavy
* normalization is factored into exported pure helpers for unit testing.
*/
import * as React from 'react';
import { useMetadataClient } from '../useMetadata';
import { readFields } from '../previews/object-fields-io';
/* ─────────────── Types ─────────────── */
export interface DatasetObjectOption {
/** Object API name (snake_case) — what `dataset.object` stores. */
name: string;
/** Human label (falls back to the name). */
label: string;
}
export interface DatasetRelationship {
/** Relationship field name — what goes in `dataset.include`. */
name: string;
/** Human label (falls back to the name). */
label: string;
/** Target object the relationship points at (for `rel.field` paths). */
referenceTo?: string;
}
export interface DatasetFieldOption {
/** Field path: a base field name or `relationship.field`. */
value: string;
/** Human label (falls back to the value). */
label: string;
/** Raw framework field type (e.g. 'text', 'currency', 'lookup'). */
type?: string;
/** Group heading: the base object label, or `rel → target`. */
group: string;
}
export interface DatasetFieldCatalog {
relationships: DatasetRelationship[];
fieldOptions: DatasetFieldOption[];
loading: boolean;
}
/* ─────────────── Pure helpers (unit-tested) ─────────────── */
/** Field types that join to another object (so they're valid `include` entries). */
const RELATIONSHIP_TYPES = new Set(['lookup', 'master_detail', 'masterdetail', 'master-detail']);
/** Resolve a string | i18n-object label down to a display string. */
export function resolveLabel(label: unknown, fallback: string): string {
if (typeof label === 'string' && label) return label;
if (label && typeof label === 'object') {
const def = (label as { default?: unknown }).default;
if (typeof def === 'string' && def) return def;
}
return fallback;
}
/** Read a lookup/master_detail field's target object from its raw def. */
export function resolveReferenceTo(def: Record<string, unknown>): string | undefined {
// Framework lookup/master_detail fields carry the target object in `reference`;
// older / spec shapes use `reference_to` / `referenceTo` / `reference_to_object`.
const raw =
def.reference ?? def.reference_to ?? (def as any).referenceTo ?? (def as any).reference_to_object;
if (typeof raw === 'string' && raw) return raw;
if (Array.isArray(raw) && typeof raw[0] === 'string') return raw[0];
if (raw && typeof raw === 'object') {
const obj = (raw as { object?: unknown }).object;
if (typeof obj === 'string' && obj) return obj;
}
return undefined;
}
/** Map a framework field type onto a dataset dimension type. */
export function fieldTypeToDimensionType(type: string | undefined): string {
switch (type) {
case 'lookup':
case 'master_detail':
case 'masterDetail':
case 'master-detail':
return 'lookup';
case 'date':
case 'datetime':
case 'time':
return 'date';
case 'number':
case 'currency':
case 'percent':
case 'int':
case 'integer':
case 'float':
case 'double':
case 'autonumber':
return 'number';
case 'boolean':
case 'toggle':
return 'boolean';
default:
return 'string';
}
}
export interface NormalizedObject {
label: string;
fields: Array<{ name: string; label: string; type?: string; def: Record<string, unknown> }>;
relationships: DatasetRelationship[];
}
/** Normalize a raw object metadata doc into label + fields + relationships. */
export function normalizeObject(doc: Record<string, unknown> | null | undefined, name: string): NormalizedObject {
if (!doc) return { label: name, fields: [], relationships: [] };
const label = resolveLabel(doc.label, name);
const fields = readFields((doc as any).fields).entries.map((e) => ({
name: e.name,
label: resolveLabel(e.def.label, e.name),
type: typeof e.def.type === 'string' ? (e.def.type as string) : undefined,
def: e.def,
}));
const relationships: DatasetRelationship[] = fields
.filter((f) => f.type && RELATIONSHIP_TYPES.has(f.type.toLowerCase()))
.map((f) => ({ name: f.name, label: f.label, referenceTo: resolveReferenceTo(f.def) }));
return { label, fields, relationships };
}
/**
* Walk a dotted relationship PATH from the base object, returning the object at
* its end (whose fields a `path.field` references) plus each hop's relationship
* label, or undefined if any hop can't be resolved (ADR-0071 multi-hop).
* `objectsByName` holds the already-fetched objects along the chain.
*/
export function resolvePath(
base: NormalizedObject,
path: string,
objectsByName: Record<string, NormalizedObject>,
): { target: NormalizedObject; labels: string[] } | undefined {
let current: NormalizedObject = base;
const labels: string[] = [];
for (const seg of path.split('.')) {
const rel = current.relationships.find((r) => r.name === seg);
if (!rel?.referenceTo) return undefined;
const next = objectsByName[rel.referenceTo];
if (!next) return undefined;
labels.push(rel.label);
current = next;
}
return { target: current, labels };
}
/**
* Build the flat `field` / `relationship[.relationship].field` option list from
* the base object and the (already-fetched) objects along each included PATH.
* Single-hop paths behave exactly as before.
*/
export function buildFieldOptions(
base: NormalizedObject,
include: string[],
objectsByName: Record<string, NormalizedObject>,
): DatasetFieldOption[] {
const options: DatasetFieldOption[] = base.fields.map((f) => ({
value: f.name,
label: f.label,
type: f.type,
group: base.label,
}));
for (const path of include) {
const resolved = resolvePath(base, path, objectsByName);
if (!resolved) continue;
const heading = [...resolved.labels, resolved.target.label].join(' → ');
for (const f of resolved.target.fields) {
options.push({ value: `${path}.${f.name}`, label: f.label, type: f.type, group: heading });
}
}
return options;
}
/** Recursively test whether a metadata doc references `datasetName` via a `dataset` key. */
export function referencesDataset(doc: unknown, datasetName: string): boolean {
if (!doc || typeof doc !== 'object') return false;
if (Array.isArray(doc)) return doc.some((d) => referencesDataset(d, datasetName));
const rec = doc as Record<string, unknown>;
if (typeof rec.dataset === 'string' && rec.dataset === datasetName) return true;
return Object.values(rec).some((v) => v && typeof v === 'object' && referencesDataset(v, datasetName));
}
/* ─────────────── Hooks ─────────────── */
/** Every object as `{ name, label }`, sorted by label. Fetched once. */
export function useObjectOptions(): { options: DatasetObjectOption[]; loading: boolean } {
const client = useMetadataClient();
const [state, setState] = React.useState<{ options: DatasetObjectOption[]; loading: boolean }>({
options: [],
loading: true,
});
React.useEffect(() => {
let cancelled = false;
setState((s) => ({ ...s, loading: true }));
client
.list<Record<string, unknown>>('object')
.then((docs) => {
if (cancelled) return;
const options = (Array.isArray(docs) ? docs : [])
.map((d) => ({ name: typeof d.name === 'string' ? d.name : '', label: resolveLabel(d.label, typeof d.name === 'string' ? d.name : '') }))
.filter((o) => !!o.name)
.sort((a, b) => a.label.localeCompare(b.label));
setState({ options, loading: false });
})
.catch(() => {
if (!cancelled) setState({ options: [], loading: false });
});
return () => {
cancelled = true;
};
}, [client]);
return state;
}
/**
* The base object's relationships (join allowlist) + a flat `field` /
* `relationship.field` option list. Refetches when `object` or the set of
* included relationships changes.
*/
export function useDatasetFieldCatalog(
object: string | undefined,
include: string[],
): DatasetFieldCatalog {
const client = useMetadataClient();
const includeKey = include.join('