glassbrain 0.2.0-alpha.5 → 0.2.0-alpha.7

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.
@@ -1,3 +1,175 @@
1
+ // src/tree.ts
2
+ var object = (x) => !!x && typeof x === "object" && !Array.isArray(x);
3
+ var ref = (x) => typeof x === "string" || typeof x === "number" ? String(x) : void 0;
4
+ var stable = (x) => JSON.stringify(x, function(_key, value) {
5
+ return object(value) ? Object.fromEntries(Object.keys(value).sort().map((k) => [k, value[k]])) : value;
6
+ });
7
+ function treeDeclarations(raw, origin) {
8
+ const declarations = [];
9
+ const rootIds = [];
10
+ const problems = [];
11
+ const stack = (Array.isArray(raw) ? raw : []).map((node, i) => ({ node, path: `nodes[${i}]`, top: true })).reverse();
12
+ if (raw !== void 0 && !Array.isArray(raw)) problems.push("nodes must be an array");
13
+ while (stack.length) {
14
+ const { node, path, top } = stack.pop();
15
+ if (!object(node) || ref(node.id) === void 0) {
16
+ problems.push(`${path}: expected a node with id`);
17
+ continue;
18
+ }
19
+ const id = ref(node.id);
20
+ if (!id.trim()) problems.push(`${path}.id: expected a non-empty identity`);
21
+ if (top) rootIds.push(id);
22
+ const { children, ...fields } = node;
23
+ if ("parent" in node || "order" in node) problems.push(`${path}: parent/order are not supported; nest nodes in children`);
24
+ if ("unordered" in node && typeof node.unordered !== "boolean") problems.push(`${path}.unordered must be a boolean`);
25
+ const declaration = { id, fields: { ...fields, id }, path: `${origin}:${path}` };
26
+ if ("children" in node) {
27
+ if (!Array.isArray(children)) problems.push(`${path}.children must be an array`);
28
+ else {
29
+ declaration.children = children.filter(object).map((n) => ref(n.id)).filter((id2) => id2 !== void 0);
30
+ for (let i = children.length - 1; i >= 0; i--) stack.push({ node: children[i], path: `${path}.children[${i}]`, top: false });
31
+ }
32
+ }
33
+ declarations.push(declaration);
34
+ }
35
+ return { declarations, rootIds, ...problems.length ? { error: problems.slice(0, 20).join("; ") } : {} };
36
+ }
37
+ function treeNodes(declarations = []) {
38
+ const placements = /* @__PURE__ */ new Map();
39
+ for (const d of declarations) d.children?.forEach((id, i) => placements.set(id, { parent: d.id, order: i + 1 }));
40
+ return declarations.map(({ id, fields }) => ({
41
+ id,
42
+ ...placements.get(id),
43
+ label: String(fields.label ?? fields.name ?? id),
44
+ ...typeof fields.kind === "string" ? { kind: fields.kind } : {},
45
+ ...Array.isArray(fields.flags) ? { flags: fields.flags.filter((f) => typeof f === "string") } : {},
46
+ data: fields
47
+ }));
48
+ }
49
+ function composeTrees(input) {
50
+ const slices = [...input].sort((a, b) => a.origin < b.origin ? -1 : a.origin > b.origin ? 1 : 0);
51
+ const errors = [];
52
+ const records = /* @__PURE__ */ new Map();
53
+ const roots = [];
54
+ for (const slice of slices) {
55
+ if (slice.error) errors.push({ origin: slice.origin, code: "schema", message: slice.error });
56
+ if (!slice.declarations && slice.nodes.length) {
57
+ errors.push({ origin: slice.origin, code: "schema", message: "Cannot compose flat runtime slices with native children fragments." });
58
+ continue;
59
+ }
60
+ roots.push(...slice.rootIds ?? []);
61
+ for (const d of slice.declarations ?? []) {
62
+ let r = records.get(d.id);
63
+ if (!r) {
64
+ r = { fields: /* @__PURE__ */ Object.create(null), locations: /* @__PURE__ */ new Map(), origins: [] };
65
+ records.set(d.id, r);
66
+ }
67
+ if (!r.origins.includes(slice.origin)) r.origins.push(slice.origin);
68
+ for (const [field, value] of [...Object.entries(d.fields), ...d.children === void 0 ? [] : [["children", d.children]]]) {
69
+ const previous = field === "children" ? r.children : r.fields[field];
70
+ if (r.locations.has(field) && stable(previous) !== stable(value)) {
71
+ errors.push({
72
+ origin: slice.origin,
73
+ node: d.id,
74
+ code: field === "children" ? "children-conflict" : "field-conflict",
75
+ message: `"${d.id}".${field}: ${r.locations.get(field)} = ${stable(previous)} conflicts with ${d.path} = ${stable(value)}; provide one consistent value (lists are not combined).`
76
+ });
77
+ } else if (!r.locations.has(field)) {
78
+ if (field === "children") r.children = value;
79
+ else r.fields[field] = value;
80
+ r.locations.set(field, d.path);
81
+ }
82
+ }
83
+ }
84
+ }
85
+ const parents = /* @__PURE__ */ new Map();
86
+ const positions = /* @__PURE__ */ new Map();
87
+ for (const [id, r] of records) {
88
+ const seen = /* @__PURE__ */ new Set();
89
+ for (const [i, child] of (r.children ?? []).entries()) {
90
+ if (seen.has(child)) errors.push({ origin: r.origins[0], node: id, code: "children-conflict", message: `${r.locations.get("children")}: "${child}" occurs twice in children of "${id}".` });
91
+ seen.add(child);
92
+ const old = parents.get(child);
93
+ if (old !== void 0 && old !== id) {
94
+ errors.push({ origin: r.origins[0], node: child, code: "parent-error", message: `"${child}" has two parents: "${old}" (${records.get(old).locations.get("children")}) and "${id}" (${r.locations.get("children")}). Keep one placement.` });
95
+ } else {
96
+ parents.set(child, id);
97
+ positions.set(child, i + 1);
98
+ }
99
+ }
100
+ }
101
+ const done = /* @__PURE__ */ new Set();
102
+ for (const id of records.keys()) {
103
+ const chain = [], at = /* @__PURE__ */ new Map();
104
+ let cur = id;
105
+ while (cur !== void 0 && !done.has(cur)) {
106
+ if (at.has(cur)) {
107
+ const loop = [...chain.slice(at.get(cur)), cur];
108
+ errors.push({ origin: records.get(cur).origins[0], node: cur, code: "parent-error", message: `parent cycle: ${loop.join(" \u2192 ")}. Remove one children placement.` });
109
+ parents.delete(cur);
110
+ positions.delete(cur);
111
+ break;
112
+ }
113
+ at.set(cur, chain.length);
114
+ chain.push(cur);
115
+ cur = parents.get(cur);
116
+ }
117
+ chain.forEach((x) => done.add(x));
118
+ }
119
+ const orderedRoots = [.../* @__PURE__ */ new Set([...roots, ...records.keys()])].filter((id) => !parents.has(id));
120
+ const ordered = [], visited = /* @__PURE__ */ new Set(), stack = [...orderedRoots].reverse();
121
+ while (stack.length) {
122
+ const id = stack.pop();
123
+ if (visited.has(id) || !records.has(id)) continue;
124
+ visited.add(id);
125
+ ordered.push(id);
126
+ const kids = records.get(id).children ?? [];
127
+ for (let i = kids.length - 1; i >= 0; i--) if (parents.get(kids[i]) === id) stack.push(kids[i]);
128
+ }
129
+ const rootRanks = new Map(orderedRoots.map((id, i) => [id, i + 1]));
130
+ const nodes = ordered.map((id) => {
131
+ const r = records.get(id);
132
+ const n = treeNodes([{ id, fields: r.fields, path: "" }])[0];
133
+ return { ...n, parent: parents.get(id), order: positions.get(id) ?? rootRanks.get(id), origin: r.origins[0], origins: r.origins };
134
+ });
135
+ return buildModel(nodes, slices.flatMap((s) => s.edges), errors);
136
+ }
137
+ function serializeTree(model) {
138
+ if (model.errors.length || model.duplicateIds?.length) throw new Error("Cannot export a graph with unresolved input conflicts");
139
+ const records = /* @__PURE__ */ new Map();
140
+ const groups = /* @__PURE__ */ new Map();
141
+ for (const n of model.nodes) {
142
+ if (records.has(n.id)) throw new Error(`Duplicate id: ${n.id}`);
143
+ if (n.parent && !model.index.has(n.parent)) throw new Error(`Missing parent: ${n.parent}`);
144
+ const { parent: _parent, order: _order, layer: _layer, children: _children, ...data } = n.data ?? {};
145
+ records.set(n.id, Object.fromEntries(Object.entries({ ...data, id: n.id, label: n.label, kind: n.kind }).filter(([, v]) => v !== void 0)));
146
+ const group = groups.get(n.parent) ?? [];
147
+ group.push(n);
148
+ groups.set(n.parent, group);
149
+ }
150
+ for (const list of groups.values()) list.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity));
151
+ const roots = groups.get(void 0) ?? [];
152
+ const visited = /* @__PURE__ */ new Set(), stack = [...roots];
153
+ while (stack.length) {
154
+ const n = stack.pop();
155
+ if (visited.has(n.id)) throw new Error(`Parent cycle: ${n.id}`);
156
+ visited.add(n.id);
157
+ const kids = groups.get(n.id);
158
+ if (kids?.length) {
159
+ const record = records.get(n.id);
160
+ if (!("unordered" in record) && kids.every((k) => k.order === void 0)) record.unordered = true;
161
+ record.children = kids.map((k) => records.get(k.id));
162
+ stack.push(...kids);
163
+ }
164
+ }
165
+ if (visited.size !== model.nodes.length) throw new Error("Parent cycle: no rooted forest can be exported");
166
+ for (const e of model.edges) if (!records.has(e.source) || !records.has(e.target)) throw new Error(`Dangling edge: ${e.source} \u2192 ${e.target}`);
167
+ return {
168
+ nodes: roots.map((n) => records.get(n.id)),
169
+ edges: model.edges.map((e) => Object.fromEntries(Object.entries({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }).filter(([, v]) => v !== void 0)))
170
+ };
171
+ }
172
+
1
173
  // src/model.ts
