@link-foundation/ui-designer 0.0.0-stage → 0.0.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,128 @@
1
+ /** Pure timeline projections and immutable editing operations. Values remain LiNo values. */
2
+ import { parse } from '@link-foundation/ui-core';
3
+
4
+ export const fieldsOf = (node) => [
5
+ ...node.properties.map(({ name, values }) => [name, ...values]),
6
+ ...node.unknown.filter(Array.isArray),
7
+ ];
8
+ export function durationMs(value) {
9
+ if (typeof value === 'number') {
10
+ return value;
11
+ }
12
+ if (value && typeof value === 'object') {
13
+ return durationMs(
14
+ value.path ? value.value : `${value.value}${value.unit ?? 'ms'}`
15
+ );
16
+ }
17
+ if (typeof value !== 'string') {
18
+ return 0;
19
+ }
20
+ return value.endsWith('ms')
21
+ ? Number(value.slice(0, -2))
22
+ : value.endsWith('s')
23
+ ? Number(value.slice(0, -1)) * 1000
24
+ : Number(value);
25
+ }
26
+ export function readTimeline(tree, resolveToken = () => undefined) {
27
+ if (typeof tree === 'string') {
28
+ tree = parse(tree);
29
+ }
30
+ if (tree.toDocument) {
31
+ tree = tree.toDocument();
32
+ }
33
+ const animations = [],
34
+ recordings = [];
35
+ const visit = (node) => {
36
+ const fields = fieldsOf(node);
37
+ const field = (name) => fields.find((f) => f[0] === name)?.[1];
38
+ if (node.kind === 'animation') {
39
+ const duration = field('duration');
40
+ const resolved = Array.isArray(duration)
41
+ ? resolveToken(duration[1])
42
+ : duration;
43
+ animations.push({
44
+ id: node.id,
45
+ target: field('target'),
46
+ durationMs: Number.isFinite(durationMs(resolved))
47
+ ? Math.max(0, durationMs(resolved))
48
+ : 0,
49
+ duration,
50
+ tracks: fields
51
+ .filter((f) => f[0] === 'track')
52
+ .map(([, property, ...keys]) => ({
53
+ property,
54
+ keys: keys
55
+ .filter((k) => k[0] === 'key')
56
+ .map(([, offset, value, easing]) => ({
57
+ offset: Number(offset),
58
+ value,
59
+ ...(easing === undefined ? {} : { easing }),
60
+ })),
61
+ })),
62
+ });
63
+ }
64
+ if (node.kind === 'recording') {
65
+ recordings.push({
66
+ id: node.id,
67
+ events: fields
68
+ .filter((f) => f[0] === 'event')
69
+ .map(([, time, action]) => ({ timeMs: durationMs(time), action })),
70
+ });
71
+ }
72
+ node.children.forEach(visit);
73
+ };
74
+ tree.roots.forEach(visit);
75
+ return { animations, recordings };
76
+ }
77
+ const finite = (n) => {
78
+ if (!Number.isFinite(n)) {
79
+ throw new RangeError('Time must be finite');
80
+ }
81
+ return n;
82
+ };
83
+ function indexAt(items, index) {
84
+ if (!Number.isInteger(index) || !items[index]) {
85
+ throw new RangeError('Invalid timeline index');
86
+ }
87
+ return items[index];
88
+ }
89
+ function sortedKeys(track, keys) {
90
+ keys.sort((a, b) => a.offset - b.offset);
91
+ if (
92
+ keys.some((key, i) => i && Math.abs(key.offset - keys[i - 1].offset) < 1e-9)
93
+ ) {
94
+ throw new RangeError('Duplicate keyframe offset');
95
+ }
96
+ return { ...track, keys };
97
+ }
98
+ export function moveKeyframe(track, index, offset) {
99
+ indexAt(track.keys, index);
100
+ offset = Math.max(0, Math.min(1, finite(offset)));
101
+ return sortedKeys(
102
+ track,
103
+ track.keys.map((k, i) => (i === index ? { ...k, offset } : { ...k }))
104
+ );
105
+ }
106
+ export function insertKeyframe(track, offset, value) {
107
+ return sortedKeys(track, [
108
+ ...track.keys,
109
+ { offset: Math.max(0, Math.min(1, finite(offset))), value },
110
+ ]);
111
+ }
112
+ export function deleteKeyframe(track, index) {
113
+ indexAt(track.keys, index);
114
+ if (track.keys.length <= 2) {
115
+ throw new RangeError('At least two keys must remain');
116
+ }
117
+ return { ...track, keys: track.keys.filter((_, i) => i !== index) };
118
+ }
119
+ export function moveEvent(recording, index, timeMs) {
120
+ indexAt(recording.events, index);
121
+ timeMs = Math.max(0, Math.round(finite(timeMs)));
122
+ return {
123
+ ...recording,
124
+ events: recording.events
125
+ .map((e, i) => (i === index ? { ...e, timeMs } : { ...e }))
126
+ .sort((a, b) => a.timeMs - b.timeMs),
127
+ };
128
+ }
@@ -0,0 +1,105 @@
1
+ /** Preview never writes into the editing store or its undo history. */
2
+ import {
3
+ createPlayer,
4
+ replay,
5
+ parseRecording,
6
+ } from '@link-foundation/ui-animation';
7
+ import { render } from '@link-foundation/ui-dom';
8
+ import { CONTROL_KIND_SPECS } from '@link-foundation/ui-components/controls';
9
+ import { logToLino } from '@link-foundation/ui-store';
10
+ import { formatLinks, parseLinks } from '@link-foundation/ui-core';
11
+ import { cloneStore } from '../sync.js';
12
+
13
+ export function createPreview(context) {
14
+ let control,
15
+ playback,
16
+ host,
17
+ handle,
18
+ hidden = [];
19
+ const cancel = () => {
20
+ control?.cancel();
21
+ control = null;
22
+ playback?.pause();
23
+ playback = null;
24
+ handle?.destroy();
25
+ handle = null;
26
+ host?.remove();
27
+ host = null;
28
+ hidden.forEach(([node, display]) => {
29
+ node.style.display = display;
30
+ });
31
+ hidden = [];
32
+ };
33
+ const player = (target) => {
34
+ const engine = createPlayer(target, {
35
+ animations: context.session.getText(),
36
+ motion: 'full',
37
+ resolveToken: context.options.resolveToken,
38
+ });
39
+ const play = engine.play;
40
+ engine.play = (...args) => {
41
+ const control = play(...args);
42
+ control.finished.catch(() => {});
43
+ return control;
44
+ };
45
+ return engine;
46
+ };
47
+ return {
48
+ cancel,
49
+ seek(item, ms, recording = false) {
50
+ if (!recording) {
51
+ if (playback) {
52
+ cancel();
53
+ }
54
+ if (!control) {
55
+ control = player(context.handle).play(item.id);
56
+ control.finished.catch(() => {});
57
+ control.pause();
58
+ }
59
+ control.seek(ms);
60
+ return;
61
+ }
62
+ if (!playback) {
63
+ cancel();
64
+ const store = cloneStore(context.store);
65
+ const ids = (id) => [id, ...store.children(id).flatMap(ids)];
66
+ const snapshot = logToLino([
67
+ {
68
+ tx: 1,
69
+ origin: 'recording',
70
+ label: null,
71
+ ops: store.toDocument().roots.map((node, index) => ({
72
+ op: 'insert',
73
+ parentId: null,
74
+ index,
75
+ node,
76
+ ids: ids(store.roots()[index]),
77
+ })),
78
+ },
79
+ ]);
80
+ const raw = parseLinks(context.session.getText()).find(
81
+ (link) => link.id === item.id
82
+ );
83
+ const data = parseRecording(formatLinks([raw]));
84
+ data.snapshot ??= snapshot;
85
+ hidden = [...context.canvas.children].map((node) => [
86
+ node,
87
+ node.style.display,
88
+ ]);
89
+ hidden.forEach(([node]) => {
90
+ node.style.display = 'none';
91
+ });
92
+ host = context.document.createElement('div');
93
+ host.className = 'timeline-preview';
94
+ context.canvas.append(host);
95
+ handle = render(host, store, {
96
+ kinds: CONTROL_KIND_SPECS,
97
+ setTitle: false,
98
+ });
99
+ playback = replay(data, { store, player: player(handle) });
100
+ }
101
+ playback.seek(ms);
102
+ handle.flush();
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,86 @@
1
+ /** Timeline selection reuses the designer's Properties dock. */
2
+ import { formatLinks } from '@link-foundation/ui-core';
3
+ import { NAMED_EASINGS } from '@link-foundation/ui-animation';
4
+ import { element } from '../dom.js';
5
+
6
+ export function timelineProperties(panel, selected, item, commit, command) {
7
+ const fields = new Set();
8
+ const document = panel.ownerDocument;
9
+ const field = (name, value, callback, choices) => {
10
+ fields.add(name);
11
+ let label = [...panel.children].find(
12
+ (node) => node.dataset.timelineField === name
13
+ );
14
+ if (!label) {
15
+ label = element(document, 'label', { 'data-timeline-field': name }, name);
16
+ const input = element(document, choices ? 'select' : 'input', {
17
+ 'aria-label': name,
18
+ });
19
+ if (choices) {
20
+ for (const choice of choices) {
21
+ input.append(element(document, 'option', { value: choice }, choice));
22
+ }
23
+ }
24
+ label.append(input);
25
+ panel.append(label);
26
+ }
27
+ const input = label.querySelector('input,select');
28
+ if (input.value !== String(value)) {
29
+ input.value = value;
30
+ }
31
+ input.onchange = () => callback(input.value);
32
+ input.onkeydown = (event) => {
33
+ // Keep native undo for an uncommitted text edit; committed fields use history.
34
+ if (
35
+ command &&
36
+ input.value === String(value) &&
37
+ (event.ctrlKey || event.metaKey) &&
38
+ event.key.toLowerCase() === 'z'
39
+ ) {
40
+ event.preventDefault();
41
+ event.stopPropagation();
42
+ void command(event.shiftKey ? 'redo' : 'undo');
43
+ }
44
+ };
45
+ };
46
+ const first = selected[0];
47
+ if (!first) {
48
+ return;
49
+ }
50
+ if (first.recording) {
51
+ const event = item.events[first.index];
52
+ if (!event) {
53
+ return;
54
+ }
55
+ field('Event time (ms)', event.timeMs, (value) =>
56
+ commit([{ ...first, type: 'event-move', ms: Number(value) }])
57
+ );
58
+ field(
59
+ 'Event action',
60
+ formatLinks([event.action], { style: 'inline' }).trim(),
61
+ (value) => commit([{ ...first, type: 'event-action', value }])
62
+ );
63
+ } else {
64
+ const key = item.tracks[first.track]?.keys[first.index];
65
+ if (!key) {
66
+ return;
67
+ }
68
+ field('Key value', key.value, (value) =>
69
+ commit([{ ...first, type: 'key-value', value }])
70
+ );
71
+ field(
72
+ 'Key easing',
73
+ key.easing ?? 'linear',
74
+ (value) => commit([{ ...first, type: 'key-easing', value }]),
75
+ Object.keys(NAMED_EASINGS)
76
+ );
77
+ field('Duration (ms)', item.durationMs, (value) =>
78
+ commit([{ id: item.id, type: 'duration', ms: Number(value) }])
79
+ );
80
+ }
81
+ for (const node of [...panel.children]) {
82
+ if (!fields.has(node.dataset.timelineField)) {
83
+ node.remove();
84
+ }
85
+ }
86
+ }
@@ -0,0 +1,16 @@
1
+ /** Zoom is CSS pixels per millisecond; scroll is CSS pixels. */
2
+ export const timeToX = (ms, { zoom = 0.2, scroll = 0 } = {}) =>
3
+ ms * zoom - scroll;
4
+ export const xToTime = (x, { zoom = 0.2, scroll = 0 } = {}) =>
5
+ (x + scroll) / zoom;
6
+ export function snapTime(
7
+ ms,
8
+ { fps = 60, candidates = [], threshold = 8 } = {}
9
+ ) {
10
+ const grid = (Math.round((ms * fps) / 1000) * 1000) / fps;
11
+ const nearest = [...candidates, grid].reduce(
12
+ (best, time) => (Math.abs(time - ms) < Math.abs(best - ms) ? time : best),
13
+ Infinity
14
+ );
15
+ return Math.abs(nearest - ms) <= threshold ? nearest : ms;
16
+ }