@seatmap-fyi/map-domain 0.1.0-alpha.1 → 0.1.0-alpha.3

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.
@@ -0,0 +1,46 @@
1
+ import { z } from "zod";
2
+ import type { PhysicalDocumentV1, UUID } from "./types.js";
3
+ export declare const mapEditorStateSchema: z.ZodObject<{
4
+ version: z.ZodLiteral<1>;
5
+ lockedIds: z.ZodArray<z.ZodString>;
6
+ hiddenIds: z.ZodArray<z.ZodString>;
7
+ }, z.core.$strict>;
8
+ export type MapEditorState = z.infer<typeof mapEditorStateSchema>;
9
+ export declare const emptyMapEditorState: MapEditorState;
10
+ type EditorNode = {
11
+ id: UUID;
12
+ parentId?: UUID | null;
13
+ sectionId?: UUID | null;
14
+ };
15
+ export declare class MapEditorPolicy {
16
+ private readonly document;
17
+ readonly nodes: Map<string, EditorNode>;
18
+ readonly rows: Set<string>;
19
+ private readonly parents;
20
+ private readonly children;
21
+ private readonly locked;
22
+ private readonly hidden;
23
+ private readonly lockOwners;
24
+ private readonly hiddenOwners;
25
+ private readonly protectedContainers;
26
+ constructor(document: PhysicalDocumentV1, state: MapEditorState);
27
+ canLock(id: UUID): boolean;
28
+ canHide(id: UUID): boolean;
29
+ childIds(id: UUID): readonly UUID[];
30
+ private parentIds;
31
+ private owner;
32
+ lockOwner(id: UUID): UUID | undefined;
33
+ hiddenOwner(id: UUID): UUID | undefined;
34
+ inheritedLockOwner(id: UUID): UUID | undefined;
35
+ inheritedHiddenOwner(id: UUID): UUID | undefined;
36
+ protectedOwner(id: UUID): UUID | undefined;
37
+ }
38
+ export declare function mapEditorPolicy(document: PhysicalDocumentV1, state: MapEditorState): MapEditorPolicy;
39
+ export declare function canonicalEditorState(state: MapEditorState): MapEditorState;
40
+ export declare function parseMapEditorState(document: PhysicalDocumentV1, input: unknown): MapEditorState;
41
+ export declare function pruneMapEditorState(document: PhysicalDocumentV1, state: MapEditorState): MapEditorState;
42
+ export declare function serializedEditorState(state: MapEditorState): string | undefined;
43
+ export declare function remapMapEditorState(state: MapEditorState, identities: ReadonlyMap<UUID, UUID>): MapEditorState;
44
+ /** Compare committed layout only; display names, numbering, paints and labels remain editable. */
45
+ export declare function protectedLayoutChanges(before: PhysicalDocumentV1, after: PhysicalDocumentV1, state: MapEditorState): UUID[];
46
+ export {};
@@ -0,0 +1,255 @@
1
+ import { z } from "zod";
2
+ import { documentCatalog } from "./catalog.js";
3
+ import { worldMatrices } from "./geometry/geometry.js";
4
+ import { uuidSchema } from "./schema.js";
5
+ export const mapEditorStateSchema = z.strictObject({
6
+ version: z.literal(1),
7
+ lockedIds: z.array(uuidSchema).max(100_000),
8
+ hiddenIds: z.array(uuidSchema).max(100_000),
9
+ });
10
+ export const emptyMapEditorState = {
11
+ version: 1,
12
+ lockedIds: [],
13
+ hiddenIds: [],
14
+ };
15
+ const policies = new WeakMap();
16
+ export class MapEditorPolicy {
17
+ document;
18
+ nodes = new Map();
19
+ rows = new Set();
20
+ parents = new Map();
21
+ children = new Map();
22
+ locked;
23
+ hidden;
24
+ lockOwners = new Map();
25
+ hiddenOwners = new Map();
26
+ protectedContainers = new Map();
27
+ constructor(document, state) {
28
+ this.document = document;
29
+ this.locked = new Set(state.lockedIds);
30
+ this.hidden = new Set(state.hiddenIds);
31
+ for (const node of [
32
+ ...document.collections,
33
+ ...document.sections,
34
+ ...document.seatingGroups,
35
+ ...document.areas,
36
+ ...document.decorations,
37
+ ]) {
38
+ this.nodes.set(node.id, node);
39
+ const parents = [
40
+ "parentId" in node ? node.parentId : null,
41
+ "sectionId" in node ? node.sectionId : null,
42
+ ].filter((id) => !!id);
43
+ this.parents.set(node.id, parents);
44
+ }
45
+ for (const group of document.seatingGroups) {
46
+ if (!("rows" in group))
47
+ continue;
48
+ for (const row of group.rows) {
49
+ this.nodes.set(row.id, row);
50
+ this.rows.add(row.id);
51
+ this.parents.set(row.id, [group.id]);
52
+ }
53
+ }
54
+ for (const [id, parents] of this.parents) {
55
+ for (const parent of parents) {
56
+ const children = this.children.get(parent) ?? [];
57
+ children.push(id);
58
+ this.children.set(parent, children);
59
+ }
60
+ }
61
+ for (const id of this.locked) {
62
+ const pending = [id], seen = new Set();
63
+ while (pending.length) {
64
+ const parent = pending.pop();
65
+ if (!parent || seen.has(parent))
66
+ continue;
67
+ seen.add(parent);
68
+ this.protectedContainers.set(parent, id);
69
+ pending.push(...(this.parents.get(parent) ?? []));
70
+ }
71
+ }
72
+ }
73
+ canLock(id) {
74
+ return this.nodes.has(id) && !this.rows.has(id);
75
+ }
76
+ canHide(id) {
77
+ return this.nodes.has(id);
78
+ }
79
+ childIds(id) {
80
+ return this.children.get(id) ?? [];
81
+ }
82
+ parentIds(id) {
83
+ const parents = this.parents.get(id);
84
+ if (parents)
85
+ return parents;
86
+ const seat = documentCatalog(this.document).seats.get(id);
87
+ return seat ? [seat.seat.rowId ?? seat.group.id] : [];
88
+ }
89
+ owner(id, flags, cache, visiting = new Set()) {
90
+ if (!flags.size || visiting.has(id))
91
+ return undefined;
92
+ if (cache.has(id))
93
+ return cache.get(id);
94
+ visiting.add(id);
95
+ let owner = flags.has(id) ? id : undefined;
96
+ for (const parent of this.parentIds(id)) {
97
+ owner ??= this.owner(parent, flags, cache, visiting);
98
+ }
99
+ visiting.delete(id);
100
+ cache.set(id, owner);
101
+ return owner;
102
+ }
103
+ lockOwner(id) {
104
+ return this.owner(id, this.locked, this.lockOwners);
105
+ }
106
+ hiddenOwner(id) {
107
+ return this.owner(id, this.hidden, this.hiddenOwners);
108
+ }
109
+ inheritedLockOwner(id) {
110
+ return this.parentIds(id)
111
+ .map((parent) => this.lockOwner(parent))
112
+ .find((owner) => owner !== undefined);
113
+ }
114
+ inheritedHiddenOwner(id) {
115
+ return this.parentIds(id)
116
+ .map((parent) => this.hiddenOwner(parent))
117
+ .find((owner) => owner !== undefined);
118
+ }
119
+ protectedOwner(id) {
120
+ return this.lockOwner(id) ?? this.protectedContainers.get(id);
121
+ }
122
+ }
123
+ export function mapEditorPolicy(document, state) {
124
+ let states = policies.get(document);
125
+ if (!states) {
126
+ states = new WeakMap();
127
+ policies.set(document, states);
128
+ }
129
+ let policy = states.get(state);
130
+ if (!policy) {
131
+ policy = new MapEditorPolicy(document, state);
132
+ states.set(state, policy);
133
+ }
134
+ return policy;
135
+ }
136
+ export function canonicalEditorState(state) {
137
+ return {
138
+ version: 1,
139
+ lockedIds: [...new Set(state.lockedIds)].sort(),
140
+ hiddenIds: [...new Set(state.hiddenIds)].sort(),
141
+ };
142
+ }
143
+ export function parseMapEditorState(document, input) {
144
+ if (input === undefined)
145
+ return emptyMapEditorState;
146
+ const state = mapEditorStateSchema.parse(input);
147
+ const policy = mapEditorPolicy(document, state);
148
+ return canonicalEditorState(mapEditorStateSchema
149
+ .superRefine((value, context) => {
150
+ for (const [key, ids] of [
151
+ ["lockedIds", value.lockedIds],
152
+ ["hiddenIds", value.hiddenIds],
153
+ ]) {
154
+ ids.forEach((id, index) => {
155
+ if (!(key === "lockedIds" ? policy.canLock(id) : policy.canHide(id))) {
156
+ context.addIssue({
157
+ code: "custom",
158
+ path: [key, index],
159
+ message: "Editor state refers to an unsupported or missing object.",
160
+ });
161
+ }
162
+ });
163
+ }
164
+ })
165
+ .parse(state));
166
+ }
167
+ export function pruneMapEditorState(document, state) {
168
+ if (!state.lockedIds.length && !state.hiddenIds.length)
169
+ return emptyMapEditorState;
170
+ const policy = mapEditorPolicy(document, state);
171
+ const next = canonicalEditorState({
172
+ version: 1,
173
+ lockedIds: state.lockedIds.filter((id) => policy.canLock(id)),
174
+ hiddenIds: state.hiddenIds.filter((id) => policy.canHide(id)),
175
+ });
176
+ return JSON.stringify(next) === JSON.stringify(state) ? state : next;
177
+ }
178
+ export function serializedEditorState(state) {
179
+ return state.lockedIds.length || state.hiddenIds.length
180
+ ? JSON.stringify(canonicalEditorState(state))
181
+ : undefined;
182
+ }
183
+ export function remapMapEditorState(state, identities) {
184
+ const remap = (ids) => ids.flatMap((id) => {
185
+ const next = identities.get(id);
186
+ return next ? [next] : [];
187
+ });
188
+ return canonicalEditorState({
189
+ version: 1,
190
+ lockedIds: remap(state.lockedIds),
191
+ hiddenIds: remap(state.hiddenIds),
192
+ });
193
+ }
194
+ const appearanceFields = new Set([
195
+ "name",
196
+ "label",
197
+ "labels",
198
+ "labelOverride",
199
+ "seatSequenceOverride",
200
+ "attributes",
201
+ "seatLabelStyle",
202
+ "labelStyle",
203
+ "rowStyle",
204
+ "style",
205
+ "displayLabel",
206
+ "labelPlacement",
207
+ "text",
208
+ "fontSizeM",
209
+ "align",
210
+ "opacity",
211
+ "assetId",
212
+ "iconId",
213
+ "zIndex",
214
+ "capacity",
215
+ ]);
216
+ function layoutValue(value) {
217
+ if (Array.isArray(value))
218
+ return value.map(layoutValue);
219
+ if (value && typeof value === "object")
220
+ return Object.fromEntries(Object.entries(value)
221
+ .filter(([key]) => !appearanceFields.has(key))
222
+ .map(([key, child]) => [key, layoutValue(child)]));
223
+ return value;
224
+ }
225
+ /** Compare committed layout only; display names, numbering, paints and labels remain editable. */
226
+ export function protectedLayoutChanges(before, after, state) {
227
+ if (!state.lockedIds.length)
228
+ return [];
229
+ const previous = mapEditorPolicy(before, state), next = mapEditorPolicy(after, state);
230
+ const beforeMatrices = worldMatrices(before), afterMatrices = worldMatrices(after);
231
+ const changed = new Set();
232
+ for (const [id, node] of previous.nodes) {
233
+ const owner = previous.lockOwner(id);
234
+ if (!owner)
235
+ continue;
236
+ const candidate = next.nodes.get(id);
237
+ const matrixId = previous.rows.has(id)
238
+ ? (documentCatalog(before).rows.get(id)?.id ?? id)
239
+ : id;
240
+ const previousValue = {
241
+ layout: layoutValue(node),
242
+ matrix: beforeMatrices.get(matrixId),
243
+ children: [...previous.childIds(id)].sort(),
244
+ };
245
+ const nextValue = {
246
+ layout: layoutValue(candidate),
247
+ matrix: afterMatrices.get(matrixId),
248
+ children: [...next.childIds(id)].sort(),
249
+ };
250
+ if (!candidate ||
251
+ JSON.stringify(previousValue) !== JSON.stringify(nextValue))
252
+ changed.add(owner);
253
+ }
254
+ return [...changed];
255
+ }
@@ -2,4 +2,5 @@ import type { PhysicalDocumentV1 } from "./types.js";
2
2
  export declare function remapDocumentSteps(source: PhysicalDocumentV1, name: string): Generator<number, {
3
3
  document: PhysicalDocumentV1;
4
4
  warnings: string[];
5
+ identities: ReadonlyMap<string, string>;
5
6
  }>;
