@altnovatrail/canvas 0.3.42 → 0.3.44

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.
@@ -48,8 +48,18 @@
48
48
  // as on the sheet: a stroke begun on the paper is the paper's and moves with it, and an erasing
49
49
  // begun on it takes the paper's strokes alone. The work for checking is the crop of the paper and
50
50
  // of the sheet's strokes, with the task's crop beside it.
51
+ //
52
+ // The learner's settings of the pen and the eraser, `pens`, come and go with `penchange`: a second
53
+ // press of the chosen pen or eraser opens its popover. Each stroke takes the style of the kind of
54
+ // pen in use — its colour, width and opacity —, which the screen, the crop for checking and the
55
+ // picture of the work draw it in. The eraser takes strokes whole, or in the mode "part" only what
56
+ // it passes over, cutting the strokes it crosses into pieces, new strokes, and the tutor's marks
57
+ // hold on to the pieces as to the strokes they were cut of. The attribute `unstyled` writes without
58
+ // styles, each stroke 3 units wide in the theme's ink: no popover opens, and the eraser takes
59
+ // whole strokes.
51
60
  import { cellOf, cellsOf, filledOf, sheetFilledOf } from "../core/boxes.js";
52
61
  import { Clock } from "../core/clock.js";
62
+ import { Cut, cutOf } from "../core/cut.js";
53
63
  import { ERASER_BUTTON, Eraser } from "../core/eraser.js";
54
64
  import { DEMO_START, demoStateOf, exampleOf, exampleTemplate, filledBy, fillValue, sameExample, } from "../core/example.js";
55
65
  import { sameItems } from "../core/fields.js";
@@ -59,12 +69,13 @@ import { Hands } from "../core/hands.js";
59
69
  import { begins, sameHistory } from "../core/history.js";
60
70
  import { NO_MANIFEST, settingsOf } from "../core/manifest.js";
61
71
  import { marksOf, placesOf, shownOf } from "../core/marks.js";
62
- import { INK_REACH, outline } from "../core/outline.js";
72
+ import { outline } from "../core/outline.js";
63
73
  import { isBox, LAYOUT, pieceWidth, } from "../core/page.js";
64
74
  import { encodePNG } from "../core/png.js";
65
75
  import { Recorder } from "../core/recorder.js";
66
76
  import { fitScale, K_MAX, scaleFor, toSheet } from "../core/screen.js";
67
77
  import { extentOf, pictureOf, REACH, SHEET } from "../core/sheet.js";
78
+ import { PALETTE, PEN_SETTINGS, penSettingsOf, reachOf, } from "../core/style.js";
68
79
  import { cellsForCheck, paperWorkForCheck, workForCheck } from "../core/submission.js";
69
80
  import { HAND, isTool, isWorkbook, NO_TASK, sameLayer, sameStatement, taskOf, templateOf, wholeSheet, } from "../core/task.js";
70
81
  import { boxOnSheet, isPaperGrid, keptOn, layOver, nextGrid, onSheet, onTracing, PAPER_GRIDS, readingOf, rulingsOf, sameTracing, scaled, scaleIn, TRACING, TRACING_START, toTracing, rectOf as tracingRect, scaleOf as tracingScaleOf, tracingStateOf, whollyOff, } from "../core/tracing.js";
@@ -73,6 +84,7 @@ import { ZOOM_MIN, ZOOM_STEP } from "../core/zoom.js";
73
84
  import { placeOver, SVG, write } from "./attributes.js";
74
85
  import { knows, labelsFor, say, sayAround } from "./labels.js";
75
86
  import { Parts } from "./parts.js";
87
+ import { pensStyle, samePens, screenColourOf } from "./pens.js";
76
88
  import { Pictures } from "./pictures.js";
77
89
  import { attachProbe } from "./probe.js";
78
90
  import { PAGE_ZOOM, PEN_MODE } from "./session.js";
@@ -102,6 +114,8 @@ const TRACING_CHANGE = "tracingchange";
102
114
  const TRACING_READ = "tracingread";
103
115
  /** The event the element sends when the learner turns a task from paper's grid with its button. */
104
116
  const GRID_CHANGE = "gridchange";
