@open-artifact/motion-stage 0.0.0-stage → 0.12.0-rc.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.
Files changed (173) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +5 -2
  4. package/package.json +71 -4
  5. package/src/build.d.ts +18 -0
  6. package/src/build.js +73 -0
  7. package/src/host.d.ts +37 -0
  8. package/src/host.js +76 -0
  9. package/src/index.d.ts +11 -0
  10. package/src/index.js +6 -0
  11. package/src/layers.d.ts +30 -0
  12. package/src/layers.js +56 -0
  13. package/src/offline/audio.d.ts +19 -0
  14. package/src/offline/audio.js +20 -0
  15. package/src/offline/data.d.ts +26 -0
  16. package/src/offline/data.js +71 -0
  17. package/src/offline/main.d.ts +9 -0
  18. package/src/offline/main.js +52 -0
  19. package/src/offline/player.d.ts +23 -0
  20. package/src/offline/player.js +155 -0
  21. package/src/protocol/guards.d.ts +6 -0
  22. package/src/protocol/guards.js +208 -0
  23. package/src/protocol/layer-guards.d.ts +7 -0
  24. package/src/protocol/layer-guards.js +97 -0
  25. package/src/protocol/layers.d.ts +123 -0
  26. package/src/protocol/layers.js +1 -0
  27. package/src/protocol/types.d.ts +261 -0
  28. package/src/protocol/types.js +7 -0
  29. package/src/protocol.d.ts +2 -0
  30. package/src/protocol.js +2 -0
  31. package/src/raster.d.ts +4 -0
  32. package/src/raster.js +2 -0
  33. package/src/runtime/assets.d.ts +19 -0
  34. package/src/runtime/assets.js +63 -0
  35. package/src/runtime/captions.d.ts +26 -0
  36. package/src/runtime/captions.js +103 -0
  37. package/src/runtime/console.d.ts +13 -0
  38. package/src/runtime/console.js +99 -0
  39. package/src/runtime/cut.d.ts +7 -0
  40. package/src/runtime/cut.js +63 -0
  41. package/src/runtime/determinism.d.ts +12 -0
  42. package/src/runtime/determinism.js +47 -0
  43. package/src/runtime/film.d.ts +40 -0
  44. package/src/runtime/film.js +29 -0
  45. package/src/runtime/focus.d.ts +8 -0
  46. package/src/runtime/focus.js +71 -0
  47. package/src/runtime/fonts.d.ts +22 -0
  48. package/src/runtime/fonts.js +109 -0
  49. package/src/runtime/frame.d.ts +9 -0
  50. package/src/runtime/frame.js +123 -0
  51. package/src/runtime/kit/camera.d.ts +40 -0
  52. package/src/runtime/kit/camera.js +56 -0
  53. package/src/runtime/kit/chip.d.ts +25 -0
  54. package/src/runtime/kit/chip.js +75 -0
  55. package/src/runtime/kit/cursor.d.ts +46 -0
  56. package/src/runtime/kit/cursor.js +108 -0
  57. package/src/runtime/kit/dom.d.ts +14 -0
  58. package/src/runtime/kit/dom.js +46 -0
  59. package/src/runtime/kit/geometry.d.ts +22 -0
  60. package/src/runtime/kit/geometry.js +46 -0
  61. package/src/runtime/kit/index.d.ts +95 -0
  62. package/src/runtime/kit/index.js +149 -0
  63. package/src/runtime/kit/mark-strokes.d.ts +65 -0
  64. package/src/runtime/kit/mark-strokes.js +226 -0
  65. package/src/runtime/kit/marks.d.ts +21 -0
  66. package/src/runtime/kit/marks.js +165 -0
  67. package/src/runtime/kit/math.d.ts +23 -0
  68. package/src/runtime/kit/math.js +35 -0
  69. package/src/runtime/kit/paper.d.ts +7 -0
  70. package/src/runtime/kit/paper.js +27 -0
  71. package/src/runtime/kit/random.d.ts +8 -0
  72. package/src/runtime/kit/random.js +32 -0
  73. package/src/runtime/kit/text-fx.d.ts +18 -0
  74. package/src/runtime/kit/text-fx.js +55 -0
  75. package/src/runtime/kit/typing.d.ts +21 -0
  76. package/src/runtime/kit/typing.js +42 -0
  77. package/src/runtime/layers/describe.d.ts +41 -0
  78. package/src/runtime/layers/describe.js +327 -0
  79. package/src/runtime/layers/item.d.ts +121 -0
  80. package/src/runtime/layers/item.js +149 -0
  81. package/src/runtime/layers/parts.d.ts +50 -0
  82. package/src/runtime/layers/parts.js +155 -0
  83. package/src/runtime/layers/rows.d.ts +4 -0
  84. package/src/runtime/layers/rows.js +233 -0
  85. package/src/runtime/layers/scan.d.ts +24 -0
  86. package/src/runtime/layers/scan.js +202 -0
  87. package/src/runtime/layers/walk.d.ts +16 -0
  88. package/src/runtime/layers/walk.js +333 -0
  89. package/src/runtime/load.d.ts +10 -0
  90. package/src/runtime/load.js +228 -0
  91. package/src/runtime/main.d.ts +1 -0
  92. package/src/runtime/main.js +69 -0
  93. package/src/runtime/modules.d.ts +23 -0
  94. package/src/runtime/modules.js +53 -0
  95. package/src/runtime/port.d.ts +8 -0
  96. package/src/runtime/port.js +46 -0
  97. package/src/runtime/questions.d.ts +24 -0
  98. package/src/runtime/questions.js +162 -0
  99. package/src/runtime/recut.d.ts +35 -0
  100. package/src/runtime/recut.js +158 -0
  101. package/src/runtime/render.d.ts +80 -0
  102. package/src/runtime/render.js +342 -0
  103. package/src/runtime/retouch/ask.d.ts +17 -0
  104. package/src/runtime/retouch/ask.js +156 -0
  105. package/src/runtime/retouch/entry.d.ts +77 -0
  106. package/src/runtime/retouch/entry.js +1 -0
  107. package/src/runtime/retouch/judge.d.ts +25 -0
  108. package/src/runtime/retouch/judge.js +209 -0
  109. package/src/runtime/retouch/look.d.ts +39 -0
  110. package/src/runtime/retouch/look.js +135 -0
  111. package/src/runtime/retouch/parts.d.ts +22 -0
  112. package/src/runtime/retouch/parts.js +166 -0
  113. package/src/runtime/retouch/retouch.d.ts +37 -0
  114. package/src/runtime/retouch/retouch.js +238 -0
  115. package/src/runtime/retouch/seat.d.ts +40 -0
  116. package/src/runtime/retouch/seat.js +228 -0
  117. package/src/runtime/retouch/state.d.ts +37 -0
  118. package/src/runtime/retouch/state.js +153 -0
  119. package/src/runtime/retouch/type-style.d.ts +19 -0
  120. package/src/runtime/retouch/type-style.js +111 -0
  121. package/src/runtime/scan.d.ts +2 -0
  122. package/src/runtime/scan.js +49 -0
  123. package/src/runtime/scenes/card.d.ts +12 -0
  124. package/src/runtime/scenes/card.js +56 -0
  125. package/src/runtime/scenes/install.d.ts +47 -0
  126. package/src/runtime/scenes/install.js +387 -0
  127. package/src/runtime/scenes/read.d.ts +15 -0
  128. package/src/runtime/scenes/read.js +57 -0
  129. package/src/runtime/scenes/scoped.d.ts +13 -0
  130. package/src/runtime/scenes/scoped.js +40 -0
  131. package/src/runtime/score.d.ts +26 -0
  132. package/src/runtime/score.js +221 -0
  133. package/src/runtime/sketch/pen.d.ts +3 -0
  134. package/src/runtime/sketch/pen.js +371 -0
  135. package/src/runtime/sketch/strokes.d.ts +41 -0
  136. package/src/runtime/sketch/strokes.js +187 -0
  137. package/src/runtime/snapshot/draw.d.ts +14 -0
  138. package/src/runtime/snapshot/draw.js +125 -0
  139. package/src/runtime/snapshot/hold-first-draw.d.ts +12 -0
  140. package/src/runtime/snapshot/hold-first-draw.js +128 -0
  141. package/src/runtime/snapshot/plate.d.ts +20 -0
  142. package/src/runtime/snapshot/plate.js +79 -0
  143. package/src/runtime/snapshot/serialize.d.ts +49 -0
  144. package/src/runtime/snapshot/serialize.js +271 -0
  145. package/src/runtime/snapshot/styles.d.ts +8 -0
  146. package/src/runtime/snapshot/styles.js +109 -0
  147. package/src/runtime/snapshot/xml.d.ts +6 -0
  148. package/src/runtime/snapshot/xml.js +110 -0
  149. package/src/runtime/stage-size.d.ts +7 -0
  150. package/src/runtime/stage-size.js +3 -0
  151. package/src/runtime/stage.d.ts +27 -0
  152. package/src/runtime/stage.js +154 -0
  153. package/src/runtime/stretch.d.ts +13 -0
  154. package/src/runtime/stretch.js +16 -0
  155. package/src/runtime/texts.d.ts +24 -0
  156. package/src/runtime/texts.js +210 -0
  157. package/src/runtime/video-sync.d.ts +26 -0
  158. package/src/runtime/video-sync.js +126 -0
  159. package/src/stills.d.ts +41 -0
  160. package/src/stills.js +253 -0
  161. package/src/tools/film.d.ts +13 -0
  162. package/src/tools/film.js +116 -0
  163. package/src/tools/main.d.ts +1 -0
  164. package/src/tools/main.js +216 -0
  165. package/src/tools/score.d.ts +4 -0
  166. package/src/tools/score.js +29 -0
  167. package/src/tools/types.d.ts +69 -0
  168. package/src/tools/types.js +2 -0
  169. package/src/tools.d.ts +5 -0
  170. package/src/tools.js +3 -0
  171. package/src/virtual.d.ts +11 -0
  172. package/src/vite.d.ts +8 -0
  173. package/src/vite.js +43 -0
