pi-better-show 0.7.1 → 0.7.2

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-show",
3
- "version": "0.7.1",
3
+ "version": "0.7.2",
4
4
  "description": "Interactive blocks for agent-written Markdown: one vocabulary, text fallback, and answer encoding shared by every host, plus the show_doc extension for pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -356,11 +356,21 @@ export class PbsDiagram extends PbsElement<MermaidData> {
356
356
  }
357
357
  });
358
358
  }
359
- // Later buttons sit above earlier ones: groups below edges below nodes, so a node inside a group is the node.
359
+ // Later buttons sit above earlier ones: groups below edges below nodes, so a node inside a group is the node. The
360
+ // DOM keeps that order, not the reading order; the description tells a screen reader to move with the arrow keys.
360
361
  const layers: DiagramTarget["kind"][] = ["group", "edge", "node"];
362
+ const keys = svg("desc", { id: "diagram-keys" });
363
+ keys.textContent = this.t("diagramKeys");
361
364
  return svg(
362
365
  "svg",
363
- { class: "targets", viewBox: map.viewBox, role: "group", "aria-label": this.t("diagram") },
366
+ {
367
+ class: "targets",
368
+ viewBox: map.viewBox,
369
+ role: "group",
370
+ "aria-label": this.t("diagram"),
371
+ "aria-describedby": "diagram-keys",
372
+ },
373
+ keys,
364
374
  ...layers.flatMap((kind) => hits.filter((_, index) => map.targets[index]?.kind === kind)),
365
375
  );
366
376
  }