117
+ /** The event the element sends when the learner changes a setting of the pen or the eraser. */
118
+ const PEN_CHANGE = "penchange";
105
119
  /**
106
120
  * A task from paper's template: no statement, the pen and the eraser, and a dotted sheet, as the
107
121
  * task comes, whose grid the learner turns.
@@ -176,7 +190,9 @@ const ERASER_RADIUS_PX = 10;
176
190
  // a button in focus shows a ring in the accent; an unavailable one is paler by its colour, not its
177
191
  // opacity, which would pale the ring too (WCAG 2.4.7, 1.4.11). A button's tooltip stands beside it,
178
192
  // white on near-black, as the mockup has it. Nothing in the element moves but the scrolling, which
179
- // jumps, and no tooltip fades (WCAG 2.3.3). The element is as tall as the statement and the sheet
193
+ // jumps, and, only to whom motion is no harm, the sign of a wait and a popover as it opens; no
194
+ // tooltip fades (WCAG 2.3.3). A pen that hovers over the sheet shows a circle as wide as its line,
195
+ // in its colour, or the eraser's circle, white seen through within a dark edge. The element is as tall as the statement and the sheet
180
196
  // unless it is given a height: then the statement and the sheet scroll in it, under the bar. A
181
197
  // consumer whose own bars float over the element's top and bottom says how far by
182
198
  // --novatrail-canvas-pad-top and -bottom: the statement starts below the first, and the sheet
@@ -480,7 +496,8 @@ canvas {
480
496
  border: 2px solid color-mix(in srgb, currentColor 25%, transparent); border-top-color: currentColor;
481
497
  }
482
498
  .tracing-scale .mode.back { background: #f2f2f7; color: var(--novatrail-canvas-ink, ${INK}); }
483
- /* The one motion: a wait for the reading the learner asked for, and only to whom it is no harm. */
499
+ /* The motions: a wait for the reading the learner asked for, and the pop-in of a popover of the
500
+ pen or the eraser (pens.ts), only to whom they are no harm. */
484
501
  @media (prefers-reduced-motion: no-preference) {
485
502
  .scan i { animation: novatrail-scan 1s ease-in-out infinite; }
486
503
  .spinner, .tracing-scale .mode.busy::before { animation: novatrail-spin 0.8s linear infinite; }
@@ -543,8 +560,23 @@ canvas {
543
560
  :is(.tools, .tracing-scale) button:focus-visible, .viewport:focus-visible + .ring {
544
561
  outline-color: Highlight;
545
562
  }
546
- }
547
- `;
563
+ .stage > .hover { background: CanvasText; }
564
+ .stage > .hover.erasing { background: Canvas; border-color: CanvasText; }
565
+ }
566
+ .stage > .hover {
567
+ inset: auto; left: var(--hover-x, 0px); top: var(--hover-y, 0px);
568
+ width: var(--hover-size, 4px); height: var(--hover-size, 4px);
569
+ margin: calc(var(--hover-size, 4px) / -2) 0 0 calc(var(--hover-size, 4px) / -2);
570
+ box-sizing: border-box; border-radius: 50%; pointer-events: none;
571
+ background: var(--hover-colour, var(--novatrail-canvas-ink, ${INK}));
572
+ opacity: var(--hover-opacity, 1);
573
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.9), 0 0 0 2px rgba(0, 0, 0, 0.25);
574
+ }
575
+ .stage > .hover.erasing {
576
+ background: rgba(255, 255, 255, 0.4); border: 1px solid rgba(0, 0, 0, 0.45); opacity: 1;
577
+ }
578
+ .stage > .hover[hidden] { display: none; }
579
+ ${pensStyle(INK, PAPER, ACCENT)}`;
548
580
  /** The sheet of STYLE that the elements of a document adopt, made by the first of them there. */
549
581
  const sheets = new WeakMap();
550
582
  /**
@@ -721,6 +753,7 @@ export class NovatrailCanvas extends HTMLElement {
721
753
  next: () => this.#openNext(),
722
754
  toggle: () => this.#toggleDemo(),
723
755
  trace: () => this.#trace(),
756
+ pens: (settings) => this.#choosePens(settings),
724
757
  }, DEMO_IDS);
725
758
  /** A task from paper's tracing paper: its layer, its grip and the crop's picture. */
726
759
  #tracingPaper = new TracingPaper({
@@ -757,11 +790,27 @@ export class NovatrailCanvas extends HTMLElement {
757
790
  this.#work.write(stroke, this.#writeOn);
758
791
  this.#changed();
759
792
  }, this.#clock);
760
- /** The eraser: what a press came near leaves the work when it lifts, if still on the sheet. */
761
- #eraser = new Eraser((from, to, reach) => this.#work.near(from, to, reach, this.#eraseOn), (ids, time) => {
762
- if (this.#work.erase(ids, time))
763
- this.#changed();
764
- });
793
+ /**
794
+ * The eraser: what a press came near leaves the work when it lifts, if still on the sheet,
795
+ * whole, or in the mode "part" cut into the pieces it leaves.
796
+ */
797
+ #eraser = new Eraser((from, to, reach) => this.#work.near(from, to, reach, this.#eraseOn), (ids, time, erasure) => this.#erased(ids, time, erasure));
798
+ /**
799
+ * What the eraser that takes a part, while it is down, leaves of each stroke it crossed, by the
800
+ * stroke's ID: its cut, fed the eraser's path as far as `fed`, and the pieces the screen shows
801
+ * in the stroke's place.
802
+ */
803
+ #cutting = new Map();
804
+ /** The learner's settings of the pen and the eraser, frozen. */
805
+ #pens = PEN_SETTINGS;
806
+ /** Whether the strokes take a style and the popovers open: not under `unstyled`. */
807
+ #styled = true;
808
+ /** Whether the colours are forced, where every stroke is the ink on the screen. */
809
+ #forced = false;
810
+ /** The circle a pen hovering over the sheet shows. */
811
+ #hover = document.createElement("div");
812
+ /** The strokes on the sheet cut of each stroke, by its ID, kept while the strokes are the same. */
813
+ #piecesById = { strokes: [], of: new Map() };
765
814
  /**
766
815
  * The hands on the sheet: which pointer may write, which is a palm, and which two fingers
767
816
  * scroll, in the page's pen mode. The recorder and the eraser say which pointer writes.
@@ -788,6 +837,7 @@ export class NovatrailCanvas extends HTMLElement {
788
837
  #resized = () => {
789
838
  this.#region();
790
839
  this.#fit();
840
+ this.#tools.pens.place();
791
841
  };
792
842
  #page = new ResizeObserver(this.#resized);
793
843
  /** A window of another size has another view: the sheet goes as far past the ink by it. */
@@ -874,9 +924,10 @@ export class NovatrailCanvas extends HTMLElement {
874
924
  this.#area = { width: box.inlineSize, height: box.blockSize };
875
925
  }
876
926
  // The container's new size, the statement's or that of the list of a demo's parts: each moves
877
- // the sheet, and the first is the room of a worked example's row.
927
+ // the sheet, and the first is the room of a worked example's row and of a popover.
878
928
  this.#layout();
879
929
  this.#fit();
930
+ this.#tools.pens.place();
880
931
  });
881
932
  /** The size of the container's visible part, in CSS pixels as laid out, before any transform. */
882
933
  #area;
@@ -921,6 +972,9 @@ export class NovatrailCanvas extends HTMLElement {
921
972
  band.firstElementChild?.setAttribute("class", "grid");
922
973
  }
923
974
  this.#print.setAttribute("class", "print");
975
+ this.#hover.className = "hover";
976
+ this.#hover.setAttribute("aria-hidden", "true");
977
+ this.#hover.hidden = true;
924
978
  // The constructor reads no attribute: the labels of a demo's boxes are English till `lang`
925
979
  // comes.
926
980
  this.#nameBoxes(null);
