@open-artifact/whiteboard-core 0.10.0 → 0.11.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 (43) hide show
  1. package/package.json +4 -4
  2. package/src/backdrop.d.ts +4 -2
  3. package/src/backdrop.js +10 -3
  4. package/src/check.d.ts +9 -1
  5. package/src/check.js +91 -11
  6. package/src/drawn-svg/looks.d.ts +166 -0
  7. package/src/drawn-svg/looks.js +594 -0
  8. package/src/drawn-svg/svg-geometry.d.ts +7 -0
  9. package/src/drawn-svg/svg-geometry.js +37 -0
  10. package/src/drawn-svg/vetting.d.ts +4 -2
  11. package/src/drawn-svg/vetting.js +11 -5
  12. package/src/edits.d.ts +2 -2
  13. package/src/edits.js +2 -2
  14. package/src/geometry.js +2 -1
  15. package/src/history/board-diff.d.ts +7 -2
  16. package/src/history/board-diff.js +31 -6
  17. package/src/history/table-steps.d.ts +8 -3
  18. package/src/history/table-steps.js +38 -7
  19. package/src/hit-test.d.ts +2 -1
  20. package/src/hit-test.js +26 -5
  21. package/src/ideas.d.ts +2 -2
  22. package/src/ideas.js +3 -1
  23. package/src/index.d.ts +5 -0
  24. package/src/index.js +5 -0
  25. package/src/links.d.ts +2 -0
  26. package/src/links.js +9 -5
  27. package/src/next-item.d.ts +16 -1
  28. package/src/next-item.js +65 -15
  29. package/src/normalize.d.ts +2 -0
  30. package/src/normalize.js +14 -4
  31. package/src/schema.d.ts +20 -0
  32. package/src/schema.js +6 -0
  33. package/src/selection.js +8 -8
  34. package/src/table-tints.d.ts +84 -0
  35. package/src/table-tints.js +217 -0
  36. package/src/table.d.ts +17 -4
  37. package/src/table.js +59 -6
  38. package/src/text/placeholder.d.ts +17 -0
  39. package/src/text/placeholder.js +16 -0
  40. package/src/text/push-down.d.ts +29 -0
  41. package/src/text/push-down.js +72 -0
  42. package/src/text/turned-anchor.d.ts +19 -0
  43. package/src/text/turned-anchor.js +32 -0
package/src/next-item.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Where a next item goes: beside an item (Mod+Return while typing), or at
2
+ * Where a next item goes: beside an item (Mod+Return while typing, or a
3
+ * click on one of its side dots, which also need room around them), or at
3
4
  * the free end of an arrow just drawn into empty board (the *next-item
4
5
  * offer*: the editor shows a faint item there that Return or a click adds,
5
6
  * joined to the arrow).
@@ -28,36 +29,85 @@ export function boxesNearlyTouch(a, b) {
28
29
  a.y < b.y + b.h + NEXT_ITEM_CLEARANCE &&
29
30
  b.y < a.y + a.h + NEXT_ITEM_CLEARANCE);
30
31
  }