package/dist/identity.js CHANGED
@@ -57,5 +57,9 @@ export function* remapDocumentSteps(source, name) {
57
57
  if (parsed.status !== DocumentParseStatus.Accepted)
58
58
  throw new Error("Identity remapping produced invalid physical structure.");
59
59
  yield 1;
60
- return { document: parsed.document, warnings: [...new Set(warnings)] };
60
+ return {
61
+ document: parsed.document,
62
+ warnings: [...new Set(warnings)],
63
+ identities: ids,
64
+ };
61
65
  }
@@ -0,0 +1,15 @@
1
+ import type { PhysicalDocumentV1 } from "./types.js";
2
+ export declare const ThumbnailPolicy: {
3
+ readonly MaximumSvgLength: 128000;
4
+ readonly MaximumContentLength: 120000;
5
+ readonly MaximumRingPoints: 64;
6
+ readonly MaximumSeatGlyphs: 512;
7
+ readonly Width: 480;
8
+ readonly Height: 300;
9
+ };
10
+ /** Produces bounded, external-resource-free geometry for recovery and private map previews. */
11
+ export declare function projectMapPreview(document: PhysicalDocumentV1): {
12
+ svg: string;
13
+ empty: boolean;
14
+ };
15
+ export declare function thumbnailSvg(document: PhysicalDocumentV1): string;
@@ -0,0 +1,158 @@
1
+ import { footprint, generateGroup, project, worldMatrices, } from "./geometry/geometry.js";
2
+ import { emptyBounds, extend } from "./geometry/primitives.js";
3
+ import { DecorationKind, SeatingKind, ShapeKind } from "./types.js";
4
+ export const ThumbnailPolicy = {
5
+ MaximumSvgLength: 128000,
6
+ MaximumContentLength: 120000,
7
+ MaximumRingPoints: 64,
8
+ MaximumSeatGlyphs: 512,
9
+ Width: 480,
10
+ Height: 300,
11
+ };
12
+ /** Produces bounded, external-resource-free geometry for recovery and private map previews. */
13
+ export function projectMapPreview(document) {
14
+ const bounds = emptyBounds();
15
+ const matrices = worldMatrices(document);
16
+ const sections = new Map(document.sections.map((section) => [section.id, section]));
17
+ const foreground = parseInt(document.background.color.slice(1, 3), 16) +
18
+ parseInt(document.background.color.slice(3, 5), 16) +
19
+ parseInt(document.background.color.slice(5, 7), 16) >
20
+ 382
21
+ ? "#000000"
22
+ : "#ffffff";
23
+ const paint = (value, fallback = foreground) => `fill="${value?.color ?? fallback}" fill-opacity="${value?.opacity ?? 0.45}"`;
24
+ const number = (value) => value.toFixed(3);
25
+ let content = "";
26
+ let glyphs = 0;
27
+ let empty = true;
28
+ const append = (markup) => {
29
+ if (content.length + markup.length <= ThumbnailPolicy.MaximumContentLength)
30
+ content += markup;
31
+ };
32
+ const point = (value, matrix) => {
33
+ const result = matrix ? project(matrix, value) : value;
34
+ extend(bounds, result);
35
+ return `${number(result.x)},${number(result.y)}`;
36
+ };
37
+ const polygon = (value, matrix) => [value.outer, ...value.holes]
38
+ .map((ring) => {
39
+ for (const entry of ring)
40
+ point(entry, matrix);
41
+ const length = Math.min(ring.length, ThumbnailPolicy.MaximumRingPoints);
42
+ return `M${Array.from({ length }, (_, index) => point(ring[Math.floor((index * ring.length) / length)], matrix)).join("L")}Z`;
43
+ })
44
+ .join("");
45
+ const rectangle = (width, height, matrix) => polygon({
46
+ outer: [
47
+ { x: -width / 2, y: -height / 2 },
48
+ { x: width / 2, y: -height / 2 },
49
+ { x: width / 2, y: height / 2 },
50
+ { x: -width / 2, y: height / 2 },
51
+ ],
52
+ holes: [],
53
+ }, matrix);
54
+ for (const section of document.sections) {
55
+ if (!section.outline)
56
+ continue;
57
+ empty = false;
58
+ append(`<path d="${polygon(section.outline)}" ${paint(section.style?.fill)} fill-rule="evenodd"/>`);
59
+ }
60
+ for (const group of document.seatingGroups) {
61
+ empty = false;
62
+ const matrix = matrices.get(group.id);
63
+ const colour = sections.get(group.sectionId ?? "")?.style?.fill?.color ?? foreground;
64
+ if (group.boundary)
65
+ append(`<path d="${polygon(group.boundary, matrix)}" fill="${colour}" fill-opacity=".3" fill-rule="evenodd"/>`);
66
+ if (group.kind === SeatingKind.Rectangular)
67
+ append(`<path d="${rectangle(group.recipe.widthM, group.recipe.depthM, matrix)}" fill="${colour}" fill-opacity=".55"/>`);
68
+ if (group.kind === SeatingKind.Round) {
69
+ const ring = Array.from({ length: 32 }, (_, index) => ({
70
+ x: (Math.cos((index * Math.PI) / 16) * group.recipe.diameterM) / 2,
71
+ y: (Math.sin((index * Math.PI) / 16) * group.recipe.diameterM) / 2,
72
+ }));
73
+ append(`<path d="${polygon({ outer: ring, holes: [] }, matrix)}" fill="${colour}" fill-opacity=".55"/>`);
74
+ }
75
+ const rows = new Map();
76
+ const rowCounts = new Map("rows" in group
77
+ ? group.rows.map((row) => [row.id, row.seats.length])
78
+ : []);
79
+ let index = 0;
80
+ const rowIndices = new Map();
81
+ for (const seat of generateGroup(group)) {
82
+ const position = project(matrix, seat.position);
83
+ const radius = Math.max(seat.size.width, seat.size.height) / 2;
84
+ for (const corner of footprint(seat, matrix))
85
+ extend(bounds, corner);
86
+ if (seat.rowId !== null) {
87
+ const row = rows.get(seat.rowId) ?? [];
88
+ const count = rowCounts.get(seat.rowId) ?? 1;
89
+ const slot = rowIndices.get(seat.rowId) ?? 0;
90
+ rowIndices.set(seat.rowId, slot + 1);
91
+ if (slot % Math.max(1, Math.ceil(count / 24)) === 0 ||
92
+ slot === count - 1)
93
+ row.push(`${number(position.x)},${number(position.y)}`);
94
+ rows.set(seat.rowId, row);
95
+ }
96
+ if (glyphs < ThumbnailPolicy.MaximumSeatGlyphs && index % 8 === 0) {
97
+ append(`<circle cx="${number(position.x)}" cy="${number(position.y)}" r="${number(radius)}" fill="${colour}" fill-opacity=".8"/>`);
98
+ glyphs++;
99
+ }
100
+ index++;
101
+ }
102
+ if (!group.boundary) {
103
+ for (const points of rows.values())
104
+ append(`<polyline points="${points.join(" ")}" fill="none" stroke="${colour}" stroke-width="${number(group.seatSizeM.height)}" stroke-opacity=".6" stroke-linecap="round"/>`);
105
+ }
106
+ }
107
+ for (const area of document.areas) {
108
+ empty = false;
109
+ const matrix = matrices.get(area.id);
110
+ const path = area.shape.kind === ShapeKind.Polygon
111
+ ? polygon(area.shape.boundary, matrix)
112
+ : rectangle(area.shape.widthM, area.shape.heightM, matrix);
113
+ append(`<path d="${path}" ${paint(sections.get(area.sectionId ?? "")?.style?.fill)} fill-rule="evenodd"/>`);
114
+ }
115
+ for (const art of [...document.decorations].sort((left, right) => left.zIndex - right.zIndex)) {
116
+ empty = false;
117
+ const matrix = matrices.get(art.id);
118
+ let path;
119
+ if (art.kind === DecorationKind.Polygon)
120
+ path = polygon(art.boundary, matrix);
121
+ else if (art.kind === DecorationKind.Line)
122
+ path = `M${art.pointsM.map((value) => point(value, matrix)).join("L")}`;
123
+ else if (art.kind === DecorationKind.Circle)
124
+ path = polygon({
125
+ outer: Array.from({ length: 32 }, (_, index) => ({
126
+ x: Math.cos((index * Math.PI) / 16) * art.radiusM,
127
+ y: Math.sin((index * Math.PI) / 16) * art.radiusM,
128
+ })),
129
+ holes: [],
130
+ }, matrix);
131
+ else if (art.kind === DecorationKind.Text)
132
+ path = rectangle(Math.max(art.fontSizeM, Array.from(art.text).length * art.fontSizeM * 0.65), art.fontSizeM, matrix);
133
+ else
134
+ path = rectangle(art.sizeM.width, art.sizeM.height, matrix);
135
+ const outline = art.kind === DecorationKind.Image ||
136
+ art.kind === DecorationKind.Line ||
137
+ art.kind === DecorationKind.Text;
138
+ append(`<path d="${path}" ${outline ? 'fill="none"' : paint(art.style?.fill)} stroke="${art.style?.stroke?.color ?? foreground}" stroke-opacity="${art.style?.stroke?.opacity ?? 0.5}" stroke-width="${art.style?.strokeWidthM ?? 0.08}" fill-rule="evenodd"/>`);
139
+ }
140
+ const width = Number.isFinite(bounds.minX)
141
+ ? Math.max(1, bounds.maxX - bounds.minX)
142
+ : 1;
143
+ const height = Number.isFinite(bounds.minY)
144
+ ? Math.max(1, bounds.maxY - bounds.minY)
145
+ : 1;
146
+ const padding = Math.max(width, height) * 0.08;
147
+ const x = Number.isFinite(bounds.minX) ? bounds.minX - padding : -padding;
148
+ const y = Number.isFinite(bounds.minY) ? bounds.minY - padding : -padding;
149
+ const viewWidth = width + padding * 2;
150
+ const viewHeight = height + padding * 2;
151
+ return {
152
+ empty,
153
+ svg: `<svg xmlns="http://www.w3.org/2000/svg" width="480" height="300" viewBox="${x} ${y} ${viewWidth} ${viewHeight}"><rect x="${x}" y="${y}" width="${viewWidth}" height="${viewHeight}" ${paint(document.background)}/>${content}</svg>`,
154
+ };
155
+ }
156
+ export function thumbnailSvg(document) {
157
+ return projectMapPreview(document).svg;
158
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seatmap-fyi/map-domain",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.3",
4
4
  "license": "UNLICENSED",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -9,6 +9,10 @@
9
9
  "src/unicode-license.txt"
10
10
  ],
11
11
  "exports": {
12
+ "./editor-state": {
13
+ "types": "./dist/editor-state.d.ts",
14
+ "import": "./dist/editor-state.js"
15
+ },
12
16
  "./types": {
13
17
  "types": "./dist/types.d.ts",
14
18
  "import": "./dist/types.js"
@@ -72,6 +76,10 @@
72
76
  "./identity": {
73
77
  "types": "./dist/identity.d.ts",
74
78
  "import": "./dist/identity.js"
79
+ },
80
+ "./preview": {
81
+ "types": "./dist/preview.d.ts",
82
+ "import": "./dist/preview.js"
75
83
  }
76
84
  },
77
85
  "scripts": {