@hyperframes/core 0.9.92 → 0.9.94

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 (34) hide show
  1. package/dist/clipFacts.d.ts +5 -0
  2. package/dist/clipFacts.js +21 -6
  3. package/dist/colorGrading.d.ts +1 -0
  4. package/dist/colorGrading.js +3 -0
  5. package/dist/compiler/htmlDocument.js +1 -1
  6. package/dist/compiler/htmlParityContract.js +1 -1
  7. package/dist/compiler/standaloneEntry.js +1 -1
  8. package/dist/figma/sanitizeSvg.js +1 -1
  9. package/dist/fonts/pageTree.d.ts +1 -1
  10. package/dist/fonts/pageTree.js +1 -1
  11. package/dist/generated/runtime-inline.js +1 -1
  12. package/dist/generators/richTextHtml.js +1 -1
  13. package/dist/hyperframe.runtime.iife.js +66 -66
  14. package/dist/mediaGradeAnalyzer.js +3 -3
  15. package/dist/runtime/clipNodes.d.ts +1 -0
  16. package/dist/runtime/clipNodes.js +1 -0
  17. package/dist/runtime/editing/gsapSnapshot.d.ts +1 -0
  18. package/dist/runtime/editing/gsapSnapshot.js +7 -0
  19. package/dist/runtime/editing/textEdit.d.ts +23 -0
  20. package/dist/runtime/editing/textEdit.js +88 -3
  21. package/dist/runtime/editingDraft.js +31 -9
  22. package/dist/runtime/editingElement.d.ts +2 -0
  23. package/dist/runtime/editingElement.js +11 -1
  24. package/dist/runtime/editingGestureStart.d.ts +5 -1
  25. package/dist/runtime/editingGestureStart.js +4 -0
  26. package/dist/runtime/editingPort.d.ts +13 -4
  27. package/dist/runtime/editingPort.js +14 -3
  28. package/dist/runtime/timeline.js +14 -1
  29. package/dist/runtime/types.d.ts +1 -0
  30. package/dist/utils/inlineTextStyleRange.d.ts +33 -0
  31. package/dist/utils/inlineTextStyleRange.js +503 -0
  32. package/dist/utils/inlineTextStyleRead.d.ts +20 -0
  33. package/dist/utils/inlineTextStyleRead.js +72 -0
  34. package/package.json +8 -4