31
- /**
32
- * Places `template` beside `from` on `side` (right by default), past
33
- * anything in the way: each time the spot would touch an item, it moves on
34
- * past that item, away from `from`. A shape is centered on `from` across
35
- * that direction, a note aligned with its top (or left) edge. Items `from`
36
- * sits centered inside (its frames) are not in the way.
37
- */
38
- export function placeNextItemBeside(from, template, elements, measures, side = 'right') {
39
- const fromBox = elementBounds(from, measures) ?? { x: 0, y: 0, w: 0, h: 0 };
32
+ /** Where `template` goes beside `box` on `side`, `gap` away, lined up with `fromBox` across that direction. */
33
+ function spotBeside(fromBox, box, template, side) {
40
34
  const gap = NEXT_ITEM_GAP[template.type];
41
35
  const align = template.type === 'shape' ? 0.5 : 0;
42
- const placeAt = (box) => ({
36
+ return {
43
37
  x: side === 'right' ? box.x + box.w + gap : side === 'left' ? box.x - template.w - gap : fromBox.x + (fromBox.w - template.w) * align,
44
38
  y: side === 'bottom' ? box.y + box.h + gap : side === 'top' ? box.y - template.h - gap : fromBox.y + (fromBox.h - template.h) * align,
45
39
  w: template.w,
46
40
  h: template.h,
47
- });
48
- const obstacles = elements.flatMap((element) => {
41
+ };
42
+ }
43
+ /** The boxes a next item placed from `fromBox` keeps clear of (not the frames `fromBox` sits in). */
44
+ function nextItemObstacles(fromBox, elements, measures) {
45
+ return elements.flatMap((element) => {
49
46
  if (NEXT_ITEM_IGNORED_TYPES.has(element.type))
50
47
  return [];
51
48
  const box = elementBounds(element, measures);
52
49
  return box && !isCenteredInside(fromBox, box) ? [box] : [];
53
50
  });
54
- let spot = placeAt(fromBox);
51
+ }
52
+ /**
53
+ * Places `template` beside `from` on `side` (right by default), past
54
+ * anything in the way: each time the spot would touch an item, it moves on
55
+ * past that item, away from `from`. A shape is centered on `from` across
56
+ * that direction, a note aligned with its top (or left) edge. Items `from`
57
+ * sits centered inside (its frames) are not in the way.
58
+ */
59
+ export function placeNextItemBeside(from, template, elements, measures, side = 'right') {
60
+ const fromBox = elementBounds(from, measures) ?? { x: 0, y: 0, w: 0, h: 0 };
61
+ const obstacles = nextItemObstacles(fromBox, elements, measures);
62
+ let spot = spotBeside(fromBox, fromBox, template, side);
55
63
  // Each step moves strictly away from `from`, so this ends after at most one step per obstacle.
56
64
  for (let blocked = obstacles.find((box) => boxesNearlyTouch(spot, box)); blocked; blocked = obstacles.find((box) => boxesNearlyTouch(spot, box))) {
57
- spot = placeAt(blocked);
65
+ spot = spotBeside(fromBox, blocked, template, side);
58
66
  }
59
67
  return { ...template, x: spot.x, y: spot.y };
60
68
  }
69
+ /**
70
+ * Where the item a click on `from`'s `side` dot adds goes: right beside
71
+ * `from` on that side when the spot is clear, else right below `from`, else
72
+ * nowhere (`undefined`). It never steps past items in the way.
73
+ */
74
+ export function placeNextItemAtSide(from, template, side, elements, measures) {
75
+ const fromBox = elementBounds(from, measures);
76
+ if (!fromBox)
77
+ return undefined;
78
+ const obstacles = nextItemObstacles(fromBox, elements, measures);
79
+ for (const toward of side === 'bottom' ? ['bottom'] : [side, 'bottom']) {
80
+ const spot = spotBeside(fromBox, fromBox, template, toward);
81
+ if (!obstacles.some((box) => boxesNearlyTouch(spot, box)))
82
+ return { ...template, x: spot.x, y: spot.y };
83
+ }
84
+ return undefined;
85
+ }
86
+ /** Items that take the room a side dot needs: notes, shapes, sections and stickers. */
87
+ export const SIDE_DOT_BLOCKING_TYPES = new Set(['note', 'shape', 'container', 'sticker']);
88
+ /** Distance from a point to a box: 0 inside it. */
89
+ function distanceToBox(box, x, y) {
90
+ const dx = x < box.x ? box.x - x : x > box.x + box.w ? x - box.x - box.w : 0;
91
+ const dy = y < box.y ? box.y - y : y > box.y + box.h ? y - box.y - box.h : 0;
92
+ return Math.hypot(dx, dy);
93
+ }
94
+ /**
95
+ * Whether a side dot at (`x`, `y`) has room: no note, shape, section or
96
+ * sticker other than `owner` within `reach` of it. A section counts by its
97
+ * outline, so a dot well inside one still has room.
98
+ */
99
+ export function sideDotHasRoom(owner, x, y, reach, elements, measures) {
100
+ return !elements.some((element) => {
101
+ if (element.id === owner.id || !SIDE_DOT_BLOCKING_TYPES.has(element.type))
102
+ return false;
103
+ const box = elementBounds(element, measures);
104
+ if (!box)
105
+ return false;
106
+ const inside = distanceToBox(box, x, y) === 0;
107
+ const distance = inside && element.type === 'container' ? Math.min(x - box.x, box.x + box.w - x, y - box.y, box.y + box.h - y) : distanceToBox(box, x, y);
108
+ return distance <= reach;
109
+ });
110
+ }
61
111
  /** The end of an arrow left on empty board while the other is on an item; `undefined` otherwise. */
62
112
  export function arrowFreeEnd(arrow) {
63
113
  if (typeof arrow.from === 'string')
@@ -27,6 +27,8 @@ export declare function normalizeArrowEnd(end: unknown): ArrowEnd | undefined;
27
27
  export declare function normalizeArrowBends(bends: unknown): ArrowBends | undefined;
28
28
  /** The `size`, `ink` and `textAlign` of notes, shapes and tables. */
29
29
  export declare function normalizeTextStyleFields(input: Loose): TextStyle;
30
+ /** A text placeholder: one plain line, cleaned like a link title, at most {@link MAX_PLACEHOLDER_CHARS}; `undefined` when empty. */
31
+ export declare function normalizePlaceholder(value: unknown): string | undefined;
30
32
  /** The agent's authorship stamps (`by: "agent"`, `words`). */
31
33
  export declare function pickAuthorshipFields(input: Loose): Authorship;
32
34
  /** True for the agent author marker. */
package/src/normalize.js CHANGED
@@ -8,10 +8,10 @@
8
8
  * The output is canonical: normalizing twice gives the same result, which
9
9
  * the sync engine relies on to recognize its own writes coming back.
10
10
  */
11
- import { ARROW_HEAD_KINDS, ARROW_HEAD_MODES, ARROW_SIDES, COORDINATE_LIMIT, DEFAULT_STICKER_SIZE, DEFAULT_TIMER_MS, ELEMENT_ID_PATTERN, FACE_STICKER_ART, HEX_COLOR_PATTERN, INK_COLOR_NAMES, isBoxElement, isRotatableElement, MAX_ARROW_BENDS, MAX_ARROW_JOG, MAX_AUTHOR_ID_CHARS, MAX_BARE_CLAIMS, MAX_BOARD_ELEMENTS, MAX_BOARD_INKS, MAX_CLAIM_IDS, MAX_CLAIMS_WITH_AREA, MAX_ELEMENT_GROUPS, MAX_ELEMENT_SIZE, MAX_HTML_CHARS, MAX_HTML_STATE_CHARS, MAX_LABEL_CHARS, MAX_NOTE_TILT, MAX_STROKE_POINTS, MAX_TIMER_MS, MIN_ELEMENT_SIZE, normalizeTurnDegrees, NOTE_COLORS, sameArrowEnd, SHAPE_KINDS, TEXT_ALIGNMENTS, TEXT_SIZES, WORDS_PATTERN, arrowEndIds, } from "./schema.js";
12
- import { clampElementText, isUploadedBlobSource, normalizeImageSource } from "./image-source.js";
11
+ import { ARROW_HEAD_KINDS, ARROW_HEAD_MODES, ARROW_SIDES, COORDINATE_LIMIT, DEFAULT_STICKER_SIZE, DEFAULT_TIMER_MS, DRAWING_STYLE_PATTERN, ELEMENT_ID_PATTERN, FACE_STICKER_ART, HEX_COLOR_PATTERN, INK_COLOR_NAMES, isBoxElement, isRotatableElement, MAX_ARROW_BENDS, MAX_ARROW_JOG, MAX_AUTHOR_ID_CHARS, MAX_BARE_CLAIMS, MAX_BOARD_ELEMENTS, MAX_BOARD_INKS, MAX_CLAIM_IDS, MAX_CLAIMS_WITH_AREA, MAX_ELEMENT_GROUPS, MAX_ELEMENT_SIZE, MAX_HTML_CHARS, MAX_HTML_STATE_CHARS, MAX_LABEL_CHARS, MAX_NOTE_TILT, MAX_PLACEHOLDER_CHARS, MAX_STROKE_POINTS, MAX_TIMER_MS, MIN_ELEMENT_SIZE, normalizeTurnDegrees, NOTE_COLORS, sameArrowEnd, SHAPE_KINDS, TEXT_ALIGNMENTS, TEXT_SIZES, WORDS_PATTERN, arrowEndIds, } from "./schema.js";
12
+ import { clampElementText, isSvgImageSource, isUploadedBlobSource, normalizeImageSource } from "./image-source.js";
13
13
  import { normalizeImageCrop } from "./image-crop.js";
14
- import { normalizeHttpUrl, normalizeLinkFields } from "./links.js";
14
+ import { normalizeHttpUrl, normalizeLinkFields, sanitizeShortLabel } from "./links.js";
15
15
  import { isStickerArt, normalizeStickerGlyph, stickerGlyphForArt } from "./stickers.js";
16
16
  import { normalizeTable } from "./table.js";
17
17
  import { sliceChars, truncateAuthorName } from "./text-limits.js";
@@ -75,6 +75,11 @@ export function normalizeTextStyleFields(input) {
75
75
  ...pickTextAlign(input),
76
76
  };
77
77
  }
78
+ /** A text placeholder: one plain line, cleaned like a link title, at most {@link MAX_PLACEHOLDER_CHARS}; `undefined` when empty. */
79
+ export function normalizePlaceholder(value) {
80
+ const placeholder = sanitizeShortLabel(value, MAX_PLACEHOLDER_CHARS);
81
+ return placeholder !== '' ? placeholder : undefined;
82
+ }
78
83
  /** The agent's authorship stamps (`by: "agent"`, `words`). */
79
84
  export function pickAuthorshipFields(input) {
80
85
  return {
@@ -286,16 +291,19 @@ function normalizeElementFields(raw, takenIds) {
286
291
  };
287
292
  case 'text': {
288
293
  const wrap = clampFiniteNumber(input.wrap, MIN_ELEMENT_SIZE, MAX_ELEMENT_SIZE);
294
+ const placeholder = normalizePlaceholder(input.placeholder);
295
+ const text = elementText(input.text);
289
296
  return {
290
297
  type: 'text',
291
298
  id,
292
299
  x,
293
300
  y,
294
- text: elementText(input.text),
301
+ text: placeholder !== undefined && text.trim() === '' ? '' : text,
295
302
  size: parseEnumValue(input.size, TEXT_SIZES, 'body'),
296
303
  color: ink(input.color),
297
304
  ...(wrap !== undefined ? { wrap } : {}),
298
305
  ...pickTextAlign(input),
306
+ ...(placeholder !== undefined ? { placeholder } : {}),
299
307
  ...pickAuthorshipFields(input),
300
308
  };
301
309
  }
@@ -306,6 +314,7 @@ function normalizeElementFields(raw, takenIds) {
306
314
  const crop = normalizeImageCrop(input.crop);
307
315
  const video = typeof input.video === 'string' && isUploadedBlobSource(input.video) ? normalizeImageSource(input.video) : undefined;
308
316
  const href = video === undefined ? normalizeHttpUrl(input.href) : undefined;
317
+ const style = isSvgImageSource(src) && typeof input.style === 'string' && DRAWING_STYLE_PATTERN.test(input.style) ? input.style : undefined;
309
318
  return {
310
319
  type: 'image',
311
320
  id,
@@ -317,6 +326,7 @@ function normalizeElementFields(raw, takenIds) {
317
326
  ...(crop !== undefined ? { crop } : {}),
318
327
  ...(video !== undefined ? { video } : {}),
319
328
  ...(href !== undefined ? { href } : {}),
329
+ ...(style !== undefined ? { style } : {}),
320
330
  ...pickBy(input),
321
331
  };
322
332
  }
package/src/schema.d.ts CHANGED
@@ -67,6 +67,8 @@ export declare const MAX_LINK_HREF_CHARS = 512;
67
67
  export declare const MAX_LINK_TITLE_CHARS = 120;
68
68
  /** Longest image link (`href`). */
69
69
  export declare const MAX_IMAGE_HREF_CHARS = 2048;
70
+ /** Longest text placeholder. */
71
+ export declare const MAX_PLACEHOLDER_CHARS = 200;
70
72
  /** Element ids: 1–40 characters of the db path alphabet, not only dots. */
71
73
  export declare const ELEMENT_ID_PATTERN: RegExp;
72
74
  /** `#rrggbb`, any case. */
@@ -125,6 +127,11 @@ export type SectionLayout = (typeof SECTION_LAYOUTS)[number];
125
127
  export declare const LINK_KINDS: readonly ["whiteboard", "design", "design-system", "slides", "doc", "dashboard", "motion", "web"];
126
128
  export type LinkKind = (typeof LINK_KINDS)[number];
127
129
  export declare const LINK_KIND_LABELS: Readonly<Record<LinkKind, string>>;
130
+ /** Looks an SVG drawing can be drawn in (`style`). */
131
+ export declare const DRAWING_STYLES: readonly ["watercolor", "comic", "draft", "paper", "blueprint", "marker", "plain"];
132
+ export type DrawingStyle = (typeof DRAWING_STYLES)[number];
133
+ /** A `style` value the format keeps: a lowercase slug, so a look added later survives older peers. */
134
+ export declare const DRAWING_STYLE_PATTERN: RegExp;
128
135
  /** Default size of a link card. */
129
136
  export declare const LINK_CARD_SIZE: {
130
137
  readonly w: 320;
@@ -214,6 +221,8 @@ export interface TextElement extends ElementBase, Authorship {
214
221
  /** Wrap width; the text does not wrap without it. */
215
222
  wrap?: number;
216
223
  textAlign?: TextAlign;
224
+ /** Shown while the text is empty; one plain line. */
225
+ placeholder?: string;
217
226
  }
218
227
  /** A freehand stroke. */
219
228
  export interface StrokeElement extends ElementBase {
@@ -269,6 +278,8 @@ export interface ImageElement extends ElementBase, BoxGeometry {
269
278
  video?: string;
270
279
  /** A web link the image opens. */
271
280
  href?: string;
281
+ /** How an SVG drawing is drawn; only SVG drawings carry it. */
282
+ style?: string;
272
283
  by?: ElementAuthor;
273
284
  }
274
285
  /**
@@ -333,6 +344,13 @@ export type TableRow = {
333
344
  } & {
334
345
  [columnId: string]: string | number | undefined;
335
346
  };
347
+ /** Cell backgrounds of a table: `{ [rowId]: { [columnId]: color } }`. */
348
+ export type TableFills = Record<string, Record<string, FillColor>>;
349
+ /** Heat maps of a table: a color per column and per row, tinting its numbers by value. */
350
+ export interface TableHeat {
351
+ cols?: Record<string, FillColor>;
352
+ rows?: Record<string, FillColor>;
353
+ }
336
354
  /** A table. Rows and columns are keyed so concurrent edits merge. */
337
355
  export interface TableElement extends ElementBase, Authorship, TextStyle {
338
356
  type: 'table';
@@ -344,6 +362,8 @@ export interface TableElement extends ElementBase, Authorship, TextStyle {
344
362
  head: boolean;
345
363
  /** Header fill. */
346
364
  color: FillColor;
365
+ fills?: TableFills;
366
+ heat?: TableHeat;
347
367
  }
348
368
  /** Every element. */
349
369
  export type BoardElement = NoteElement | ShapeElement | ContainerElement | TextElement | StrokeElement | ArrowElement | ImageElement | StickerElement | HtmlElement | TimerElement | LinkElement | TableElement;
package/src/schema.js CHANGED
@@ -70,6 +70,8 @@ export const MAX_LINK_HREF_CHARS = 512;
70
70
  export const MAX_LINK_TITLE_CHARS = 120;
71
71
  /** Longest image link (`href`). */
72
72
  export const MAX_IMAGE_HREF_CHARS = 2048;
73
+ /** Longest text placeholder. */
74
+ export const MAX_PLACEHOLDER_CHARS = 200;
73
75
  /** Element ids: 1–40 characters of the db path alphabet, not only dots. */
74
76
  export const ELEMENT_ID_PATTERN = /^(?!\.{1,40}$)[A-Za-z0-9_.~:@+-]{1,40}$/;
75
77
  /** `#rrggbb`, any case. */
@@ -150,6 +152,10 @@ export const LINK_KIND_LABELS = {
150
152
  motion: 'Motion',
151
153
  web: 'Web page',
152
154
  };
155
+ /** Looks an SVG drawing can be drawn in (`style`). */
156
+ export const DRAWING_STYLES = ['watercolor', 'comic', 'draft', 'paper', 'blueprint', 'marker', 'plain'];
157
+ /** A `style` value the format keeps: a lowercase slug, so a look added later survives older peers. */
158
+ export const DRAWING_STYLE_PATTERN = /^[a-z][a-z0-9-]{0,39}$/;
153
159
  /** Default size of a link card. */
154
160
  export const LINK_CARD_SIZE = { w: 320, h: 56 };
155
161
  /** Element types that may be rotated (`turn`). */
package/src/selection.js CHANGED
@@ -446,15 +446,15 @@ export function applyResizeDrag(elements, drag, to, fitting) {
446
446
  }
447
447
  /** Selection behavior per element type. */
448
448
  export const ELEMENT_KIND_AFFORDANCES = {
449
- note: { words: 'body', resizes: true, dots: 'adds' },
449
+ note: { words: 'body', resizes: true, dots: 'adds, connects' },
450
450
  shape: { words: 'body', resizes: true, dots: 'adds, connects' },
451
- text: { words: 'body', resizes: true, dots: 'connects', hairline: true },
452
- table: { words: 'body', resizes: true, dots: 'connects' },
453
- container: { words: 'label', resizes: true, dots: 'connects' },
451
+ text: { words: 'body', resizes: true, dots: 'none', hairline: true },
452
+ table: { words: 'body', resizes: true, dots: 'none' },
453
+ container: { words: 'label', resizes: true, dots: 'none' },
454
454
  arrow: { words: 'label', resizes: false, dots: 'none', line: true },
455
- image: { words: 'none', resizes: true, dots: 'connects' },
456
- link: { words: 'none', resizes: false, dots: 'connects' },
457
- timer: { words: 'none', resizes: false, dots: 'connects' },
455
+ image: { words: 'none', resizes: true, dots: 'none' },
456
+ link: { words: 'none', resizes: false, dots: 'none' },
457
+ timer: { words: 'none', resizes: false, dots: 'none' },
458
458
  sticker: { words: 'none', resizes: true, dots: 'none' },
459
459
  stroke: { words: 'none', resizes: true, dots: 'none' },
460
460
  html: { words: 'source', resizes: true, dots: 'none' },
@@ -479,7 +479,7 @@ export function selectionChromeFor(kind, state, context) {
479
479
  return NO_SELECTION_CHROME;
480
480
  return {
481
481
  outline: 'thin',
482
- dots: context.finger === true || context.tool === 'hand' || (kind === 'text' && context.empty === true)
482
+ dots: context.finger === true || context.tool === 'hand' || affordance.dots === 'none'
483
483
  ? 'none'
484
484
  : context.tool === 'arrow'
485
485
  ? 'connects'
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Table colors as drawn: cell fills and heat maps turned into a background
3
+ * and, where the usual text would not read on it, a text color.
4
+ *
5
+ * A fill named after a block color is a soft tint of that color on the
6
+ * paper, under the table's usual text; a `#rrggbb` fill is drawn as
7
+ * written, with dark or light text, whichever reads. A heat map shades each
8
+ * number of its column (or row) by where it falls between the smallest and
9
+ * largest number of the same unit there, faint at the low end and strong at
10
+ * the top, with dark or light text, whichever reads. The header row is
11
+ * never shaded.
12
+ */
13
+ import { type FillColor, type TableElement, type TableHeat } from './schema.ts';
14
+ import { type TableAxis } from './table.ts';
15
+ import { type ColorScheme } from './theme.ts';
16
+ /** How strongly a named fill tints the paper. */
17
+ export declare const TABLE_FILL_TINT = 0.25;
18
+ /** How strongly a heat map's color covers the paper at its lowest and highest number. */
19
+ export declare const TABLE_HEAT_OPACITY: {
20
+ readonly low: 0.08;
21
+ readonly high: 0.92;
22
+ };
23
+ /** Longest cell text a heat map reads as a number. */
24
+ export declare const MAX_TABLE_NUMBER_CHARS = 60;
25
+ /** One cell's paint: its background, and a text color when the table's usual text would not read on it. */
26
+ export interface TableCellPaint {
27
+ fill: string;
28
+ ink?: string;
29
+ }
30
+ /** One cell of a heat map: its color and where its number falls, 0 (lowest) to 1 (highest). */
31
+ export interface TableHeatLevel {
32
+ color: FillColor;
33
+ level: number;
34
+ }
35
+ /** A number read from a cell, and its unit: a currency sign, `%`, or `""`. */
36
+ export interface TableCellNumber {
37
+ value: number;
38
+ unit: string;
39
+ }
40
+ /** Values by row id, then column id. */
41
+ export type TableCellMap<V> = Record<string, Record<string, V>>;
42
+ /** The table fields heat maps read. */
43
+ export type TableHeatSource = Pick<TableElement, 'cols' | 'rows' | 'head' | 'heat'>;
44
+ /** The table fields fills and heat maps read. */
45
+ export type TableTintSource = TableHeatSource & Pick<TableElement, 'fills'>;
46
+ /**
47
+ * The number a cell's text shows, or `undefined`. Markdown `*`, `_` and
48
+ * backtick wrappers are read through; then it is digits with optional
49
+ * thousands commas and decimals, an optional sign (`-`, `+` or `−`), and
50
+ * either a leading `$`, `€` or `£` or a trailing `%` (`$1,200`, `−3.5%`).
51
+ */
52
+ export declare function tableCellNumber(text: string): TableCellNumber | undefined;
53
+ /**
54
+ * The heat-map level of every numeric cell a heat map covers. Numbers are
55
+ * ranked against those of the same unit; when a line mixes units, a unit
56
+ * with a single number is left unshaded. Equal numbers sit at 0.5. Where a
57
+ * row and a column heat map cross, the column's wins.
58
+ */
59
+ export declare function tableHeatLevels(table: TableHeatSource): TableCellMap<TableHeatLevel>;
60
+ /** The paint of a cell fill. */
61
+ export declare function tableFillPaint(color: FillColor, scheme: ColorScheme): TableCellPaint;
62
+ /** The paint of a heat-map cell at `level` (0–1): the color laid over the paper, with dark or light text. */
63
+ export declare function tableHeatPaint(color: FillColor, level: number, scheme: ColorScheme): Required<TableCellPaint>;
64
+ /** The paint of every tinted cell: its fill, or else its heat-map shade. The header row keeps the header's color. */
65
+ export declare function tableCellPaints(table: TableTintSource, scheme: ColorScheme): TableCellMap<TableCellPaint>;
66
+ /** The color a new heat map takes: the table's own color, or blue on a white table. */
67
+ export declare function defaultTableHeatColor(table: Pick<TableElement, 'color'>): FillColor;
68
+ /**
69
+ * The table with a heat map set on one column or row (`""` takes it off).
70
+ * Heat maps run along one axis at a time, so setting one removes those of
71
+ * the other axis, and the cells it shades lose their own fills. The header
72
+ * row takes no row heat map.
73
+ */
74
+ export declare function withTableHeat<T extends TableTintSource>(table: T, axis: TableAxis, id: string, color: FillColor | ''): T;
75
+ /** A cell's own fill, `""` for none. */
76
+ export declare function tableCellFill(table: Pick<TableElement, 'fills'>, rowId: string, columnId: string): FillColor | '';
77
+ /** One fill change: `[row, column, expected, value]`, where `""` is no fill. */
78
+ export type TableFillSwap = readonly [rowId: string, columnId: string, expected: FillColor | '', value: FillColor | ''];
79
+ /** Sets each cell's fill to its value, but only where the cell still has the expected fill. */
80
+ export declare function setTableFillsWhereUnchanged<T extends TableTintSource>(table: T, swaps: readonly TableFillSwap[]): T;
81
+ /** The table's heat maps set to `value`, but only where they are still `expected`. */
82
+ export declare function setTableHeatWhereUnchanged<T extends TableTintSource>(table: T, expected: TableHeat | undefined, value: TableHeat | undefined): T;
83
+ /** The fill changes between two versions of a table, as swaps from `before` to `after`. */
84
+ export declare function tableFillSwaps(before: Pick<TableElement, 'fills'>, after: Pick<TableElement, 'fills'>): TableFillSwap[];
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Table colors as drawn: cell fills and heat maps turned into a background
3
+ * and, where the usual text would not read on it, a text color.
4
+ *
5
+ * A fill named after a block color is a soft tint of that color on the
6
+ * paper, under the table's usual text; a `#rrggbb` fill is drawn as
7
+ * written, with dark or light text, whichever reads. A heat map shades each
8
+ * number of its column (or row) by where it falls between the smallest and
9
+ * largest number of the same unit there, faint at the low end and strong at
10
+ * the top, with dark or light text, whichever reads. The header row is
11
+ * never shaded.
12
+ */
13
+ import { canonicalValuesEqual } from "./json.js";
14
+ import { HEX_COLOR_PATTERN } from "./schema.js";
15
+ import { tableCellValue, tableColumnIds, tableRowIds } from "./table.js";
16
+ import { BOARD_THEME_COLORS, contrastTextColorOn, mixHexColors, shapeFillForColor } from "./theme.js";
17
+ /** How strongly a named fill tints the paper. */
18
+ export const TABLE_FILL_TINT = 0.25;
19
+ /** How strongly a heat map's color covers the paper at its lowest and highest number. */
20
+ export const TABLE_HEAT_OPACITY = { low: 0.08, high: 0.92 };
21
+ /** Longest cell text a heat map reads as a number. */
22
+ export const MAX_TABLE_NUMBER_CHARS = 60;
23
+ const NUMBER_PATTERN = /^([-+−]?)([$€£]?)([-+−]?)(\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\.\d+)(%?)$/;
24
+ const INLINE_WRAPPER_PATTERN = /^([*_`]+)(.+)\1$/s;
25
+ /**
26
+ * The number a cell's text shows, or `undefined`. Markdown `*`, `_` and
27
+ * backtick wrappers are read through; then it is digits with optional
28
+ * thousands commas and decimals, an optional sign (`-`, `+` or `−`), and
29
+ * either a leading `$`, `€` or `£` or a trailing `%` (`$1,200`, `−3.5%`).
30
+ */
31
+ export function tableCellNumber(text) {
32
+ let value = text.trim();
33
+ if (value.length > MAX_TABLE_NUMBER_CHARS)
34
+ return undefined;
35
+ for (let match = INLINE_WRAPPER_PATTERN.exec(value); match !== null; match = INLINE_WRAPPER_PATTERN.exec(value))
36
+ value = match[2].trim();
37
+ const match = NUMBER_PATTERN.exec(value);
38
+ if (match === null)
39
+ return undefined;
40
+ const [, signBefore, currency, signAfter, digits, percent] = match;
41
+ if ((signBefore !== '' && signAfter !== '') || (currency !== '' && percent !== ''))
42
+ return undefined;
43
+ const magnitude = Number(digits.replaceAll(',', ''));
44
+ return { value: /[-−]/.test(signBefore + signAfter) ? -magnitude : magnitude, unit: currency + percent };
45
+ }
46
+ function setCell(map, rowId, columnId, value) {
47
+ (map[rowId] ??= {})[columnId] = value;
48
+ }
49
+ /** The rows a heat map may cover: every row but the header. */
50
+ function tableBodyRowIds(table) {
51
+ const rowIds = tableRowIds(table);
52
+ return table.head ? rowIds.slice(1) : rowIds;
53
+ }
54
+ /**
55
+ * The heat-map level of every numeric cell a heat map covers. Numbers are
56
+ * ranked against those of the same unit; when a line mixes units, a unit
57
+ * with a single number is left unshaded. Equal numbers sit at 0.5. Where a
58
+ * row and a column heat map cross, the column's wins.
59
+ */
60
+ export function tableHeatLevels(table) {
61
+ const levels = {};
62
+ if (table.heat === undefined)
63
+ return levels;
64
+ const bodyRowIds = tableBodyRowIds(table);
65
+ const columnIds = tableColumnIds(table);
66
+ const shade = (cells, color) => {
67
+ const byUnit = new Map();
68
+ for (const [rowId, columnId] of cells) {
69
+ const number = tableCellNumber(tableCellValue(table, rowId, columnId));
70
+ if (number === undefined)
71
+ continue;
72
+ const group = byUnit.get(number.unit) ?? [];
73
+ group.push([rowId, columnId, number.value]);
74
+ byUnit.set(number.unit, group);
75
+ }
76
+ for (const group of byUnit.values()) {
77
+ if (byUnit.size > 1 && group.length === 1)
78
+ continue;
79
+ const values = group.map(([, , value]) => value);
80
+ const [low, high] = [Math.min(...values), Math.max(...values)];
81
+ for (const [rowId, columnId, value] of group)
82
+ setCell(levels, rowId, columnId, { color, level: high === low ? 0.5 : (value - low) / (high - low) });
83
+ }
84
+ };
85
+ for (const rowId of bodyRowIds) {
86
+ const color = table.heat.rows?.[rowId];
87
+ if (color !== undefined)
88
+ shade(columnIds.map((columnId) => [rowId, columnId]), color);
89
+ }
90
+ for (const columnId of columnIds) {
91
+ const color = table.heat.cols?.[columnId];
92
+ if (color !== undefined)
93
+ shade(bodyRowIds.map((rowId) => [rowId, columnId]), color);
94
+ }
95
+ return levels;
96
+ }
97
+ /** The paint of a cell fill. */
98
+ export function tableFillPaint(color, scheme) {
99
+ if (HEX_COLOR_PATTERN.test(color))
100
+ return { fill: color, ink: contrastTextColorOn(color) };
101
+ return { fill: mixHexColors(BOARD_THEME_COLORS[scheme].paper, shapeFillForColor(color), TABLE_FILL_TINT) };
102
+ }
103
+ /** The paint of a heat-map cell at `level` (0–1): the color laid over the paper, with dark or light text. */
104
+ export function tableHeatPaint(color, level, scheme) {
105
+ const full = HEX_COLOR_PATTERN.test(color) ? color : shapeFillForColor(color);
106
+ const opacity = TABLE_HEAT_OPACITY.low + (TABLE_HEAT_OPACITY.high - TABLE_HEAT_OPACITY.low) * Math.min(1, Math.max(0, level));
107
+ const fill = mixHexColors(BOARD_THEME_COLORS[scheme].paper, full, opacity);
108
+ return { fill, ink: contrastTextColorOn(fill) };
109
+ }
110
+ /** The paint of every tinted cell: its fill, or else its heat-map shade. The header row keeps the header's color. */
111
+ export function tableCellPaints(table, scheme) {
112
+ const paints = {};
113
+ for (const [rowId, cells] of Object.entries(tableHeatLevels(table))) {
114
+ for (const [columnId, { color, level }] of Object.entries(cells))
115
+ setCell(paints, rowId, columnId, tableHeatPaint(color, level, scheme));
116
+ }
117
+ const bodyRowIds = new Set(tableBodyRowIds(table));
118
+ for (const [rowId, cells] of Object.entries(table.fills ?? {})) {
119
+ if (!bodyRowIds.has(rowId))
120
+ continue;
121
+ for (const [columnId, color] of Object.entries(cells))
122
+ setCell(paints, rowId, columnId, tableFillPaint(color, scheme));
123
+ }
124
+ return paints;
125
+ }
126
+ /** The color a new heat map takes: the table's own color, or blue on a white table. */
127
+ export function defaultTableHeatColor(table) {
128
+ return table.color === 'white' || table.color.toLowerCase() === '#ffffff' ? 'blue' : table.color;
129
+ }
130
+ /**
131
+ * The table with a heat map set on one column or row (`""` takes it off).
132
+ * Heat maps run along one axis at a time, so setting one removes those of
133
+ * the other axis, and the cells it shades lose their own fills. The header
134
+ * row takes no row heat map.
135
+ */
136
+ export function withTableHeat(table, axis, id, color) {
137
+ const bodyRowIds = tableBodyRowIds(table);
138
+ if (axis === 'rows' ? !bodyRowIds.includes(id) : table.cols[id] === undefined)
139
+ return table;
140
+ const { [id]: _previous, ...others } = table.heat?.[axis] ?? {};
141
+ const line = color === '' ? others : { ...others, [id]: color };
142
+ const kept = color === '' ? { ...table.heat } : {};
143
+ if (Object.keys(line).length > 0)
144
+ kept[axis] = line;
145
+ else
146
+ delete kept[axis];
147
+ const fills = { ...table.fills };
148
+ if (color !== '' && axis === 'rows')
149
+ delete fills[id];
150
+ else if (color !== '') {
151
+ for (const rowId of bodyRowIds) {
152
+ const cells = fills[rowId];
153
+ if (cells?.[id] === undefined)
154
+ continue;
155
+ const { [id]: _cleared, ...rest } = cells;
156
+ if (Object.keys(rest).length > 0)
157
+ fills[rowId] = rest;
158
+ else
159
+ delete fills[rowId];
160
+ }
161
+ }
162
+ const result = { ...table, heat: kept, fills };
163
+ if (kept.cols === undefined && kept.rows === undefined)
164
+ Reflect.deleteProperty(result, 'heat');
165
+ if (Object.keys(fills).length === 0)
166
+ Reflect.deleteProperty(result, 'fills');
167
+ return result;
168
+ }
169
+ /** A cell's own fill, `""` for none. */
170
+ export function tableCellFill(table, rowId, columnId) {
171
+ return table.fills?.[rowId]?.[columnId] ?? '';
172
+ }
173
+ /** Sets each cell's fill to its value, but only where the cell still has the expected fill. */
174
+ export function setTableFillsWhereUnchanged(table, swaps) {
175
+ const fills = { ...table.fills };
176
+ let changed = false;
177
+ for (const [rowId, columnId, expected, value] of swaps) {
178
+ if (table.rows[rowId] === undefined || table.cols[columnId] === undefined || expected === value || tableCellFill({ fills }, rowId, columnId) !== expected)
179
+ continue;
180
+ const { [columnId]: _previous, ...rest } = fills[rowId] ?? {};
181
+ const cells = value === '' ? rest : { ...rest, [columnId]: value };
182
+ if (Object.keys(cells).length > 0)
183
+ fills[rowId] = cells;
184
+ else
185
+ delete fills[rowId];
186
+ changed = true;
187
+ }
188
+ if (!changed)
189
+ return table;
190
+ const result = { ...table, fills };
191
+ if (Object.keys(fills).length === 0)
192
+ Reflect.deleteProperty(result, 'fills');
193
+ return result;
194
+ }
195
+ /** The table's heat maps set to `value`, but only where they are still `expected`. */
196
+ export function setTableHeatWhereUnchanged(table, expected, value) {
197
+ if (!canonicalValuesEqual(table.heat, expected) || canonicalValuesEqual(expected, value))
198
+ return table;
199
+ const result = { ...table, heat: value };
200
+ if (value === undefined)
201
+ Reflect.deleteProperty(result, 'heat');
202
+ return result;
203
+ }
204
+ /** The fill changes between two versions of a table, as swaps from `before` to `after`. */
205
+ export function tableFillSwaps(before, after) {
206
+ const swaps = [];
207
+ const rowIds = new Set([...Object.keys(before.fills ?? {}), ...Object.keys(after.fills ?? {})]);
208
+ for (const rowId of rowIds) {
209
+ const columnIds = new Set([...Object.keys(before.fills?.[rowId] ?? {}), ...Object.keys(after.fills?.[rowId] ?? {})]);
210
+ for (const columnId of columnIds) {
211
+ const [from, to] = [tableCellFill(before, rowId, columnId), tableCellFill(after, rowId, columnId)];
212
+ if (from !== to)
213
+ swaps.push([rowId, columnId, from, to]);
214
+ }
215
+ }
216
+ return swaps;
217
+ }
package/src/table.d.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  * built-in glyph-width table, so sizing is the same in every browser and in
12
12
  * Node (the agent's checks).
13
13
  */
14
- import type { TableElement, TextSize } from './schema.ts';
14
+ import { type FillColor, type TableElement, type TextSize } from './schema.ts';
15
15
  /** Most cells one table holds, and most bytes of its JSON. */
16
16
  export declare const TABLE_LIMITS: {
17
17
  readonly cells: 3000;
@@ -71,6 +71,8 @@ export declare function tableCellValue(table: Pick<TableData, 'rows'>, rowId: st
71
71
  export declare function hasTableCell(table: TableData, rowId: string, columnId: string): boolean;
72
72
  /** Every cell's text, row by row. */
73
73
  export declare function tableCellGrid(table: TableData): string[][];
74
+ /** A cell fill or heat-map color: a block color name or `#rrggbb` (lower-cased); `undefined` for anything else, `""` included. */
75
+ export declare function tableTintColor(value: unknown): FillColor | undefined;
74
76
  /** True when a grid of this size would exceed {@link TABLE_LIMITS}. */
75
77
  export declare function exceedsTableCellLimit(rows: number, columns: number): boolean;
76
78
  /** Estimated width of a text in em, or 0 when no glyph is known (CJK, emoji). */
@@ -111,11 +113,22 @@ export declare function tableTotalHeight(table: TableData): number;
111
113
  * columns derived from the cells when missing, cells as strings, and at
112
114
  * least one row and one column. Empty cells of unknown columns are kept as
113
115
  * `""` (they are tombstones a concurrent column delete left).
116
+ *
117
+ * `fills` and `heat` keep valid colors of rows and columns that exist. A
118
+ * cell written as `{text, color}` reads as its text, with its color as the
119
+ * cell's fill unless `fills` names that cell.
114
120
  */
115
121
  export declare function normalizeTable(raw: {
116
122
  cols?: unknown;
117
123
  rows?: unknown;
118
- }, cellText: (text: string) => string): Pick<TableElement, 'cols' | 'rows'>;
124
+ fills?: unknown;
125
+ heat?: unknown;
126
+ head?: unknown;
127
+ }, cellText: (text: string) => string): Pick<TableElement, 'cols' | 'rows' | 'fills' | 'heat'>;
128
+ /** True when a fill or a heat map tints the row. */
129
+ export declare function tableRowIsTinted(table: Pick<TableElement, 'fills' | 'heat'>, rowId: string): boolean;
130
+ /** True when a fill or a heat map tints the column. */
131
+ export declare function tableColumnIsTinted(table: Pick<TableElement, 'fills' | 'heat'>, columnId: string): boolean;
119
132
  /** A table from a grid of texts (rows of cells). */
120
133
  export declare function tableFromGrid(grid: readonly (readonly string[])[]): Pick<TableElement, 'cols' | 'rows'>;
121
134
  /** A random key (`prefix` + 8 letters) not already in `existing`. */
@@ -160,8 +173,8 @@ export declare function pinColumnWidths<T extends TableData>(table: T): T;
160
173
  export declare function scaleTableWidth<T extends TableData>(table: T, width: number, reference?: TableData): T;
161
174
  /**
162
175
  * Undo/redo of a table edit applied over current content: takes the
163
- * incoming rows and columns but keeps column widths that changed locally
164
- * since `base`.
176
+ * incoming rows, columns, fills and heat maps but keeps column widths that
177
+ * changed locally since `base`.
165
178
  */
166
179
  export declare function mergeTableEdit<T extends {
167
180
  type: string;