@@ -41,6 +41,8 @@ export interface Strings {
41
41
  diagramNode: string;
42
42
  diagramEdge: string;
43
43
  diagramGroup: string;
44
+ /** How to move through a diagram's elements, for screen readers. */
45
+ diagramKeys: string;
44
46
  diff: string;
45
47
  table: string;
46
48
  mindmap: string;
@@ -98,6 +100,7 @@ export const STRINGS: Record<Locale, Strings> = {
98
100
  diagramNode: "node",
99
101
  diagramEdge: "edge",
100
102
  diagramGroup: "group",
103
+ diagramKeys: "Arrow keys move between its elements; Enter or Space comments on one.",
101
104
  diff: "Diff",
102
105
  table: "Table",
103
106
  mindmap: "Mind map",
@@ -152,6 +155,7 @@ export const STRINGS: Record<Locale, Strings> = {
152
155
  diagramNode: "節點",
153
156
  diagramEdge: "連線",
154
157
  diagramGroup: "群組",
158
+ diagramKeys: "用方向鍵在元素之間移動,按 Enter 或空白鍵針對它留言。",
155
159
  diff: "差異",
156
160
  table: "表格",
157
161
  mindmap: "心智圖",
@@ -97,13 +97,26 @@ function enclosing(groups: Element[], node: Element): Element | undefined {
97
97
  */
98
98
  type Draft = DiagramTarget & { tag: string; id?: string };
99
99
 
100
+ /**
101
+ * What a number is written after: a run of `#` that no label or id of the drawing has, so a numbered quote never reads
102
+ * as another element's own words (`A → B ##1` beside a node labelled `B #1`). `#` unless a label has one.
103
+ */
104
+ function numberingOf(svg: Element): string {
105
+ const said = [...svg.querySelectorAll("[data-label], [data-id]")].flatMap((element) => [
106
+ words(element.getAttribute("data-label")),
107
+ words(element.getAttribute("data-id")),
108
+ ]);
109
+ let mark = "#";
110
+ while (said.some((text) => text.includes(mark))) mark += "#";
111
+ return mark;
112
+ }
113
+
100
114
  /**
101
115
  * Makes every target's text unique among `targets` (one kind), so one quote names one element. Only a text that more
102
116
  * than one target has changes: each adds its tag where the tags differ (`Check (B)`), and what is still alike is
103
- * numbered in drawing order (`#1`, `#2`), skipping a number whose text another target already has (a label written as
104
- * `B #1`).
117
+ * numbered in drawing order after `numbering` (`#1`, `#2`), which no label has, so a numbered text is no other's.
105
118
  */
106
- function disambiguated(targets: Draft[]): DiagramTarget[] {
119
+ function disambiguated(targets: Draft[], numbering: string): DiagramTarget[] {
107
120
  const count = (list: DiagramTarget[]): Map<string, number> => {
108
121
  const seen = new Map<string, number>();
109
122
  for (const target of list) seen.set(target.text, (seen.get(target.text) ?? 0) + 1);
@@ -119,16 +132,12 @@ function disambiguated(targets: Draft[]): DiagramTarget[] {
119
132
  : target,
120
133
  );
121
134
  const second = count(named);
122
- const taken = new Set(named.filter((target) => (second.get(target.text) ?? 0) < 2).map((target) => target.text));
123
135
  const next = new Map<string, number>();
124
136
  return named.map((target) => {
125
137
  if ((second.get(target.text) ?? 0) < 2) return target;
126
- let ordinal = next.get(target.text) ?? 0;
127
- do ordinal += 1;
128
- while (taken.has(`${target.text} #${ordinal}`));
138
+ const ordinal = (next.get(target.text) ?? 0) + 1;
129
139
  next.set(target.text, ordinal);
130
- taken.add(`${target.text} #${ordinal}`);
131
- return { ...target, text: `${target.text} #${ordinal}` };
140
+ return { ...target, text: `${target.text} ${numbering}${ordinal}` };
132
141
  });
133
142
  }
134
143
 
@@ -136,13 +145,18 @@ function disambiguated(targets: Draft[]): DiagramTarget[] {
136
145
  * Tells apart the nodes or the groups, and records each one's final name and tag by id: later targets (a `[*]`'s
137
146
  * composite state, an edge's ends) are named by them. A target with no text or shape is left out.
138
147
  */
139
- function settle(drafts: Draft[], names: Map<string, string>, tags: Map<string, string>): DiagramTarget[] {
148
+ function settle(
149
+ drafts: Draft[],
150
+ names: Map<string, string>,
151
+ tags: Map<string, string>,
152
+ numbering: string,
153
+ ): DiagramTarget[] {
140
154
  for (const draft of drafts) {
141
155
  names.set(draft.id ?? "", draft.text);
142
156
  tags.set(draft.id ?? "", draft.tag);
143
157
  }
144
158
  const kept = drafts.filter((draft) => draft.text && draft.shapes.length > 0);
145
- const targets = disambiguated(kept);
159
+ const targets = disambiguated(kept, numbering);
146
160
  for (const [index, draft] of kept.entries()) names.set(draft.id ?? "", targets[index]?.text ?? draft.text);
147
161
  return targets;
148
162
  }
@@ -214,6 +228,7 @@ export function diagramMap(svg: Element): DiagramMap | undefined {
214
228
  /** Each node's and group's name, and the tag that tells it apart, by id: what an edge is named by. */
215
229
  const names = new Map<string, string>();
216
230
  const tags = new Map<string, string>();
231
+ const numbering = numberingOf(svg);
217
232
 
218
233
  const groupElements = [...svg.querySelectorAll("g.subgraph")];
219
234
  const groups = settle(
@@ -225,6 +240,7 @@ export function diagramMap(svg: Element): DiagramMap | undefined {
225
240
  }),
226
241
  names,
227
242
  tags,
243
+ numbering,
228
244
  );
229
245
 
230
246
  const nodeElements = [...svg.querySelectorAll("g.node")];
@@ -250,6 +266,7 @@ export function diagramMap(svg: Element): DiagramMap | undefined {
250
266
  }),
251
267
  names,
252
268
  tags,
269
+ numbering,
253
270
  );
254
271
 
255
272
  const name = (id: string | null): string => names.get(id ?? "") || words(id);
@@ -281,7 +298,7 @@ export function diagramMap(svg: Element): DiagramMap | undefined {
281
298
  });
282
299
  }
283
300
 
284
- const targets = inReadingOrder([...groups, ...disambiguated(edges), ...nodes]);
301
+ const targets = inReadingOrder([...groups, ...disambiguated(edges, numbering), ...nodes]);
285
302
  return targets.length > 0 ? { viewBox, targets } : undefined;
286
303
  }
287
304
 
@@ -324,18 +341,18 @@ export function diagramRef(diagram: Element): string {
324
341
 
325
342
  /**
326
343
  * A `diagramQuote` made on an earlier load, with the position its diagram (found by `diagramRef`) has on the page now.
327
- * A diagram whose source changed is not found, and the quote keeps the position it has.
344
+ * A diagram whose source changed is not found: `undefined`, and the panel keeps the quote's position.
328
345
  */
329
- export function requoteDiagram(quote: string, ref: string): string {
346
+ export function requoteDiagram(quote: string, ref: string): string | undefined {
330
347
  let found: Element | undefined;
331
348
  try {
332
349
  const [source, nth] = JSON.parse(ref) as [unknown, unknown];
333
350
  const alike = [...document.querySelectorAll("pbs-diagram")].filter((other) => sourceOf(other) === source);
334
351
  found = typeof nth === "number" ? alike[nth] : undefined;
335
352
  } catch {
336
- // A ref that cannot be read leaves the quote as it is.
353
+ // A ref that cannot be read finds nothing.
337
354
  }
338
- if (!found) return quote;
355
+ if (!found) return undefined;
339
356
  const position = [...document.querySelectorAll("pbs-diagram")].indexOf(found) + 1;
340
357
  return quote.replace(/^\[Diagram \d+,/, `[Diagram ${position},`);
341
358
  }
@@ -81,9 +81,22 @@ export interface FeedbackOptions {
81
81
  diagrams?: boolean;
82
82
  /**
83
83
  * Rewrites a restored draft's quote that came with a `ref` for the page as it is now: the reload an agent's edit causes
84
- * may have moved what the quote names.
84
+ * may have moved what the quote names. `undefined` when what the ref names is no longer on the page: the quote keeps
85
+ * its text, marked (`STALE`) while another draft's quote reads the same.
85
86
  */
86
- requote?: (quote: string, ref: string) => string;
87
+ requote?: (quote: string, ref: string) => string | undefined;
88
+ }
89
+
90
+ /**
91
+ * What a draft's quote adds when what it named is no longer on the page and another draft's quote reads the same, so
92
+ * two drafts never share a quote. Part of the message the agent reads; keep it stable.
93
+ */
94
+ export const STALE = " (from an earlier version of the page)";
95
+
96
+ /** A quote without the `STALE` mark (and its number) it was saved with. */
97
+ function unmarked(quote: string): string {
98
+ const at = quote.lastIndexOf(STALE);
99
+ return at !== -1 && /^(?: #\d+)?$/.test(quote.slice(at + STALE.length)) ? quote.slice(0, at) : quote;
87
100
  }
88
101
 
89
102
  /** A passage to comment on, and where the Add button goes (viewport coordinates of the panel's document). */
@@ -122,19 +135,48 @@ export function mountFeedback(options: FeedbackOptions): {
122
135
  const { words, storage, storageKey } = options;
123
136
  let items: FeedbackItem[] = [];
124
137
  let overall = "";
138
+ /** The restored drafts whose `ref` names nothing on the page now, with their quote as it was made (unmarked). */
139
+ const stale = new Map<FeedbackItem, string>();
125
140
  try {
126
141
  const saved = JSON.parse(storage.getItem(storageKey) ?? "null") as {
127
142
  items?: FeedbackItem[];
128
143
  overall?: string;
129
144
  } | null;
130
145
  const { requote } = options;
131
- items = (saved?.items ?? []).map((item) =>
132
- item.ref && requote ? { ...item, quote: requote(item.quote, item.ref) } : item,
133
- );
146
+ items = (saved?.items ?? []).map((item) => {
147
+ if (!item.ref || !requote) return item;
148
+ const made = unmarked(item.quote);
149
+ const quote = requote(made, item.ref);
150
+ if (quote !== undefined) return { ...item, quote };
151
+ const kept = { ...item, quote: made };
152
+ stale.set(kept, made);
153
+ return kept;
154
+ });
134
155
  overall = saved?.overall ?? "";
135
156
  } catch {
136
157
  // A draft that cannot be read is dropped.
137
158
  }
159
+ /**
160
+ * Marks each stale quote that reads like another draft's, current or stale, and numbers marks that would still be
161
+ * alike; a stale quote that reads like no other is left as it was made.
162
+ */
163
+ const settle = (): void => {
164
+ const used = new Set(items.filter((item) => !stale.has(item)).map((item) => item.quote));
165
+ const made = [...stale.values()];
166
+ for (const item of items) {
167
+ const quote = stale.get(item);
168
+ if (quote === undefined) continue;
169
+ if (!used.has(quote) && made.filter((other) => other === quote).length < 2) {
170
+ item.quote = quote;
171
+ continue;
172
+ }
173
+ let marked = `${quote}${STALE}`;
174
+ for (let n = 2; used.has(marked); n += 1) marked = `${quote}${STALE} #${n}`;
175
+ item.quote = marked;
176
+ used.add(marked);
177
+ }
178
+ };
179
+ settle();
138
180
  const save = (): void => {
139
181
  if (items.length === 0 && !overall) storage.removeItem(storageKey);
140
182
  else storage.setItem(storageKey, JSON.stringify({ items, overall }));
@@ -171,8 +213,8 @@ export function mountFeedback(options: FeedbackOptions): {
171
213
  const remove = make("button", { type: "button", textContent: words.remove });
172
214
  remove.addEventListener("click", () => {
173
215
  items.splice(index, 1);
174
- save();
175
- draw();
216
+ stale.delete(item);
217
+ changed();
176
218
  });
177
219
  entry.append(quote, box, remove);
178
220
  return entry;
@@ -180,6 +222,12 @@ export function mountFeedback(options: FeedbackOptions): {
180
222
  );
181
223
  toggle.textContent = items.length > 0 ? `${words.feedback} (${items.length})` : words.feedback;
182
224
  };
225
+ /** After a draft is added or removed: marks the quotes that now read alike, keeps, and redraws. */
226
+ const changed = (): void => {
227
+ settle();
228
+ save();
229
+ draw();
230
+ };
183
231
  overallBox.addEventListener("input", () => {
184
232
  overall = overallBox.value;
185
233
  save();
@@ -191,6 +239,8 @@ export function mountFeedback(options: FeedbackOptions): {
191
239
  panel.hidden = !panel.hidden;
192
240
  });
193
241
  panel.addEventListener("keydown", (event) => {
242
+ // An Escape that ends an input method's composition belongs to the input method.
243
+ if (event.isComposing || event.keyCode === 229) return;
194
244
  if (event.key !== "Escape" || !back?.isConnected) return;
195
245
  event.preventDefault();
196
246
  back.focus();
@@ -229,11 +279,11 @@ export function mountFeedback(options: FeedbackOptions): {
229
279
  const comment = (quote: string, from: { ref?: string; back?: HTMLElement | SVGElement } = {}): void => {
230
280
  const { ref } = from;
231
281
  back = from.back;
232
- const known = items.findIndex((item) => item.quote === quote);
282
+ // A stale draft names something the page no longer has, even when its quote reads the same.
283
+ const known = items.findIndex((item) => item.quote === quote && !stale.has(item));
233
284
  if (known === -1) {
234
285
  items.push(ref ? { quote, comment: "", ref } : { quote, comment: "" });
235
- save();
236
- draw();
286
+ changed();
237
287
  }
238
288
  open(known === -1 ? items.length - 1 : known);
239
289
  };
@@ -244,8 +294,7 @@ export function mountFeedback(options: FeedbackOptions): {
244
294
  add.hidden = true;
245
295
  getSelection()?.removeAllRanges();
246
296
  if (quote) items.push({ quote, comment: "" });
247
- save();
248
- draw();
297
+ changed();
249
298
  open(items.length - 1);
250
299
  });
251
300
  sendButton.addEventListener("click", () => {
@@ -260,6 +309,7 @@ export function mountFeedback(options: FeedbackOptions): {
260
309
  .then(
261
310
  () => {
262
311
  items = [];
312
+ stale.clear();
263
313
  overall = "";
264
314
  overallBox.value = "";
265
315
  save();