@@ -929,7 +983,7 @@ export class NovatrailCanvas extends HTMLElement {
929
983
  this.#print.append(this.#lines);
930
984
  this.#template.append(this.#grid, this.#print);
931
985
  this.#show.append(this.#parts.layer);
932
- this.#stage.append(this.#template, this.#widget, this.#show, this.#tracingPaper.layer, this.#tracingPaper.cover, this.#sketch, this.#canvas, this.#marksLayer, this.#tracingPaper.frame, this.#tracingPaper.sign, this.#tracingPaper.grip, this.#tracingPaper.tip, this.#tracingPaper.bar);
986
+ this.#stage.append(this.#template, this.#widget, this.#show, this.#tracingPaper.layer, this.#tracingPaper.cover, this.#sketch, this.#canvas, this.#hover, this.#marksLayer, this.#tracingPaper.frame, this.#tracingPaper.sign, this.#tracingPaper.grip, this.#tracingPaper.tip, this.#tracingPaper.bar);
933
987
  this.#sheet.append(this.#stage, this.#parts.spot);
934
988
  // The bands come after the sheet: the ruling on its edge, half past the band, lies over it.
935
989
  this.#column.append(this.#statement.element, this.#parts.list, this.#parts.status, this.#sheet, this.#above, this.#below);
@@ -945,6 +999,9 @@ export class NovatrailCanvas extends HTMLElement {
945
999
  this.#canvas.addEventListener("pointerdown", (event) => this.#down(event));
946
1000
  this.#canvas.addEventListener("pointermove", (event) => this.#move(event));
947
1001
  this.#canvas.addEventListener("pointerup", (event) => this.#up(event));
1002
+ for (const type of ["pointerleave", "pointerout"]) {
1003
+ this.#canvas.addEventListener(type, () => this.#unhover());
1004
+ }
948
1005
  this.#canvas.addEventListener("pointercancel", (event) => {
949
1006
  this.#drop(event.pointerId);
950
1007
  this.#lifted(event.pointerId);
@@ -988,6 +1045,7 @@ export class NovatrailCanvas extends HTMLElement {
988
1045
  marks: this.#shown.map(({ name, placed, frame }) => ({ name, ids: placed.ids, frame })),
989
1046
  roles: this.#hands.roles,
990
1047
  }));
1048
+ this.#adopt("pens");
991
1049
  this.#adopt("tool");
992
1050
  this.#adopt("task");
993
1051
  this.#adopt("workedExample");
@@ -1003,8 +1061,33 @@ export class NovatrailCanvas extends HTMLElement {
1003
1061
  this.#adopt("history");
1004
1062
  this.#adopt("marks");
1005
1063
  }
