@altnovatrail/canvas 0.3.42 → 0.3.43

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.
@@ -1,35 +1,41 @@
1
- import type { HistoryEvent } from "@altnovatrail/spec/canvas";
1
+ import type { HistoryEvent, Piece } from "@altnovatrail/spec/canvas";
2
2
  import type { Stroke } from "./ink.js";
3
3
  /**
4
4
  * An event of the history of writing: spec's type, of the contract of canvas and app.
5
5
  * What an action on the sheet did, at the sheet's time `t` when it landed, in the
6
6
  * order the actions landed; each event says which strokes it put on the sheet or took off, so
7
7
  * whoever reads the history replays it without the rules of the stack of undo. Those the
8
- * sheet hands out are frozen through.
8
+ * sheet hands out are frozen through. A piece of a stroke the eraser cut, spec's type too: the ID
9
+ * of the stroke it was cut of, and the piece, a stroke of its own.
9
10
  */
10
- export type { HistoryEvent };
11
+ export type { HistoryEvent, Piece };
11
12
  /**
12
- * The strokes a history leaves on the sheet, in the order they were written: what the sheet shows
13
- * after it.
13
+ * The strokes a history leaves on the sheet, in the sheet's order: as they were written, and each
14
+ * piece a cut left at the place of the stroke it was cut of, as the sheet puts it there. What the
15
+ * sheet shows after it.
14
16
  */
15
17
  export declare function replay(history: readonly HistoryEvent[]): Stroke[];
16
18
  /**
17
19
  * The events of a history given to the sheet, each checked field by field and copied into
18
20
  * frozen objects of the sheet's own, with only the fields the sheet keeps: others are passed over.
19
21
  * A value that is not such a history is a TypeError that names the field. Each event must be one of
20
- * the four, at a time from 0 that never goes back along the history; a stroke must have a new ID, a
21
- * whole number from 1, and one point at least, each on the sheet, with a pressure from 0 to 1, its
22
- * times never going back and none after the time it landed. Times are checked for their order
23
- * alone: strokes may overlap in time, as several pointers at once would write them. On a task from
24
- * paper, `paper`, a stroke written on the tracing paper says so, `on: "tracing"`, its points from
25
- * the paper's top left corner within the sheet's size; anywhere else `on` is a TypeError.
26
- * Whether the actions keep the rules of the stack, the work on the sheet checks as it
27
- * replays them (`Work.restore`).
22
+ * the five, at a time from 0 that never goes back along the history; a stroke must have a new ID, a
23
+ * whole number from 1, its style if it has one, and one point at least, each on the sheet, with a
24
+ * pressure from 0 to 1, its times never going back and none after the time it landed. Times are
25
+ * checked for their order alone: strokes may overlap in time, as several pointers at once would
26
+ * write them. A cut names one stroke written at least, none twice, and its pieces are new strokes,
27
+ * in the order of its IDs and along each stroke, each of one of them with its pointer and style: a
28
+ * run of its points with one point of its own at most at each end, at times within the stroke's,
29
+ * and never the whole stroke. On a task from paper, `paper`, a stroke written on the tracing
30
+ * paper says so, `on: "tracing"`, its points from the paper's top left corner within the sheet's
31
+ * size, and a piece cut of it is the tracing paper's too; anywhere else `on` is a TypeError.
32
+ * Whether the actions keep the rules of the stack, and take off strokes the sheet shows, the work
33
+ * on the sheet checks as it replays them (`Work.restore`).
28
34
  */
29
35
  export declare function historyOf(value: unknown, paper?: boolean): HistoryEvent[];
30
36
  /**
31
- * An event, frozen through: its stroke with its points, or its lists of IDs. Whoever holds
32
- * an event the sheet handed out cannot change the sheet by it.
37
+ * An event, frozen through: its stroke with its points and its style, a cut's pieces with theirs,
38
+ * or its lists of IDs. Whoever holds an event the sheet handed out cannot change the sheet by it.
33
39
  */
34
40
  export declare function frozen(event: HistoryEvent): HistoryEvent;
35
41
  /**
@@ -1,11 +1,16 @@
1
1
  import { record, shown } from "./fields.js";
2
+ import { segmentDistance } from "./geometry.js";
2
3
  import { REACH } from "./sheet.js";
4
+ import { sameStyle, styleOf } from "./style.js";
3
5
  /**
4
- * The strokes a history leaves on the sheet, in the order they were written: what the sheet shows
5
- * after it.
6
+ * The strokes a history leaves on the sheet, in the sheet's order: as they were written, and each
7
+ * piece a cut left at the place of the stroke it was cut of, as the sheet puts it there. What the
8
+ * sheet shows after it.
6
9
  */