@@ -0,0 +1,221 @@
1
+ const MOST_EVENTS = 20000;
2
+ const LONGEST_S = 600;
3
+ const NOTE_STEPS = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
4
+ const VOICE_KEYS = ['pan', 'gain', 'rev', 'detune', 'bright'];
5
+ const FX_KEYS = [...VOICE_KEYS, 'into', 'rate'];
6
+ const num = (value, fallback) => (typeof value === 'number' && isFinite(value) ? value : fallback);
7
+ const field = (options, key) => (options ? options[key] : undefined);
8
+ function textOf(value) {
9
+ try {
10
+ return String(value);
11
+ }
12
+ catch {
13
+ return typeof value;
14
+ }
15
+ }
16
+ function isListLike(value) {
17
+ return value !== null && typeof value === 'object' && typeof Reflect.get(value, 'length') === 'number' && Number(Reflect.get(value, 'length')) >= 0;
18
+ }
19
+ /**
20
+ * Runs `write(S)` and gives back plain score data on the film's own clock. A pitch that cannot be read costs its
21
+ * own note, not the score; past MOST_EVENTS refusals it throws all the same, so an endless list ends.
22
+ */
23
+ export function recordScore(write) {
24
+ const events = [];
25
+ let master = { gain: -6, fadeOut: 1, loudness: -16 };
26
+ const grid = { bpm: 120, t0: 0 };
27
+ const tracks = new Map();
28
+ const refused = { count: 0, names: [] };
29
+ let seed = 7;
30
+ const random = () => {
31
+ seed = (seed + 0x6d2b79f5) | 0;
32
+ let x = Math.imul(seed ^ (seed >>> 15), 1 | seed);
33
+ x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;
34
+ return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
35
+ };
36
+ const secondsPerBeat = () => 60 / grid.bpm;
37
+ const beatTime = (beat) => grid.t0 + beat * secondsPerBeat();
38
+ const refuse = (pitch, where) => {
39
+ if (refused.count >= MOST_EVENTS)
40
+ throw new Error('score: over 20,000 pitches could not be read');
41
+ const name = (pitch === null || pitch === undefined || typeof pitch === 'number' ? String(pitch) : JSON.stringify(textOf(pitch).slice(0, 24))) + where;
42
+ refused.count++;
43
+ if (refused.names.length < 6 && !refused.names.includes(name))
44
+ refused.names.push(name);
45
+ return null;
46
+ };
47
+ const midiOf = (pitch) => {
48
+ let midi = NaN;
49
+ if (typeof pitch === 'number')
50
+ midi = pitch;
51
+ else {
52
+ const found = /^([A-Ga-g])([#b♯♭]?)(-?\d)$/.exec(textOf(pitch).trim());
53
+ if (found) {
54
+ const [, letter = 'C', accidental = '', octave = '0'] = found;
55
+ midi = 12 * (Number(octave) + 1) + (NOTE_STEPS[letter.toUpperCase()] ?? 0) + (/[#♯]/.test(accidental) ? 1 : accidental ? -1 : 0);
56
+ }
57
+ }
58
+ return Number.isNaN(midi) ? refuse(pitch, '') : Math.max(0, Math.min(127, Math.round(midi)));
59
+ };
60
+ // Anything that is not a list is refused whole: a chord's name such as "G7" would otherwise play as one very high note.
61
+ const listOf = (pitches, call) => (isListLike(pitches) ? pitches : (refuse(pitches, ' where ' + call + ' takes a list'), []));
62
+ /** {beat, beats} on the grid or {t, dur} in seconds. */
63
+ const when = (options, defaultDur) => {
64
+ const t = field(options, 't') !== undefined ? num(field(options, 't'), 0) : beatTime(num(field(options, 'beat'), 0));
65
+ const given = field(options, 'dur');
66
+ const beats = field(options, 'beats');
67
+ const dur = given !== undefined ? num(given, defaultDur) : beats !== undefined ? num(beats, 1) * secondsPerBeat() : defaultDur;
68
+ return [t, Math.max(0.01, dur)];
69
+ };
70
+ const push = (kind, patch, midi, at, dur, vel, params) => {
71
+ if (midi === null)
72
+ return;
73
+ // Humanized jitter round beat 0.
74
+ const t = at < 0 && at > -0.1 ? 0 : at;
75
+ if (!(t >= 0) || t > LONGEST_S)
76
+ return;
77
+ const event = { t: t, dur, kind, patch: String(patch), midi, vel: Math.max(1, Math.min(127, Math.round(num(vel, 64)))) };
78
+ if (params)
79
+ event.params = params;
80
+ events.push(event);
81
+ };
82
+ const notes = (patch, pitch, t, dur, vel, params) => {
83
+ for (const each of Array.isArray(pitch) ? pitch : [pitch])
84
+ push('note', patch, midiOf(each), t, dur, vel, params);
85
+ };
86
+ const trackOf = (name) => tracks.get(name) ?? { patch: String(name), params: null };
87
+ const merged = (base, options, keys) => {
88
+ let out = base ? { ...base } : null;
89
+ for (const key of keys) {
90
+ const value = field(options, key);
91
+ if (typeof value === 'number')
92
+ out = { ...(out ?? {}), [key]: value };
93
+ }
94
+ return out;
95
+ };
96
+ const builder = {
97
+ // The grid: beats per minute and where beat 0 sits on the film clock.
98
+ tempo(bpm, options) {
99
+ grid.bpm = Math.max(20, Math.min(300, num(bpm, 120)));
100
+ grid.t0 = num(field(options, 't0'), 0);
101
+ return builder;
102
+ },
103
+ beat: (beat) => beatTime(beat),
104
+ toBeat: (time) => (time - grid.t0) / secondsPerBeat(),
105
+ seed(next) {
106
+ seed = num(next, 7) | 0;
107
+ return builder;
108
+ },
109
+ rand: random,
110
+ program(track, patch, options) {
111
+ tracks.set(track, { patch: String(patch || track), params: merged(null, options, VOICE_KEYS) });
112
+ return builder;
113
+ },
114
+ note(track, pitch, options) {
115
+ const chosen = trackOf(track);
116
+ const [t, dur] = when(options, 0.3);
117
+ notes(chosen.patch, pitch, t, dur, field(options, 'vel'), merged(chosen.params, options, VOICE_KEYS));
118
+ return builder;
119
+ },
120
+ chord(track, pitches, options) {
121
+ const chosen = trackOf(track);
122
+ const [t, dur] = when(options, 1);
123
+ const spread = num(field(options, 'spread'), 0);
124
+ const list = listOf(pitches, 'chord');
125
+ for (let i = 0; i < list.length; i++)
126
+ notes(chosen.patch, list[i], t + i * spread, Math.max(0.02, dur - i * spread), field(options, 'vel'), merged(chosen.params, options, VOICE_KEYS));
127
+ return builder;
128
+ },
129
+ // 'x.x.x-xx' on a step grid from beat `from`: x a hit (the pitch list cycles), X an accent, anything else a rest.
130
+ pattern(track, pattern, options = {}) {
131
+ const chosen = trackOf(track);
132
+ const step = num(options['step'], 0.5);
133
+ const from = num(options['from'], 0);
134
+ const repeats = Math.max(1, num(options['repeat'], 1));
135
+ const given = options['pitch'];
136
+ const pitches = Array.isArray(given) ? given : [given !== undefined ? given : 'C4'];
137
+ const vel = num(options['vel'], 64);
138
+ const human = num(options['humanize'], 0.004);
139
+ let hit = 0;
140
+ for (let r = 0; r < repeats; r++)
141
+ for (let i = 0; i < pattern.length; i++) {
142
+ const mark = pattern.charAt(i);
143
+ if (mark !== 'x' && mark !== 'X')
144
+ continue;
145
+ const beat = from + (r * pattern.length + i) * step;
146
+ notes(chosen.patch, pitches[hit % pitches.length], beatTime(beat) + (random() * 2 - 1) * human, num(options['dur'], step * secondsPerBeat() * 0.9), vel + (mark === 'X' ? 12 : 0) + Math.round((random() * 2 - 1) * num(options['velJitter'], 4)), merged(chosen.params, options, VOICE_KEYS));
147
+ hit++;
148
+ }
149
+ return builder;
150
+ },
151
+ // Evenly stepped, in seconds.
152
+ run(track, pitches, options = {}) {
153
+ const chosen = trackOf(track);
154
+ const t = num(options['t'], 0);
155
+ const step = num(options['step'], 0.1);
156
+ const list = listOf(pitches, 'run');
157
+ for (let i = 0; i < list.length; i++)
158
+ notes(chosen.patch, list[i], t + i * step, num(options['dur'], 0.3), num(options['vel'], 64) + num(options['cresc'], 0) * i, merged(chosen.params, options, VOICE_KEYS));
159
+ return builder;
160
+ },
161
+ drum(name, options) {
162
+ const [t, dur] = when(options, 0.1);
163
+ push('drum', name, 0, t, dur, field(options, 'vel'), merged(null, options, VOICE_KEYS));
164
+ return builder;
165
+ },
166
+ drums(patterns, options = {}) {
167
+ const step = num(options['step'], 0.5);
168
+ const from = num(options['from'], 0);
169
+ const repeats = Math.max(1, num(options['repeat'], 1));
170
+ for (const [name, written] of Object.entries(patterns)) {
171
+ const pattern = String(written);
172
+ for (let r = 0; r < repeats; r++)
173
+ for (let i = 0; i < pattern.length; i++) {
174
+ const mark = pattern.charAt(i);
175
+ if (mark !== 'x' && mark !== 'X' && mark !== 'o')
176
+ continue;
177
+ const accent = mark === 'X' ? 16 : mark === 'o' ? -22 : 0;
178
+ push('drum', name, 0, beatTime(from + (r * pattern.length + i) * step), 0.1, num(options['vel'], 70) + accent + Math.round((random() * 2 - 1) * 4), merged(null, options, VOICE_KEYS));
179
+ }
180
+ }
181
+ return builder;
182
+ },
183
+ // Foley at an exact film time, off the grid.
184
+ fx(name, time, options = {}) {
185
+ const pitch = options['pitch'];
186
+ push('fx', name, (pitch !== undefined && midiOf(pitch)) || 0, num(time, 0), Math.max(0.01, num(options['dur'], 0.25)), num(options['vel'], 64), merged(null, options, FX_KEYS));
187
+ return builder;
188
+ },
189
+ // One tick per time: typing.
190
+ ticks(times, options = {}) {
191
+ const jitter = num(options['jitter'], 6);
192
+ const name = typeof options['name'] === 'string' ? options['name'] : 'tick';
193
+ for (let i = 0; i < times.length; i++)
194
+ builder.fx(name, num(times[i], 0), { vel: num(options['vel'], 36) + Math.round((random() * 2 - 1) * jitter), pan: options['pan'] });
195
+ return builder;
196
+ },
197
+ // gain trims before the master; loudness is the integrated LUFS the host normalizes to (false leaves it raw).
198
+ master(options = {}) {
199
+ const loudness = options['loudness'];
200
+ master = {
201
+ gain: Math.max(-40, Math.min(6, num(options['gain'], -6))),
202
+ fadeOut: Math.max(0, Math.min(10, num(options['fadeOut'], 1))),
203
+ loudness: loudness === false || loudness === null ? null : Math.max(-40, Math.min(-6, num(loudness, -16))),
204
+ };
205
+ return builder;
206
+ },
207
+ };
208
+ write(builder);
209
+ if (refused.count > 0)
210
+ console.error('score: ' +
211
+ refused.count +
212
+ (refused.count === 1 ? ' pitch could not be read and was' : ' pitches could not be read and were') +
213
+ ' left out: ' +
214
+ refused.names.slice(0, 5).join(', ') +
215
+ (refused.names.length > 5 ? ' and others' : '') +
216
+ ' (write "C4", "F#3", "Bb2" or a MIDI number)');
217
+ events.sort((a, b) => a.t - b.t);
218
+ if (events.length > MOST_EVENTS)
219
+ events.length = MOST_EVENTS;
220
+ return { events, master, tempo: { bpm: grid.bpm, t0: grid.t0 } };
221
+ }
@@ -0,0 +1,3 @@
1
+ import type { Sketcher } from '../scenes/install.ts';
2
+ /** The pen for one rough scene: a call that sketches the scene as it stands, made after every render, since a scene may show a state by its borders. */
3
+ export declare const sketchScene: Sketcher;
@@ -0,0 +1,371 @@
1
+ import { stageParts } from "../stage.js";
2
+ import { stageSize } from "../stage-size.js";
3
+ import { sketchBox } from "./strokes.js";
4
+ /*
5
+ * A rough scene's outlines redrawn as hand-drawn strokes. It goes by what is drawn, a border or a flat colour, since
6
+ * the class names are the film's own. If the pen itself fails, the scene loses its sketch and plays on.
7
+ */
8
+ const SVG = 'http://www.w3.org/2000/svg';
9
+ const SIDES = ['Top', 'Right', 'Bottom', 'Left'];
10
+ const CORNERS = ['TopLeft', 'TopRight', 'BottomRight', 'BottomLeft'];
11
+ const LEFT_ALONE = /^(?:IMG|CANVAS|VIDEO|AUDIO|IFRAME|OBJECT|EMBED|INPUT|TEXTAREA|SELECT|BUTTON|PROGRESS|METER|DETAILS|HR|BR|STYLE|TABLE|TD|TH|TR)$/;
12
+ const KITS_OWN = '.film-cursor,.film-chip';
13
+ /** A scene of more elements is left clean, since each is read at every frame. */
14
+ const MOST = 300;
15
+ const DRAWABLE = /^(?:solid|dashed|dotted)$/;
16
+ const CLIPS = /^(?:hidden|clip|scroll|auto)$/;
17
+ const OUT_OF_FLOW = /^(?:absolute|fixed)$/;
18
+ /*
19
+ * data-sketch on an element says what of its own is put aside while it is sketched. edge: its border's colour. fill:
20
+ * its background's. flow: it is position: static, and is made relative so the strokes can be placed by it. label:
21
+ * where its ::after is placed. shape: nothing; no rule reads it.
22
+ */
23
+ const RULES = '[data-sketch-on] [data-sketch~=edge]{border-color:transparent!important}' +
24
+ '[data-sketch-on] [data-sketch~=fill]{background-color:transparent!important}[data-sketch-on] [data-sketch~=flow]{position:relative!important}' +
25
+ '[data-sketch-on] [data-sketch~=label]::after{left:50%!important;top:50%!important;right:auto!important;bottom:auto!important;transform:translate(-50%,-50%)!important;width:max-content!important;min-width:min-content!important;max-width:100%!important;margin:0!important;translate:none!important;rotate:none!important;scale:none!important;text-align:center!important}';
26
+ // Inline, so that a film's plain rules for svg, path or "every child" do not reach these properties.
27
+ const SVG_CSS = ';width:1px;height:1px;margin:0;padding:0;border:0;outline:0;box-sizing:content-box;display:block;visibility:inherit;opacity:1;transform:none;filter:none;clip-path:none;mix-blend-mode:normal;z-index:auto;overflow:visible;pointer-events:none';
28
+ const PATH_CSS = ';transform:none;visibility:inherit;stroke-opacity:1;stroke-dashoffset:0;stroke-linecap:round;stroke-linejoin:round;opacity:';
29
+ const n1 = (n) => String(Math.round(n * 10) / 10);
30
+ const isClear = (c) => !c || c === 'transparent' || /^rgba\(.*,\s*0\)$/.test(c) || /\/\s*0\)$/.test(c);
31
+ const isSet = (v) => /\(/.test(v || '');
32
+ const toPx = (v, of) => (v && /%$/.test(v) ? (parseFloat(v) / 100) * of : parseFloat(v ?? '') || 0);
33
+ const isPens = (n) => n.namespaceURI === SVG && n.hasAttribute('data-sketch-pen');
34
+ function ink(colour, width, kind, opacity) {
35
+ const w = Number(width);
36
+ const dash = kind === 'dashed' ? w * 3.5 + ' ' + w * 3 : kind === 'dotted' ? '0.1 ' + w * 2.6 : 'none';
37
+ return 'fill:none;stroke:' + colour + ';stroke-width:' + width + 'px;stroke-dasharray:' + dash + PATH_CSS + opacity;
38
+ }
39
+ /** Remembered for the length of one drawing. */
40
+ const positions = new Map();
41
+ function position(n, pseudo) {
42
+ let m = positions.get(n);
43
+ if (!m)
44
+ positions.set(n, (m = new Map()));
45
+ const k = pseudo ?? 'self';
46
+ let p = m.get(k);
47
+ if (p === undefined)
48
+ m.set(k, (p = getComputedStyle(n, pseudo).position));
49
+ return p;
50
+ }
51
+ /** Does el hold anything placed absolutely or fixed, a ::before or ::after too, that an ancestor of el positions? Made relative, el would position it instead. */
52
+ function anchors(el) {
53
+ const all = el.firstElementChild ? Array.from(el.querySelectorAll('*')) : [];
54
+ const out = (n, pseudo) => OUT_OF_FLOW.test(position(n, pseudo));
55
+ for (let i = -1; i < all.length; i++) {
56
+ const n = i < 0 ? el : all[i];
57
+ if (!n)
58
+ continue;
59
+ const inSvg = n.namespaceURI === SVG;
60
+ if (inSvg && (isPens(n) || (n.parentNode instanceof Element && n.parentNode.namespaceURI === SVG)))
61
+ continue;
62
+ const self = i >= 0 && out(n, null);
63
+ if (!self && (inSvg || !(out(n, '::before') || out(n, '::after'))))
64
+ continue;
65
+ let p = self ? n.parentElement : n;
66
+ while (p && p !== el && position(p, null) === 'static')
67
+ p = p.parentElement;
68
+ if (p === el)
69
+ return true;
70
+ }
71
+ return false;
72
+ }
73
+ /** What to draw for an element, read from the film's own styles; null leaves it as the scene drew it. */
74
+ function plan(s, u) {
75
+ const el = s.el;
76
+ const cs = s.cs;
77
+ const w = el.offsetWidth;
78
+ const h = el.offsetHeight;
79
+ const thin = Math.min(w, h);
80
+ const share = (w * h) / (stageSize.width * stageSize.height);
81
+ let other = false;
82
+ const raw = [0, 0, 0, 0];
83
+ SIDES.forEach((side, i) => {
84
+ raw[i] = parseFloat(cs.getPropertyValue('border-' + side.toLowerCase() + '-width')) || 0;
85
+ });
86
+ const sides = SIDES.map((side, i) => {
87
+ const kind = cs.getPropertyValue('border-' + side.toLowerCase() + '-style');
88
+ const color = cs.getPropertyValue('border-' + side.toLowerCase() + '-color');
89
+ const wide = raw[i] ?? 0;
90
+ if (!wide || !kind || kind === 'none' || kind === 'hidden' || isClear(color))
91
+ return null;
92
+ if (!DRAWABLE.test(kind))
93
+ other = true;
94
+ return { wide, color, kind };
95
+ });
96
+ const on = sides.filter((x) => x !== null);
97
+ const first = on[0];
98
+ const flat = !isClear(cs.backgroundColor);
99
+ const empty = !(el.textContent ?? '').trim() && Array.from(el.children).every(isPens);
100
+ if (!on.length && !(flat && empty))
101
+ return null;
102
+ // The pen runs along and past the border, where an element that clips would cut it off.
103
+ const mask = cs.getPropertyValue('mask-image') || cs.getPropertyValue('-webkit-mask-image');
104
+ if (!w || !h || other || CLIPS.test(cs.overflowX) || CLIPS.test(cs.overflowY) || isSet(cs.clipPath) || isSet(mask) || /paint|content|strict/.test(cs.contain) || isSet(cs.borderImageSource))
105
+ return null;
106
+ // The strokes are a positioned child, which an inline box or a table's part cannot hold.
107
+ if (/^(?:inline|contents|table)/.test(cs.display) && !/^inline-(?:block|flex|grid)$/.test(cs.display))
108
+ return null;
109
+ const whole = on.length === 4;
110
+ const alike = on.every((x) => !!first && x.wide === first.wide && x.color === first.color && x.kind === first.kind);
111
+ const radii = CORNERS.map((c) => cs.getPropertyValue('border-' + c.replace(/([a-z])([A-Z])/, '$1-$2').toLowerCase() + '-radius'));
112
+ const r = (radii[0] ?? '').split(' ');
113
+ const rx = toPx(r[0], w);
114
+ const ry = toPx(r[1] || r[0], h);
115
+ const curved = radii.some((v) => {
116
+ const a = v.split(' ');
117
+ const x = toPx(a[0], w);
118
+ const y = toPx(a[1] || a[0], h);
119
+ return Math.min(x, y) * Math.min(1, x ? w / (2 * x) : 1, y ? h / (2 * y) : 1) >= 0.3 * thin;
120
+ });
121
+ const meet = on.length > 0 && (raw[1] + raw[3] + 1 >= w || raw[0] + raw[2] + 1 >= h);
122
+ // A shape: empty, and filled by its background or by four like borders that meet. An empty flat colour over 29% of the stage is the background.
123
+ const shape = empty && (on.length ? meet && whole && alike : share < 0.29);
124
+ if (!on.length && !shape)
125
+ return null;
126
+ // Borders that meet at a corner, clear ones too, make a triangle; one border on an element of no thickness is a line.
127
+ if (meet && !shape && sides.some((x, i) => x && (raw[(i + 1) % 4] || raw[(i + 3) % 4])))
128
+ return null;
129
+ // One line goes round a curve: not round an arch, a ring whose sides differ, or corners that differ.
130
+ if (curved && (!radii.every((v) => v === radii[0]) || (!shape && !(whole && alike))))
131
+ return null;
132
+ const inFlow = cs.position === 'static';
133
+ if (inFlow && anchors(el))
134
+ return null;
135
+ const hatch = shape || !whole || !empty || flat || isSet(cs.backgroundImage) || share >= 0.29 ? 0 : share > 0.077 ? 2 : 1;
136
+ let skip = null;
137
+ const pad = 8 * u;
138
+ const bar = shape && thin <= 8 * u;
139
+ let label = false;
140
+ if (empty && !bar && (hatch || el.hasAttribute('data-label'))) {
141
+ const after = (s.after ??= getComputedStyle(el, '::after'));
142
+ let lx = parseFloat(after.left) + raw[3];
143
+ let ly = parseFloat(after.top) + raw[0];
144
+ const lw = parseFloat(after.width);
145
+ const lh = parseFloat(after.height);
146
+ const room = w - raw[1] - raw[3];
147
+ const moved = /^matrix\(1, 0, 0, 1, (-?[\d.e-]+), (-?[\d.e-]+)\)$/.exec(after.transform || '');
148
+ if (moved) {
149
+ lx += parseFloat(moved[1] ?? '0');
150
+ ly += parseFloat(moved[2] ?? '0');
151
+ }
152
+ // A placeholder's label goes in the middle: at a corner it would cross a circle's line. One wholly outside is a caption, and stays.
153
+ const mx = parseFloat(after.marginLeft) || 0;
154
+ const my = parseFloat(after.marginTop) || 0;
155
+ label = el.hasAttribute('data-label') && after.position === 'absolute' && lx + mx < w - raw[1] && ly + my < h - raw[2] && lx + mx + lw > raw[3] && ly + my + lh > raw[0];
156
+ if (label) {
157
+ lx = raw[3] + (room - lw) / 2;
158
+ ly = raw[0] + (h - raw[0] - raw[2] - lh) / 2;
159
+ }
160
+ if (hatch && lw > 0 && lh > 0 && !Number.isNaN(lx) && !Number.isNaN(ly))
161
+ skip = [lx - pad, ly - pad, lx + lw + pad, ly + lh + pad];
162
+ }
163
+ return {
164
+ w,
165
+ h,
166
+ left: raw[3],
167
+ top: raw[0],
168
+ fill: first ? first.color : cs.backgroundColor,
169
+ sides: shape ? null : sides,
170
+ mark: (shape ? (bar ? 'fill edge' : 'shape') : 'edge') + (inFlow ? ' flow' : '') + (label ? ' label' : ''),
171
+ o: {
172
+ u,
173
+ sides: shape ? [2, 2, 2, 2] : [sides[0]?.wide ?? 0, sides[1]?.wide ?? 0, sides[2]?.wide ?? 0, sides[3]?.wide ?? 0],
174
+ onEdge: shape,
175
+ bar,
176
+ broken: !shape && !!first && first.kind !== 'solid',
177
+ rx,
178
+ ry,
179
+ hatch,
180
+ skip,
181
+ },
182
+ };
183
+ }
184
+ let sheet = null;
185
+ /** The pen for one rough scene: a call that sketches the scene as it stands, made after every render, since a scene may show a state by its borders. */
186
+ export const sketchScene = (box, id) => {
187
+ let known = new WeakMap();
188
+ const owner = new WeakMap();
189
+ let seed = 7;
190
+ let dead = false;
191
+ let said = false;
192
+ for (let c = 0; c < id.length; c++)
193
+ seed = (seed * 31 + id.charCodeAt(c)) % 2147483646;
194
+ const off = () => {
195
+ box.removeAttribute('data-sketch-on');
196
+ for (const n of Array.from(box.querySelectorAll('svg[data-sketch-pen]')))
197
+ n.remove();
198
+ for (const n of Array.from(box.querySelectorAll('[data-sketch]')))
199
+ n.removeAttribute('data-sketch');
200
+ known = new WeakMap();
201
+ };
202
+ const say = (why) => {
203
+ if (!said)
204
+ console.warn('rough scene ' + id + ' is shown without its sketch (' + why + '); nothing in the film needs changing');
205
+ said = true;
206
+ };
207
+ const root = { path: seed, kids: 0, lone: 0 };
208
+ const draw = () => {
209
+ if (!box.parentNode)
210
+ return;
211
+ const u = Math.sqrt(stageSize.width * stageSize.height) / 960;
212
+ const all = Array.from(box.querySelectorAll('*'));
213
+ const seen = [];
214
+ const strays = [];
215
+ const todo = [];
216
+ let fresh = [];
217
+ root.kids = root.lone = 0;
218
+ const keyOf = (s) => {
219
+ const d = plan(s, u);
220
+ return { s, d, key: d ? JSON.stringify([s.path, d]) : '' };
221
+ };
222
+ // Not kit.css, which places by the canvas: a scene may have taken the canvas into its box.
223
+ const stage = stageParts()?.stage;
224
+ if (stage && (!sheet || !sheet.parentNode)) {
225
+ sheet = document.createElement('style');
226
+ sheet.textContent = RULES;
227
+ stage.insertBefore(sheet, stage.firstChild);
228
+ }
229
+ // Read with the rules off, so that what is read is the film's own; then written, all at once.
230
+ box.removeAttribute('data-sketch-on');
231
+ positions.clear();
232
+ for (const el of all) {
233
+ // cloneNode and innerHTML copy the pen's strokes and marks.
234
+ if (el.namespaceURI === SVG) {
235
+ if (isPens(el) && owner.get(el) !== el.parentNode)
236
+ strays.push(el);
237
+ continue;
238
+ }
239
+ if (!(el instanceof HTMLElement))
240
+ continue;
241
+ let s = known.get(el);
242
+ if (!s) {
243
+ s = { el, svg: null, paths: [], key: '', path: 0, kids: 0, lone: 0, after: null, cs: getComputedStyle(el) };
244
+ known.set(el, s);
245
+ el.removeAttribute('data-sketch');
246
+ }
247
+ /*
248
+ * Seeded by where the element sits among its parent's elements, all the way down: only an earlier sibling that
249
+ * comes or goes moves them. What is left alone has a count of its own, so the canvas moving in and out of a
250
+ * scene's box does not change what is sketched beside it.
251
+ */
252
+ const parent = el.parentNode instanceof Element ? known.get(el.parentNode) : undefined;
253
+ const up = parent ?? root;
254
+ const alone = LEFT_ALONE.test(el.tagName) || !!el.closest(KITS_OWN);
255
+ s.path = (up.path * 131 + (alone ? 65537 * ++up.lone : ++up.kids)) % 2147483646;
256
+ s.kids = s.lone = 0;
257
+ if (!alone && seen.push(s) > MOST)
258
+ break;
259
+ }
260
+ // For this frame alone: a frame follows from t, never from the frames before it.
261
+ if (seen.length > MOST) {
262
+ off();
263
+ say('over ' + MOST + ' elements');
264
+ return;
265
+ }
266
+ for (const s of seen) {
267
+ const t = keyOf(s);
268
+ if (t.key !== s.key || (t.d && s.svg?.parentNode !== s.el))
269
+ todo.push(t);
270
+ }
271
+ box.setAttribute('data-sketch-on', '');
272
+ for (const n of strays)
273
+ n.remove();
274
+ for (const t of todo) {
275
+ const s = t.s;
276
+ const d = t.d;
277
+ if (!d) {
278
+ s.el.removeAttribute('data-sketch');
279
+ s.svg?.remove();
280
+ s.key = '';
281
+ continue;
282
+ }
283
+ let svg = s.svg;
284
+ if (!svg) {
285
+ svg = document.createElementNS(SVG, 'svg');
286
+ svg.setAttribute('data-sketch-pen', '');
287
+ svg.setAttribute('aria-hidden', 'true');
288
+ owner.set(svg, s.el);
289
+ s.svg = svg;
290
+ }
291
+ if (svg.parentNode !== s.el) {
292
+ s.el.appendChild(svg);
293
+ fresh.push(t);
294
+ }
295
+ if (t.key === s.key)
296
+ continue;
297
+ s.key = t.key;
298
+ const k = sketchBox(s.path + 1, d.w, d.h, d.o);
299
+ const parts = [
300
+ [k.wash, 'fill:' + d.fill + ';stroke:none' + PATH_CSS + 0.05],
301
+ [k.hatch, ink(d.fill, k.fine, 'solid', 0.36)],
302
+ [k.cross, ink(d.fill, k.fine, 'solid', 0.2)],
303
+ ];
304
+ const soft = new Map();
305
+ const faint = new Map();
306
+ const firm = new Map();
307
+ const add = (to, css, path) => {
308
+ to.set(css, (to.get(css) ?? '') + path);
309
+ };
310
+ k.lines.forEach((l, i) => {
311
+ if (!l)
312
+ return;
313
+ const side = d.sides?.[i] ?? { color: d.fill, kind: 'solid' };
314
+ const wide = (part) => n1(Number(l.width) * (d.o.bar ? 1 : 0.66) * part);
315
+ // Each pass thinner and fainter than the one over it; a bar's first is as thick as the bar.
316
+ add(firm, ink(side.color, wide(1), side.kind, 0.88), l.main);
317
+ add(faint, ink(side.color, wide(0.74), side.kind, 0.5), l.again);
318
+ if (l.third)
319
+ add(soft, ink(side.color, wide(0.55), side.kind, 0.32), l.third);
320
+ });
321
+ for (const g of [soft, faint, firm])
322
+ for (const [css, path] of g)
323
+ parts.push([path, css]);
324
+ s.el.setAttribute('data-sketch', d.mark);
325
+ svg.setAttribute('style', 'position:absolute;left:' + -d.left + 'px;top:' + -d.top + 'px' + SVG_CSS);
326
+ while (s.paths.length < parts.length)
327
+ s.paths.push(svg.appendChild(document.createElementNS(SVG, 'path')));
328
+ while (s.paths.length > parts.length)
329
+ s.paths.pop()?.remove();
330
+ s.paths.forEach((p, i) => {
331
+ p.setAttribute('d', parts[i]?.[0] ?? '');
332
+ p.setAttribute('style', parts[i]?.[1] ?? '');
333
+ });
334
+ }
335
+ if (!fresh.length) {
336
+ positions.clear();
337
+ return;
338
+ }
339
+ // The strokes are a child, which :empty and its like can tell. Where the film's styles ask for something else now, they come off again in this drawing.
340
+ box.removeAttribute('data-sketch-on');
341
+ positions.clear();
342
+ fresh = fresh.filter((t) => keyOf(t.s).key !== t.key);
343
+ box.setAttribute('data-sketch-on', '');
344
+ for (const t of fresh) {
345
+ t.s.el.removeAttribute('data-sketch');
346
+ t.s.svg?.remove();
347
+ t.s.key = '';
348
+ }
349
+ positions.clear();
350
+ };
351
+ return () => {
352
+ if (dead)
353
+ return;
354
+ try {
355
+ draw();
356
+ }
357
+ catch (error) {
358
+ dead = true;
359
+ let why = 'error';
360
+ try {
361
+ off();
362
+ why = String(error instanceof Error ? error.message : error).slice(0, 200);
363
+ }
364
+ catch {
365
+ // The reason could not be read.
366
+ }
367
+ said = false;
368
+ say(why);
369
+ }
370
+ };
371
+ };
@@ -0,0 +1,41 @@
1
+ export type Sides = [number, number, number, number];
2
+ export interface SketchBoxOptions {
3
+ /** The square root of the stage's area over that of 1280 by 720. */
4
+ u: number;
5
+ /** The border's width at top, right, bottom, left; 0 for a side not drawn. */
6
+ sides: Sides;
7
+ /** Drawn on the box's edge, not down the border's middle. */
8
+ onEdge: boolean;
9
+ /** One stroke along the longer side. */
10
+ bar: boolean;
11
+ /** Dashed or dotted. */
12
+ broken: boolean;
13
+ /** The corner as CSS states it. */
14
+ rx: number;
15
+ ry: number;
16
+ /** 0: none; 1: close; 2: wide. */
17
+ hatch: 0 | 1 | 2;
18
+ /** [x0, y0, x1, y1] that the hatching keeps off. */
19
+ skip: Sides | null;
20
+ }
21
+ /** One line as three pencil passes, each straying further than the last, as path data. */
22
+ export interface SketchStroke {
23
+ main: string;
24
+ again: string;
25
+ third: string;
26
+ width: string;
27
+ }
28
+ export interface SketchBox {
29
+ wash: string;
30
+ hatch: string;
31
+ cross: string;
32
+ /** The hatching's pen width. */
33
+ fine: string;
34
+ /** Top, right, bottom, left; or the one line of a bar or a round box first. */
35
+ lines: [SketchStroke | null, SketchStroke | null, SketchStroke | null, SketchStroke | null];
36
+ }
37
+ /**
38
+ * The strokes for one element of w by h px, as path data: a pure function of its arguments, so that a frame follows
39
+ * from t alone.
40
+ */
41
+ export declare function sketchBox(seed: number, w: number, h: number, o: SketchBoxOptions): SketchBox;