@@ -0,0 +1,503 @@
1
+ /**
2
+ * Styling a run of characters inside an element being edited in place.
3
+ *
4
+ * Not `document.execCommand`. That is deprecated, and what it emits varies by
5
+ * browser between `<font>`, a class, and an inline style depending on
6
+ * `styleWithCSS`. The output of this goes into the user's composition file, so
7
+ * it has to be one predictable shape, and the shape is a `<span>` carrying an
8
+ * inline style.
9
+ *
10
+ * Not DOM range surgery either, which is the obvious way and the wrong one.
11
+ * Wrapping a range in a span is three lines and then every interesting case is
12
+ * a special case: recolouring nests spans that shadow each other, removing a
13
+ * style cannot reach the ancestor that set it, and styling across an existing
14
+ * run's boundary has to split it. Each fix is a new branch and the branches
15
+ * interact.
16
+ *
17
+ * So the element is read into a flat list of styled runs, the styling is
18
+ * applied to a span of characters in that list, and the element is rebuilt
19
+ * from it. Replacing, removing, splitting and merging all stop being cases:
20
+ * the rebuild emits one span per distinct run and cannot nest or duplicate,
21
+ * whatever was there before. Text elements in a composition are a headline or
22
+ * a sentence, so reading and rebuilding one is not a cost worth avoiding.
23
+ */
24
+ import { isRichTextFormattingAttribute, isRichTextFormattingStyle, isRichTextFormattingTag, } from "./richTextSanitize.js";
25
+ /**
26
+ * Tags that mean a style. They are read as styling and written back as spans,
27
+ * so there is one representation to reason about instead of two that have to
28
+ * agree. Rendering is unchanged; the markup for an edited element is not.
29
+ */
30
+ const TAG_STYLES = {
31
+ B: { "font-weight": "700" },
32
+ STRONG: { "font-weight": "700" },
33
+ I: { "font-style": "italic" },
34
+ EM: { "font-style": "italic" },
35
+ U: { "text-decoration-line": "underline" },
36
+ };
37
+ /**
38
+ * Stands in for a `<br>` while the element is a flat string, so a break counts
39
+ * as one character and offsets survive the rebuild.
40
+ *
41
+ * Not a newline. Compositions are written across lines, so an element's text
42
+ * routinely contains real newlines that are only source formatting, and using
43
+ * one as the marker turned every one of them into a visible line break the
44
+ * first time a word was styled. A NUL never appears: the HTML parser replaces
45
+ * it with U+FFFD, so no document can contain one.
46
+ */
47
+ const BREAK = "\u0000";
48
+ /** Apply `style` to the characters the range covers, then rebuild the element. */
49
+ export function applyInlineStyle(range, style) {
50
+ if (range.collapsed)
51
+ return;
52
+ // Resolved from where the selection starts, not from where it and its end
53
+ // happen to meet. A selection dragged past the element's edge meets its end
54
+ // at an ancestor, and taking that as the host would rebuild the ancestor:
55
+ // every sibling element inside it flattened into text by an edit that was
56
+ // meant to colour a word.
57
+ const host = editingHost(range.startContainer);
58
+ if (!host || !holdsBothEnds(host, range))
59
+ return;
60
+ const runs = readRuns(host);
61
+ const span = graphemeBounds(runs, offsetOf(host, range.startContainer, range.startOffset), offsetOf(host, range.endContainer, range.endOffset));
62
+ if (!span)
63
+ return;
64
+ const next = restyle(runs, span.start, span.end, style);
65
+ render(host, next);
66
+ reconcileFillColors(host);
67
+ selectRange(host, span.start, span.end);
68
+ }
69
+ /**
70
+ * Whether something above the run is painting the glyphs a different colour.
71
+ *
72
+ * `-webkit-text-fill-color` inherits and paints the glyph fill, so an ancestor
73
+ * that sets it wins over any `color` a descendant sets. A composition doing so
74
+ * is not doing anything wrong, but from the editor it reads as the colour
75
+ * picker being broken: the run is saved with the colour asked for and renders
76
+ * in someone else's.
77
+ *
78
+ * Asked of the rendered span rather than worked out from the stylesheet. Its
79
+ * own `color` is set, so its computed colour IS the one that was asked for, and
80
+ * if the fill differs from it then something else is painting it. Both sides
81
+ * come from the same computed style, so neither notation nor inheritance has to
82
+ * be untangled by hand.
83
+ */
84
+ function reconcileFillColors(host) {
85
+ const view = host.ownerDocument.defaultView;
86
+ if (!view?.getComputedStyle)
87
+ return;
88
+ for (const span of host.querySelectorAll("span")) {
89
+ if (!span.style.color)
90
+ continue;
91
+ // A generated mirror repeats the run's colour. Remove that before asking
92
+ // what would paint the run without it; an authored, different fill stays
93
+ // in place long enough to be detected as the overpaint it is.
94
+ const existingFill = span.style.getPropertyValue("-webkit-text-fill-color");
95
+ if (existingFill === span.style.color) {
96
+ span.style.removeProperty("-webkit-text-fill-color");
97
+ }
98
+ const computed = view.getComputedStyle(span);
99
+ const fill = computed.webkitTextFillColor;
100
+ if (!fill || !computed.color)
101
+ continue;
102
+ if (fill !== computed.color) {
103
+ span.style.setProperty("-webkit-text-fill-color", span.style.color);
104
+ }
105
+ }
106
+ }
107
+ /**
108
+ * The offsets to style, widened so they never fall inside a character.
109
+ *
110
+ * Selection offsets count UTF-16 units, while one visible character can be a
111
+ * surrogate pair, combining sequence, flag, modifier sequence, or a family
112
+ * joined by zero-width joiners. Splitting any of those across spans corrupts
113
+ * what the user selected even when every individual code point remains valid.
114
+ */
115
+ function graphemeBounds(runs, start, end) {
116
+ if (start === null || end === null || start >= end)
117
+ return null;
118
+ const text = runs.map((run) => run.text).join("");
119
+ const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
120
+ const boundaries = [0, ...Array.from(segmenter.segment(text), atEndOfSegment)];
121
+ return {
122
+ start: boundaryAtOrBefore(boundaries, start),
123
+ end: boundaries.find((boundary) => boundary >= end) ?? end,
124
+ };
125
+ }
126
+ function atEndOfSegment({ index, segment }) {
127
+ return index + segment.length;
128
+ }
129
+ function boundaryAtOrBefore(boundaries, offset) {
130
+ let previous = offset;
131
+ for (const boundary of boundaries) {
132
+ if (boundary > offset)
133
+ return previous;
134
+ previous = boundary;
135
+ }
136
+ return previous;
137
+ }
138
+ /** Whether the whole selection lives inside this element. */
139
+ function holdsBothEnds(host, range) {
140
+ return host.contains(range.startContainer) && host.contains(range.endContainer);
141
+ }
142
+ /** Every character the range covers with its style, or null when it covers none. */
143
+ export function readCoveredInlineStyleChars(range) {
144
+ const host = editingHost(range.startContainer);
145
+ if (!host || !holdsBothEnds(host, range))
146
+ return null;
147
+ const start = offsetOf(host, range.startContainer, range.startOffset);
148
+ const end = offsetOf(host, range.endContainer, range.endOffset);
149
+ if (start === null || end === null)
150
+ return null;
151
+ const collapsed = start === end;
152
+ const covered = charRuns(readRuns(host))
153
+ .slice(collapsed ? Math.max(0, start - 1) : start, collapsed ? Math.max(1, start) : end)
154
+ .map((entry) => ({ char: entry.char, style: entry.style, painter: entry.painter ?? null }));
155
+ return covered.length > 0 ? covered : null;
156
+ }
157
+ /**
158
+ * The element the caret is in: the one made editable, never a span inside it.
159
+ *
160
+ * Reading the nearest element instead would rebuild only the run the caret
161
+ * happened to land in, which is how a recolour ends up nested inside the
162
+ * colour it was meant to replace.
163
+ */
164
+ function editingHost(node) {
165
+ let element = (node.nodeType === 1 ? node : node.parentElement);
166
+ const editable = element?.closest("[contenteditable]");
167
+ if (editable) {
168
+ return editable.getAttribute("contenteditable")?.toLowerCase() === "false" ? null : editable;
169
+ }
170
+ // No open edit, so climb out of the formatting to the element that owns it.
171
+ while (element?.parentElement && isRichTextFormattingTag(element.tagName)) {
172
+ element = element.parentElement;
173
+ }
174
+ return element;
175
+ }
176
+ function readRuns(host) {
177
+ const runs = [];
178
+ const pending = Array.from(host.childNodes, (node) => ({ node, inherited: {}, origin: null })).reverse();
179
+ for (let frame = pending.pop(); frame; frame = pending.pop()) {
180
+ pending.push(...visitRunFrame(frame, runs));
181
+ }
182
+ return runs;
183
+ }
184
+ function visitRunFrame(frame, runs) {
185
+ const { node, inherited, origin } = frame;
186
+ if (node.nodeType === 3) {
187
+ const text = node.textContent ?? "";
188
+ if (text)
189
+ runs.push({ ...styledRun(text, inherited, origin), painter: node.parentElement });
190
+ return [];
191
+ }
192
+ if (!isStyleElement(node))
193
+ return [];
194
+ const element = node;
195
+ if (element.tagName === "BR") {
196
+ runs.push(styledRun(BREAK, inherited, origin));
197
+ return [];
198
+ }
199
+ return childRunFrames(element, inherited, origin);
200
+ }
201
+ function isStyleElement(node) {
202
+ return node.nodeType === 1 && "style" in node;
203
+ }
204
+ function styledRun(text, style, origin) {
205
+ return { text, style, origin, identity: identityOf(origin) };
206
+ }
207
+ function childRunFrames(element, inherited, origin) {
208
+ const formatting = isRichTextFormattingTag(element.tagName);
209
+ const nextInherited = formatting
210
+ ? { ...inherited, ...TAG_STYLES[element.tagName], ...ownStyle(element) }
211
+ : inherited;
212
+ // The outermost formatting child that carries anything is the one the panel
213
+ // knows as a layer. Tags the sanitizer unwraps cannot own a layer.
214
+ const nextOrigin = formatting && !origin && preservedAttributes(element).size > 0 ? element : origin;
215
+ return Array.from(element.childNodes, (node) => ({ node, inherited: nextInherited, origin: nextOrigin })).reverse();
216
+ }
217
+ /** A child's identity as a comparable string, empty when it has none. */
218
+ function identityOf(element) {
219
+ if (!element)
220
+ return "";
221
+ return JSON.stringify([...preservedAttributes(element)].sort(([a], [b]) => (a < b ? -1 : 1)));
222
+ }
223
+ function ownStyle(element) {
224
+ const style = {};
225
+ for (let index = 0; index < element.style.length; index += 1) {
226
+ const property = element.style.item(index);
227
+ if (!property)
228
+ continue;
229
+ const value = element.style.getPropertyValue(property);
230
+ if (isRichTextFormattingStyle(property, value))
231
+ style[property] = value;
232
+ }
233
+ return style;
234
+ }
235
+ /** One entry per character, which is the easiest thing to slice and compare. */
236
+ function charRuns(runs) {
237
+ const perChar = [];
238
+ for (const run of runs) {
239
+ // By UTF-16 unit, not code point: `restyle` indexes this list with selection
240
+ // offsets, which count units, so an emoji has to stay two entries long.
241
+ for (let index = 0; index < run.text.length; index += 1) {
242
+ perChar.push({
243
+ char: run.text[index] ?? "",
244
+ style: run.style,
245
+ origin: run.origin,
246
+ identity: run.identity,
247
+ painter: run.painter,
248
+ });
249
+ }
250
+ }
251
+ return perChar;
252
+ }
253
+ /** Apply the delta to `[start, end)` and hand back runs covering the element. */
254
+ function restyle(runs, start, end, delta) {
255
+ const text = runs.map((run) => run.text).join("");
256
+ const perChar = charRuns(runs);
257
+ const next = [];
258
+ // Indexed by UTF-16 unit, not by code point: `perChar`, `start` and `end` all
259
+ // count units, and spreading the string would count a surrogate pair once and
260
+ // slide every index after an emoji.
261
+ for (let index = 0; index < text.length; index += 1) {
262
+ appendChar(next, text[index] ?? "", charAfter(perChar[index], index >= start && index < end, delta));
263
+ }
264
+ return next;
265
+ }
266
+ /** What one character is styled with once the delta has been applied to it. */
267
+ function charAfter(at, inside, delta) {
268
+ const style = at?.style ?? {};
269
+ return {
270
+ style: inside ? withDelta(style, delta) : style,
271
+ origin: at?.origin ?? null,
272
+ identity: at?.identity ?? "",
273
+ };
274
+ }
275
+ /**
276
+ * One character onto the run list, merged into the run before it when they
277
+ * belong together.
278
+ *
279
+ * Merged as it is built, so equal neighbours never become two spans. Two that
280
+ * the design panel tracks as separate layers stay apart even when they now look
281
+ * identical, because merging them deletes one of them.
282
+ */
283
+ function appendChar(runs, char, at) {
284
+ const last = runs[runs.length - 1];
285
+ if (last && last.identity === at.identity && sameStyle(last.style, at.style)) {
286
+ last.text += char;
287
+ return;
288
+ }
289
+ runs.push({ text: char, ...at });
290
+ }
291
+ function withDelta(style, delta) {
292
+ const next = { ...style };
293
+ for (const [property, value] of Object.entries(delta)) {
294
+ if (value === null)
295
+ delete next[property];
296
+ else
297
+ next[property] = value;
298
+ }
299
+ return next;
300
+ }
301
+ function sameStyle(a, b) {
302
+ return styleKey(a) === styleKey(b);
303
+ }
304
+ /** Sorted, so two runs styled the same way compare equal whatever the order. */
305
+ function styleKey(style) {
306
+ return Object.keys(style)
307
+ .sort()
308
+ .map((property) => `${property}: ${style[property]}`)
309
+ .join("; ");
310
+ }
311
+ /** Rebuild the element: bare text where there is no styling, one span where there is. */
312
+ function render(host, runs) {
313
+ const doc = host.ownerDocument;
314
+ const nodes = runNodes(doc, runs);
315
+ host.replaceChildren();
316
+ if (nodes.length > 1 && laysOutItsChildren(host)) {
317
+ // Wrapped, because in a flex or grid container every child is an item to
318
+ // be laid out. Text that was one anonymous item becomes several boxes the
319
+ // moment a word inside it is coloured, and the element visibly reflows:
320
+ // centring, wrapping and order all change under an edit that was only ever
321
+ // meant to change a colour. One wrapper keeps it a single item, and the
322
+ // runs inside it stay inline text.
323
+ const wrapper = doc.createElement("span");
324
+ wrapper.append(...nodes);
325
+ host.append(wrapper);
326
+ return;
327
+ }
328
+ host.append(...nodes);
329
+ }
330
+ function runNodes(doc, runs) {
331
+ const nodes = [];
332
+ // One span per origin keeps its attributes: an identity that appeared twice
333
+ // would be two layers claiming to be the same one. A run split off from an
334
+ // origin is a new layer and is written as one.
335
+ const claimed = new Set();
336
+ for (const run of runs) {
337
+ const carried = run.origin && !claimed.has(run.origin) ? preservedAttributes(run.origin) : new Map();
338
+ if (carried.size > 0 && run.origin)
339
+ claimed.add(run.origin);
340
+ nodes.push(...runNode(doc, run, carried));
341
+ }
342
+ return nodes;
343
+ }
344
+ /**
345
+ * One run's nodes: its line breaks as `<br>`, and its text as bare text when it
346
+ * has nothing to carry or a span when it has. The identity goes on the first
347
+ * piece only, so a run broken across lines does not claim it twice.
348
+ */
349
+ function runNode(doc, run, carried) {
350
+ const key = styleKey(run.style);
351
+ const nodes = [];
352
+ for (const [index, piece] of run.text.split(BREAK).entries()) {
353
+ if (index > 0)
354
+ nodes.push(doc.createElement("br"));
355
+ if (!piece)
356
+ continue;
357
+ if (!key && carried.size === 0) {
358
+ nodes.push(doc.createTextNode(piece));
359
+ continue;
360
+ }
361
+ const span = doc.createElement("span");
362
+ for (const [name, value] of carried)
363
+ span.setAttribute(name, value);
364
+ if (key)
365
+ span.setAttribute("style", key);
366
+ span.textContent = piece;
367
+ nodes.push(span);
368
+ carried.clear();
369
+ }
370
+ return nodes;
371
+ }
372
+ /**
373
+ * The one attribute the writer assigns rather than the author.
374
+ *
375
+ * Left out on purpose. It is stamped onto every element on the way to disk, so
376
+ * carrying it preserves nothing — and it made the wrapper this rebuild adds
377
+ * inside a flex container look like a layer as soon as the file had been saved
378
+ * once, which put it back to shadowing the real layers underneath it.
379
+ */
380
+ const DERIVED_ATTR = "data-hf-id";
381
+ /**
382
+ * What a child carries besides its styling: the identity the design panel
383
+ * tracks it by. Its style is not copied — that is what the run holds, already
384
+ * merged with whatever the edit changed.
385
+ */
386
+ function preservedAttributes(element) {
387
+ const kept = new Map();
388
+ for (const name of element.getAttributeNames()) {
389
+ if (name === "style" || name === DERIVED_ATTR)
390
+ continue;
391
+ const value = element.getAttribute(name) ?? "";
392
+ if (isRichTextFormattingAttribute(name, value))
393
+ kept.set(name, value);
394
+ }
395
+ return kept;
396
+ }
397
+ /** Displays whose children are boxes it positions, rather than text it flows. */
398
+ const LAYS_OUT_CHILDREN = new Set([
399
+ "flex",
400
+ "inline-flex",
401
+ "grid",
402
+ "inline-grid",
403
+ // How line clamping is written, and it boxes its children like flex.
404
+ "-webkit-box",
405
+ "-webkit-inline-box",
406
+ ]);
407
+ function laysOutItsChildren(host) {
408
+ const view = host.ownerDocument.defaultView;
409
+ if (!view)
410
+ return false;
411
+ return LAYS_OUT_CHILDREN.has(view.getComputedStyle(host).display);
412
+ }
413
+ /** Where a DOM position falls, counted in characters from the element's start. */
414
+ function offsetOf(host, container, containerOffset) {
415
+ // A position between children, expressed as a child index.
416
+ if (container === host) {
417
+ return Array.from(host.childNodes)
418
+ .slice(0, containerOffset)
419
+ .reduce((count, child) => count + subtreeCharLength(child), 0);
420
+ }
421
+ let count = 0;
422
+ const walker = host.ownerDocument.createTreeWalker(host, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
423
+ let node = walker.nextNode();
424
+ while (node) {
425
+ if (node === container)
426
+ return count + containerOffset;
427
+ count += charLength(node);
428
+ node = walker.nextNode();
429
+ }
430
+ return null;
431
+ }
432
+ /** How many character positions a node occupies itself: its own text, or one
433
+ * for a break. An element contributes nothing; the walk visits its text. */
434
+ function charLength(node) {
435
+ if (node.nodeType === 3)
436
+ return (node.textContent ?? "").length;
437
+ return nodeName(node) === "BR" ? 1 : 0;
438
+ }
439
+ /** The same count for a child and everything inside it, for a position given as
440
+ * a child index rather than a place in a text node. */
441
+ function subtreeCharLength(node) {
442
+ let count = 0;
443
+ const pending = [node];
444
+ for (let current = pending.pop(); current; current = pending.pop()) {
445
+ count += charLength(current);
446
+ pending.push(...Array.from(current.childNodes));
447
+ }
448
+ return count;
449
+ }
450
+ function nodeName(node) {
451
+ return node.nodeType === 1 ? node.tagName : "";
452
+ }
453
+ /** Put the selection back over the characters that were just styled. */
454
+ function selectRange(host, start, end) {
455
+ const doc = host.ownerDocument;
456
+ const selection = doc.defaultView?.getSelection();
457
+ const from = positionAt(host, start);
458
+ const to = positionAt(host, end);
459
+ if (!selection || !from || !to)
460
+ return;
461
+ const range = doc.createRange();
462
+ range.setStart(from.node, from.offset);
463
+ range.setEnd(to.node, to.offset);
464
+ selection.removeAllRanges();
465
+ selection.addRange(range);
466
+ }
467
+ /**
468
+ * The DOM position a character offset lands on, after a rebuild.
469
+ *
470
+ * Counts a line break as one position, because everything that produced the
471
+ * offset did. This walked text nodes only, so in an element containing a `<br>`
472
+ * it landed one character early for every break before the offset — and the
473
+ * selection it put back was not the one that had just been styled.
474
+ *
475
+ * Which was invisible until a control fired more than once. The colour input
476
+ * does: a native picker reports every sample while the pointer moves in it, and
477
+ * each one restyled a selection that had walked one character further along
478
+ * than the last. Choosing a colour for three characters painted a different
479
+ * shade onto each character of the whole line.
480
+ */
481
+ function positionAt(host, offset) {
482
+ let count = 0;
483
+ const walker = host.ownerDocument.createTreeWalker(host, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
484
+ let node = walker.nextNode();
485
+ let last = null;
486
+ while (node) {
487
+ if (node.nodeType !== 3) {
488
+ if (nodeName(node) === "BR")
489
+ count += 1;
490
+ node = walker.nextNode();
491
+ continue;
492
+ }
493
+ const length = (node.textContent ?? "").length;
494
+ if (count + length >= offset)
495
+ return { node, offset: offset - count };
496
+ count += length;
497
+ last = node;
498
+ node = walker.nextNode();
499
+ }
500
+ if (last)
501
+ return { node: last, offset: (last.textContent ?? "").length };
502
+ return { node: host, offset: 0 };
503
+ }
@@ -0,0 +1,20 @@
1
+ /** What the formatting toolbar shows and sets on a selection. */
2
+ export declare const INLINE_STYLE_PROPERTIES: string[];
3
+ /**
4
+ * What the range is styled with, for a toolbar that has to open showing the
5
+ * truth rather than a default. Reports a property only when the whole range
6
+ * agrees about it, which is what a control can honestly display.
7
+ */
8
+ export declare function readInlineStyle(range: Range, properties: string[]): Record<string, string>;
9
+ /**
10
+ * The distinct values one property takes across the range, in document order:
11
+ * `["red", "lime"]`.
12
+ *
13
+ * `readInlineStyle` above answers "what is this range" and reports nothing when
14
+ * the range disagrees with itself — right for a toggle, which can only be on or
15
+ * off. A swatch can show more than one value at once, and showing the default
16
+ * instead reads as "this text is white" when none of it is.
17
+ */
18
+ export declare function readInlineStyleSpread(range: Range, property: string): string[];
19
+ export declare function readFirstPaintedElement(range: Range, property: string): Element | null;
20
+ export { applyInlineStyle, type InlineStyleDelta } from "./inlineTextStyleRange.js";
@@ -0,0 +1,72 @@
1
+ import { readCoveredInlineStyleChars } from "./inlineTextStyleRange.js";
2
+ /** What the formatting toolbar shows and sets on a selection. */
3
+ export const INLINE_STYLE_PROPERTIES = [
4
+ "color",
5
+ "font-weight",
6
+ "font-style",
7
+ "text-decoration-line",
8
+ ];
9
+ /**
10
+ * What the range is styled with, for a toolbar that has to open showing the
11
+ * truth rather than a default. Reports a property only when the whole range
12
+ * agrees about it, which is what a control can honestly display.
13
+ */
14
+ export function readInlineStyle(range, properties) {
15
+ const chars = readCoveredInlineStyleChars(range);
16
+ if (!chars)
17
+ return {};
18
+ const styles = {};
19
+ for (const property of properties) {
20
+ const first = chars[0]?.style[property];
21
+ if (first === undefined)
22
+ continue;
23
+ if (chars.every(({ style }) => style[property] === first))
24
+ styles[property] = first;
25
+ }
26
+ return styles;
27
+ }
28
+ /**
29
+ * The distinct values one property takes across the range, in document order:
30
+ * `["red", "lime"]`.
31
+ *
32
+ * `readInlineStyle` above answers "what is this range" and reports nothing when
33
+ * the range disagrees with itself — right for a toggle, which can only be on or
34
+ * off. A swatch can show more than one value at once, and showing the default
35
+ * instead reads as "this text is white" when none of it is.
36
+ */
37
+ export function readInlineStyleSpread(range, property) {
38
+ const covered = readCoveredInlineStyleChars(range);
39
+ if (!covered)
40
+ return [];
41
+ const seen = new Set();
42
+ const spread = [];
43
+ for (const { char, style, painter } of covered) {
44
+ // A space paints nothing, so the colour it inherits is not a colour anyone
45
+ // can see. Counting it puts the element's own colour in the swatch for text
46
+ // that shows none of it — the stray band on a selection that happens to
47
+ // start or end next to a space.
48
+ if (!char.trim())
49
+ continue;
50
+ if (style[property] === undefined)
51
+ continue;
52
+ // As painted, where `var()` and `currentColor` mean what they mean for the text.
53
+ const shown = painter?.ownerDocument.defaultView
54
+ ?.getComputedStyle(painter)
55
+ .getPropertyValue(property);
56
+ const value = shown || style[property];
57
+ if (seen.has(value))
58
+ continue;
59
+ seen.add(value);
60
+ spread.push(value);
61
+ }
62
+ return spread;
63
+ }
64
+ export function readFirstPaintedElement(range, property) {
65
+ const covered = readCoveredInlineStyleChars(range);
66
+ if (!covered)
67
+ return null;
68
+ const painted = covered.filter(({ char }) => char.trim());
69
+ const owner = painted.find(({ style }) => style[property] !== undefined) ?? painted[0] ?? covered[0];
70
+ return owner?.painter ?? null;
71
+ }
72
+ export { applyInlineStyle } from "./inlineTextStyleRange.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hyperframes/core",
3
- "version": "0.9.92",
3
+ "version": "0.9.94",
4
4
  "description": "",
5
5
  "repository": {
6
6
  "type": "git",
@@ -120,6 +120,10 @@
120
120
  "import": "./dist/utils/richTextSanitize.js",
121
121
  "types": "./dist/utils/richTextSanitize.d.ts"
122
122
  },
123
+ "./inline-text-style": {
124
+ "import": "./dist/utils/inlineTextStyleRead.js",
125
+ "types": "./dist/utils/inlineTextStyleRead.d.ts"
126
+ },
123
127
  "./composition-contract": {
124
128
  "import": "./dist/compositionContract.js",
125
129
  "types": "./dist/compositionContract.d.ts"
@@ -509,9 +513,9 @@
509
513
  "linkedom": "^0.18.12",
510
514
  "postcss": "^8.5.8",
511
515
  "wawoff2": "^2.0.1",
512
- "@hyperframes/lint": "0.9.92",
513
- "@hyperframes/parsers": "0.9.92",
514
- "@hyperframes/studio-server": "0.9.92"
516
+ "@hyperframes/lint": "0.9.94",
517
+ "@hyperframes/studio-server": "0.9.94",
518
+ "@hyperframes/parsers": "0.9.94"
515
519
  },
516
520
  "devDependencies": {
517
521
  "@fontsource/archivo-black": "^5.2.8",