7
10
  export function replay(history) {
8
11
  const written = [];
12
+ // The pieces cut of each stroke, which stand where it stood.
13
+ const cutOf = new Map();
9
14
  const visible = new Set();
10
15
  for (const event of history) {
11
16
  switch (event.kind) {
@@ -18,6 +23,18 @@ export function replay(history) {
18
23
  for (const id of event.ids)
19
24
  visible.delete(id);
20
25
  break;
26
+ case "cut":
27
+ for (const id of event.ids)
28
+ visible.delete(id);
29
+ for (const { of, stroke } of event.pieces) {
30
+ const pieces = cutOf.get(of);
31
+ if (pieces === undefined)
32
+ cutOf.set(of, [stroke]);
33
+ else
34
+ pieces.push(stroke);
35
+ visible.add(stroke.id);
36
+ }
37
+ break;
21
38
  case "undo":
22
39
  for (const id of event.removed)
23
40
  visible.delete(id);
@@ -26,26 +43,47 @@ export function replay(history) {
26
43
  break;
27
44
  }
28
45
  }
29
- return written.filter((stroke) => visible.has(stroke.id));
46
+ const strokes = [];
47
+ // A stack rather than a recursion: a stroke cut again and again nests its pieces as deep.
48
+ const next = [...written].reverse();
49
+ for (let stroke = next.pop(); stroke !== undefined; stroke = next.pop()) {
50
+ if (visible.has(stroke.id))
51
+ strokes.push(stroke);
52
+ const pieces = cutOf.get(stroke.id) ?? [];
53
+ for (let k = pieces.length - 1; k >= 0; k--)
54
+ next.push(pieces[k]);
55
+ }
56
+ return strokes;
30
57
  }
31
58
  /**
32
59
  * The events of a history given to the sheet, each checked field by field and copied into
33
60
  * frozen objects of the sheet's own, with only the fields the sheet keeps: others are passed over.
34
61
  * A value that is not such a history is a TypeError that names the field. Each event must be one of
35
- * the four, at a time from 0 that never goes back along the history; a stroke must have a new ID, a
36
- * whole number from 1, and one point at least, each on the sheet, with a pressure from 0 to 1, its
37
- * times never going back and none after the time it landed. Times are checked for their order
38
- * alone: strokes may overlap in time, as several pointers at once would write them. On a task from
39
- * paper, `paper`, a stroke written on the tracing paper says so, `on: "tracing"`, its points from
40
- * the paper's top left corner within the sheet's size; anywhere else `on` is a TypeError.
41
- * Whether the actions keep the rules of the stack, the work on the sheet checks as it
42
- * replays them (`Work.restore`).
62
+ * the five, at a time from 0 that never goes back along the history; a stroke must have a new ID, a
63
+ * whole number from 1, its style if it has one, and one point at least, each on the sheet, with a
64
+ * pressure from 0 to 1, its times never going back and none after the time it landed. Times are
65
+ * checked for their order alone: strokes may overlap in time, as several pointers at once would
66
+ * write them. A cut names one stroke written at least, none twice, and its pieces are new strokes,
67
+ * in the order of its IDs and along each stroke, each of one of them with its pointer and style: a
68
+ * run of its points with one point of its own at most at each end, at times within the stroke's,
69
+ * and never the whole stroke. On a task from paper, `paper`, a stroke written on the tracing
70
+ * paper says so, `on: "tracing"`, its points from the paper's top left corner within the sheet's
71
+ * size, and a piece cut of it is the tracing paper's too; anywhere else `on` is a TypeError.
72
+ * Whether the actions keep the rules of the stack, and take off strokes the sheet shows, the work
73
+ * on the sheet checks as it replays them (`Work.restore`).
43
74
  */
44
75
  export function historyOf(value, paper = false) {
45
76
  if (!Array.isArray(value))
46
77
  throw new TypeError(`history: a list of events, not ${shown(value)}`);
47
- const ids = new Set();
78
+ const written = new Map();
48
79
  let latest = 0;
80
+ // A stroke written or a piece cut, which no stroke before it had the ID of.
81
+ const fresh = (stroke, path) => {
82
+ if (written.has(stroke.id)) {
83
+ throw new TypeError(`${path}.id: ${stroke.id}, the ID of a stroke written before`);
84
+ }
85
+ written.set(stroke.id, stroke);
86
+ };
49
87
  // Array.from visits every index, a hole too, which map would pass over unchecked.
50
88
  return Array.from(value, (item, n) => {
51
89
  const path = `history[${n}]`;
@@ -58,14 +96,8 @@ export function historyOf(value, paper = false) {
58
96
  switch (fields.kind) {
59
97
  case "write": {
60
98
  const stroke = strokeOf(fields.stroke, `${path}.stroke`);
61
- if (ids.has(stroke.id)) {
62
- throw new TypeError(`${path}.stroke.id: ${stroke.id}, the ID of a stroke written before`);
63
- }
64
- ids.add(stroke.id);
65
- const end = stroke.points.at(-1)?.t ?? 0;
66
- if (t < end) {
67
- throw new TypeError(`${path}.t: ${t}, earlier than the stroke's last point, at ${end}`);
68
- }
99
+ fresh(stroke, `${path}.stroke`);
100
+ landed(stroke, t, path);
69
101
  if (fields.on === undefined)
70
102
  return frozen({ kind: "write", t, stroke });
71
103
  if (fields.on !== "tracing" || !paper) {
@@ -75,6 +107,8 @@ export function historyOf(value, paper = false) {
75
107
  }
76
108
  case "erase":
77
109
  return frozen({ kind: "erase", t, ids: idsOf(fields.ids, `${path}.ids`) });
110
+ case "cut":
111
+ return frozen(cutOf(fields, t, path, written, fresh));
78
112
  case "clear":
79
113
  return frozen({ kind: "clear", t, ids: idsOf(fields.ids, `${path}.ids`) });
80
114
  case "undo":
@@ -85,20 +119,145 @@ export function historyOf(value, paper = false) {
85
119
  restored: idsOf(fields.restored, `${path}.restored`),
86
120
  });
87
121
  default:
88
- throw new TypeError(`${path}.kind: "write", "erase", "clear" or "undo", not ${shown(fields.kind)}`);
122
+ throw new TypeError(`${path}.kind: "write", "erase", "cut", "clear" or "undo", not ${shown(fields.kind)}`);
123
+ }
124
+ });
125
+ }
126
+ /** A stroke lands no sooner than its last point: a piece too, when its cut lands. */
127
+ function landed(stroke, t, path) {
128
+ const end = stroke.points.at(-1)?.t ?? 0;
129
+ if (t < end) {
130
+ throw new TypeError(`${path}.t: ${t}, earlier than the stroke's last point, at ${end}`);
131
+ }
132
+ }
133
+ /** A cut's fields, checked against the strokes written before it, `written`. */
134
+ function cutOf(fields, t, path, written, fresh) {
135
+ const ids = idsOf(fields.ids, `${path}.ids`);
136
+ if (ids.length === 0) {
137
+ throw new TypeError(`${path}.ids: a list of stroke IDs, one at least, not an empty one`);
138
+ }
139
+ const named = new Set();
140
+ for (const [k, id] of ids.entries()) {
141
+ if (named.has(id))
142
+ throw new TypeError(`${path}.ids[${k}]: ${id}, named twice`);
143
+ if (!written.has(id))
144
+ throw new TypeError(`${path}.ids[${k}]: ${id}, no stroke written before`);
145
+ named.add(id);
146
+ }
147
+ if (!Array.isArray(fields.pieces)) {
148
+ throw new TypeError(`${path}.pieces: a list of pieces, not ${shown(fields.pieces)}`);
149
+ }
150
+ // How far along its stroke the last piece of each went: the place of its last point of the
151
+ // stroke's own, and its last time.
152
+ const along = new Map();
153
+ let order = 0;
154
+ const pieces = Array.from(fields.pieces, (item, j) => {
155
+ const at = `${path}.pieces[${j}]`;
156
+ const piece = record(item, at);
157
+ const of = idOf(piece.of, `${at}.of`);
158
+ const place = ids.indexOf(of);
159
+ if (place < 0)
160
+ throw new TypeError(`${at}.of: ${of}, none of the strokes the cut takes off`);
161
+ if (place < order) {
162
+ throw new TypeError(`${at}.of: ${of}, after a piece of a stroke later in ids: the pieces go in their order`);
89
163
  }
164
+ order = place;
165
+ const stroke = strokeOf(piece.stroke, `${at}.stroke`);
166
+ fresh(stroke, `${at}.stroke`);
167
+ landed(stroke, t, path);
168
+ // Every ID the cut names is of a stroke written: no lookup misses.
169
+ const source = written.get(of);
170
+ along.set(of, pieceOf(stroke, source, `${at}.stroke`, along.get(of)));
171
+ return { of, stroke };
90
172
  });
173
+ return { kind: "cut", t, ids, pieces };
174
+ }
175
+ /** Where the first piece of a stroke may begin: anywhere along it. */
176
+ const ALONG_START = Object.freeze({ index: -1, time: Number.NEGATIVE_INFINITY });
177
+ /**
178
+ * What a piece must be of the stroke it was cut of: its pointer and its style, and a run of its
179
+ * points with one point of its own at most at each end, past the piece of it before, `after`, at
180
+ * times within the stroke's, and not the whole stroke. Where it ends along the stroke.
181
+ */
182
+ function pieceOf(piece, source, path, after = ALONG_START) {
183
+ if (piece.kind !== source.kind) {
184
+ throw new TypeError(`${path}.kind: ${shown(source.kind)}, the pointer of the stroke ${source.id} it was cut of, not ${shown(piece.kind)}`);
185
+ }
186
+ if (!sameStyle(piece.style, source.style)) {
187
+ throw new TypeError(`${path}.style: ${shown(source.style ?? null)}, the style of the stroke ${source.id} it was cut of, not ${shown(piece.style ?? null)}`);
188
+ }
189
+ const { points } = piece;
190
+ const own = source.points;
191
+ if (points.length === own.length && points.every((point, k) => equalPoints(point, own[k]))) {
192
+ throw new TypeError(`${path}.points: the whole stroke ${source.id}: a cut leaves only pieces`);
193
+ }
194
+ const inner = points.slice(1, -1);
195
+ let start = -1;
196
+ if (inner.length > 0) {
197
+ const runAt = (k) => inner.every((point, j) => equalPoints(point, own[k + j]));
198
+ for (let k = after.index + 1; k + inner.length <= own.length && start < 0; k++) {
199
+ if (runAt(k))
200
+ start = k;
201
+ }
202
+ if (start < 0) {
203
+ const anywhere = own.some((_, k) => runAt(k));
204
+ throw new TypeError(anywhere
205
+ ? `${path}.points: a run of the stroke ${source.id} before the end of its piece before: the pieces go along it`
206
+ : `${path}.points: no run of the points of the stroke ${source.id}, with one of its own at most at each end`);
207
+ }
208
+ }
209
+ for (const k of [0, points.length - 1]) {
210
+ const end = points[k];
211
+ if (end !== undefined && !onLine(end, own)) {
212
+ throw new TypeError(`${path}.points[${k}]: not on the line of the stroke ${source.id}, where a cut's edge crosses it`);
213
+ }
214
+ }
215
+ const first = own[0]?.t ?? 0;
216
+ const last = own.at(-1)?.t ?? 0;
217
+ const begins = points[0]?.t ?? 0;
218
+ const ends = points.at(-1)?.t ?? 0;
219
+ if (begins < after.time) {
220
+ throw new TypeError(`${path}.points[0].t: ${begins}, before the piece of the stroke ${source.id} before it ends, at ${after.time}`);
221
+ }
222
+ for (const [k, time] of [
223
+ [0, begins],
224
+ [points.length - 1, ends],
225
+ ]) {
226
+ if (time < first || time > last) {
227
+ throw new TypeError(`${path}.points[${k}].t: ${time}, outside the times of the stroke ${source.id}, ${first} to ${last}`);
228
+ }
229
+ }
230
+ return { index: start < 0 ? after.index : start + inner.length - 1, time: ends };
231
+ }
232
+ /**
233
+ * How far a piece's own end may lie off its stroke's line, in units: it was put on a segment by
234
+ * interpolation, which rounds in the last bits alone.
235
+ */
236
+ const ON_LINE = 1e-6;
237
+ /** Whether a point lies on the line through a stroke's points, a segment of it or its one point. */
238
+ function onLine(point, own) {
239
+ if (own.length === 1 && own[0] !== undefined) {
240
+ return segmentDistance(point, point, own[0], own[0]) <= ON_LINE;
241
+ }
242
+ for (let k = 1; k < own.length; k++) {
243
+ const [a, b] = [own[k - 1], own[k]];
244
+ if (a !== undefined && b !== undefined && segmentDistance(point, point, a, b) <= ON_LINE) {
245
+ return true;
246
+ }
247
+ }
248
+ return false;
249
+ }
250
+ /** Whether two points are the same: the place, the time and the pressure. */
251
+ function equalPoints(a, b) {
252
+ return b !== undefined && a.x === b.x && a.y === b.y && a.t === b.t && a.p === b.p;
91
253
  }
92
254
  /**
93
- * An event, frozen through: its stroke with its points, or its lists of IDs. Whoever holds
94
- * an event the sheet handed out cannot change the sheet by it.
255
+ * An event, frozen through: its stroke with its points and its style, a cut's pieces with theirs,
256
+ * or its lists of IDs. Whoever holds an event the sheet handed out cannot change the sheet by it.
95
257
  */
96
258
  export function frozen(event) {
97
259
  if (event.kind === "write") {
98
- for (const point of event.stroke.points)
99
- Object.freeze(point);
100
- Object.freeze(event.stroke.points);
101
- Object.freeze(event.stroke);
260
+ frozenStroke(event.stroke);
102
261
  }
103
262
  else if (event.kind === "undo") {
104
263
  Object.freeze(event.removed);
@@ -106,9 +265,24 @@ export function frozen(event) {
106
265
  }
107
266
  else {
108
267
  Object.freeze(event.ids);
268
+ if (event.kind === "cut") {
269
+ for (const piece of event.pieces) {
270
+ frozenStroke(piece.stroke);
271
+ Object.freeze(piece);
272
+ }
273
+ Object.freeze(event.pieces);
274
+ }
109
275
  }
110
276
  return Object.freeze(event);
111
277
  }
278
+ function frozenStroke(stroke) {
279
+ for (const point of stroke.points)
280
+ Object.freeze(point);
281
+ Object.freeze(stroke.points);
282
+ if (stroke.style !== undefined)
283
+ Object.freeze(stroke.style);
284
+ Object.freeze(stroke);
285
+ }
112
286
  /**
113
287
  * Whether a value given as a history is the history the sheet has: the very array, or a list
114
288
  * whose every event says what the sheet's says, by the fields the sheet keeps — others are passed
@@ -149,10 +323,25 @@ export function sameEvent(value, event) {
149
323
  case "erase":
150
324
  case "clear":
151
325
  return sameIds(given.ids, event.ids);
326
+ case "cut":
327
+ return sameIds(given.ids, event.ids) && samePieces(given.pieces, event.pieces);
152
328
  case "undo":
153
329
  return sameIds(given.removed, event.removed) && sameIds(given.restored, event.restored);
154
330
  }
155
331
  }
332
+ function samePieces(value, pieces) {
333
+ if (value === pieces)
334
+ return true;
335
+ if (!Array.isArray(value) || value.length !== pieces.length)
336
+ return false;
337
+ return pieces.every(({ of, stroke }, n) => {
338
+ const given = value[n];
339
+ if (typeof given !== "object" || given === null)
340
+ return false;
341
+ const piece = given;
342
+ return piece.of === of && sameStroke(piece.stroke, stroke);
343
+ });
344
+ }
156
345
  function sameStroke(value, stroke) {
157
346
  if (value === stroke)
158
347
  return true;
@@ -162,10 +351,24 @@ function sameStroke(value, stroke) {
162
351
  const points = given.points;
163
352
  return (given.id === stroke.id &&
164
353
  given.kind === stroke.kind &&
354
+ sameStyleOf(given.style, stroke) &&
165
355
  Array.isArray(points) &&
166
356
  points.length === stroke.points.length &&
167
357
  stroke.points.every((point, n) => samePoint(points[n], point)));
168
358
  }
359
+ /** Whether a value says a stroke's style, by its four fields: none for a stroke without one. */
360
+ function sameStyleOf(value, stroke) {
361
+ const { style } = stroke;
362
+ if (style === undefined || value === undefined)
363
+ return value === style;
364
+ if (typeof value !== "object" || value === null)
365
+ return false;
366
+ const given = value;
367
+ return (given.pen === style.pen &&
368
+ given.color === style.color &&
369
+ given.width === style.width &&
370
+ given.opacity === style.opacity);
371
+ }
169
372
  function samePoint(value, point) {
170
373
  if (value === point)
171
374
  return true;
@@ -184,6 +387,7 @@ function strokeOf(value, path) {
184
387
  if (typeof fields.kind !== "string") {
185
388
  throw new TypeError(`${path}.kind: the pointer's type, a string, not ${shown(fields.kind)}`);
186
389
  }
390
+ const style = fields.style === undefined ? undefined : styleOf(fields.style, `${path}.style`);
187
391
  if (!Array.isArray(fields.points)) {
188
392
  throw new TypeError(`${path}.points: a list of points, not ${shown(fields.points)}`);
189
393
  }
@@ -204,7 +408,9 @@ function strokeOf(value, path) {
204
408
  const p = within(point.p, `${at}.p`, 0, 1);
205
409
  return { x, y, t, p };
206
410
  });
207
- return { id, kind: fields.kind, points };
411
+ return style === undefined
412
+ ? { id, kind: fields.kind, points }
413
+ : { id, kind: fields.kind, style, points };
208
414
  }
209
415
  function idsOf(value, path) {
210
416
  if (!Array.isArray(value)) {
@@ -4,10 +4,11 @@ export type { Crop, Frame } from "./crop.js";
4
4
  export type { DemoState, WorkedExample } from "./example.js";
5
5
  export type { GridKind } from "./grid.js";
6
6
  export type { Group } from "./groups.js";
7
- export { type HistoryEvent, replay } from "./history.js";
7
+ export { type HistoryEvent, type Piece, replay } from "./history.js";
8
8
  export type { InkPoint, Stroke } from "./ink.js";
9
9
  export type { Manifest } from "./manifest.js";
10
10
  export type { Anchor, CellPlace, CropNumbers, Mark, Marks, PaperSubmission, SheetSubmission, Submission, WorkbookSubmission, } from "./marks.js";
11
11
  export { SHEET } from "./sheet.js";
12
+ export type { EraserMode, PenKind, PenSettings, StrokeStyle } from "./style.js";
12
13
  export type { Canvas, Task } from "./task.js";
13
14
  export type { TracingState } from "./tracing.js";
package/lib/core/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // The DOM-free part of the canvas, the package's entry point @altnovatrail/canvas/core: plain
2
2
  // TypeScript that runs the same in a browser and in Node, for the tests and the synthetic samples
3
3
  // too. Importing it registers no element: the element is the other entry point. It
4
- // gives the sheet's size, the types of the data the element takes and gives — the strokes and the
5
- // history of writing, the task, the worked example and the manifest, how far the learner has gone
4
+ // gives the sheet's size, the types of the data the element takes and gives — the strokes, their
5
+ // styles and the pieces the eraser cuts, the history of writing, the settings of the pen and the
6
+ // eraser, the task, the worked example and the manifest, how far the learner has gone
6
7
  // through the example's demo and the context of a submission, of a sheet, a workbook or a
7
8
  // task from paper with where its tracing paper lay, all of spec's types, and the tutor's marks,
8
9
  // spec's types too — and the fold of a history into the strokes it leaves, so that a consumer reads
@@ -21,10 +21,20 @@ export declare function penWidth(pressure: number): number;
21
21
  export declare const INK_REACH: number;
22
22
  /** Whether a stroke's line widens with its pressure on the screen: only a pen's does. */
23
23
  export declare function followsPressure(stroke: Stroke): boolean;
24
+ /**
25
+ * The speed at which a pen of the kind "pen" without a pen's pressure draws its finest line, in
26
+ * sheet units a millisecond: a quick stroke of a finger or a mouse. Slower, the line is wider.
27
+ */
28
+ export declare const SPEED_FINEST = 1.5;
24
29
  /**
25
30
  * The outline of a stroke on the screen, as perfect-freehand draws it: a closed polygon around the
26
- * stroke's points, in sheet units, to be filled. A pen's line widens with its pressure; a mouse's
27
- * or a finger's is as wide all along. `complete` says the stroke has ended: its last point is
28
- * then taken as it is, rather than eased toward.
31
+ * stroke's points, in sheet units, to be filled. `complete` says the stroke has ended: its last
32
+ * point is then taken as it is, rather than eased toward. A stroke without a style is 3 units wide,
33
+ * black in the theme's ink: a pen's line widens with its pressure, and a mouse's or a
34
+ * finger's is as wide all along. A stroke with a style is its width: a liner's and a marker's line
35
+ * as wide all along; one of the kind "pen" wider and finer by a pen's pressure, as a pen without a
36
+ * style, or without one by the speed between its points, slow wider, and finer at its start, and
37
+ * at its end once it is complete. Its pressure stays the pointer's: a width from the speed is
38
+ * never written into a point.
29
39
  */
30
40
  export declare function outline(stroke: Stroke, complete: boolean): Vec2[];
@@ -54,22 +54,121 @@ const EVEN = 0;
54
54
  export function followsPressure(stroke) {
55
55
  return stroke.kind === "pen";
56
56
  }
57
+ /**
58
+ * The speed at which a pen of the kind "pen" without a pen's pressure draws its finest line, in
59
+ * sheet units a millisecond: a quick stroke of a finger or a mouse. Slower, the line is wider.
60
+ */
61
+ export const SPEED_FINEST = 1.5;
62
+ /**
63
+ * The share of a pen's line, of the kind "pen", that its speed sets without a pen's pressure: as
64
+ * a pressure, 0.45 at its first point, then each point's leaning on the one's before it by
65
+ * `SPEED_FOLLOW`, from 0.75 at rest down to 0.15 at `SPEED_FINEST` and faster.
66
+ */
67
+ const SPEED_START = 0.45;
68
+ const SPEED_FOLLOW = 0.25;
69
+ const SPEED_SLOWEST = 0.75;
70
+ const SPEED_RANGE = 0.6;
71
+ /**
72
+ * How a pen's line of the kind "pen" thins at its ends: its width there is this share of what it
73
+ * would be, and it widens to all of it over `TAPER_LENGTH` widths along the stroke.
74
+ */
75
+ const TAPER_LEAST = 0.45;
76
+ const TAPER_LENGTH = 4;
57
77
  /**
58
78
  * The outline of a stroke on the screen, as perfect-freehand draws it: a closed polygon around the
59
- * stroke's points, in sheet units, to be filled. A pen's line widens with its pressure; a mouse's
60
- * or a finger's is as wide all along. `complete` says the stroke has ended: its last point is
61
- * then taken as it is, rather than eased toward.
79
+ * stroke's points, in sheet units, to be filled. `complete` says the stroke has ended: its last
80
+ * point is then taken as it is, rather than eased toward. A stroke without a style is 3 units wide,
81
+ * black in the theme's ink: a pen's line widens with its pressure, and a mouse's or a
82
+ * finger's is as wide all along. A stroke with a style is its width: a liner's and a marker's line
83
+ * as wide all along; one of the kind "pen" wider and finer by a pen's pressure, as a pen without a
84
+ * style, or without one by the speed between its points, slow wider, and finer at its start, and
85
+ * at its end once it is complete. Its pressure stays the pointer's: a width from the speed is
86
+ * never written into a point.
62
87
  */
63
88
  export function outline(stroke, complete) {
64
- return polygon(stroke, followsPressure(stroke) ? PEN_THINNING : EVEN, complete);
89
+ const { style } = stroke;
90
+ if (style === undefined) {
91
+ return polygon(stroke, followsPressure(stroke) ? PEN_THINNING : EVEN, complete);
92
+ }
93
+ if (style.pen !== "pen")
94
+ return styled(stroke.points.map(() => 1), stroke, style.width, complete);
95
+ const factors = stroke.kind === "pen" ? pressed(stroke.points) : stroke.points.map(speedOf(stroke.points));
96
+ return styled(tapered(factors, stroke.points, style.width, complete), stroke, style.width, complete);
65
97
  }
66
- function polygon(stroke, thinning, complete) {
67
- // Each point's pressure leans on the point's before it: the line widens and narrows smoothly.
68
- let eased;
69
- const points = stroke.points.map(({ x, y, p }) => {
70
- eased = eased === undefined ? p : (1 - PEN_FOLLOW) * eased + PEN_FOLLOW * p;
71
- return [x, y, eased];
98
+ /** A pen's pressure, eased from point to point, as the width it gives the line, in widths. */
99
+ function pressed(points) {
100
+ return eased(points).map(penWidth);
101
+ }
102
+ /** Each point's pressure leaning on the point's before it, so the line widens and narrows smoothly. */
103
+ function eased(points) {
104
+ let last;
105
+ return points.map(({ p }) => {
106
+ last = last === undefined ? p : (1 - PEN_FOLLOW) * last + PEN_FOLLOW * p;
107
+ return last;
108
+ });
109
+ }
110
+ /** The width the speed gives each point of a line without a pen's pressure, in widths. */
111
+ function speedOf(points) {
112
+ let share = SPEED_START;
113
+ return (point, k) => {
114
+ const before = points[k - 1];
115
+ // A point at the time of the one before it has no speed of its own, and changes nothing.
116
+ if (before !== undefined && point.t > before.t) {
117
+ const speed = Math.hypot(point.x - before.x, point.y - before.y) / (point.t - before.t);
118
+ const target = SPEED_SLOWEST - SPEED_RANGE * Math.min(speed / SPEED_FINEST, 1);
119
+ share = (1 - SPEED_FOLLOW) * share + SPEED_FOLLOW * target;
120
+ }
121
+ return penWidth(share);
122
+ };
123
+ }
124
+ /**
125
+ * Widths of a line, finer at its start, and at its end once it is complete. A dot or a dash of two
126
+ * points keeps its width.
127
+ */
128
+ function tapered(factors, points, width, complete) {
129
+ if (points.length <= 2)
130
+ return factors;
131
+ const along = [];
132
+ let length = 0;
133
+ for (const [k, point] of points.entries()) {
134
+ const before = points[k - 1];
135
+ if (before !== undefined)
136
+ length += Math.hypot(point.x - before.x, point.y - before.y);
137
+ along.push(length);
138
+ }
139
+ const reach = TAPER_LENGTH * width;
140
+ const share = (distance) => Math.max(TAPER_LEAST, Math.min(1, TAPER_LEAST + ((1 - TAPER_LEAST) * distance) / reach));
141
+ return factors.map((factor, k) => {
142
+ const from = along[k] ?? 0;
143
+ const thinned = complete ? Math.min(share(from), share(length - from)) : share(from);
144
+ return factor * thinned;
72
145
  });
146
+ }
147
+ /**
148
+ * The outline of a stroke in a style, each point its width in widths of the style's: the library
149
+ * takes the width as each point's pressure and halves it, so its radius is the style's width times
150
+ * that, halved. Its size is the line's without a style, and its easing scales it to the style's
151
+ * width: the size also sets how far the library smooths the outline and how much of the stroke's
152
+ * start it passes over, which a wide marker would otherwise draw as a chord. A liner as wide as
153
+ * the line without a style draws a finger's very line.
154
+ */
155
+ function styled(factors, stroke, width, complete) {
156
+ const points = stroke.points.map(({ x, y }, k) => [x, y, factors[k] ?? 1]);
157
+ const scale = width / INK_WIDTH;
158
+ return freehand(points, {
159
+ ...OPTIONS,
160
+ easing: (factor) => (factor * scale) / 2,
161
+ thinning: PEN_THINNING,
162
+ last: complete,
163
+ });
164
+ }
165
+ function polygon(stroke, thinning, complete) {
166
+ const pressures = eased(stroke.points);
167
+ const points = stroke.points.map(({ x, y }, k) => [x, y, pressures[k] ?? 0]);
168
+ return freehand(points, { ...OPTIONS, thinning, last: complete });
169
+ }
170
+ /** perfect-freehand's outline of points [x, y, pressure], with the few points it draws amiss. */
171
+ function freehand(points, options) {
73
172
  // One point alone perfect-freehand pairs with another a unit off and draws as an oval. The same
74
173
  // point twice it draws as a round dot, as wide as the line.
75
174
  const [only, end] = points;
@@ -81,5 +180,5 @@ function polygon(stroke, thinning, complete) {
81
180
  const between = [1, 2, 3].map((quarter) => only.map((value, i) => value + ((end[i] ?? value) - value) * (quarter / 4)));
82
181
  points.splice(1, 0, ...between);
83
182
  }
84
- return getStroke(points, { ...OPTIONS, thinning, last: complete });
183
+ return getStroke(points, options);
85
184
  }
package/lib/core/png.d.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  /**
2
- * The PNG of a grey image, a byte to a pixel, row by row from the top: own code, so that the
3
- * same pixels give the same bytes in every browser and in Node, as no browser's canvas promises.
2
+ * The PNG of an image row by row from the top, grey, a byte to a pixel, or RGB, three bytes to a
3
+ * pixel, as `channels` says: own code, so that the same pixels give the same bytes in every browser
4
+ * and in Node, as no browser's canvas promises.
4
5
  * The file is the least PNG holds: its signature, the header, one chunk of data and the end,
5
6
  * no ancillary chunk, for a decoder may ignore them (PNG Third Edition, 11.3). The data is a zlib
6
7
  * stream of one deflate block with the fixed Huffman codes (RFC 1950, RFC 1951): every row
7
8
  * unfiltered, and a repeat looked for in two places only — the byte before, which takes the runs of
8
9
  * white, and the row above, which takes the rows a stroke runs straight down through.
9
10
  */
10
- export declare function encodePNG(gray: Uint8Array, width: number, height: number): Uint8Array<ArrayBuffer>;
11
+ export declare function encodePNG(pixels: Uint8Array, width: number, height: number, channels?: 1 | 3): Uint8Array<ArrayBuffer>;
11
12
  export declare function crc32(bytes: Uint8Array): number;
12
13
  /** zlib's checksum of the data before compression: two sums modulo 65521 (RFC 1950). */
13
14
  export declare function adler32(bytes: Uint8Array): number;