@link-foundation/ui-designer 0.0.0-stage → 0.1.0

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,111 @@
1
+ /** Single-document Source panel using the shared, lazy LiNo editor engine. */
2
+ import { createEditorEngine } from '@link-foundation/ui-components/editor';
3
+ import { element } from './dom.js';
4
+
5
+ export function mountSourcePanel(
6
+ panel,
7
+ { text, error, onChange, report, readOnly: initialReadOnly = false }
8
+ ) {
9
+ const host = element(panel.ownerDocument, 'div', {
10
+ class: 'designer-source ui-editor-area',
11
+ });
12
+ panel.append(host, error);
13
+ let value = text;
14
+ let adapter;
15
+ let stopped = false;
16
+ let invalid = false;
17
+ let readOnly = initialReadOnly;
18
+ let diagnostic;
19
+ function attributes() {
20
+ const input = host.querySelector('[role=textbox]');
21
+ input?.setAttribute('aria-describedby', error.id);
22
+ input?.setAttribute(
23
+ 'aria-description',
24
+ 'Tab indents. Press Escape then Tab to leave Source.'
25
+ );
26
+ input?.setAttribute('aria-invalid', String(invalid));
27
+ input?.setAttribute('aria-readonly', String(readOnly));
28
+ }
29
+ async function display() {
30
+ if (!adapter || stopped) {
31
+ return;
32
+ }
33
+ await adapter.setDocument({
34
+ id: 'document.lino',
35
+ text: value,
36
+ language: 'lino',
37
+ });
38
+ if (!stopped) {
39
+ adapter.setReadOnly(readOnly);
40
+ adapter.setDiagnostics(
41
+ diagnostic ? [{ ...diagnostic, severity: 'error' }] : []
42
+ );
43
+ attributes();
44
+ }
45
+ }
46
+ const ready = createEditorEngine('codemirror', host, {
47
+ label: 'LiNo source',
48
+ onChange: (text) => {
49
+ value = text;
50
+ onChange(text);
51
+ },
52
+ }).then(async (loaded) => {
53
+ if (stopped) {
54
+ loaded.destroy();
55
+ return;
56
+ }
57
+ adapter = loaded;
58
+ await display();
59
+ host.dataset.ready = 'true';
60
+ });
61
+ void ready.catch((failure) => {
62
+ if (!stopped) {
63
+ host.dataset.ready = 'error';
64
+ report(`Unable to load Source editor: ${failure.message}`);
65
+ }
66
+ });
67
+ // Tab indents inside the editor; Escape followed by Tab leaves it.
68
+ let escape = false;
69
+ const keyboard = (event) => {
70
+ if (event.key === 'Tab' && escape) {
71
+ event.stopImmediatePropagation();
72
+ escape = false;
73
+ } else {
74
+ escape = event.key === 'Escape';
75
+ }
76
+ };
77
+ host.addEventListener('keydown', keyboard, true);
78
+ return {
79
+ ready,
80
+ contains: (target) => host.contains(target),
81
+ invalid: () => invalid,
82
+ setText(text) {
83
+ if (value !== text) {
84
+ value = text;
85
+ void display();
86
+ }
87
+ },
88
+ setError(problem) {
89
+ diagnostic = problem;
90
+ invalid = !!problem;
91
+ error.textContent = problem
92
+ ? `Line ${problem.line}, column ${problem.column}: ${problem.message}`
93
+ : '';
94
+ void display();
95
+ },
96
+ setReadOnly(enabled) {
97
+ readOnly = enabled;
98
+ adapter?.setReadOnly(enabled);
99
+ attributes();
100
+ },
101
+ focus() {
102
+ adapter?.focus();
103
+ },
104
+ destroy() {
105
+ stopped = true;
106
+ adapter?.destroy();
107
+ host.removeEventListener('keydown', keyboard, true);
108
+ host.remove();
109
+ },
110
+ };
111
+ }
package/src/sync.js ADDED
@@ -0,0 +1,284 @@
1
+ /** Two-way source synchronization through ui-core/source (#22) and ui-store (#16). */
2
+ import { parse, formatLinks } from '@link-foundation/ui-core';
3
+ import {
4
+ applyOpsToSource,
5
+ indexSource,
6
+ applyEdits,
7
+ } from '@link-foundation/ui-core/source';
8
+ import { createStore } from '@link-foundation/ui-store';
9
+ import { designerVocabulary } from './catalog.js';
10
+
11
+ const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
12
+ const options = () => ({ vocabulary: designerVocabulary() });
13
+ export function storeIds(store) {
14
+ const visit = (id) => [id, ...store.children(id).flatMap(visit)];
15
+ return store.roots().flatMap(visit);
16
+ }
17
+ export const cloneStore = (store) =>
18
+ createStore({ document: store.toDocument(), ids: storeIds(store) });
19
+
20
+ function namedPrefix(id) {
21
+ const fragment = formatLinks([{ id, values: ['text'] }]);
22
+ const span = indexSource(fragment).root.children[0];
23
+ return fragment.slice(0, span.kindSpan.start);
24
+ }
25
+
26
+ /** Add source names only to anonymous nodes addressed by this canvas gesture. */
27
+ function addressAnonymous(text, ops, store) {
28
+ if (!store) {
29
+ return text;
30
+ }
31
+ const addressed = new Set(ops.flatMap((op) => [op.id, op.parentId]));
32
+ const spans = [];
33
+ const visit = (node) => {
34
+ if (node.kind === 'element') {
35
+ spans.push(node);
36
+ }
37
+ node.children.forEach(visit);
38
+ };
39
+ visit(indexSource(text, options()).root);
40
+ const ids = storeIds(store);
41
+ const edits = spans.flatMap((node, i) =>
42
+ node.id === null && addressed.has(ids[i])
43
+ ? [
44
+ {
45
+ start: node.kindSpan.start,
46
+ end: node.kindSpan.start,
47
+ insert: namedPrefix(ids[i]),
48
+ },
49
+ ]
50
+ : []
51
+ );
52
+ return applyEdits(text, edits);
53
+ }
54
+
55
+ /** A change is one store op or an array. Throws before any store mutation. */
56
+ export function canvasToSource(sourceText, change, { store } = {}) {
57
+ const ops = Array.isArray(change) ? change : [change];
58
+ const text = addressAnonymous(sourceText, ops, store);
59
+ const result = applyOpsToSource(text, ops, options());
60
+ if (!result.ok) {
61
+ throw new Error(result.error);
62
+ }
63
+ return result.text;
64
+ }
65
+
66
+ /** Parser diagnostics already carry source positions; semantic errors use their element span. */
67
+ function errorLocation(text, diagnostic) {
68
+ let line = diagnostic.at?.line;
69
+ let column = diagnostic.at?.column;
70
+ if (!line) {
71
+ try {
72
+ const root = indexSource(text, options()).root;
73
+ let offset = 0;
74
+ const visit = (node) => {
75
+ if (node.kind === 'element' && node.id === diagnostic.at?.element) {
76
+ offset = node.start;
77
+ }
78
+ node.children.forEach(visit);
79
+ };
80
+ visit(root);
81
+ const before = text.slice(0, offset).split('\n');
82
+ line = before.length;
83
+ column = before.at(-1).length + 1;
84
+ } catch {
85
+ line = 1;
86
+ column = 1;
87
+ }
88
+ }
89
+ return { line, column: column ?? 1, message: diagnostic.message };
90
+ }
91
+
92
+ function readDocument(text) {
93
+ const document = parse(text, options());
94
+ const diagnostic = document.diagnostics.find((d) => d.severity === 'error');
95
+ return diagnostic ? { error: errorLocation(text, diagnostic) } : { document };
96
+ }
97
+
98
+ function matchId(store, node, parentId, used, named) {
99
+ let id = node.id;
100
+ if (!id) {
101
+ const candidates = (
102
+ parentId === null ? store.roots() : store.children(parentId)
103
+ ).filter(
104
+ (candidate) =>
105
+ !used.has(candidate) &&
106
+ !named.has(candidate) &&
107
+ store.get(candidate).name === null &&
108
+ store.get(candidate).kind === node.kind
109
+ );
110
+ id =
111
+ candidates.find(
112
+ (candidate) =>
113
+ equal(store.get(candidate).positional, node.positional) &&
114
+ equal(store.get(candidate).properties, node.properties)
115
+ ) ?? candidates[0];
116
+ }
117
+ return id;
118
+ }
119
+
120
+ /** Reconcile names globally and anonymous nodes by equal content, then sibling kind. */
121
+ function reconcile(store, document) {
122
+ const used = new Set();
123
+ const retained = new Set();
124
+ const named = new Set(document.byId.keys());
125
+ const update = (node, parentId, index) => {
126
+ let id = matchId(store, node, parentId, used, named);
127
+ if (
128
+ id &&
129
+ store.has(id) &&
130
+ (store.get(id).kind !== node.kind ||
131
+ !equal(store.get(id).unknown, node.unknown))
132
+ ) {
133
+ // Preserve existing child identities even when their parent's kind changes.
134
+ for (const child of store.children(id)) {
135
+ store.move(child, null);
136
+ }
137
+ store.remove(id);
138
+ }
139
+ if (!id || !store.has(id)) {
140
+ id = store.insert(parentId, index, {
141
+ ...node,
142
+ id: id ?? null,
143
+ children: [],
144
+ });
145
+ } else {
146
+ const view = store.get(id);
147
+ if (view.parentId !== parentId || store.indexOf(id) !== index) {
148
+ store.move(id, parentId, index);
149
+ }
150
+ if (!equal(view.positional, node.positional)) {
151
+ store.setPositional(id, node.positional);
152
+ }
153
+ if (!equal(view.properties, node.properties)) {
154
+ for (let i = view.properties.length - 1; i >= 0; i--) {
155
+ store.apply({
156
+ op: 'removeProp',
157
+ id,
158
+ name: view.properties[i].name,
159
+ index: i,
160
+ });
161
+ }
162
+ node.properties.forEach((prop, i) =>
163
+ store.apply({ op: 'setProp', id, ...prop, index: i })
164
+ );
165
+ }
166
+ }
167
+ used.add(id);
168
+ retained.add(id);
169
+ node.children.forEach((child, i) => update(child, id, i));
170
+ };
171
+ document.roots.forEach((node, i) => update(node, null, i));
172
+ // Remove obsolete nodes after moving survivors out of deleted parents.
173
+ for (const id of storeIds(store).reverse()) {
174
+ if (!retained.has(id)) {
175
+ store.remove(id);
176
+ }
177
+ }
178
+ }
179
+
180
+ /** Parse and diff on an isolated store before applying one real transaction. */
181
+ export function sourceToStore(store, text) {
182
+ const result = readDocument(text);
183
+ if (result.error) {
184
+ return result;
185
+ }
186
+ const preview = cloneStore(store);
187
+ try {
188
+ preview.transaction('Edit source', () =>
189
+ reconcile(preview, result.document)
190
+ );
191
+ const ops = preview.log().at(-1)?.ops ?? [];
192
+ store.transaction('Edit source', () =>
193
+ ops.forEach((op) => store.apply(op))
194
+ );
195
+ return { ids: storeIds(store), ops };
196
+ } catch (error) {
197
+ return { error: { line: 1, column: 1, message: error.message } };
198
+ }
199
+ }
200
+
201
+ /** Source snapshots accompany store transactions so undo restores exact comments and whitespace. */
202
+ export function createDocumentSession(initialText) {
203
+ const parsed = readDocument(initialText);
204
+ if (parsed.error) {
205
+ throw new Error(
206
+ `${parsed.error.line}:${parsed.error.column}: ${parsed.error.message}`
207
+ );
208
+ }
209
+ const store = createStore({ document: parsed.document });
210
+ let text = initialText;
211
+ let pending = null;
212
+ const snapshots = new Map();
213
+ const listeners = new Set();
214
+ const stop = store.subscribe((events, entry) => {
215
+ const before = text;
216
+ if (entry.undoes !== undefined) {
217
+ text = snapshots.get(entry.undoes).before;
218
+ } else if (entry.redoes !== undefined) {
219
+ text = snapshots.get(entry.redoes).after;
220
+ } else {
221
+ text = pending ?? canvasToSource(text, entry.ops);
222
+ }
223
+ snapshots.set(entry.tx, { before, after: text });
224
+ listeners.forEach((listener) => listener(events, entry));
225
+ });
226
+ function commit(ops, nextText, label) {
227
+ pending = nextText;
228
+ try {
229
+ store.transaction(label, () => ops.forEach((op) => store.apply(op)));
230
+ if (!ops.length && text !== nextText) {
231
+ // Whitespace/comment-only source changes still need one undoable gesture.
232
+ const id = store.roots()[0];
233
+ if (id) {
234
+ store.transaction(label, () =>
235
+ store.setPositional(id, [...store.get(id).positional])
236
+ );
237
+ } else {
238
+ store.transaction(label, () => {
239
+ const temporary = store.insert(null, 0, { kind: 'text' });
240
+ store.remove(temporary);
241
+ });
242
+ }
243
+ }
244
+ } finally {
245
+ pending = null;
246
+ }
247
+ }
248
+ return {
249
+ store,
250
+ getText: () => text,
251
+ run(command, label = 'Canvas edit', validate = () => {}) {
252
+ const preview = cloneStore(store);
253
+ const value = preview.transaction(label, () => command(preview));
254
+ const ops = preview.log().at(-1)?.ops ?? [];
255
+ validate(ops);
256
+ const nextText = canvasToSource(text, ops, { store });
257
+ commit(ops, nextText, label);
258
+ return value;
259
+ },
260
+ editSource(nextText, validate = () => {}) {
261
+ const preview = cloneStore(store);
262
+ const result = sourceToStore(preview, nextText);
263
+ if (!result.error) {
264
+ try {
265
+ validate(result.ops);
266
+ commit(result.ops, nextText, 'Edit source');
267
+ } catch (error) {
268
+ return { error: { line: 1, column: 1, message: error.message } };
269
+ }
270
+ }
271
+ return result;
272
+ },
273
+ undo: () => store.undo(),
274
+ redo: () => store.redo(),
275
+ subscribe(listener) {
276
+ listeners.add(listener);
277
+ return () => listeners.delete(listener);
278
+ },
279
+ destroy() {
280
+ stop();
281
+ listeners.clear();
282
+ },
283
+ };
284
+ }
@@ -0,0 +1,208 @@
1
+ /** Source-span edits, committed through the designer session as one transaction. */
2
+ import { formatLinks, parseLinks } from '@link-foundation/ui-core';
3
+ import {
4
+ indexSource,
5
+ findElement,
6
+ applyEdits,
7
+ } from '@link-foundation/ui-core/source';
8
+ import {
9
+ readTimeline,
10
+ moveKeyframe,
11
+ insertKeyframe,
12
+ deleteKeyframe,
13
+ moveEvent,
14
+ } from './model.js';
15
+
16
+ const edit = (span, insert) => ({ start: span.start, end: span.end, insert });
17
+ const atom = (value) =>
18
+ formatLinks([['value', value]])
19
+ .trim()
20
+ .slice(6);
21
+ const formatted = (values, span) => {
22
+ const text = formatLinks([values]).trimEnd();
23
+ if (!span.startsLine) {
24
+ return formatLinks([values], { style: 'inline' }).trim();
25
+ }
26
+ return text.split('\n').join(`\n${span.indent}`);
27
+ };
28
+ function replaceOrdered(text, spans, values, order) {
29
+ return applyEdits(
30
+ text,
31
+ spans.map((span, i) => edit(span, values[order[i]]))
32
+ );
33
+ }
34
+ /** Returns text only; callers may compose multiple operations before committing. */
35
+ export function timelineEdit(text, change) {
36
+ const { id, type } = change;
37
+ const { node } = findElement(indexSource(text).root, id) ?? {};
38
+ if (!node) {
39
+ throw new RangeError(`Unknown timeline ${id}`);
40
+ }
41
+ const model = readTimeline(text);
42
+ const animation = model.animations.find((a) => a.id === id);
43
+ const recording = model.recordings.find((r) => r.id === id);
44
+ const props = (name) => node.children.filter((p) => p.name === name);
45
+ if (type === 'duration') {
46
+ if (!Number.isFinite(change.ms) || change.ms <= 0) {
47
+ throw new RangeError('Duration must be positive');
48
+ }
49
+ if (Array.isArray(animation.duration) && !change.replaceToken) {
50
+ throw new Error('Replacing a duration token requires confirmation');
51
+ }
52
+ const span = props('duration')[0];
53
+ return applyEdits(text, [
54
+ edit(span, formatted(['duration', `${Math.round(change.ms)}ms`], span)),
55
+ ]);
56
+ }
57
+ if (type.startsWith('key-')) {
58
+ return editKey(text, change, animation, props);
59
+ }
60
+ return editEvent(text, change, recording, node, props);
61
+ }
62
+
63
+ function editKey(text, change, animation, props) {
64
+ const { track: trackIndex = 0, index, type } = change;
65
+ const track = animation.tracks[trackIndex];
66
+ const span = props('track')[trackIndex];
67
+ const keys = span.children.filter((c) => c.children[0]?.text === 'key');
68
+ if (type === 'key-insert') {
69
+ const next = insertKeyframe(track, change.offset, change.value);
70
+ const key = next.keys.find((k) => !track.keys.includes(k));
71
+ const before = keys.find((_, i) => track.keys[i].offset > key.offset);
72
+ const reference = before ?? keys.at(-1);
73
+ const raw = formatted(['key', String(key.offset), key.value], reference);
74
+ const point = before ? before.start : reference.end;
75
+ const insert = before
76
+ ? `${raw}\n${reference.indent}`
77
+ : `\n${reference.indent}${raw}`;
78
+ return applyEdits(text, [{ start: point, end: point, insert }]);
79
+ }
80
+ if (type === 'key-delete') {
81
+ deleteKeyframe(track, index);
82
+ return applyEdits(text, [edit(keys[index], '')]);
83
+ }
84
+ if (type === 'key-value' || type === 'key-easing') {
85
+ const key = keys[index];
86
+ if (type === 'key-value') {
87
+ return applyEdits(text, [edit(key.children[2], atom(change.value))]);
88
+ }
89
+ const easing = key.children[3];
90
+ return applyEdits(text, [
91
+ easing
92
+ ? edit(easing, atom(change.value))
93
+ : {
94
+ start: key.children.at(-1).end,
95
+ end: key.children.at(-1).end,
96
+ insert: ` ${atom(change.value)}`,
97
+ },
98
+ ]);
99
+ }
100
+ const next = moveKeyframe(track, index, change.offset);
101
+ const moved = Math.max(0, Math.min(1, change.offset));
102
+ const times = track.keys.map((k, i) => (i === index ? moved : k.offset));
103
+ const order = times.map((_, i) => i).sort((a, b) => times[a] - times[b]);
104
+ const values = keys.map((k, i) =>
105
+ i === index
106
+ ? applyEdits(text.slice(k.start, k.end), [
107
+ {
108
+ start: k.children[1].start - k.start,
109
+ end: k.children[1].end - k.start,
110
+ insert: String(moved),
111
+ },
112
+ ])
113
+ : text.slice(k.start, k.end)
114
+ );
115
+ if (next.keys.length !== keys.length) {
116
+ throw new Error('Invalid track');
117
+ }
118
+ // A non-crossing move changes only the offset atom, preserving all other bytes.
119
+ if (order.every((n, i) => n === i)) {
120
+ return applyEdits(text, [edit(keys[index].children[1], String(moved))]);
121
+ }
122
+ return replaceOrdered(text, keys, values, order);
123
+ }
124
+
125
+ function editEvent(text, change, recording, node, props) {
126
+ const { index, type } = change;
127
+ const spans = props('event');
128
+ if (type === 'event-delete') {
129
+ return applyEdits(text, [edit(spans[index], '')]);
130
+ }
131
+ if (type === 'event-action') {
132
+ const links = parseLinks(change.value);
133
+ if (links.length !== 1 || !Array.isArray(links[0])) {
134
+ throw new Error('Enter one LiNo action');
135
+ }
136
+ const span = spans[index].children[1];
137
+ return applyEdits(text, [edit(span, formatted(links[0], span))]);
138
+ }
139
+ if (type === 'event-insert') {
140
+ return insertEvent(text, change, recording, node, spans);
141
+ }
142
+ moveEvent(recording, index, change.ms);
143
+ const times = recording.events.map((e, i) =>
144
+ i === index ? Math.max(0, Math.round(change.ms)) : e.timeMs
145
+ );
146
+ const order = times.map((_, i) => i).sort((a, b) => times[a] - times[b]);
147
+ if (order.every((n, i) => n === i)) {
148
+ return applyEdits(text, [
149
+ edit(spans[index].children[0], `${times[index]}ms`),
150
+ ]);
151
+ }
152
+ const values = spans.map((s, i) =>
153
+ applyEdits(text.slice(s.start, s.end), [
154
+ edit(
155
+ {
156
+ start: s.children[0].start - s.start,
157
+ end: s.children[0].end - s.start,
158
+ },
159
+ `${times[i]}ms`
160
+ ),
161
+ ])
162
+ );
163
+ return replaceOrdered(text, spans, values, order);
164
+ }
165
+ function insertEvent(text, change, recording, node, spans) {
166
+ if (!Number.isFinite(change.ms)) {
167
+ throw new RangeError('Time must be finite');
168
+ }
169
+ const actions = parseLinks(change.value ?? "mark 'New event'");
170
+ const action = actions[0];
171
+ if (actions.length !== 1 || !Array.isArray(action)) {
172
+ throw new Error('Enter one LiNo action');
173
+ }
174
+ // Keep inline events inside their containing link; nested events retain indentation.
175
+ const before = spans.find((_, i) => recording.events[i].timeMs > change.ms);
176
+ const reference = before ?? spans.at(-1);
177
+ const shape = reference ?? {
178
+ startsLine: node.form !== 'inline',
179
+ indent: `${node.indent} `,
180
+ };
181
+ const raw = formatted(
182
+ ['event', `${Math.max(0, Math.round(change.ms))}ms`, action],
183
+ shape
184
+ );
185
+ const separator = shape.startsLine ? `\n${shape.indent}` : ' ';
186
+ const point =
187
+ before?.start ??
188
+ reference?.end ??
189
+ (node.form === 'inline' ? node.end - 1 : node.end);
190
+ return applyEdits(text, [
191
+ {
192
+ start: point,
193
+ end: point,
194
+ insert: before ? `${raw}${separator}` : `${separator}${raw}`,
195
+ },
196
+ ]);
197
+ }
198
+ export function runTimelineCommand(session, changes) {
199
+ const text = (Array.isArray(changes) ? changes : [changes]).reduce(
200
+ timelineEdit,
201
+ session.getText()
202
+ );
203
+ const result = session.editSource(text);
204
+ if (result.error) {
205
+ throw new Error(result.error.message);
206
+ }
207
+ return result;
208
+ }
@@ -0,0 +1,3 @@
1
+ /** Embedded timeline layout, checked against timeline.lino in tests. */
2
+ export const TIMELINE_LAYOUT =
3
+ "timeline-ui: stack\n gap 6px\n timeline-toolbar: stack\n direction horizontal\n gap 4px\n timeline-play: button\n label Play\n timeline-pause: button\n label Pause\n timeline-stop: button\n label Stop\n timeline-loop: button\n label Loop\n timeline-add: button\n label 'Add key/event (K)'\n timeline-delete: button\n label 'Delete selected'\n timeline-zoom-out: button\n label 'Zoom out'\n timeline-zoom-in: button\n label 'Zoom in'\n timeline-content: stack\n gap 4px\n";