@miadi/stateloom-canvas 0.1.6 → 0.1.9

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.
@@ -11,17 +11,25 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
11
11
  * scrim with a hole around each spotlighted element, and each hole is ringed;
12
12
  * - **frames** an area the agent names;
13
13
  * - **pins** each mark at what it points at, numbered, coloured by whether it
14
- * waits (open), was answered, or is done — a tap opens its thread;
14
+ * waits (open), was answered, or is done — a tap opens its thread; a mark
15
+ * the host lists in `unread` (an agent's word not yet opened) wears a quiet
16
+ * "new" ring and dot. Every pin stays inside the board, pins that land on one
17
+ * point fan out down its right edge, and none sits under a box the host says
18
+ * to keep clear (`avoid`: the board's own buttons) — `placePins`;
15
19
  * - **takes a mark** when the host turns marking on: a tap names the element
16
20
  * under it, a drag names the elements inside the area drawn (and the area).
21
+ * A mouse or pen tap on empty board marks a small area there; a finger's tap
22
+ * on empty board does nothing, so a phone's stray touch never makes a mark
23
+ * (a finger's drag still frames an area).
17
24
  *
18
25
  * Positioned over the canvas by the host (both in one `position: relative`
19
26
  * box); it lets every pointer through to the canvas except on its pins and
20
27
  * while marking.
21
28
  */
22
- import { useId, useMemo, useRef, useState } from "react";
29
+ import { useEffect, useId, useMemo, useRef, useState } from "react";
23
30
  import { boxesOf, elementAt, elementsInRegion, padBox, screenToWorld, unionBox, viewportTransform, worldToScreen, } from "@miadi/stateloom-protocol";
24
31
  import { themeStyle } from "./theme.js";
32
+ import { placePins } from "./pins.js";
25
33
  /** Below this many screen pixels a press is a tap, not an area. */
26
34
  const DRAG_THRESHOLD = 6;
27
35
  /** A tap on empty board marks a square this many screen pixels wide around it. */
@@ -39,14 +47,39 @@ function pinTone(mark) {
39
47
  return mark.status === "answered" ? "answered" : "question";
40
48
  return mark.status === "answered" ? "answered" : "open";
41
49
  }
42
- export function StageOverlay({ viewport, boxes, spotlight, region, marks, selectedMark = null, onSelectMark, hideResolved = true, marking = false, onDraft, draft = null, theme, className, style, }) {
50
+ export function StageOverlay({ viewport, boxes, spotlight, region, marks, selectedMark = null, onSelectMark, unread, hideResolved = true, marking = false, onDraft, draft = null, avoid, theme, className, style, }) {
43
51
  const maskId = `slc-stage-mask-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
44
52
  const rootRef = useRef(null);
45
53
  const press = useRef(null);
46
54
  const [drag, setDrag] = useState(null);
55
+ // The board's size, for keeping pins inside it; and whether a finger (bigger pins) points.
56
+ const [size, setSize] = useState(null);
57
+ const [coarse, setCoarse] = useState(false);
58
+ useEffect(() => {
59
+ const el = rootRef.current;
60
+ if (!el)
61
+ return;
62
+ const measure = () => {
63
+ const r = el.getBoundingClientRect();
64
+ setSize((s) => (s && s.w === r.width && s.h === r.height ? s : { w: r.width, h: r.height }));
65
+ };
66
+ measure();
67
+ try {
68
+ setCoarse(window.matchMedia("(pointer: coarse)").matches);
69
+ }
70
+ catch {
71
+ // No media queries here: mouse-sized pins.
72
+ }
73
+ if (typeof ResizeObserver === "undefined")
74
+ return;
75
+ const watch = new ResizeObserver(measure);
76
+ watch.observe(el);
77
+ return () => watch.disconnect();
78
+ }, []);
47
79
  const holes = useMemo(() => (spotlight?.length ? boxesOf(boxes, spotlight).map((b) => padBox(b, HOLE_PAD)) : []), [boxes, spotlight]);
48
80
  const vt = viewportTransform(viewport);
49
81
  const selected = marks?.find((m) => m.id === selectedMark) ?? null;
82
+ const unreadIds = useMemo(() => new Set(unread ?? []), [unread]);
50
83
  const ringed = useMemo(() => {
51
84
  const out = [];
52
85
  if (selected?.elements?.length)
@@ -56,7 +89,7 @@ export function StageOverlay({ viewport, boxes, spotlight, region, marks, select
56
89
  return out.map((b) => padBox(b, 4));
57
90
  }, [boxes, selected, draft]);
58
91
  const framed = [selected?.region, draft?.region].filter((b) => !!b);
59
- const pins = (marks ?? [])
92
+ const anchored = (marks ?? [])
60
93
  .map((m, i) => ({ mark: m, n: i + 1 }))
61
94
  .filter(({ mark }) => !(hideResolved && mark.status === "resolved" && mark.id !== selectedMark))
62
95
  .map(({ mark, n }) => {
@@ -67,6 +100,8 @@ export function StageOverlay({ viewport, boxes, spotlight, region, marks, select
67
100
  return { mark, n, x: p.x, y: p.y };
68
101
  })
69
102
  .filter((p) => p !== null);
103
+ const placed = size?.w ? placePins(anchored, { width: size.w, height: size.h, size: coarse ? 30 : 22, avoid }) : anchored;
104
+ const pins = anchored.map((p, i) => ({ ...p, x: placed[i].x, y: placed[i].y }));
70
105
  const local = (e) => {
71
106
  const r = rootRef.current?.getBoundingClientRect();
72
107
  return { x: e.clientX - (r?.left ?? 0), y: e.clientY - (r?.top ?? 0) };
@@ -106,10 +141,13 @@ export function StageOverlay({ viewport, boxes, spotlight, region, marks, select
106
141
  const hit = elementAt(boxes, w.x, w.y);
107
142
  if (hit)
108
143
  return onDraft?.({ elements: [hit] });
144
+ // A finger's tap on empty board is a pan or a dismiss gone astray, not a mark.
145
+ if (e.pointerType === "touch")
146
+ return;
109
147
  const half = TAP_AREA / 2 / (viewport.scale || 1);
110
148
  onDraft?.({ elements: [], region: { x: w.x - half, y: w.y - half, width: half * 2, height: half * 2 } });
111
149
  };
112
- return (_jsxs("div", { ref: rootRef, className: `slc-stage${marking ? " slc-stage--marking" : ""}${className ? ` ${className}` : ""}`, style: { ...themeStyle(theme), ...style }, children: [_jsxs("svg", { className: "slc-stage-svg", "aria-hidden": "true", children: [holes.length > 0 && (_jsxs(_Fragment, { children: [_jsx("defs", { children: _jsxs("mask", { id: maskId, maskUnits: "userSpaceOnUse", x: "0", y: "0", width: "100%", height: "100%", children: [_jsx("rect", { x: "0", y: "0", width: "100%", height: "100%", fill: "white" }), _jsx("g", { transform: vt, children: holes.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 10, fill: "black" }, i))) })] }) }), _jsx("rect", { x: "0", y: "0", width: "100%", height: "100%", className: "slc-stage-scrim", mask: `url(#${maskId})` }), _jsx("g", { transform: vt, children: holes.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 10, className: "slc-stage-ring", vectorEffect: "non-scaling-stroke" }, i))) })] })), _jsxs("g", { transform: vt, children: [region && (_jsx("rect", { x: region.x, y: region.y, width: region.width, height: region.height, rx: 6, className: "slc-stage-region", vectorEffect: "non-scaling-stroke" })), ringed.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 8, className: "slc-stage-mark-ring", vectorEffect: "non-scaling-stroke" }, `r${i}`))), framed.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 4, className: "slc-stage-mark-area", vectorEffect: "non-scaling-stroke" }, `f${i}`)))] }), drag && _jsx("rect", { x: drag.x, y: drag.y, width: drag.w, height: drag.h, rx: 4, className: "slc-stage-drag" })] }), pins.map(({ mark, n, x, y }) => (_jsxs("button", { type: "button", className: `slc-stage-pin slc-stage-pin--${pinTone(mark)}${mark.id === selectedMark ? " slc-stage-pin--selected" : ""}`, style: { left: x, top: y }, title: `${mark.author.name}: ${mark.text}${mark.replies?.length ? ` (${mark.replies.length} repl${mark.replies.length === 1 ? "y" : "ies"})` : ""}`, "aria-label": `Mark ${n}, ${mark.status}: ${mark.text}`, onPointerDown: (e) => e.stopPropagation(), onClick: (e) => {
150
+ return (_jsxs("div", { ref: rootRef, className: `slc-stage${marking ? " slc-stage--marking" : ""}${className ? ` ${className}` : ""}`, style: { ...themeStyle(theme), ...style }, children: [_jsxs("svg", { className: "slc-stage-svg", "aria-hidden": "true", children: [holes.length > 0 && (_jsxs(_Fragment, { children: [_jsx("defs", { children: _jsxs("mask", { id: maskId, maskUnits: "userSpaceOnUse", x: "0", y: "0", width: "100%", height: "100%", children: [_jsx("rect", { x: "0", y: "0", width: "100%", height: "100%", fill: "white" }), _jsx("g", { transform: vt, children: holes.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 10, fill: "black" }, i))) })] }) }), _jsx("rect", { x: "0", y: "0", width: "100%", height: "100%", className: "slc-stage-scrim", mask: `url(#${maskId})` }), _jsx("g", { transform: vt, children: holes.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 10, className: "slc-stage-ring", vectorEffect: "non-scaling-stroke" }, i))) })] })), _jsxs("g", { transform: vt, children: [region && (_jsx("rect", { x: region.x, y: region.y, width: region.width, height: region.height, rx: 6, className: "slc-stage-region", vectorEffect: "non-scaling-stroke" })), ringed.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 8, className: "slc-stage-mark-ring", vectorEffect: "non-scaling-stroke" }, `r${i}`))), framed.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 4, className: "slc-stage-mark-area", vectorEffect: "non-scaling-stroke" }, `f${i}`)))] }), drag && _jsx("rect", { x: drag.x, y: drag.y, width: drag.w, height: drag.h, rx: 4, className: "slc-stage-drag" })] }), pins.map(({ mark, n, x, y }) => (_jsxs("button", { type: "button", className: `slc-stage-pin slc-stage-pin--${pinTone(mark)}${unreadIds.has(mark.id) ? " slc-stage-pin--new" : ""}${mark.id === selectedMark ? " slc-stage-pin--selected" : ""}`, style: { left: x, top: y }, title: `${mark.author.name}: ${mark.text}${mark.replies?.length ? ` (${mark.replies.length} repl${mark.replies.length === 1 ? "y" : "ies"})` : ""}${unreadIds.has(mark.id) ? " · new" : ""}`, "aria-label": `Mark ${n}, ${mark.status}${unreadIds.has(mark.id) ? ", new" : ""}: ${mark.text}`, onPointerDown: (e) => e.stopPropagation(), onClick: (e) => {
113
151
  e.stopPropagation();
114
152
  onSelectMark?.(mark.id);
115
153
  }, children: [n, (mark.replies?.length ?? 0) > 0 && _jsx("span", { className: "slc-stage-pin-count", children: mark.replies.length })] }, mark.id))), marking && (_jsx("div", { className: "slc-stage-catch", onPointerDown: onDown, onPointerMove: onMove, onPointerUp: onUp, onPointerCancel: () => {
package/dist/icons.d.ts CHANGED
@@ -25,4 +25,6 @@ export declare function ThumbDownIcon(p: IconProps): import("react").JSX.Element
25
25
  export declare function CloseIcon(p: IconProps): import("react").JSX.Element;
26
26
  /** A pencil: marking is on, a tap or a drag marks the drawing. */
27
27
  export declare function MarkIcon(p: IconProps): import("react").JSX.Element;
28
+ /** A map pin: a mark on a drawing, in the conversation. */
29
+ export declare function PinIcon(p: IconProps): import("react").JSX.Element;
28
30
  export {};
package/dist/icons.js CHANGED
@@ -43,4 +43,8 @@ export function CloseIcon(p) {
43
43
  export function MarkIcon(p) {
44
44
  return (_jsxs(Icon, { ...p, children: [_jsx("path", { d: "M4.5 19.5l1-4.2L15.8 5a1.8 1.8 0 0 1 2.5 0l.7.7a1.8 1.8 0 0 1 0 2.5L8.7 18.5z" }), _jsx("path", { d: "M13.8 7l3.2 3.2" })] }));
45
45
  }
46
+ /** A map pin: a mark on a drawing, in the conversation. */
47
+ export function PinIcon(p) {
48
+ return (_jsxs(Icon, { ...p, children: [_jsx("path", { d: "M12 21s-6.5-6.2-6.5-11.2a6.5 6.5 0 0 1 13 0C18.5 14.8 12 21 12 21z" }), _jsx("circle", { cx: "12", cy: "9.8", r: "2.3" })] }));
49
+ }
46
50
  //# sourceMappingURL=icons.js.map
package/dist/index.d.ts CHANGED
@@ -20,15 +20,20 @@ export { SequenceCanvas, drawableSequence } from "./SequenceCanvas.js";
20
20
  export type { SequenceCanvasProps, SequenceCanvasTarget, SequenceSelection, SequenceTargetKind, } from "./SequenceCanvas.js";
21
21
  export { StageOverlay, markAnchor } from "./StageOverlay.js";
22
22
  export type { StageOverlayProps, MarkDraft } from "./StageOverlay.js";
23
+ export { placePins, fitLegibly } from "./pins.js";
24
+ export type { PinSpot, PinLayout, LegibleFitOptions } from "./pins.js";
25
+ export { elementName, markedNames, namesText, markPlace, drawingName, markStanding, marksSummary } from "./names.js";
26
+ export type { ElementLabels, MarkLike, MarkStanding } from "./names.js";
23
27
  export { StageCaption } from "./StageCaption.js";
24
28
  export type { StageCaptionProps } from "./StageCaption.js";
25
- export { MarkComposer, MarkThread, MarksPanel } from "./MarkCards.js";
29
+ export { MarkComposer, MarkThread, MarksPanel, MarkNotice } from "./MarkCards.js";
30
+ export { useMarksRead, loadMarksRead, saveMarksRead, marksReadKey } from "./marksRead.js";
26
31
  export { CompanionDock } from "./CompanionDock.js";
27
- export type { CompanionDockProps, DockItem, DockReply, DockStep, DockTake } from "./CompanionDock.js";
28
- export { MicIcon, SpeakerIcon, SpeakerOffIcon, MarksIcon, MarkIcon, PlayIcon, PauseIcon, StopIcon, PrevIcon, NextIcon, ThumbUpIcon, ThumbDownIcon, CloseIcon, } from "./icons.js";
29
- export type { MarkComposerProps, MarkThreadProps, MarksPanelProps, ListenerLike } from "./MarkCards.js";
32
+ export type { CompanionDockProps, DockItem, DockMark, DockReply, DockStep, DockTake } from "./CompanionDock.js";
33
+ export { MicIcon, SpeakerIcon, SpeakerOffIcon, MarksIcon, MarkIcon, PlayIcon, PauseIcon, StopIcon, PrevIcon, NextIcon, ThumbUpIcon, ThumbDownIcon, CloseIcon, PinIcon, } from "./icons.js";
34
+ export type { MarkComposerProps, MarkThreadProps, MarksPanelProps, MarkNoticeProps, ListenerLike } from "./MarkCards.js";
30
35
  export { themeStyle, CANVAS_THEME_VARS } from "./theme.js";
31
36
  export type { CanvasTheme } from "./theme.js";
32
37
  export { childByName, childStatesAt, childrenOf, definedEvents, findState, livePath, parentAt, } from "./drill.js";
33
- export { autoLayout, AUTO_LAYOUT_DEFAULTS, IDENTITY_VIEWPORT, VIEWPORT_LIMITS, clampScale, fitToBoxes, normalizeViewport, panBy, sameViewport, screenDeltaToWorld, screenToWorld, viewportTransform, worldToScreen, zoomAt, zoomTo, routeEdges, erdAutoLayout, erdEntitySize, sequenceLayout, placeLabels, eventGlyph, guardText, machineElementBoxes, erdElementBoxes, sequenceElementBoxes, elementsInRegion, elementAt, boxesOf, unionBox, } from "@miadi/stateloom-protocol";
34
- export type { AutoLayoutOptions, Box, EntityRelationshipDefinition, FitOptions, LayoutBox, Point, ScaleLimits, SequenceDefinition, SequenceLayout, StateDef, StateMachineDefinition, TransitionDef, Viewport, ElementBox, Mark, MarkKind, TourStep, TourDefinition, } from "@miadi/stateloom-protocol";
38
+ export { autoLayout, AUTO_LAYOUT_DEFAULTS, IDENTITY_VIEWPORT, VIEWPORT_LIMITS, clampScale, fitToBoxes, normalizeViewport, panBy, sameViewport, screenDeltaToWorld, screenToWorld, viewportTransform, worldToScreen, zoomAt, zoomTo, routeEdges, erdAutoLayout, erdEntitySize, sequenceLayout, placeLabels, eventGlyph, guardText, machineElementBoxes, erdElementBoxes, sequenceElementBoxes, elementsInRegion, elementAt, boxesOf, unionBox, marksWaitingOn, markCounts, unreadMarks, isMarkUnread, withMarkRead, lastWordOf, agentWordIn, agentWordText, } from "@miadi/stateloom-protocol";
39
+ export type { AutoLayoutOptions, Box, EntityRelationshipDefinition, FitOptions, LayoutBox, Point, ScaleLimits, SequenceDefinition, SequenceLayout, StateDef, StateMachineDefinition, TransitionDef, Viewport, ElementBox, Mark, MarkKind, MarksRead, MarksEnvelope, AgentWord, TourStep, TourDefinition, } from "@miadi/stateloom-protocol";
package/dist/index.js CHANGED
@@ -19,14 +19,28 @@ export { SequenceCanvas, drawableSequence } from "./SequenceCanvas.js";
19
19
  // agent points at and takes a person's marks, the caption that plays a tour,
20
20
  // and the cards marks are written and read in.
21
21
  export { StageOverlay, markAnchor } from "./StageOverlay.js";
22
+ // Where pins stand (inside the board, fanned, clear of the board's buttons), and a view
23
+ // that frames the marks without going below a legible scale.
24
+ export { placePins, fitLegibly } from "./pins.js";
25
+ // Elements and marks in the person's words: "Witnessing", "id in WaveCount", "message 8";
26
+ // "Witnessing and 2 more"; "7 marks on Screenwalk, 6 answered".
27
+ export { elementName, markedNames, namesText, markPlace, drawingName, markStanding, marksSummary } from "./names.js";
22
28
  export { StageCaption } from "./StageCaption.js";
23
- export { MarkComposer, MarkThread, MarksPanel } from "./MarkCards.js";
29
+ export { MarkComposer, MarkThread, MarksPanel, MarkNotice } from "./MarkCards.js";
30
+ // Whether an agent's word has been read, per drawing in this browser, and
31
+ // what a marks button counts — for any host that shows marks (Miadi's room
32
+ // as the loom): `useMarksRead(doc)` + `unreadMarks(marks, read)` give the
33
+ // pins' and the list's `unread`; `markCounts(marks, read)` gives `forYou`
34
+ // (what waits on the person: the main number) and `forAgent` (the quiet one);
35
+ // `agentWordIn(envelope)` + `agentWordText(word)` turn a `marks:changed` that
36
+ // carries an agent's answer into the line for `<MarkNotice>`.
37
+ export { useMarksRead, loadMarksRead, saveMarksRead, marksReadKey } from "./marksRead.js";
24
38
  // Talking with a companion from the canvas (Spec 84).
25
39
  export { CompanionDock } from "./CompanionDock.js";
26
- export { MicIcon, SpeakerIcon, SpeakerOffIcon, MarksIcon, MarkIcon, PlayIcon, PauseIcon, StopIcon, PrevIcon, NextIcon, ThumbUpIcon, ThumbDownIcon, CloseIcon, } from "./icons.js";
40
+ export { MicIcon, SpeakerIcon, SpeakerOffIcon, MarksIcon, MarkIcon, PlayIcon, PauseIcon, StopIcon, PrevIcon, NextIcon, ThumbUpIcon, ThumbDownIcon, CloseIcon, PinIcon, } from "./icons.js";
27
41
  export { themeStyle, CANVAS_THEME_VARS } from "./theme.js";
28
42
  export { childByName, childStatesAt, childrenOf, definedEvents, findState, livePath, parentAt, } from "./drill.js";
29
43
  // The geometry and the model, re-exported at the address a host reaching for a
30
44
  // canvas is already looking at.
31
- export { autoLayout, AUTO_LAYOUT_DEFAULTS, IDENTITY_VIEWPORT, VIEWPORT_LIMITS, clampScale, fitToBoxes, normalizeViewport, panBy, sameViewport, screenDeltaToWorld, screenToWorld, viewportTransform, worldToScreen, zoomAt, zoomTo, routeEdges, erdAutoLayout, erdEntitySize, sequenceLayout, placeLabels, eventGlyph, guardText, machineElementBoxes, erdElementBoxes, sequenceElementBoxes, elementsInRegion, elementAt, boxesOf, unionBox, } from "@miadi/stateloom-protocol";
45
+ export { autoLayout, AUTO_LAYOUT_DEFAULTS, IDENTITY_VIEWPORT, VIEWPORT_LIMITS, clampScale, fitToBoxes, normalizeViewport, panBy, sameViewport, screenDeltaToWorld, screenToWorld, viewportTransform, worldToScreen, zoomAt, zoomTo, routeEdges, erdAutoLayout, erdEntitySize, sequenceLayout, placeLabels, eventGlyph, guardText, machineElementBoxes, erdElementBoxes, sequenceElementBoxes, elementsInRegion, elementAt, boxesOf, unionBox, marksWaitingOn, markCounts, unreadMarks, isMarkUnread, withMarkRead, lastWordOf, agentWordIn, agentWordText, } from "@miadi/stateloom-protocol";
32
46
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,12 @@
1
+ import { type Mark, type MarksRead } from "@miadi/stateloom-protocol";
2
+ export declare function marksReadKey(doc: string): string;
3
+ export declare function loadMarksRead(doc: string): MarksRead;
4
+ export declare function saveMarksRead(doc: string, read: MarksRead): void;
5
+ /**
6
+ * The read record of one drawing, and `markRead(mark)` to call when the person
7
+ * opens a thread (and again while it stays open as replies arrive).
8
+ */
9
+ export declare function useMarksRead(doc: string | null): {
10
+ read: MarksRead;
11
+ markRead: (mark: Pick<Mark, "id" | "replies">) => void;
12
+ };
@@ -0,0 +1,64 @@
1
+ /**
2
+ * What a person has read of a drawing's marks, kept in this browser (Spec 83).
3
+ *
4
+ * Per drawing, `stateloom.marks.read.v1:<doc>` holds mark id → the number of
5
+ * replies the thread had when the person last opened it. With the protocol's
6
+ * `unreadMarks(marks, read)` it says which threads carry an agent's word they
7
+ * have not seen. Every access is guarded: a private window, blocked storage or
8
+ * a server render reads as nothing read, and a write that fails is dropped.
9
+ */
10
+ import { useCallback, useEffect, useState } from "react";
11
+ import { withMarkRead } from "@miadi/stateloom-protocol";
12
+ const PREFIX = "stateloom.marks.read.v1:";
13
+ export function marksReadKey(doc) {
14
+ return `${PREFIX}${doc}`;
15
+ }
16
+ export function loadMarksRead(doc) {
17
+ try {
18
+ const raw = window.localStorage.getItem(marksReadKey(doc));
19
+ const parsed = raw ? JSON.parse(raw) : null;
20
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
21
+ return {};
22
+ const out = {};
23
+ for (const [id, n] of Object.entries(parsed)) {
24
+ if (typeof n === "number" && Number.isFinite(n) && n >= 0)
25
+ out[id] = n;
26
+ }
27
+ return out;
28
+ }
29
+ catch {
30
+ return {};
31
+ }
32
+ }
33
+ export function saveMarksRead(doc, read) {
34
+ try {
35
+ window.localStorage.setItem(marksReadKey(doc), JSON.stringify(read));
36
+ }
37
+ catch {
38
+ // Storage refused (private mode, quota): the marks read again as new next time.
39
+ }
40
+ }
41
+ /**
42
+ * The read record of one drawing, and `markRead(mark)` to call when the person
43
+ * opens a thread (and again while it stays open as replies arrive).
44
+ */
45
+ export function useMarksRead(doc) {
46
+ const [state, setState] = useState(() => ({ doc, read: doc ? loadMarksRead(doc) : {} }));
47
+ useEffect(() => {
48
+ setState((s) => (s.doc === doc ? s : { doc, read: doc ? loadMarksRead(doc) : {} }));
49
+ }, [doc]);
50
+ const markRead = useCallback((mark) => {
51
+ if (!doc)
52
+ return;
53
+ setState((s) => {
54
+ const base = s.doc === doc ? s.read : loadMarksRead(doc);
55
+ if (base[mark.id] === (mark.replies?.length ?? 0) && s.doc === doc)
56
+ return s;
57
+ const read = withMarkRead(base, mark);
58
+ saveMarksRead(doc, read);
59
+ return { doc, read };
60
+ });
61
+ }, [doc]);
62
+ return { read: state.doc === doc ? state.read : {}, markRead };
63
+ }
64
+ //# sourceMappingURL=marksRead.js.map
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The elements a mark points at, named as the person sees them on the board (Spec 83).
3
+ *
4
+ * A mark keeps its elements as focus keys — `state:Witnessing`, `attribute:Screenwalk.state`,
5
+ * `message:8` — which is what agents read. A person reads the board: a state's name, an
6
+ * entity's name, a message's number and words. The host may pass `labels` (focus key →
7
+ * words), which win; a sequence host gives each message its words that way.
8
+ *
9
+ * Pure: no React, no DOM.
10
+ */
11
+ import type { Box } from "@miadi/stateloom-protocol";
12
+ export type ElementLabels = Readonly<Record<string, string>>;
13
+ /** One element by the name the board shows: `state:Witnessing` → "Witnessing", `message:8` → "message 8". */
14
+ export declare function elementName(focus: string, labels?: ElementLabels): string;
15
+ /** The names of what is marked; an entity's attributes are left to the entity when it is marked too. */
16
+ export declare function markedNames(elements: readonly string[] | undefined, labels?: ElementLabels): string[];
17
+ /** "A", "A and B", "A, B and C", "A, B and 4 more". */
18
+ export declare function namesText(names: readonly string[]): string;
19
+ /** What a mark points at, in words: its elements, else an area (inside a machine's level), else the drawing. */
20
+ export declare function markPlace(mark: {
21
+ elements?: readonly string[];
22
+ region?: Box | null;
23
+ level?: string;
24
+ }, labels?: ElementLabels): string;
25
+ /** A drawing named for a person: its own name when known, else its file name without the format's extensions. */
26
+ export declare function drawingName(path: string | null | undefined, title?: string | null): string;
27
+ /** A mark as the conversation lists it: who wrote it, what it points at, and where it stands. */
28
+ export interface MarkLike {
29
+ doc?: string;
30
+ drawing?: string;
31
+ title?: string;
32
+ elements?: readonly string[];
33
+ region?: Box | null;
34
+ level?: string;
35
+ status: string;
36
+ author: {
37
+ name?: string;
38
+ role?: string;
39
+ };
40
+ }
41
+ export type MarkStanding = "waits for agent" | "waits for you" | "answered" | "resolved";
42
+ /**
43
+ * Where a mark stands: a person's mark waits for the agent until answered; an agent's
44
+ * question waits for the person until answered, and then for the agent.
45
+ */
46
+ export declare function markStanding(mark: Pick<MarkLike, "status" | "author">): MarkStanding;
47
+ /** "7 marks on Screenwalk, 6 answered, 1 resolved; 1 mark on ScreenwalkRecords, 1 answered". */
48
+ export declare function marksSummary(marks: readonly MarkLike[], who?: string): string;
package/dist/names.js ADDED
@@ -0,0 +1,90 @@
1
+ /** One element by the name the board shows: `state:Witnessing` → "Witnessing", `message:8` → "message 8". */
2
+ export function elementName(focus, labels) {
3
+ const given = labels?.[focus];
4
+ if (given)
5
+ return given;
6
+ const at = focus.indexOf(":");
7
+ if (at <= 0)
8
+ return focus;
9
+ const kind = focus.slice(0, at);
10
+ const name = focus.slice(at + 1);
11
+ if (kind === "message")
12
+ return `message ${name}`;
13
+ if (kind === "attribute") {
14
+ const dot = name.indexOf(".");
15
+ return dot > 0 ? `${name.slice(dot + 1)} in ${name.slice(0, dot)}` : name;
16
+ }
17
+ return name;
18
+ }
19
+ /** The names of what is marked; an entity's attributes are left to the entity when it is marked too. */
20
+ export function markedNames(elements, labels) {
21
+ const refs = elements ?? [];
22
+ const marked = new Set(refs);
23
+ return refs
24
+ .filter((ref) => {
25
+ const owner = /^attribute:([^.]+)\./.exec(ref);
26
+ return !owner || !marked.has(`entity:${owner[1]}`);
27
+ })
28
+ .map((ref) => elementName(ref, labels));
29
+ }
30
+ /** "A", "A and B", "A, B and C", "A, B and 4 more". */
31
+ export function namesText(names) {
32
+ if (names.length <= 1)
33
+ return names[0] ?? "";
34
+ if (names.length <= 3)
35
+ return `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
36
+ return `${names.slice(0, 2).join(", ")} and ${names.length - 2} more`;
37
+ }
38
+ /** What a mark points at, in words: its elements, else an area (inside a machine's level), else the drawing. */
39
+ export function markPlace(mark, labels) {
40
+ const names = markedNames(mark.elements, labels);
41
+ if (names.length)
42
+ return namesText(names);
43
+ if (mark.region)
44
+ return mark.level && mark.level !== "Root" ? `an area inside ${mark.level}` : "an area";
45
+ return "the drawing";
46
+ }
47
+ /** A drawing named for a person: its own name when known, else its file name without the format's extensions. */
48
+ export function drawingName(path, title) {
49
+ if (title)
50
+ return title;
51
+ const file = path ? path.split("/").pop() ?? path : "";
52
+ return file.replace(/\.(smdf|erdf|sqdf|sysdf)\.json$/i, "").replace(/\.json$/i, "") || "the drawing";
53
+ }
54
+ /**
55
+ * Where a mark stands: a person's mark waits for the agent until answered; an agent's
56
+ * question waits for the person until answered, and then for the agent.
57
+ */
58
+ export function markStanding(mark) {
59
+ if (mark.status === "resolved")
60
+ return "resolved";
61
+ const agent = mark.author?.role === "agent";
62
+ if (mark.status === "answered")
63
+ return agent ? "waits for agent" : "answered";
64
+ return agent ? "waits for you" : "waits for agent";
65
+ }
66
+ /** "7 marks on Screenwalk, 6 answered, 1 resolved; 1 mark on ScreenwalkRecords, 1 answered". */
67
+ export function marksSummary(marks, who = "the agent") {
68
+ const byDrawing = new Map();
69
+ for (const m of marks) {
70
+ const name = drawingName(m.doc ?? m.drawing, m.title);
71
+ byDrawing.set(name, [...(byDrawing.get(name) ?? []), m]);
72
+ }
73
+ return [...byDrawing.entries()]
74
+ .sort((a, b) => b[1].length - a[1].length)
75
+ .map(([name, list]) => {
76
+ const count = (s) => list.filter((m) => markStanding(m) === s).length;
77
+ const parts = [`${list.length} mark${list.length === 1 ? "" : "s"} on ${name}`];
78
+ if (count("answered"))
79
+ parts.push(`${count("answered")} answered`);
80
+ if (count("waits for agent"))
81
+ parts.push(`${count("waits for agent")} waiting on ${who}`);
82
+ if (count("waits for you"))
83
+ parts.push(`${count("waits for you")} waiting on you`);
84
+ if (count("resolved"))
85
+ parts.push(`${count("resolved")} resolved`);
86
+ return parts.join(", ");
87
+ })
88
+ .join("; ");
89
+ }
90
+ //# sourceMappingURL=names.js.map
package/dist/pins.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Where a drawing's pins stand on the screen, and the view that shows its marks (Spec 83).
3
+ *
4
+ * A pin is drawn at the top-right corner of what its mark points at. Marks that point at
5
+ * the same elements share that corner, a corner can fall outside the board, and the
6
+ * board's own buttons sit in its top-right corner too. `placePins` moves each pin as
7
+ * little as it can so that every one can be read and tapped:
8
+ *
9
+ * - inside the board, `inset` pixels from each edge;
10
+ * - out from under the boxes it is told to keep clear of (the board's buttons): just
11
+ * below them;
12
+ * - apart from the pins already placed: pins on one point fan down the anchor's right
13
+ * edge, `spacing` apart, and upward when the board ends first.
14
+ *
15
+ * `fitLegibly` frames boxes as `fitToBoxes` does, but never below a scale at which a
16
+ * state's name can still be read: past that floor the view keeps the floor and starts at
17
+ * the boxes' top (and left, when they are wider than the board).
18
+ *
19
+ * Pure: no React, no DOM.
20
+ */
21
+ import { type Box, type Viewport } from "@miadi/stateloom-protocol";
22
+ export interface PinSpot {
23
+ x: number;
24
+ y: number;
25
+ }
26
+ export interface PinLayout {
27
+ /** The board's size on screen. */
28
+ width: number;
29
+ height: number;
30
+ /** A pin's side, in screen pixels. Default 22 (30 under a finger). */
31
+ size?: number;
32
+ /** How far apart fanned pins stand. Default size + 4. */
33
+ spacing?: number;
34
+ /** Distance kept from the board's edges. Default 8. */
35
+ inset?: number;
36
+ /** Boxes no pin may cover, in the board's screen coordinates (the board's buttons). */
37
+ avoid?: readonly Box[];
38
+ }
39
+ /** Each spot moved as little as needed: clamped into the board, clear of `avoid`, apart from the others. In order. */
40
+ export declare function placePins(spots: readonly PinSpot[], layout: PinLayout): PinSpot[];
41
+ export interface LegibleFitOptions {
42
+ /** Screen-space breathing room on every side. Default 48. */
43
+ padding?: number;
44
+ /** The smallest scale the view may take. Default 0.55. */
45
+ floor?: number;
46
+ /** Never larger than this. Default 1. */
47
+ maxScale?: number;
48
+ }
49
+ /** The view that frames `boxes` in a board of `width` × `height`, never smaller than `floor`. */
50
+ export declare function fitLegibly(boxes: readonly Box[], width: number, height: number, options?: LegibleFitOptions): Viewport;
package/dist/pins.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Where a drawing's pins stand on the screen, and the view that shows its marks (Spec 83).
3
+ *
4
+ * A pin is drawn at the top-right corner of what its mark points at. Marks that point at
5
+ * the same elements share that corner, a corner can fall outside the board, and the
6
+ * board's own buttons sit in its top-right corner too. `placePins` moves each pin as
7
+ * little as it can so that every one can be read and tapped:
8
+ *
9
+ * - inside the board, `inset` pixels from each edge;
10
+ * - out from under the boxes it is told to keep clear of (the board's buttons): just
11
+ * below them;
12
+ * - apart from the pins already placed: pins on one point fan down the anchor's right
13
+ * edge, `spacing` apart, and upward when the board ends first.
14
+ *
15
+ * `fitLegibly` frames boxes as `fitToBoxes` does, but never below a scale at which a
16
+ * state's name can still be read: past that floor the view keeps the floor and starts at
17
+ * the boxes' top (and left, when they are wider than the board).
18
+ *
19
+ * Pure: no React, no DOM.
20
+ */
21
+ import { fitToBoxes } from "@miadi/stateloom-protocol";
22
+ /** A pin is drawn translated by (-40%, -60%) of its size from its point. */
23
+ const LEFT = 0.4;
24
+ const UP = 0.6;
25
+ const AVOID_GAP = 4;
26
+ function overlaps(a, b, gap = 0) {
27
+ return a.x < b.x + b.width + gap && b.x < a.x + a.width + gap && a.y < b.y + b.height + gap && b.y < a.y + a.height + gap;
28
+ }
29
+ /** Each spot moved as little as needed: clamped into the board, clear of `avoid`, apart from the others. In order. */
30
+ export function placePins(spots, layout) {
31
+ const size = layout.size ?? 22;
32
+ const spacing = layout.spacing ?? size + 4;
33
+ const inset = layout.inset ?? 8;
34
+ const avoid = layout.avoid ?? [];
35
+ const minX = inset + LEFT * size;
36
+ const maxX = layout.width - inset - (1 - LEFT) * size;
37
+ const minY = inset + UP * size;
38
+ const maxY = layout.height - inset - (1 - UP) * size;
39
+ const clamp = (v, lo, hi) => (hi < lo ? (lo + hi) / 2 : Math.min(hi, Math.max(lo, v)));
40
+ const boxAt = (x, y) => ({ x: x - LEFT * size, y: y - UP * size, width: size, height: size });
41
+ const blocked = (x, y) => avoid.find((a) => overlaps(boxAt(x, y), a, AVOID_GAP));
42
+ const placed = [];
43
+ const crowded = (x, y) => placed.some((q) => Math.abs(q.x - x) < size && Math.abs(q.y - y) < size);
44
+ const limit = spots.length + avoid.length + 2;
45
+ /** Down from `y` until nothing is in the way. */
46
+ const down = (x, y) => {
47
+ for (let i = 0; i < limit; i++) {
48
+ const under = blocked(x, y);
49
+ if (under)
50
+ y = under.y + under.height + AVOID_GAP + UP * size;
51
+ else if (crowded(x, y))
52
+ y += spacing;
53
+ else
54
+ break;
55
+ }
56
+ return y;
57
+ };
58
+ /** Up from `y` until nothing is in the way. */
59
+ const up = (x, y) => {
60
+ for (let i = 0; i < limit; i++) {
61
+ const over = blocked(x, y);
62
+ if (over)
63
+ y = over.y - AVOID_GAP - (1 - UP) * size;
64
+ else if (crowded(x, y))
65
+ y -= spacing;
66
+ else
67
+ break;
68
+ }
69
+ return y;
70
+ };
71
+ for (const spot of spots) {
72
+ const x = clamp(spot.x, minX, maxX);
73
+ const wanted = clamp(spot.y, minY, maxY);
74
+ let y = down(x, wanted);
75
+ // The board ended first: fan upward from where the pin wanted to be.
76
+ if (y > maxY)
77
+ y = Math.max(minY, up(x, wanted));
78
+ placed.push({ x, y });
79
+ }
80
+ return placed;
81
+ }
82
+ /** The view that frames `boxes` in a board of `width` × `height`, never smaller than `floor`. */
83
+ export function fitLegibly(boxes, width, height, options = {}) {
84
+ const padding = options.padding ?? 48;
85
+ const floor = options.floor ?? 0.55;
86
+ const fitted = fitToBoxes(boxes, width, height, { padding, maxScale: options.maxScale ?? 1 });
87
+ if (!boxes.length || fitted.scale >= floor)
88
+ return fitted;
89
+ let minX = Infinity;
90
+ let minY = Infinity;
91
+ let maxX = -Infinity;
92
+ let maxY = -Infinity;
93
+ for (const b of boxes) {
94
+ minX = Math.min(minX, b.x);
95
+ minY = Math.min(minY, b.y);
96
+ maxX = Math.max(maxX, b.x + b.width);
97
+ maxY = Math.max(maxY, b.y + b.height);
98
+ }
99
+ const scale = floor;
100
+ const w = (maxX - minX) * scale;
101
+ const h = (maxY - minY) * scale;
102
+ return {
103
+ x: w <= width - padding * 2 ? (width - w) / 2 - minX * scale : padding - minX * scale,
104
+ y: h <= height - padding * 2 ? (height - h) / 2 - minY * scale : padding - minY * scale,
105
+ scale,
106
+ };
107
+ }
108
+ //# sourceMappingURL=pins.js.map