1006
- /** The element follows its own `lang`: its buttons are labelled in it. */
1007
- static observedAttributes = ["lang", "tools-hidden"];
1064
+ /**
1065
+ * The element follows its own `lang`, its buttons labelled in it, `tools-hidden`, and
1066
+ * `unstyled`, under which the strokes take no style.
1067
+ */
1068
+ static observedAttributes = ["lang", "tools-hidden", "unstyled"];
1069
+ /**
1070
+ * The settings of the pen and the eraser, frozen: canvas's as the element comes — a pen, black
1071
+ * and three units wide, a blue liner, a yellow marker, and an eraser of strokes whole, 16 units
1072
+ * across. The learner changes them in the popovers of the pen and the eraser, which a `penchange`
1073
+ * tells; the consumer keeps them and gives them back to the next element, which tells nothing.
1074
+ * The next stroke takes the style of the kind in use, and the eraser its mode and its size: a
1075
+ * stroke written keeps its own. Settings not of `PenSettings` are a TypeError that names the
1076
+ * field, and leave the settings as they were; `undefined` changes nothing. Under the attribute
1077
+ * `unstyled` they are kept and given all the same, and the strokes take none of them.
1078
+ */
1079
+ get pens() {
1080
+ return this.#pens;
1081
+ }
1082
+ set pens(settings) {
1083
+ if (settings === undefined)
1084
+ return;
1085
+ const checked = penSettingsOf(settings);
1086
+ if (samePens(checked, this.#pens))
1087
+ return;
1088
+ this.#pens = checked;
1089
+ this.#refresh();
1090
+ }
1008
1091
  /**
1009
1092
  * What a press of the primary button does: "pen" writes, as the element starts, "eraser" erases,
1010
1093
  * and "hand" moves the sheet, under any pointer. The learner switches it with the
@@ -1467,14 +1550,23 @@ export class NovatrailCanvas extends HTMLElement {
1467
1550
  * `tools-hidden` did: while the element has it, the bar is out of sight and of the accessibility
1468
1551
  * tree, as `app` hides it on a phone under its tutor's sheet. An attribute the
1469
1552
  * element had before it was defined comes here just after the constructor, which reads no
1470
- * attribute.
1553
+ * attribute. Or `unstyled` did: while the element has it, a stroke takes no style, 3 units wide
1554
+ * in the theme's ink, no popover opens, and the eraser takes whole strokes as near as it
1555
+ * always took them — the samples page writes so, while its texts say nothing of a style.
1471
1556
  */
1472
1557
  attributeChangedCallback(name) {
1473
1558
  if (name === "tools-hidden") {
1474
1559
  this.#tools.rail.hidden = this.hasAttribute("tools-hidden");
1560
+ this.#tools.pens.close();
1475
1561
  this.#fit();
1476
1562
  return;
1477
1563
  }
1564
+ if (name === "unstyled") {
1565
+ this.#styled = !this.hasAttribute("unstyled");
1566
+ this.#unhover();
1567
+ this.#refresh();
1568
+ return;
1569
+ }
1478
1570
  this.#tools.label(this.getAttribute("lang"));
1479
1571
  this.#nameGrip();
1480
1572
  this.#nameRegion();
@@ -1580,26 +1672,36 @@ export class NovatrailCanvas extends HTMLElement {
1580
1672
  * The picture of the work, for the `picture` of a stored work that app puts on the server, a
1581
1673
  * method of the agreement with app: the PNG of the strokes the surface shows,
1582
1674
  * with no condition — the sheet's page, or the workbook's whole page with its draft, and the ink
1583
- * past the page, right and down, with the tracing paper where it lies: one pixel a unit,
1584
- * 1000 × 1400 for the page alone, and scaled down past the page to hold no more pixels than it,
1585
- * its size in its PNG's header —, whatever is filled and whether the work was sent to be checked
1586
- * or not; an empty surface, and a worked example's, is white. The strokes are those
1587
- * `exportWork()` takes, as the history has them: not the stroke under way, but those under an
1588
- * eraser not yet lifted. Each is the outline the screen fills, black on white with no theme and
1589
- * no template — on a task from paper the strokes of both layers, the tracing paper's where it
1590
- * lies, hidden or not, with the crop's picture laid in grey and multiplied —, and the pixels go
1591
- * through the crop's encoder, grey a byte each: so the picture looks as the sheet does, and holds
1592
- * at most 1,576,640 bytes, for the encoder spends at most 9 bits on a byte of a row, under the 4
1593
- * MiB of a stored work.
1675
+ * past the page, right and down, with the tracing paper where it lies —, whatever is filled and
1676
+ * whether the work was sent to be checked or not; an empty surface, and a worked example's, is
1677
+ * white. The strokes are those `exportWork()` takes, as the history has them: not the stroke
1678
+ * under way, but those under an eraser not yet lifted. Each is the outline the screen fills, on
1679
+ * white with no theme and no template, in its style — its own colour, the palette's black too,
1680
+ * at its opacity, a marker multiplied —, and a stroke without one black; on a task from paper
1681
+ * the strokes of both layers, the tracing paper's where it lies, hidden or not, with the crop's
1682
+ * picture laid in grey and multiplied. While every stroke is grey — black, and the palette's
1683
+ * black, a hair off grey, among them —, the pixels
1684
+ * are grey, a byte each, one pixel a unit, 1000 × 1400 for the page alone, and scaled down past
1685
+ * the page to hold no more pixels than it; with a colour among them they are RGB, three bytes
1686
+ * each, and scaled down to hold no more bytes. Its size is in its PNG's header. The pixels go
1687
+ * through the crop's encoder: so the picture looks as the sheet does, and holds at most
1688
+ * 1,576,640 bytes, for the encoder spends at most 9 bits on a byte of a row, under the 4 MiB of a
1689
+ * stored work.
1594
1690
  */
1595
1691
  async exportPicture() {
1596
- // A pixel a unit, the ink 3 px wide as on a screen of a pixel a unit, while the page and the
1597
- // ink past it hold no more pixels than the page; scaled down to hold them past that.
1692
+ const tracing = this.#tracing;
1693
+ const work = this.#work;
1694
+ const strokes = work.strokes;
1695
+ const channels = strokes.every(({ style }) => style === undefined || isGrey(style.color))
1696
+ ? 1
1697
+ : 3;
1698
+ // A pixel a unit, the ink as wide as on a screen of a pixel a unit, while the page and the ink
1699
+ // past it hold no more bytes than the page in grey; scaled down to hold them past that.
1598
1700
  const reach = this.#inkReach();
1599
- const { width, height, scale } = pictureOf({
1600
- maxX: reach.maxX + INK_REACH,
1601
- maxY: reach.maxY + INK_REACH,
1602
- });
1701
+ // A stroke of the tracing paper reaches as far as the paper's scale draws it.
1702
+ const by = tracing === undefined ? 1 : scaleIn(tracing);
1703
+ const past = strokes.reduce((most, stroke) => Math.max(most, reachOf(stroke) * (work.onTracing(stroke.id) ? by : 1)), 0);
1704
+ const { width, height, scale } = pictureOf({ maxX: reach.maxX + past, maxY: reach.maxY + past }, channels);
1603
1705
  const canvas = document.createElement("canvas");
1604
1706
  canvas.width = width;
1605
1707
  canvas.height = height;
@@ -1608,42 +1710,45 @@ export class NovatrailCanvas extends HTMLElement {
1608
1710
  throw new Error(`<${TAG}> got no 2D context to draw its picture on`);
1609
1711
  context.fillStyle = "#fff";
1610
1712
  context.fillRect(0, 0, width, height);
1611
- context.fillStyle = "#000";
1612
- const tracing = this.#tracing;
1613
- const strokes = this.#work.strokes;
1614
- const work = this.#work;
1615
1713
  for (const stroke of strokes) {
1616
1714
  const traced = tracing !== undefined && work.onTracing(stroke.id);
1617
1715
  const [x, y] = traced ? tracing.at : [0, 0];
1618
1716
  // A stroke of the tracing paper is as large as the paper's scale draws it.
1619
1717
  const by = traced ? scale * scaleIn(tracing) : scale;
1620
1718
  context.setTransform(by, 0, 0, by, x * scale, y * scale);
1719
+ const { style } = stroke;
1720
+ context.fillStyle = style?.color ?? "#000";
1721
+ context.globalAlpha = style === undefined ? 1 : style.opacity / 100;
1722
+ context.globalCompositeOperation = style?.pen === "marker" ? "multiply" : "source-over";
1621
1723
  context.fill(this.#finished(stroke).path);
1622
1724
  }
1623
1725
  const { data } = context.getImageData(0, 0, width, height);
1624
1726
  // The canvas's memory goes at once, not at a collection: WebKit caps what all canvases hold.
1625
1727
  canvas.width = 0;
1626
1728
  canvas.height = 0;
1627
- // Black on white: the red of a pixel is its grey. Every index is within the pixels' four bytes
1628
- // a pixel, so none reads past them.
1629
- const gray = new Uint8Array(width * height);
1630
- for (let at = 0; at < gray.length; at++)
1631
- gray[at] = data[4 * at];
1729
+ // On opaque white, grey ink leaves a pixel's red its grey. Every index is within the pixels'
1730
+ // four bytes a pixel, so none reads past them.
1731
+ const pixels = new Uint8Array(channels * width * height);
1732
+ for (let at = 0; at < width * height; at++) {
1733
+ for (let c = 0; c < channels; c++)
1734
+ pixels[channels * at + c] = data[4 * at + c];
1735
+ }
1632
1736
  // A task from paper's crop lies over it where the tracing paper lies, shown or hidden, at the
1633
1737
  // picture's scale, as the crop of the work has it.
1634
1738
  if (tracing !== undefined) {
1635
1739
  const { size, gray: picture } = await this.#tracingPaper.read;
1636
1740
  if (picture !== null) {
1637
1741
  const rect = tracingRect(tracing.at, scaled(size, scaleIn(tracing)));
1638
- layOver(gray, width, picture, {
1742
+ const place = {
1639
1743
  left: rect.minX * scale,
1640
1744
  top: rect.minY * scale,
1641
1745
  right: rect.maxX * scale,
1642
1746
  bottom: rect.maxY * scale,
1643
- });
1747
+ };
1748
+ layOver(pixels, width, picture, place, channels);
1644
1749
  }
1645
1750
  }
1646
- return blobOf(encodePNG(gray, width, height));
1751
+ return blobOf(encodePNG(pixels, width, height, channels));
1647
1752
  }
1648
1753
  disconnectedCallback() {
1649
1754
  // A stroke or an erasing under way ends where it is: its pointerup will not reach a sheet off
@@ -1709,6 +1814,8 @@ export class NovatrailCanvas extends HTMLElement {
1709
1814
  #present(template) {
1710
1815
  const shown = this.#shownTemplate;
1711
1816
  this.#shownTemplate = template;
1817
+ if (!sameLayer(template, shown) || !sameStatement(template, shown))
1818
+ this.#tools.pens.close();
1712
1819
  if (!sameLayer(template, shown)) {
1713
1820
  this.#lay(template);
1714
1821
  // A page of other boxes, or of the other kind, puts the marks back or takes them off.
@@ -1848,13 +1955,21 @@ export class NovatrailCanvas extends HTMLElement {
1848
1955
  this.#showMarks([]);
1849
1956
  }
1850
1957
  }
1851
- /** Every stroke the sheet has known, erased or not, as its history wrote them. */
1958
+ /**
1959
+ * Every stroke the sheet has known, erased or not, as its history wrote them: the strokes
1960
+ * written, and the pieces the eraser cut.
1961
+ */
1852
1962
  #known() {
1853
1963
  const tracing = this.#tracing;
1854
1964
  return this.#work.history.flatMap((event) => {
1855
- if (event.kind !== "write")
1856
- return [];
1857
- return [tracing === undefined ? event.stroke : this.#onSheet(event.stroke, tracing)];
1965
+ const strokes = event.kind === "write"
1966
+ ? [event.stroke]
1967
+ : event.kind === "cut"
1968
+ ? event.pieces.map(({ stroke }) => stroke)
1969
+ : [];
1970
+ return tracing === undefined
1971
+ ? strokes
1972
+ : strokes.map((stroke) => this.#onSheet(stroke, tracing));
1858
1973
  });
1859
1974
  }
1860
1975
  /**
@@ -1920,6 +2035,9 @@ export class NovatrailCanvas extends HTMLElement {
1920
2035
  * recorder takes the primary button alone.
1921
2036
  */
1922
2037
  #down(event) {
2038
+ // A press on the sheet closes a popover of the pen or the eraser, and writes or erases as well.
2039
+ this.#tools.pens.close();
2040
+ this.#unhover();
1923
2041
  // A worked example's sheet takes no input: the canvas takes no pointer then, and an event
1924
2042
  // that a script sends it does nothing either, nor puts the page in pen mode.
1925
2043
  if (this.#example !== undefined)
@@ -1980,14 +2098,148 @@ export class NovatrailCanvas extends HTMLElement {
1980
2098
  const sample = traced && tracing !== undefined
1981
2099
  ? { ...onSheetSample, ...toTracing(onSheetSample, tracing.at, size, scale) }
1982
2100
  : onSheetSample;
1983
- // On the tracing paper the eraser reaches as far on the screen, in the paper's own units.
1984
- const reach = traced ? ERASER_RADIUS_PX / screen.k / scale : ERASER_RADIUS_PX / screen.k;
2101
+ // On the tracing paper the eraser is as large on the screen, in the paper's own units, and a
2102
+ // stroke there keeps its width in them. The work adds how far each stroke's ink reaches past
2103
+ // its points.
2104
+ const { radius, mode } = this.#eraserOf(screen.k);
2105
+ const reach = traced ? radius / scale : radius;
2106
+ if (erases)
2107
+ this.#cutting.clear();
2108
+ const style = this.#styled ? this.#pens.styles[this.#pens.pen] : undefined;
1985
2109
  const began = erases
1986
- ? this.#eraser.down(sample, reach + INK_REACH)
1987
- : this.#recorder.down(sample);
2110
+ ? this.#eraser.down(sample, reach, mode)
2111
+ : this.#recorder.down(sample, style);
1988
2112
  if (began)
1989
2113
  this.#request();
1990
2114
  }
2115
+ /**
2116
+ * The eraser's radius on the sheet, in its units, at a scale of the screen, and its mode. One
2117
+ * that takes strokes whole reaches as far as its size, and never less on the screen than it
2118
+ * always reached; one that takes a part, its size exactly. Without styles, it takes strokes
2119
+ * whole, as near as it always took them, whatever the settings.
2120
+ */
2121
+ #eraserOf(k) {
2122
+ const least = ERASER_RADIUS_PX / k;
2123
+ if (!this.#styled)
2124
+ return { radius: least, mode: "stroke" };
2125
+ const half = this.#pens.eraserSize / 2;
2126
+ return this.#pens.eraser === "part"
2127
+ ? { radius: half, mode: "part" }
2128
+ : { radius: Math.max(half, least), mode: "stroke" };
2129
+ }
2130
+ /**
2131
+ * A press of the eraser lifted, with what it came near: in the mode "stroke" it erases those
2132
+ * strokes still on the sheet; in the mode "part" each of them its path crossed goes, and its
2133
+ * pieces come in its place, in one cut, numbered in the sheet's order and along each stroke. A
2134
+ * stroke it came near but did not cross stays as it is, and with none crossed nothing is done.
2135
+ */
2136
+ #erased(ids, time, erasure) {
2137
+ this.#cutting.clear();
2138
+ if (erasure.mode === "stroke") {
2139
+ if (this.#work.erase(ids, time))
2140
+ this.#changed();
2141
+ return;
2142
+ }
2143
+ const hit = new Set(ids);
2144
+ const crossed = [];
2145
+ for (const stroke of this.#work.strokes) {
2146
+ if (!hit.has(stroke.id))
2147
+ continue;
2148
+ const pieces = cutOf(stroke, erasure.path, erasure.reach + reachOf(stroke));
2149
+ if (pieces !== null)
2150
+ crossed.push({ stroke, pieces });
2151
+ }
2152
+ if (crossed.length === 0) {
2153
+ this.#request();
2154
+ return;
2155
+ }
2156
+ let id = this.#recorder.reserve(crossed.reduce((count, { pieces }) => count + pieces.length, 0));
2157
+ const cuts = crossed.map(({ stroke, pieces }) => ({
2158
+ id: stroke.id,
2159
+ pieces: pieces.map((points) => pieceOf(stroke, id++, points)),
2160
+ }));
2161
+ if (this.#work.cut(cuts, time))
2162
+ this.#changed();
2163
+ }
2164
+ /**
2165
+ * What the eraser that takes a part, still down, leaves of a stroke it came near, for the
2166
+ * screen: its cut fed the path's places it has not had yet, and the pieces anew when they
2167
+ * changed — the stroke whole while the path has not crossed it.
2168
+ */
2169
+ #piecesOf(stroke, erasure) {
2170
+ let entry = this.#cutting.get(stroke.id);
2171
+ if (entry === undefined || entry.cut.stroke !== stroke) {
2172
+ entry = { cut: new Cut(stroke, erasure.reach + reachOf(stroke)), fed: 0, pieces: [stroke] };
2173
+ this.#cutting.set(stroke.id, entry);
2174
+ }
2175
+ const { path } = erasure;
2176
+ let more = false;
2177
+ for (; entry.fed < path.length; entry.fed++) {
2178
+ const to = path[entry.fed];
2179
+ more = entry.cut.add(path[entry.fed - 1] ?? to, to) || more;
2180
+ }
2181
+ if (more) {
2182
+ const pieces = entry.cut.pieces();
2183
+ entry.pieces =
2184
+ pieces === null ? [stroke] : pieces.map((points) => pieceOf(stroke, stroke.id, points));
2185
+ }
2186
+ return entry.pieces;
2187
+ }
2188
+ /**
2189
+ * The learner made a choice in a popover of the pen or the eraser: the settings are those now,
2190
+ * and whoever listens hears of them, unless they are the same. A consumer that gives the
2191
+ * settings follows them.
2192
+ */
2193
+ #choosePens(settings) {
2194
+ if (samePens(settings, this.#pens))
2195
+ return;
2196
+ this.#pens = settings;
2197
+ this.#refresh();
2198
+ this.dispatchEvent(new CustomEvent(PEN_CHANGE, { bubbles: true, composed: true, detail: settings }));
2199
+ }
2200
+ /**
2201
+ * A pen hovering over the sheet, its buttons up, as Apple Pencil Pro does, shows a circle at its
2202
+ * point: the pen's as wide as the line of the kind in use, in its colour, a little seen through
2203
+ * at the least, and the eraser's as large as it erases. None with the hand, without styles, on a
2204
+ * worked example, or with any other pointer.
2205
+ */
2206
+ #hoverAt(event) {
2207
+ const screen = this.#view();
2208
+ const eraser = this.#tool === "eraser";
2209
+ if (event.buttons !== 0 ||
2210
+ !this.#styled ||
2211
+ this.#example !== undefined ||
2212
+ this.#tool === HAND ||
2213
+ screen === undefined) {
2214
+ this.#unhover();
2215
+ return;
2216
+ }
2217
+ // CSS pixels of the stage to a client pixel, under whatever transform the page puts on it.
2218
+ const by = this.#canvas.offsetWidth > 0 ? screen.width / this.#canvas.offsetWidth : 1;
2219
+ const style = this.#pens.styles[this.#pens.pen];
2220
+ const size = eraser
2221
+ ? 2 * this.#eraserOf(screen.k).radius * screen.k
2222
+ : Math.max(4 * by, style.width * screen.k);
2223
+ const hover = this.#hover;
2224
+ hover.classList.toggle("erasing", eraser);
2225
+ hover.style.setProperty("--hover-x", `${(event.clientX - screen.left) / by}px`);
2226
+ hover.style.setProperty("--hover-y", `${(event.clientY - screen.top) / by}px`);
2227
+ hover.style.setProperty("--hover-size", `${size / by}px`);
2228
+ if (eraser) {
2229
+ hover.style.removeProperty("--hover-colour");
2230
+ hover.style.removeProperty("--hover-opacity");
2231
+ }
2232
+ else {
2233
+ const colour = screenColourOf(style, this.#canvasStyle.color, this.#forced);
2234
+ hover.style.setProperty("--hover-colour", colour);
2235
+ hover.style.setProperty("--hover-opacity", String(Math.max(0.35, style.opacity / 100)));
2236
+ }
2237
+ hover.hidden = false;
2238
+ }
2239
+ /** The hovering pen's circle goes: the pen came down, or left the sheet. */
2240
+ #unhover() {
2241
+ this.#hover.hidden = true;
2242
+ }
1991
2243
  /** The canvas holds on to a pointer until it lifts. */
1992
2244
  #capture(pointerId) {
1993
2245
  try {
@@ -1998,6 +2250,8 @@ export class NovatrailCanvas extends HTMLElement {
1998
2250
  }
1999
2251
  }
2000
2252
  #move(event) {
2253
+ if (event.pointerType === "pen")
2254
+ this.#hoverAt(event);
2001
2255
  // The sheet goes with the hand, as with two fingers.
2002
2256
  const pan = this.#pan;
2003
2257
  if (pan !== undefined && pan.pointerId === event.pointerId) {
@@ -2079,8 +2333,10 @@ export class NovatrailCanvas extends HTMLElement {
2079
2333
  }
2080
2334
  /** A pointer's stroke or erasing goes, as on `pointercancel`, and the sheet is drawn anew. */
2081
2335
  #drop(pointerId) {
2082
- if (this.#recorder.cancel(pointerId) || this.#eraser.cancel(pointerId))
2336
+ if (this.#recorder.cancel(pointerId) || this.#eraser.cancel(pointerId)) {
2337
+ this.#cutting.clear();
2083
2338
  this.#request();
2339
+ }
2084
2340
  }
2085
2341
  /** The input a pointer drives: the recorder while it writes, the eraser while it erases. */
2086
2342
  #inputOf(pointerId) {
@@ -2502,7 +2758,11 @@ export class NovatrailCanvas extends HTMLElement {
2502
2758
  */
2503
2759
  #watchColours() {
2504
2760
  const forced = matchMedia("(forced-colors: active)");
2505
- const changed = () => this.#request();
2761
+ this.#forced = forced.matches;
2762
+ const changed = () => {
2763
+ this.#forced = forced.matches;
2764
+ this.#request();
2765
+ };
2506
2766
  forced.addEventListener("change", changed);
2507
2767
  this.#unwatchColours = () => forced.removeEventListener("change", changed);
2508
2768
  }
@@ -2880,6 +3140,8 @@ export class NovatrailCanvas extends HTMLElement {
2880
3140
  expanded: demo?.hidden !== true,
2881
3141
  traced: this.#tracing?.hidden !== true,
2882
3142
  grid: this.#paperGrid,
3143
+ pens: this.#pens,
3144
+ styled: this.#styled,
2883
3145
  });
2884
3146
  this.#sheet.classList.toggle("hand", this.#tool === HAND);
2885
3147
  this.#nameRegion();
@@ -2981,17 +3243,34 @@ export class NovatrailCanvas extends HTMLElement {
2981
3243
  const tracing = this.#tracing;
2982
3244
  const work = this.#work;
2983
3245
  // A stroke of the tracing paper is where the paper lies, and out of sight while it is hidden.
2984
- // Its box moves with the paper, and the stroke is not copied for each place of a drag.
2985
- const onScreen = (id) => {
2986
- const stroke = pending.has(id) ? undefined : byId.get(id);
2987
- if (stroke === undefined)
3246
+ // Its box moves with the paper, and the stroke is not copied for each place of a drag. An
3247
+ // eraser that takes a part, still down, leaves the frames where they are till it lifts.
3248
+ const hidden = this.#eraser.erasure?.mode === "part" ? new Set() : pending;
3249
+ const boxOn = (stroke) => {
3250
+ if (hidden.has(stroke.id))
2988
3251
  return undefined;
2989
- if (tracing === undefined || !work.onTracing(id))
3252
+ if (tracing === undefined || !work.onTracing(stroke.id))
2990
3253
  return this.#pointBoxOf(stroke);
2991
3254
  return tracing.hidden
2992
3255
  ? undefined
2993
3256
  : boxOnSheet(this.#pointBoxOf(stroke), tracing.at, scaleIn(tracing));
2994
3257
  };
3258
+ // A stroke the eraser cut is where its pieces are, however many times they were cut since.
3259
+ const cut = this.#cutOf();
3260
+ const onScreen = (id) => {
3261
+ const stroke = byId.get(id);
3262
+ if (stroke !== undefined)
3263
+ return boxOn(stroke);
3264
+ const boxes = (cut.get(id) ?? []).flatMap((piece) => boxOn(piece) ?? []);
3265
+ if (boxes.length === 0)
3266
+ return undefined;
3267
+ return {
3268
+ minX: Math.min(...boxes.map((box) => box.minX)),
3269
+ minY: Math.min(...boxes.map((box) => box.minY)),
3270
+ maxX: Math.max(...boxes.map((box) => box.maxX)),
3271
+ maxY: Math.max(...boxes.map((box) => box.maxY)),
3272
+ };
3273
+ };
2995
3274
  const half = 1 / screen.k;
2996
3275
  for (const mark of this.#shown) {
2997
3276
  const shown = shownOf(mark.placed, onScreen);
@@ -3014,7 +3293,8 @@ export class NovatrailCanvas extends HTMLElement {
3014
3293
  const on = this.#writeOn === "tracing" ? this.#tracing : undefined;
3015
3294
  const [dx, dy] = on?.at ?? [0, 0];
3016
3295
  const by = on === undefined ? 1 : scaleIn(on);
3017
- mark.under = points.some((point) => near({ ...point, x: point.x * by + dx, y: point.y * by + dy }, frame, INK_REACH + half));
3296
+ const reach = reachOf(this.#writing.stroke) * by + half;
3297
+ mark.under = points.some((point) => near({ ...point, x: point.x * by + dx, y: point.y * by + dy }, frame, reach));
3018
3298
  }
3019
3299
  mark.frame = frame;
3020
3300
  const drawn = frame === null
@@ -3066,6 +3346,27 @@ export class NovatrailCanvas extends HTMLElement {
3066
3346
  this.#writing.seen = live.points.length;
3067
3347
  return fresh;
3068
3348
  }
3349
+ /**
3350
+ * The strokes on the sheet cut of each stroke, by its ID: the pieces of a stroke the eraser cut,
3351
+ * and the pieces of those pieces. Each action on the work gives a new array of strokes.
3352
+ */
3353
+ #cutOf() {
3354
+ const strokes = this.#work.strokes;
3355
+ if (this.#piecesById.strokes !== strokes) {
3356
+ const of = new Map();
3357
+ for (const stroke of strokes) {
3358
+ for (const id of this.#work.cutFrom(stroke.id)) {
3359
+ const pieces = of.get(id);
3360
+ if (pieces === undefined)
3361
+ of.set(id, [stroke]);
3362
+ else
3363
+ pieces.push(stroke);
3364
+ }
3365
+ }
3366
+ this.#piecesById = { strokes, of };
3367
+ }
3368
+ return this.#piecesById.of;
3369
+ }
3069
3370
  /** The strokes on the sheet by ID: each action on the work gives a new array of them. */
3070
3371
  #byId() {
3071
3372
  const strokes = this.#work.strokes;
@@ -3087,7 +3388,11 @@ export class NovatrailCanvas extends HTMLElement {
3087
3388
  * by the path it was given once, the stroke under way outlined anew. A stroke whose points lie
3088
3389
  * far out of sight is not outlined till it comes into sight: a history given to the sheet may
3089
3390
  * hold thousands. What the eraser under way has come near is out of sight already, though
3090
- * still on the sheet until it lifts. The ink's colour is the canvas's, as the theme makes it.
3391
+ * still on the sheet until it lifts — or, for an eraser that takes a part, drawn as the pieces it
3392
+ * would leave. A stroke without a style is in the ink's colour, the canvas's, as the theme makes
3393
+ * it; one with a style in its colour, filled once at its opacity, so that it is one layer
3394
+ * however it crosses itself, and a marker's multiplied with the ink under it. The palette's
3395
+ * black is the theme's ink, and with forced colours every stroke is.
3091
3396
  */
3092
3397
  #draw() {
3093
3398
  const screen = this.#view();
@@ -3111,37 +3416,59 @@ export class NovatrailCanvas extends HTMLElement {
3111
3416
  const right = screen.vx + screen.width / screen.k;
3112
3417
  const bottom = screen.vy + screen.height / screen.k;
3113
3418
  const erasing = this.#eraser.pending;
3419
+ const erasure = this.#eraser.erasure;
3114
3420
  // A task from paper's tracing paper: its strokes over the sheet's, moved to where it lies, and
3115
3421
  // none while it is hidden.
3116
3422
  const tracing = this.#tracing;
3117
3423
  const work = this.#work;
3118
3424
  const shown = tracing !== undefined && !tracing.hidden;
3425
+ const fill = (stroke, path) => {
3426
+ const { style } = stroke;
3427
+ if (style === undefined) {
3428
+ context.fill(path);
3429
+ return;
3430
+ }
3431
+ context.fillStyle = screenColourOf(style, colour, this.#forced);
3432
+ context.globalAlpha = style.opacity / 100;
3433
+ if (style.pen === "marker")
3434
+ context.globalCompositeOperation = "multiply";
3435
+ context.fill(path);
3436
+ context.fillStyle = colour;
3437
+ context.globalAlpha = 1;
3438
+ context.globalCompositeOperation = "source-over";
3439
+ };
3119
3440
  const draw = (stroke, dx, dy, by = 1) => {
3120
3441
  // The outline keeps within half the widest line of the points: twice that is out of sight.
3121
3442
  const box = this.#pointBoxOf(stroke);
3122
- const reach = 2 * INK_REACH * by;
3443
+ const reach = 2 * reachOf(stroke) * by;
3123
3444
  if (box.maxY * by + dy + reach < screen.vy || box.minY * by + dy - reach > bottom)
3124
3445
  return;
3125
3446
  if (box.maxX * by + dx + reach < screen.vx || box.minX * by + dx - reach > right)
3126
3447
  return;
3127
3448
  const ink = this.#finished(stroke);
3128
3449
  if (ink.bottom * by + dy >= screen.vy && ink.top * by + dy <= bottom)
3129
- context.fill(ink.path);
3450
+ fill(stroke, ink.path);
3451
+ };
3452
+ // A stroke an eraser has come near: out of sight, or the pieces a cut would leave of it.
3453
+ const drawn = (stroke) => {
3454
+ if (!erasing.has(stroke.id))
3455
+ return [stroke];
3456
+ return erasure?.mode === "part" ? this.#piecesOf(stroke, erasure) : [];
3130
3457
  };
3131
3458
  context.setTransform(across, 0, 0, down, -screen.vx * across, -screen.vy * down);
3132
3459
  const traced = [];
3133
3460
  for (const stroke of work.strokes) {
3134
- if (erasing.has(stroke.id))
3135
- continue;
3136
- if (tracing === undefined || !work.onTracing(stroke.id))
3137
- draw(stroke, 0, 0);
3461
+ if (tracing === undefined || !work.onTracing(stroke.id)) {
3462
+ for (const each of drawn(stroke))
3463
+ draw(each, 0, 0);
3464
+ }
3138
3465
  else if (shown)
3139
- traced.push(stroke);
3466
+ traced.push(...drawn(stroke));
3140
3467
  }
3141
3468
  const live = this.#recorder.live;
3142
3469
  const liveTraced = this.#writeOn === "tracing";
3143
3470
  if (live !== undefined && !liveTraced)
3144
- context.fill(pathOf(this.#outline(live, false)));
3471
+ fill(live, pathOf(this.#outline(live, false)));
3145
3472
  if (!shown)
3146
3473
  return;
3147
3474
  const [dx, dy] = tracing.at;
@@ -3151,7 +3478,7 @@ export class NovatrailCanvas extends HTMLElement {
3151
3478
  for (const stroke of traced)
3152
3479
  draw(stroke, dx, dy, by);
3153
3480
  if (live !== undefined && liveTraced)
3154
- context.fill(pathOf(this.#outline(live, false)));
3481
+ fill(live, pathOf(this.#outline(live, false)));
3155
3482
  }
3156
3483
  #finished(stroke) {
3157
3484
  let ink = this.#inks.get(stroke);
@@ -3221,6 +3548,21 @@ function rectOf(box, item) {
3221
3548
  rect.setAttribute("role", "img");
3222
3549
  return rect;
3223
3550
  }
3551
+ /**
3552
+ * Whether a stroke's colour `#rrggbb` is a grey for the picture of the work: its three channels
3553
+ * alike, or the palette's black, a hair off grey, which a picture of black ink keeps at a pixel a
3554
+ * unit: its grey is the red of its pixels.
3555
+ */
3556
+ function isGrey(colour) {
3557
+ if (colour === PALETTE[0])
3558
+ return true;
3559
+ return colour.slice(1, 3) === colour.slice(3, 5) && colour.slice(3, 5) === colour.slice(5, 7);
3560
+ }
3561
+ /** A piece of a stroke the eraser cut: a stroke of its own, of the stroke's pointer and style. */
3562
+ function pieceOf(stroke, id, points) {
3563
+ const { kind, style } = stroke;
3564
+ return style === undefined ? { id, kind, points } : { id, kind, style, points };
3565
+ }
3224
3566
  /** The bytes of a PNG as a Blob, for the consumer to send or show. */
3225
3567
  function blobOf(png) {
3226
3568
  return new Blob([png], { type: "image/png" });