2
174
  var EMPTY_MODEL = { nodes: [], edges: [], errors: [], index: /* @__PURE__ */ new Map() };
3
175
  function buildModel(nodes, edges, errors = []) {
@@ -6,6 +178,10 @@ function buildModel(nodes, edges, errors = []) {
6
178
  return { nodes, edges, errors, index };
7
179
  }
8
180
  function mergeSlices(slices) {
181
+ if (slices.some((s) => s.declarations?.length) || slices.every((s) => !s.nodes.length)) return composeTrees(slices);
182
+ return mergeRuntimeSlices(slices);
183
+ }
184
+ function mergeRuntimeSlices(slices) {
9
185
  const byId = /* @__PURE__ */ new Map();
10
186
  const edges = [];
11
187
  const errors = [];
@@ -90,19 +266,6 @@ function originsOf(model) {
90
266
  for (const n of model.nodes) for (const o of originsOfNode(n)) seen.add(o);
91
267
  return [...seen].sort();
92
268
  }
93
- function encodeParent(parent, order) {
94
- if (!parent) return null;
95
- if (order === void 0) return `${parent}@-1`;
96
- if (!Number.isFinite(order) || order <= 0) throw new Error("order must be finite and positive");
97
- const text = String(order);
98
- if (!/[eE]/.test(text)) return `${parent}@${text}`;
99
- const [mantissa, exponent] = text.toLowerCase().split("e");
100
- const [whole, fraction = ""] = mantissa.split(".");
101
- const digits = whole + fraction;
102
- const at = whole.length + Number(exponent);
103
- const decimal = at <= 0 ? `0.${"0".repeat(-at)}${digits}` : at >= digits.length ? digits + "0".repeat(at - digits.length) : `${digits.slice(0, at)}.${digits.slice(at)}`;
104
- return `${parent}@${decimal}`;
105
- }
106
269
 
107
270
  // src/profile.ts
108
271
  function parsePhysical(origin, text) {
@@ -113,30 +276,6 @@ function parsePhysical(origin, text) {
113
276
  return { origin, title: origin, nodes: [], edges: [], error: e instanceof Error ? e.message : String(e) };
114
277
  }
115
278
  if (!raw || typeof raw !== "object" || !("nodes" in raw) && !("edges" in raw)) return null;
116
- const ref = (v) => typeof v === "string" || typeof v === "number" ? String(v) : void 0;
117
- const parentOf = (v) => {
118
- const rawParent = ref(v);
119
- const at = rawParent?.lastIndexOf("@") ?? -1;
120
- const tail = at > 0 ? rawParent.slice(at + 1) : "";
121
- if (!/^(-1|\d+(\.\d+)?)$/.test(tail)) return { parent: rawParent, order: void 0 };
122
- const order = tail === "-1" ? void 0 : Number(tail);
123
- return { parent: rawParent.slice(0, at), order: order !== void 0 && order > 0 ? order : void 0 };
124
- };
125
- const nodes = (Array.isArray(raw.nodes) ? raw.nodes : []).filter((n) => n && typeof n === "object" && ref(n.id) !== void 0).map((n) => {
126
- const { parent, order } = parentOf(n.parent);
127
- return {
128
- id: String(n.id),
129
- label: String(n.label ?? n.name ?? n.id),
130
- kind: typeof n.kind === "string" ? n.kind : void 0,
131
- parent,
132
- order,
133
- layer: typeof n.layer === "string" ? n.layer : void 0,
134
- // Marks carried by the data itself (e.g. a placeholder "with no content yet"). They are data, not derived: when the profile's
135
- // `placeholderFlags` recognizes one, it is drawn as skeleton.
136
- ...Array.isArray(n.flags) ? { flags: n.flags.filter((f) => typeof f === "string") } : {},
137
- data: n
138
- };
139
- });
140
279
  const edges = (Array.isArray(raw.edges) ? raw.edges : []).filter((e) => e && typeof e === "object").map((e) => ({
141
280
  source: String(e.source ?? e.from),
142
281
  target: String(e.target ?? e.to),
@@ -146,23 +285,22 @@ function parsePhysical(origin, text) {
146
285
  // The whole record, like nodes' `data`: fields the library does not know survive a round trip (convert, toPhysical).
147
286
  data: e
148
287
  }));
149
- return { origin, title: String(raw.name ?? raw.title ?? origin), nodes, edges };
288
+ const parsed = treeDeclarations(raw.nodes, origin);
289
+ return { origin, title: String(raw.name ?? raw.title ?? origin), nodes: treeNodes(parsed.declarations), edges, ...parsed };
150
290
  }
151
291
  function toPhysical(model) {
152
- const clean = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== void 0 && v !== ""));
153
- return {
154
- // `layer` is derived, never written: a file that gains it would freeze a view decision into the data.
155
- // `parent` is always written, `null` for a root, and carries the order: `"<id>@<order|-1>"`. `order` is never a field of its own.
156
- nodes: model.nodes.map((n) => {
157
- const { order: _order, layer: _layer, ...data } = n.data ?? {};
158
- return clean({ ...data, id: n.id, label: n.label, kind: n.kind, parent: encodeParent(n.parent, n.order) });
159
- }),
160
- edges: model.edges.map((e) => clean({ ...e.data, source: e.source, target: e.target, kind: e.kind, label: e.label, weight: e.weight }))
161
- };
292
+ return serializeTree(model);
293
+ }
294
+ function toBundle(model, profile = null) {
295
+ const palette = Object.assign(/* @__PURE__ */ Object.create(null), profile?.nodePalette ?? {});
296
+ const wheel = ["#6366f1", "#f59e0b", "#10b981", "#ef4444", "#8b5cf6", "#06b6d4", "#ec4899", "#84cc16"];
297
+ const kinds = [...new Set(model.nodes.map((n) => n.kind).filter((k) => !!k))];
298
+ for (const [i, kind] of kinds.entries()) if (!Object.hasOwn(palette, kind)) palette[kind] = wheel[i % wheel.length];
299
+ return { profile: { ...profile, nodePalette: palette }, ...toPhysical(model) };
162
300
  }
163
301
  var DEFAULT_LAYER = { id: "default", label: "Graph", z: 0, structural: true };
164
302
  function validateStructure(model) {
165
- const out = [];
303
+ const out = model.errors.map((e) => ({ kind: e.code ?? "schema", group: "Invalid graph", level: "error", nodeId: e.node, message: `${e.origin}: ${e.message}` }));
166
304
  const seen = /* @__PURE__ */ new Set();
167
305
  const dup = /* @__PURE__ */ new Set();
168
306
  for (const n of model.nodes) {
@@ -193,6 +331,9 @@ function validateStructure(model) {
193
331
  }
194
332
  return out;
195
333
  }
334
+ function kindTable(...entries) {
335
+ return Object.assign(/* @__PURE__ */ Object.create(null), ...entries);
336
+ }
196
337
  function defineProfile(input) {
197
338
  const layers = input.layers?.length ? input.layers : [DEFAULT_LAYER];
198
339
  const fallbackLayer = layers[0].id;
@@ -202,15 +343,15 @@ function defineProfile(input) {
202
343
  merge: input.merge ?? mergeSlices,
203
344
  layers,
204
345
  layerOf: input.layerOf ?? ((n) => n.layer ?? fallbackLayer),
205
- nodePalette: input.nodePalette ?? {},
206
- edgePalette: input.edgePalette ?? {},
207
- nodeSize: input.nodeSize ?? {},
208
- edgeWidth: input.edgeWidth ?? {},
346
+ nodePalette: kindTable(input.nodePalette),
347
+ edgePalette: kindTable(input.edgePalette),
348
+ nodeSize: kindTable(input.nodeSize),
349
+ edgeWidth: kindTable(input.edgeWidth),
209
350
  placeholderFlags: input.placeholderFlags ?? [],
210
351
  style: input.style ?? [],
211
352
  nodeClass: input.nodeClass ?? (() => ""),
212
353
  edgeClass: input.edgeClass ?? ((e) => e.kind ?? ""),
213
- kindLabels: input.kindLabels ?? {},
354
+ kindLabels: kindTable(input.kindLabels),
214
355
  detail: input.detail ?? {},
215
356
  validate: input.validate ?? (() => []),
216
357
  layoutEdge: input.layoutEdge ?? (() => false),
@@ -254,7 +395,7 @@ var DIFF_FLAG = {
254
395
  merged: "gb-merged"
255
396
  };
256
397
  var KEPT_FLAG = "gb-kept";
257
- var stable = (v, ignore) => {
398
+ var stable2 = (v, ignore) => {
258
399
  const walk = (x) => {
259
400
  if (Array.isArray(x)) return x.map(walk);
260
401
  if (x && typeof x === "object") {
@@ -272,7 +413,7 @@ function changedFields(a, b, ignore) {
272
413
  const ob = b ?? {};
273
414
  const keys = new Set([...Object.keys(oa), ...Object.keys(ob)].filter((k) => !ignore.has(k)));
274
415
  const out = [];
275
- for (const k of keys) if (stable(oa[k], ignore) !== stable(ob[k], ignore)) out.push(k);
416
+ for (const k of keys) if (stable2(oa[k], ignore) !== stable2(ob[k], ignore)) out.push(k);
276
417
  return out.sort();
277
418
  }
278
419
  var EDIT_CAP = 512;
@@ -307,7 +448,7 @@ function editDistance(a, b) {
307
448
  return prev[m] + over;
308
449
  }
309
450
  function changeAmount(a, b, fields, ignore) {
310
- const pick = (n) => fields.map((k) => stable((n.data ?? {})[k], ignore)).join("\0");
451
+ const pick = (n) => fields.map((k) => stable2((n.data ?? {})[k], ignore)).join("\0");
311
452
  return editDistance(pick(a), pick(b)) + editDistance(a.label ?? "", b.label ?? "");
312
453
  }
313
454
  var edgeKey = (e) => `${e.source} ${e.target} ${e.kind ?? ""}`;
@@ -330,8 +471,30 @@ function diffModels(before, after, opts = {}) {
330
471
  const b = afterByKey.get(k);
331
472
  if (b) resolve.set(list[0].id, b.id);
332
473
  }
333
- const ref = (id) => id === void 0 ? void 0 : resolve.get(id) ?? id;
474
+ const ref2 = (id) => id === void 0 ? void 0 : resolve.get(id) ?? id;
334
475
  const consumed = new Set(resolve.keys());
476
+ const reordered = /* @__PURE__ */ new Set();
477
+ if (!ignore.has("position")) {
478
+ const groups = /* @__PURE__ */ new Map();
479
+ for (const a of before.nodes) {
480
+ const id = resolve.get(a.id), b = id ? after.index.get(id) : void 0;
481
+ if (!b || ref2(a.parent) !== b.parent) continue;
482
+ if (a.parent && before.index.get(a.parent)?.data?.unordered === true || b.parent && after.index.get(b.parent)?.data?.unordered === true) continue;
483
+ const p = b.parent;
484
+ const g = groups.get(p) ?? { old: [], next: [] };
485
+ g.old.push(a);
486
+ g.next.push(b);
487
+ groups.set(p, g);
488
+ }
489
+ for (const g of groups.values()) {
490
+ g.old.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity));
491
+ const ranks = new Map(after.nodes.map((n, i) => [n.id, i]));
492
+ g.next.sort((a, b) => (a.order ?? ranks.get(a.id)) - (b.order ?? ranks.get(b.id)));
493
+ g.old.forEach((a, i) => {
494
+ if (resolve.get(a.id) !== g.next[i].id) reordered.add(g.next[i].id);
495
+ });
496
+ }
497
+ }
335
498
  const changes = [];
336
499
  const prevData = /* @__PURE__ */ new Map();
337
500
  const moved = /* @__PURE__ */ new Map();
@@ -343,8 +506,13 @@ function diffModels(before, after, opts = {}) {
343
506
  flag = DIFF_FLAG.added;
344
507
  changes.push({ kind: "added", id: b.id });
345
508
  } else {
346
- const fields = changedFields(a.data, b.data, ignore);
347
- const aParent = ref(a.parent) ?? null;
509
+ const own = (n) => {
510
+ const { children: _children, parent: _parent, order: _order, ...data } = n.data ?? {};
511
+ return { ...data, kind: n.kind };
512
+ };
513
+ const fields = changedFields(own(a), own(b), ignore);
514
+ if (reordered.has(b.id)) fields.push("position");
515
+ const aParent = ref2(a.parent) ?? null;
348
516
  if (aParent !== (b.parent ?? null)) {
349
517
  flag = DIFF_FLAG.moved;
350
518
  changes.push({
@@ -381,7 +549,7 @@ function diffModels(before, after, opts = {}) {
381
549
  const merged = !!to && after.index.has(to);
382
550
  const kind = merged ? "merged" : "removed";
383
551
  changes.push({ kind, id: a.id, pairId: merged ? to : void 0 });
384
- const parent = ref(a.parent);
552
+ const parent = ref2(a.parent);
385
553
  nodes.push({
386
554
  ...withFlag(a, DIFF_FLAG[kind]),
387
555
  parent: parent && (unionIds.has(parent) || !consumed.has(a.parent)) ? parent : void 0
@@ -391,7 +559,7 @@ function diffModels(before, after, opts = {}) {
391
559
  const afterEdges = new Map(after.edges.map((e) => [edgeKey(e), e]));
392
560
  const beforeEdges = new Map(
393
561
  before.edges.map((e) => {
394
- const r = { ...e, source: ref(e.source), target: ref(e.target) };
562
+ const r = { ...e, source: ref2(e.source), target: ref2(e.target) };
395
563
  return [edgeKey(r), r];
396
564
  })
397
565
  );
@@ -435,22 +603,22 @@ function unionSides(d) {
435
603
  const afterEdges = d.model.edges.filter(
436
604
  (e) => !has(e, DIFF_FLAG.removed) && aIds.has(e.source) && aIds.has(e.target)
437
605
  );
438
- const ref = (id) => id === void 0 ? void 0 : d.resolved.get(id) ?? id;
606
+ const ref2 = (id) => id === void 0 ? void 0 : d.resolved.get(id) ?? id;
439
607
  const beforeNodes = d.before.nodes.map((n) => {
440
- const id = ref(n.id);
608
+ const id = ref2(n.id);
441
609
  const now = d.model.index.get(id);
442
- const relinked = now && (now.parent ?? null) !== (ref(n.parent) ?? null);
610
+ const relinked = now && (now.parent ?? null) !== (ref2(n.parent) ?? null);
443
611
  return {
444
612
  ...n,
445
613
  id,
446
- parent: ref(n.parent),
614
+ parent: ref2(n.parent),
447
615
  flags: now?.flags ?? n.flags,
448
616
  ...relinked ? { prevParent: now.parent ?? null } : {}
449
617
  };
450
618
  });
451
619
  const bIds = new Set(beforeNodes.map((n) => n.id));
452
620
  const afterKeys = new Set(afterEdges.map(edgeKey));
453
- const beforeEdges = d.before.edges.map((e) => ({ ...e, source: ref(e.source), target: ref(e.target) })).filter((e) => bIds.has(e.source) && bIds.has(e.target)).map((e) => withFlag(e, afterKeys.has(edgeKey(e)) ? KEPT_FLAG : DIFF_FLAG.removed));
621
+ const beforeEdges = d.before.edges.map((e) => ({ ...e, source: ref2(e.source), target: ref2(e.target) })).filter((e) => bIds.has(e.source) && bIds.has(e.target)).map((e) => withFlag(e, afterKeys.has(edgeKey(e)) ? KEPT_FLAG : DIFF_FLAG.removed));
454
622
  return { before: buildModel(beforeNodes, beforeEdges), after: buildModel(afterNodes, afterEdges) };
455
623
  }
456
624
  var STEP_FLAG = { added: "gb-step-added", removed: "gb-step-removed" };
@@ -463,7 +631,7 @@ function stepUnion(before, after, key = (n) => n.id) {
463
631
  const b = afterByKey.get(key(a));
464
632
  if (b) resolved.set(a.id, b.id);
465
633
  }
466
- const ref = (id) => id === void 0 ? void 0 : resolved.get(id) ?? id;
634
+ const ref2 = (id) => id === void 0 ? void 0 : resolved.get(id) ?? id;
467
635
  const paired = new Set(resolved.values());
468
636
  const changes = [];
469
637
  const nodes = [];
@@ -475,12 +643,12 @@ function stepUnion(before, after, key = (n) => n.id) {
475
643
  for (const a of before.nodes) {
476
644
  if (resolved.has(a.id)) continue;
477
645
  changes.push({ kind: "removed", id: a.id });
478
- nodes.push(withFlag({ ...a, parent: ref(a.parent) }, STEP_FLAG.removed));
646
+ nodes.push(withFlag({ ...a, parent: ref2(a.parent) }, STEP_FLAG.removed));
479
647
  }
480
648
  const ids = new Set(nodes.map((n) => n.id));
481
649
  const afterEdges = new Map(after.edges.map((e) => [edgeKey(e), e]));
482
650
  const beforeEdges = new Map(before.edges.map((e) => {
483
- const r = { ...e, source: ref(e.source), target: ref(e.target) };
651
+ const r = { ...e, source: ref2(e.source), target: ref2(e.target) };
484
652
  return [edgeKey(r), r];
485
653
  }));
486
654
  const edges = [];
@@ -617,7 +785,7 @@ function buildElements(model, profile, opts = {}) {
617
785
  kind: n.kind ?? "",
618
786
  layer,
619
787
  origin: n.origin ?? null,
620
- order: n.order ?? null,
788
+ order: n.parent && model.index.get(n.parent)?.data?.unordered === true ? null : n.order ?? null,
621
789
  // Parentage for the layout's order pass. A separate key, not `parent`: cytoscape treats `data.parent` as a compound.
622
790
  parentId: effParent ?? null,
623
791
  share: shareOf(n.id),
@@ -1152,7 +1320,7 @@ var GK_CSS = `
1152
1320
  .gb-root { display:flex; height:100%; min-height:0; font-family: var(--gb-font, ui-sans-serif, system-ui, sans-serif);
1153
1321
  color: var(--gb-text, var(--gb-default-text,#1f2937)); position:relative; container-type:inline-size; container-name:gk; }
1154
1322
  .gb-stage { flex:1; min-width:0; position:relative; container-type:inline-size; container-name:gks; }
1155
- .gb-canvas { position:absolute; inset:0; }
1323
+ .gb-scene, .gb-canvas { position:absolute; inset:0; }
1156
1324
  /* The node text layer: cytoscape's canvases are z-index 1\u20133; this one sits above them and below the toolbar.
1157
1325
  canvas is a replaced element; inset alone is not enough, it needs an explicit 100%. */
1158
1326
  .gb-labels { position:absolute; left:0; top:0; pointer-events:none; z-index:4; }
@@ -1179,7 +1347,10 @@ var GK_CSS = `
1179
1347
  stroke-linejoin:round; vector-effect:non-scaling-stroke; }
1180
1348
  /* The in-column truncation notice sits one line above the column name. */
1181
1349
  .gb-pane .gb-diff-trunc { top:auto; left:auto; bottom:44px; right:12px; }
1182
- .gb-planes, .gb-plane-labels { position:absolute; inset:0; width:100%; height:100%;
1350
+ .gb-glass-plane { position:absolute; pointer-events:none; }
1351
+ .gb-glass-surface { position:absolute; inset:0; backdrop-filter:blur(18px) saturate(160%); -webkit-backdrop-filter:blur(18px) saturate(160%); }
1352
+ .gb-glass-rim { position:absolute; inset:0; overflow:visible; }
1353
+ .gb-glass-planes, .gb-plane-labels { position:absolute; inset:0; width:100%; height:100%;
1183
1354
  pointer-events:none; overflow:hidden; }
1184
1355
  /* svg is a replaced element: inset:0 alone falls back to its intrinsic 300x150, so it needs an explicit 100%. */
1185
1356
  /* Plates are drawn **under** the graph (cytoscape's canvases are z-index 1\u20133); layer names **above**,
@@ -1200,7 +1371,7 @@ var GK_CSS = `
1200
1371
  * --gb-r-pop layers that pop out (dropdowns, panels, cards on overlays)
1201
1372
  * --gb-r-in-face / --gb-r-in-pop controls inside a face: outer radius minus padding (concentric), 10\u22123, 12\u22126
1202
1373
  * --gb-r-chip small inline tags (keycaps, kind tags, focus tags) */
1203
- .gb-field, .gb-segm, .gb-icon-btn, .gb-group, .gb-pill, .gb-note, .gb-chip, .gb-legend {
1374
+ .gb-field, .gb-segm, .gb-icon-btn, .gb-group, .gb-note, .gb-chip, .gb-legend {
1204
1375
  background: var(--gb-panel, var(--gb-default-panel,rgba(255,255,255,.86))); border:1px solid var(--gb-border,var(--gb-default-border,#e2e8f0));
1205
1376
  box-shadow: 0 1px 2px rgba(15,23,42,.05), 0 6px 18px -6px rgba(15,23,42,.12);
1206
1377
  -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); border-radius:var(--gb-r-face,10px); }
@@ -1318,15 +1489,17 @@ var GK_CSS = `
1318
1489
  border-radius:var(--gb-r-in-pop,6px); background: var(--gb-panel2,var(--gb-default-panel2,#fff)); color: var(--gb-text,var(--gb-default-text,#1f2937)); font: inherit; font-size:12.5px; }
1319
1490
 
1320
1491
  /* Bottom right: the camera. */
1321
- .gb-dock { position:absolute; right:12px; bottom:12px; z-index:10; display:flex; align-items:flex-end; gap:8px; }
1492
+ .gb-footer { position:absolute; inset:12px; z-index:10; pointer-events:none;
1493
+ display:flex; align-items:flex-end; gap:8px; }
1494
+ .gb-dock { display:flex; align-items:flex-end; gap:8px; flex:none; margin-left:auto; }
1495
+ .gb-dock > * { pointer-events:auto; }
1322
1496
  .gb-group { display:inline-flex; overflow:hidden; }
1323
1497
  .gb-group > button { display:grid; place-items:center; width:34px; height:34px; padding:0; border:0; background:transparent;
1324
1498
  color: var(--gb-muted,var(--gb-default-muted,#64748b)); transition: color .15s, background-color .15s; }
1325
1499
  .gb-group > button:hover { color: var(--gb-text,var(--gb-default-text,#1f2937)); background: var(--gb-tint,var(--gb-default-tint,#f1f5f9)); }
1326
1500
  .gb-group > button:active { background: var(--gb-active,var(--gb-default-active,#e0f2fe)); }
1327
1501
  .gb-group > button + button { border-left:1px solid var(--gb-border,var(--gb-default-border,#e2e8f0)); }
1328
- .gb-pill { display:inline-flex; align-items:center; gap:6px; height:34px; padding:0 11px; font-size:12.5px; }
1329
- .gb-issues { width:320px; max-height:340px; overflow:auto; padding-bottom:6px; }
1502
+ .gb-issues { width:min(440px, calc(100vw - 24px)); max-height:min(520px, 70vh); overflow:auto; padding-bottom:6px; }
1330
1503
  .gb-issues details { border-top:1px solid var(--gb-border,var(--gb-default-border,#e2e8f0)); }
1331
1504
  .gb-issues summary { display:flex; align-items:center; gap:8px; padding:7px 12px; cursor:pointer; font-size:12.5px;
1332
1505
  color: var(--gb-text,var(--gb-default-text,#1f2937)); list-style:none; }
@@ -1337,12 +1510,21 @@ var GK_CSS = `
1337
1510
  .gb-issues summary:hover { background: var(--gb-tint,var(--gb-default-tint,#f1f5f9)); }
1338
1511
  .gb-issues summary span { flex:1; }
1339
1512
  .gb-issues summary b { font-weight:500; font-variant-numeric: tabular-nums; color: var(--gb-muted,var(--gb-default-muted,#64748b)); }
1340
- .gb-issues summary.is-err b { color: var(--gb-err,var(--gb-default-err,#dc2626)); }
1341
1513
  .gb-issues ul { margin:0; padding:0 0 6px; list-style:none; font-size:11.5px; line-height:1.5; color: var(--gb-muted,var(--gb-default-muted,#64748b)); }
1342
1514
  .gb-issues li { overflow-wrap:break-word; padding:3px 12px 3px 25px; }
1343
- .gb-issues li.is-link { cursor:pointer; }
1344
- .gb-issues li.is-link:hover { color: var(--gb-text,var(--gb-default-text,#1f2937)); background: var(--gb-tint,var(--gb-default-tint,#f1f5f9)); }
1345
- .gb-issues li.gb-more { font-style:italic; }
1515
+ .gb-check-button { position:relative; }
1516
+ .gb-check-button .gb-ico { transform:translate(-2px,2px); }
1517
+ .gb-check-badge { position:absolute; top:1px; right:1px; padding:0 2px; border-radius:4px;
1518
+ background:var(--gb-panel2,var(--gb-default-panel2,#fff));
1519
+ font-size:10px; font-weight:700; line-height:12px; font-variant-numeric:tabular-nums; }
1520
+ .gb-check-error { color:var(--gb-err, #dc2626); }
1521
+ .gb-check-warn { color:var(--gb-warn, #b45309); }
1522
+ .gb-check-info { color:var(--gb-muted, #64748b); }
1523
+ .gb-issue-target { display:block; border:0; background:none; color:inherit; padding:0; font:inherit; text-align:left; cursor:pointer; }
1524
+ .gb-issue-target:hover { text-decoration:underline; }
1525
+ .gb-issue-where { display:block; opacity:.75; margin-top:3px; }
1526
+ .gb-issue-fix { white-space:pre-wrap; border-left:2px solid var(--gb-border, #e2e8f0); padding-left:8px; margin:6px 0 10px; }
1527
+
1346
1528
  .gb-err { color: var(--gb-err,var(--gb-default-err,#dc2626)); border-color: var(--gb-err-border,var(--gb-default-err-border,#fca5a5)); background: var(--gb-err-bg,var(--gb-default-err-bg,#fef2f2)); }
1347
1529
  .gb-hint { color: var(--gb-muted,var(--gb-default-muted,#64748b)); }
1348
1530
  .gb-hint .gb-ico { color: var(--gb-warn,var(--gb-default-warn,#b45309)); }
@@ -1352,9 +1534,8 @@ var GK_CSS = `
1352
1534
  .gb-search, .gb-thumb { transition:none; }
1353
1535
  .gb-drop, .gb-panel { animation:none; }
1354
1536
  }
1355
- /* The caption goes **bottom left**: top left is tools, bottom right is the camera. The right side leaves room for the camera group so they do not collide on narrow screens. */
1356
- .gb-bl { position:absolute; top:12px; bottom:12px; left:12px; z-index:10; max-width:calc(100% - 180px);
1357
- display:flex; flex-direction:column; justify-content:flex-end; align-items:flex-start; gap:8px; pointer-events:none; }
1537
+ /* Share the available width with the dock. Stretch vertically to give the legend its height cap. */
1538
+ .gb-bl { min-width:0; align-self:stretch; display:flex; flex-direction:column; justify-content:flex-end; align-items:flex-start; gap:8px; }
1358
1539
  .gb-bl > * { pointer-events:auto; }
1359
1540
  .gb-note { font-size:11px; color: var(--gb-muted,var(--gb-default-muted,#64748b)); padding:4px 8px; display:flex; gap:8px; align-items:center; }
1360
1541
  .gb-warn { color: var(--gb-warn,var(--gb-default-warn,#b45309)); border-color: var(--gb-warn-border,var(--gb-default-warn-border,#fcd34d)); background: var(--gb-warn-bg,var(--gb-default-warn-bg,#fffbeb)); }
@@ -1514,10 +1695,9 @@ var GK_CSS = `
1514
1695
  .gb-bar.has-layers .gb-search { flex:1 1 100%; width:auto; max-width:none; min-width:0; }
1515
1696
  .gb-bar.has-layers .gb-segm { flex:1 1 0; }
1516
1697
  .gb-bar.has-layers .gb-menu { flex:none; }
1517
- /* Without layers one row is enough; the search can shrink, but never to just the icon. */
1518
- .gb-bar:not(.has-layers) .gb-search { flex:1 1 auto; width:auto; min-width:160px; }
1519
- /* The camera becomes a compact vertical stack; the legend gets the freed horizontal room. */
1520
- .gb-bl { max-width:calc(100% - 60px); }
1698
+ /* Folded layers and settings take only their button widths; search fills the rest. */
1699
+ .gb-bar:not(.has-layers) .gb-search { flex:1 1 9rem; width:auto; min-width:min(9rem,100%); }
1700
+ .gb-layers.is-collapsed .gb-layer-track { display:none; }
1521
1701
  .gb-dock { flex-direction:column; align-items:flex-end; }
1522
1702
  .gb-dock .gb-group { flex-direction:column; }
1523
1703
  .gb-dock .gb-group > button + button { border-left:0; border-top:1px solid var(--gb-border,var(--gb-default-border,#e2e8f0)); }
@@ -1656,8 +1836,12 @@ function checkEdit(model, op) {
1656
1836
  if (order != null && (!Number.isFinite(order) || order <= 0)) return "order-invalid";
1657
1837
  const current = model.index.get(op.id);
1658
1838
  const parent = op.set.parent !== void 0 ? op.set.parent : current?.parent;
1839
+ if (op.set.before != null) {
1840
+ const sibling = model.index.get(op.set.before);
1841
+ if (!sibling || sibling.id === op.id || (sibling.parent ?? null) !== (parent ?? null)) return "invalid-position";
1842
+ }
1659
1843
  const value = order === null ? void 0 : order ?? current?.order;
1660
- if (parent && value !== void 0 && model.nodes.some((n) => n.id !== op.id && n.parent === parent && n.order === value)) return "order-invalid";
1844
+ if (op.set.before === void 0 && (op.set.parent === void 0 || order !== void 0) && parent && value !== void 0 && model.nodes.some((n) => n.id !== op.id && n.parent === parent && n.order === value)) return "order-invalid";
1661
1845
  }
1662
1846
  switch (op.op) {
1663
1847
  case "addNode":
@@ -1689,7 +1873,7 @@ function applyEdit(model, op, profile) {
1689
1873
  function apply(model, op, profile) {
1690
1874
  const layerOf = (n) => profile ? profile.layerOf(n) : n.layer;
1691
1875
  const fields = (n, set) => {
1692
- const { parent, order, ...rest } = set;
1876
+ const { parent, order, before: _before, ...rest } = set;
1693
1877
  const next = { ...n, ...rest };
1694
1878
  if (parent !== void 0) {
1695
1879
  if (parent) {
@@ -1702,6 +1886,18 @@ function apply(model, op, profile) {
1702
1886
  next.layer = layerOf(next);
1703
1887
  return next;
1704
1888
  };
1889
+ const place = (nodes) => {
1890
+ if (op.op !== "addNode" && op.op !== "updateNode") return nodes;
1891
+ const old = model.index.get(op.id);
1892
+ const changedParent = op.op === "addNode" || "parent" in op.set && (old?.parent ?? null) !== op.set.parent;
1893
+ if (!("before" in op.set) && (!changedParent || typeof op.set.order === "number")) return nodes;
1894
+ const moved = nodes.find((n) => n.id === op.id);
1895
+ const siblings = nodes.filter((n) => n.id !== moved.id && n.parent === moved.parent).sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity));
1896
+ const at = op.set.before ? siblings.findIndex((n) => n.id === op.set.before) : siblings.length;
1897
+ siblings.splice(at < 0 ? siblings.length : at, 0, moved);
1898
+ const ranks = new Map(siblings.map((n, i) => [n.id, i + 1]));
1899
+ return nodes.map((n) => ranks.has(n.id) ? { ...n, order: ranks.get(n.id) } : n);
1900
+ };
1705
1901
  switch (op.op) {
1706
1902
  case "addNode": {
1707
1903
  const dad = op.set.parent ? model.index.get(op.set.parent) : void 0;
@@ -1712,11 +1908,11 @@ function apply(model, op, profile) {
1712
1908
  layer: dad?.layer,
1713
1909
  ...origin ? { origin, origins: [origin] } : {}
1714
1910
  };
1715
- return buildModel([...model.nodes, fields(seed, op.set)], model.edges, model.errors);
1911
+ return buildModel(place([...model.nodes, fields(seed, op.set)]), model.edges, model.errors);
1716
1912
  }
1717
1913
  case "updateNode":
1718
1914
  return buildModel(
1719
- model.nodes.map((n) => n.id === op.id ? fields(n, op.set) : n),
1915
+ place(model.nodes.map((n) => n.id === op.id ? fields(n, op.set) : n)),
1720
1916
  model.edges,
1721
1917
  model.errors
1722
1918
  );
@@ -1753,25 +1949,7 @@ function applyEdits(model, ops, profile) {
1753
1949
  }
1754
1950
  return { model: m, skipped };
1755
1951
  }
1756
- function checkNativeEdit(model, op) {
1757
- if (op.op === "addNode" && !/^[^\s@]{1,80}$/.test(op.id)) return "id-format";
1758
- const basic = checkEdit(model, op);
1759
- if (basic) return basic;
1760
- const next = apply(model, op);
1761
- const oldRoots = model.nodes.filter((n) => !n.parent).length;
1762
- if (next.nodes.filter((n) => !n.parent).length > Math.max(1, oldRoots)) return "multiple-roots";
1763
- const siblings = /* @__PURE__ */ new Map();
1764
- for (const n of next.nodes) if (n.parent) {
1765
- const xs = siblings.get(n.parent) ?? [];
1766
- xs.push(n);
1767
- siblings.set(n.parent, xs);
1768
- }
1769
- for (const xs of siblings.values()) {
1770
- const count = xs.filter((n) => n.order !== void 0).length;
1771
- if (count && count !== xs.length) return "order-mixed";
1772
- }
1773
- return null;
1774
- }
1952
+ var checkNativeEdit = checkEdit;
1775
1953
 
1776
1954
  // src/animate.ts
1777
1955
  var easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
@@ -2332,10 +2510,11 @@ export {
2332
2510
  originsOfNode,
2333
2511
  indexModel,
2334
2512
  originsOf,
2335
- encodeParent,
2336
2513
  parsePhysical,
2337
2514
  toPhysical,
2515
+ toBundle,
2338
2516
  validateStructure,
2517
+ kindTable,
2339
2518
  defineProfile,
2340
2519
  defaultProfile,
2341
2520
  parseSources,