@altnovatrail/picture-kit 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +7 -0
  3. package/README.md +28 -2
  4. package/lib/emoji.d.ts +16 -0
  5. package/lib/emoji.js +64 -0
  6. package/lib/index.d.ts +9 -0
  7. package/lib/index.js +10 -0
  8. package/lib/kind.d.ts +22 -0
  9. package/lib/kind.js +2 -0
  10. package/lib/kinds/balance.d.ts +34 -0
  11. package/lib/kinds/balance.js +217 -0
  12. package/lib/kinds/branches.d.ts +33 -0
  13. package/lib/kinds/branches.js +473 -0
  14. package/lib/kinds/calendar.d.ts +55 -0
  15. package/lib/kinds/calendar.js +532 -0
  16. package/lib/kinds/chart.d.ts +48 -0
  17. package/lib/kinds/chart.js +645 -0
  18. package/lib/kinds/choices.d.ts +14 -0
  19. package/lib/kinds/choices.js +53 -0
  20. package/lib/kinds/clock.d.ts +36 -0
  21. package/lib/kinds/clock.js +219 -0
  22. package/lib/kinds/coins.d.ts +37 -0
  23. package/lib/kinds/coins.js +550 -0
  24. package/lib/kinds/column.d.ts +37 -0
  25. package/lib/kinds/column.js +410 -0
  26. package/lib/kinds/commands-parts.d.ts +12 -0
  27. package/lib/kinds/commands-parts.js +24 -0
  28. package/lib/kinds/commands.d.ts +66 -0
  29. package/lib/kinds/commands.js +789 -0
  30. package/lib/kinds/containers.d.ts +52 -0
  31. package/lib/kinds/containers.js +758 -0
  32. package/lib/kinds/countfig.d.ts +41 -0
  33. package/lib/kinds/countfig.js +372 -0
  34. package/lib/kinds/cubes.d.ts +70 -0
  35. package/lib/kinds/cubes.js +371 -0
  36. package/lib/kinds/die.d.ts +32 -0
  37. package/lib/kinds/die.js +301 -0
  38. package/lib/kinds/domino.d.ts +37 -0
  39. package/lib/kinds/domino.js +450 -0
  40. package/lib/kinds/dotgrid.d.ts +38 -0
  41. package/lib/kinds/dotgrid.js +411 -0
  42. package/lib/kinds/figure.d.ts +62 -0
  43. package/lib/kinds/figure.js +687 -0
  44. package/lib/kinds/fold-parts.d.ts +73 -0
  45. package/lib/kinds/fold-parts.js +315 -0
  46. package/lib/kinds/fold.d.ts +52 -0
  47. package/lib/kinds/fold.js +650 -0
  48. package/lib/kinds/fraction.d.ts +50 -0
  49. package/lib/kinds/fraction.js +568 -0
  50. package/lib/kinds/gauges.d.ts +53 -0
  51. package/lib/kinds/gauges.js +880 -0
  52. package/lib/kinds/gears.d.ts +40 -0
  53. package/lib/kinds/gears.js +787 -0
  54. package/lib/kinds/grid.d.ts +45 -0
  55. package/lib/kinds/grid.js +591 -0
  56. package/lib/kinds/groups.d.ts +23 -0
  57. package/lib/kinds/groups.js +335 -0
  58. package/lib/kinds/index.d.ts +3 -0
  59. package/lib/kinds/index.js +87 -0
  60. package/lib/kinds/lanes.d.ts +36 -0
  61. package/lib/kinds/lanes.js +220 -0
  62. package/lib/kinds/layers.d.ts +31 -0
  63. package/lib/kinds/layers.js +419 -0
  64. package/lib/kinds/line.d.ts +38 -0
  65. package/lib/kinds/line.js +739 -0
  66. package/lib/kinds/magic-parts.d.ts +72 -0
  67. package/lib/kinds/magic-parts.js +186 -0
  68. package/lib/kinds/magic.d.ts +66 -0
  69. package/lib/kinds/magic.js +664 -0
  70. package/lib/kinds/map.d.ts +32 -0
  71. package/lib/kinds/map.js +370 -0
  72. package/lib/kinds/matchsticks.d.ts +26 -0
  73. package/lib/kinds/matchsticks.js +434 -0
  74. package/lib/kinds/necklace.d.ts +27 -0
  75. package/lib/kinds/necklace.js +342 -0
  76. package/lib/kinds/net.d.ts +47 -0
  77. package/lib/kinds/net.js +241 -0
  78. package/lib/kinds/overlay.d.ts +50 -0
  79. package/lib/kinds/overlay.js +519 -0
  80. package/lib/kinds/pieces.d.ts +41 -0
  81. package/lib/kinds/pieces.js +420 -0
  82. package/lib/kinds/pipes.d.ts +46 -0
  83. package/lib/kinds/pipes.js +657 -0
  84. package/lib/kinds/plane-parts.d.ts +105 -0
  85. package/lib/kinds/plane-parts.js +372 -0
  86. package/lib/kinds/plane.d.ts +35 -0
  87. package/lib/kinds/plane.js +755 -0
  88. package/lib/kinds/pyramid.d.ts +26 -0
  89. package/lib/kinds/pyramid.js +228 -0
  90. package/lib/kinds/ropes.d.ts +30 -0
  91. package/lib/kinds/ropes.js +571 -0
  92. package/lib/kinds/shapes.d.ts +59 -0
  93. package/lib/kinds/shapes.js +490 -0
  94. package/lib/kinds/solids.d.ts +78 -0
  95. package/lib/kinds/solids.js +1058 -0
  96. package/lib/kinds/tangram.d.ts +52 -0
  97. package/lib/kinds/tangram.js +713 -0
  98. package/lib/kinds/target.d.ts +39 -0
  99. package/lib/kinds/target.js +761 -0
  100. package/lib/kinds/tiles.d.ts +55 -0
  101. package/lib/kinds/tiles.js +606 -0
  102. package/lib/kinds/venn.d.ts +38 -0
  103. package/lib/kinds/venn.js +710 -0
  104. package/lib/noto.d.ts +2 -0
  105. package/lib/noto.js +212 -0
  106. package/lib/objects.d.ts +7 -0
  107. package/lib/objects.js +226 -0
  108. package/lib/pen.d.ts +32 -0
  109. package/lib/pen.js +60 -0
  110. package/lib/read.d.ts +9 -0
  111. package/lib/read.js +49 -0
  112. package/lib/render.d.ts +24 -0
  113. package/lib/render.js +68 -0
  114. package/lib/solve/balance.d.ts +46 -0
  115. package/lib/solve/balance.js +118 -0
  116. package/lib/style.d.ts +70 -0
  117. package/lib/style.js +39 -0
  118. package/lib/svg.d.ts +22 -0
  119. package/lib/svg.js +48 -0
  120. package/lib/things.d.ts +40 -0
  121. package/lib/things.js +269 -0
  122. package/package.json +28 -4
@@ -0,0 +1,710 @@
1
+ import { margin } from "../kind.js";
2
+ import { textWidth } from "../pen.js";
3
+ import { int, isObj, list, oneOf, only, text } from "../read.js";
4
+ import { colorNames, colors, ink, isColor, outline, soft, textOn, } from "../style.js";
5
+ import { checkThing, count, drawThing, sameThing, wordOf } from "../things.js";
6
+ /**
7
+ * A Venn or Euler diagram: one to three circles, each a set with a label and
8
+ * a colour of its own, arranged by a layout — overlapping, one inside
9
+ * another, apart, in a chain —, and maybe a box around them, the whole that
10
+ * the sets are taken from. A part of the picture is named by the sets it is
11
+ * inside, "in": [1, 2] for inside sets 1 and 2 and no other, "in": [] for the
12
+ * box outside every circle. A part holds a number, a "?", texts or things;
13
+ * the picture puts each in a place of its own, whole inside its part and
14
+ * clear of every line, so a part shows exactly what the scene says.
15
+ */
16
+ export const vennLayouts = ["overlap", "inside", "apart", "chain", "nested"];
17
+ const shapes = {
18
+ "1": { circles: [[0, 0, 1]], angles: [270], parts: [[1], []] },
19
+ "2 overlap": {
20
+ circles: [
21
+ [-0.56, 0, 1],
22
+ [0.56, 0, 1],
23
+ ],
24
+ angles: [235, 305],
25
+ parts: [[1], [1, 2], [2], []],
26
+ },
27
+ "2 inside": {
28
+ circles: [
29
+ [0, 0, 1.25],
30
+ [0.4, 0.12, 0.68],
31
+ ],
32
+ angles: [232, 270],
33
+ parts: [[1], [1, 2], []],
34
+ },
35
+ "2 apart": {
36
+ circles: [
37
+ [-1.14, 0, 1],
38
+ [1.14, 0, 1],
39
+ ],
40
+ angles: [270, 270],
41
+ parts: [[1], [2], []],
42
+ },
43
+ "3 overlap": {
44
+ circles: [
45
+ [-0.56, -0.323, 1],
46
+ [0.56, -0.323, 1],
47
+ [0, 0.647, 1],
48
+ ],
49
+ angles: [222, 318, 90],
50
+ parts: [[1], [1, 2], [2], [1, 3], [1, 2, 3], [2, 3], [3], []],
51
+ },
52
+ "3 chain": {
53
+ circles: [
54
+ [-1.3, 0, 1],
55
+ [0, 0, 1],
56
+ [1.3, 0, 1],
57
+ ],
58
+ angles: [235, 270, 305],
59
+ parts: [[1], [1, 2], [2], [2, 3], [3], []],
60
+ },
61
+ "3 nested": {
62
+ circles: [
63
+ [0, 0, 1.5],
64
+ [0.33, 0.08, 1.02],
65
+ [0.62, 0.14, 0.56],
66
+ ],
67
+ angles: [238, 255, 270],
68
+ parts: [[1], [1, 2], [1, 2, 3], []],
69
+ },
70
+ "3 apart": {
71
+ circles: [
72
+ [-2.25, 0, 1],
73
+ [0, 0, 1],
74
+ [2.25, 0, 1],
75
+ ],
76
+ angles: [270, 270, 270],
77
+ parts: [[1], [2], [3], []],
78
+ },
79
+ "3 inside": {
80
+ circles: [
81
+ [0, 0, 1.65],
82
+ [-0.78, 0.12, 0.7],
83
+ [0.78, 0.12, 0.7],
84
+ ],
85
+ angles: [270, 262, 278],
86
+ parts: [[1], [1, 2], [1, 3], []],
87
+ },
88
+ };
89
+ /** The layouts each number of sets may have. */
90
+ const layoutsOf = {
91
+ 1: [],
92
+ 2: ["overlap", "inside", "apart"],
93
+ 3: ["overlap", "chain", "nested", "apart", "inside"],
94
+ };
95
+ const defaultColors = ["blue", "yellow", "red"];
96
+ const mostItems = 12;
97
+ const labelMost = 12;
98
+ const boxMost = 16;
99
+ const textMost = 4;
100
+ const thingSize = 34;
101
+ const pillH = 30;
102
+ const labelSize = 16;
103
+ /** The least distance between what a part holds and any line. */
104
+ const gap = 4;
105
+ const boxPad = 20;
106
+ const widest = 640;
107
+ function shapeOf(v) {
108
+ const k = v.sets.length;
109
+ return shapes[k === 1 ? "1" : `${k} ${v.layout ?? "overlap"}`];
110
+ }
111
+ function maskOf(sets) {
112
+ return sets.reduce((m, s) => m | (1 << (s - 1)), 0);
113
+ }
114
+ function colorOf(v, i) {
115
+ return v.sets[i].color ?? defaultColors[i];
116
+ }
117
+ // --- geometry -------------------------------------------------------------
118
+ function overlaps(a, b, pad = 0) {
119
+ return a.x0 < b.x1 + pad && b.x0 < a.x1 + pad && a.y0 < b.y1 + pad && b.y0 < a.y1 + pad;
120
+ }
121
+ function around(p, hw, hh) {
122
+ return { x0: p.x - hw, y0: p.y - hh, x1: p.x + hw, y1: p.y + hh };
123
+ }
124
+ function union(rects) {
125
+ return {
126
+ x0: Math.min(...rects.map((r) => r.x0)),
127
+ y0: Math.min(...rects.map((r) => r.y0)),
128
+ x1: Math.max(...rects.map((r) => r.x1)),
129
+ y1: Math.max(...rects.map((r) => r.y1)),
130
+ };
131
+ }
132
+ function circleBox(c) {
133
+ return { x0: c.x - c.r, y0: c.y - c.r, x1: c.x + c.r, y1: c.y + c.r };
134
+ }
135
+ /** pillWidth is the width of a set's label: its thing, then its words. */
136
+ function pillWidth(s) {
137
+ const words = s.label ? textWidth(s.label, labelSize) : 0;
138
+ return 24 + (s.thing !== undefined ? 24 + (s.label ? 6 : 0) : 0) + words;
139
+ }
140
+ function layoutAt(v, R, extra) {
141
+ const shape = shapeOf(v);
142
+ const circles = shape.circles.map(([x, y, r]) => ({ x: x * R, y: y * R, r: r * R }));
143
+ const pills = v.sets.map((s, i) => {
144
+ if (s.label === undefined && s.thing === undefined)
145
+ return undefined;
146
+ const c = circles[i];
147
+ const a = (shape.angles[i] * Math.PI) / 180;
148
+ return around({ x: c.x + c.r * Math.cos(a), y: c.y + c.r * Math.sin(a) }, pillWidth(s) / 2, pillH / 2);
149
+ });
150
+ const drawn = union([...circles.map(circleBox), ...pills.filter((p) => p !== undefined)]);
151
+ if (v.box === undefined)
152
+ return { circles, pills, box: undefined, tab: undefined };
153
+ const label = typeof v.box === "string" ? v.box : undefined;
154
+ const box = {
155
+ x0: drawn.x0 - boxPad,
156
+ y0: drawn.y0 - boxPad - (label ? 12 : 0),
157
+ x1: drawn.x1 + boxPad,
158
+ y1: drawn.y1 + boxPad + extra,
159
+ };
160
+ const tab = label
161
+ ? {
162
+ x0: box.x0 + 14,
163
+ y0: box.y0 - 14,
164
+ x1: box.x0 + 14 + textWidth(label, labelSize) + 22,
165
+ y1: box.y0 + 14,
166
+ }
167
+ : undefined;
168
+ return { circles, pills, box, tab };
169
+ }
170
+ /** extentOf is everything a layout draws, before its contents. */
171
+ function extentOf(l) {
172
+ if (l.box)
173
+ return l.tab ? union([l.box, l.tab]) : l.box;
174
+ return union([...l.circles.map(circleBox), ...l.pills.filter((p) => p !== undefined)]);
175
+ }
176
+ /** fits tells whether a box lies whole in a part, gap away from every line and label. */
177
+ function fits(r, mask, l) {
178
+ for (let i = 0; i < l.circles.length; i++) {
179
+ const c = l.circles[i];
180
+ if (mask & (1 << i)) {
181
+ // Inside a circle: its farthest point from the centre is a corner.
182
+ for (const x of [r.x0, r.x1])
183
+ for (const y of [r.y0, r.y1])
184
+ if (Math.hypot(x - c.x, y - c.y) > c.r - gap)
185
+ return false;
186
+ }
187
+ else {
188
+ // Outside a circle: its nearest point to the centre.
189
+ const nx = Math.min(Math.max(c.x, r.x0), r.x1);
190
+ const ny = Math.min(Math.max(c.y, r.y0), r.y1);
191
+ if (Math.hypot(nx - c.x, ny - c.y) < c.r + gap)
192
+ return false;
193
+ }
194
+ }
195
+ if (mask === 0) {
196
+ const b = l.box;
197
+ if (!b)
198
+ return false;
199
+ if (r.x0 < b.x0 + gap || r.y0 < b.y0 + gap || r.x1 > b.x1 - gap || r.y1 > b.y1 - gap)
200
+ return false;
201
+ }
202
+ for (const o of [...l.pills, l.tab])
203
+ if (o && overlaps(r, o, gap))
204
+ return false;
205
+ return true;
206
+ }
207
+ /** areaOf is a rectangle that holds a part. */
208
+ function areaOf(mask, l) {
209
+ if (mask === 0)
210
+ return l.box;
211
+ const boxes = l.circles.filter((_, i) => mask & (1 << i)).map(circleBox);
212
+ return {
213
+ x0: Math.max(...boxes.map((b) => b.x0)),
214
+ y0: Math.max(...boxes.map((b) => b.y0)),
215
+ x1: Math.min(...boxes.map((b) => b.x1)),
216
+ y1: Math.min(...boxes.map((b) => b.y1)),
217
+ };
218
+ }
219
+ /** poleOf is the point of a part farthest from its lines, where one thing sits best. */
220
+ function poleOf(mask, l) {
221
+ const a = areaOf(mask, l);
222
+ let best = { x: (a.x0 + a.x1) / 2, y: (a.y0 + a.y1) / 2 };
223
+ let most = Number.NEGATIVE_INFINITY;
224
+ for (let y = a.y0; y <= a.y1; y += 3)
225
+ for (let x = a.x0; x <= a.x1; x += 3) {
226
+ let room = Number.POSITIVE_INFINITY;
227
+ let inside = true;
228
+ l.circles.forEach((c, i) => {
229
+ const d = Math.hypot(x - c.x, y - c.y);
230
+ const want = (mask & (1 << i)) !== 0;
231
+ if (want !== d < c.r)
232
+ inside = false;
233
+ room = Math.min(room, Math.abs(d - c.r));
234
+ });
235
+ for (const o of [...l.pills, l.tab])
236
+ if (o) {
237
+ const dx = Math.max(o.x0 - x, 0, x - o.x1);
238
+ const dy = Math.max(o.y0 - y, 0, y - o.y1);
239
+ room = Math.min(room, Math.hypot(dx, dy));
240
+ }
241
+ if (mask === 0 && l.box)
242
+ room = Math.min(room, x - l.box.x0, l.box.x1 - x, y - l.box.y0, l.box.y1 - y);
243
+ if (inside && room > most) {
244
+ most = room;
245
+ best = { x, y };
246
+ }
247
+ }
248
+ return best;
249
+ }
250
+ /** slotsOf lists the places of a lattice where a box of hw by hh fits whole in a part. */
251
+ function slotsOf(mask, l, hw, hh) {
252
+ const a = areaOf(mask, l);
253
+ const px = 2 * hw + 8;
254
+ const py = 2 * hh + 8;
255
+ let best = [];
256
+ for (const oy of [0, py / 2])
257
+ for (const ox of [0, px / 3, (2 * px) / 3]) {
258
+ const found = [];
259
+ for (let row = 0, y = a.y0 + hh + oy; y <= a.y1 - hh; row++, y += py)
260
+ for (let x = a.x0 + hw + ox + (row % 2 === 1 ? px / 2 : 0); x <= a.x1 - hw; x += px)
261
+ if (fits(around({ x, y }, hw, hh), mask, l))
262
+ found.push({ x, y });
263
+ if (found.length > best.length)
264
+ best = found;
265
+ }
266
+ return best;
267
+ }
268
+ /** sizeOf is the half width and half height of the box each item of a part takes. */
269
+ function sizeOf(region) {
270
+ if (region.ask)
271
+ return { hw: 19, hh: 19 };
272
+ if (region.count !== undefined)
273
+ return { hw: textWidth(String(region.count), 26) / 2 + 3, hh: 14 };
274
+ if (region.texts) {
275
+ const asks = region.texts.some((t) => typeof t !== "string");
276
+ const widest_ = Math.max(...region.texts.map((t) => (typeof t === "string" ? textWidth(t, 20) : 30)));
277
+ return { hw: widest_ / 2 + 4, hh: asks ? 16 : 12 };
278
+ }
279
+ return { hw: thingSize / 2, hh: thingSize / 2 };
280
+ }
281
+ function itemsOf(region) {
282
+ if (region.texts)
283
+ return region.texts.length;
284
+ if (region.things)
285
+ return region.things.length;
286
+ return region.count !== undefined || region.ask ? 1 : 0;
287
+ }
288
+ /**
289
+ * placeIn finds a place for each item of a part: a single item at the
290
+ * part's pole when it fits there; else the places of a lattice nearest the
291
+ * pole (the box's lower right corner outside every circle), the group then
292
+ * moved as far toward the pole as it still fits.
293
+ */
294
+ function placeIn(region, l) {
295
+ const mask = maskOf(region.in);
296
+ const k = itemsOf(region);
297
+ const { hw, hh } = sizeOf(region);
298
+ if (k === 0)
299
+ return { at: [], room: 0 };
300
+ const pole = mask === 0 ? { x: l.box.x1, y: l.box.y1 } : poleOf(mask, l);
301
+ if (k === 1 && mask !== 0 && fits(around(pole, hw, hh), mask, l))
302
+ return { at: [pole], room: 1 };
303
+ const slots = slotsOf(mask, l, hw, hh);
304
+ if (slots.length < k)
305
+ return { at: [], room: slots.length };
306
+ const near = [...slots]
307
+ .sort((a, b) => Math.hypot(a.x - pole.x, a.y - pole.y) - Math.hypot(b.x - pole.x, b.y - pole.y) ||
308
+ a.y - b.y ||
309
+ a.x - b.x)
310
+ .slice(0, k)
311
+ .sort((a, b) => a.y - b.y || a.x - b.x);
312
+ if (mask === 0)
313
+ return { at: near, room: slots.length };
314
+ const cx = near.reduce((s, p) => s + p.x, 0) / k;
315
+ const cy = near.reduce((s, p) => s + p.y, 0) / k;
316
+ for (const t of [1, 0.75, 0.5, 0.25]) {
317
+ const moved = near.map((p) => ({ x: p.x + (pole.x - cx) * t, y: p.y + (pole.y - cy) * t }));
318
+ if (moved.every((p) => fits(around(p, hw, hh), mask, l)))
319
+ return { at: moved, room: slots.length };
320
+ }
321
+ return { at: near, room: slots.length };
322
+ }
323
+ /**
324
+ * bandOf lays the things or texts outside every circle out in rows along
325
+ * the bottom of the box, below every circle and label, as even as can be.
326
+ */
327
+ function bandOf(region, box, top) {
328
+ const k = itemsOf(region);
329
+ const { hw, hh } = sizeOf(region);
330
+ const pitch = 2 * hw + 12;
331
+ const perRow = Math.max(1, Math.floor((box.x1 - box.x0 - 24) / pitch));
332
+ const rows = Math.ceil(k / perRow);
333
+ const rowH = 2 * hh + 10;
334
+ const at = [];
335
+ const middle = (box.x0 + box.x1) / 2;
336
+ for (let r = 0; r < rows; r++) {
337
+ const m = Math.floor(k / rows) + (r < k % rows ? 1 : 0);
338
+ for (let i = 0; i < m; i++)
339
+ at.push({ x: middle + (i - (m - 1) / 2) * pitch, y: top + (r + 0.5) * rowH });
340
+ }
341
+ return { at, height: rows * rowH };
342
+ }
343
+ function planAt(v, R) {
344
+ let l = layoutAt(v, R, 0);
345
+ const regions = v.regions ?? [];
346
+ const at = [];
347
+ const short = [];
348
+ const out = regions.findIndex((r) => r.in.length === 0 && itemsOf(r) > 0);
349
+ let band;
350
+ if (out >= 0 && l.box) {
351
+ const region = regions[out];
352
+ // One number or "?" stands in the box's lower right corner when it has room there.
353
+ const corner = itemsOf(region) === 1 ? placeIn(region, l).at : [];
354
+ if (corner.length === 1)
355
+ band = corner;
356
+ else {
357
+ const top = l.box.y1 - boxPad + 8;
358
+ const laid = bandOf(region, l.box, top);
359
+ l = layoutAt(v, R, laid.height + 18 - boxPad);
360
+ band = laid.at;
361
+ }
362
+ }
363
+ regions.forEach((region, i) => {
364
+ if (i === out && band) {
365
+ at.push(band);
366
+ return;
367
+ }
368
+ const placed = placeIn(region, l);
369
+ if (placed.at.length < itemsOf(region))
370
+ short.push({ region: i, room: placed.room });
371
+ at.push(placed.at);
372
+ });
373
+ return { ...l, R, at, short };
374
+ }
375
+ /** touching tells whether two labels of circles touch. */
376
+ function touching(l) {
377
+ const pills = l.pills.filter((p) => p !== undefined);
378
+ return pills.some((a, i) => pills.slice(i + 1).some((b) => overlaps(a, b, 4)));
379
+ }
380
+ /** largest is the largest radius at which the picture keeps within the widest. */
381
+ function largest(v) {
382
+ for (let R = 150; R > 40; R -= 5) {
383
+ const e = extentOf(layoutAt(v, R, 0));
384
+ if (e.x1 - e.x0 + 2 * margin <= widest)
385
+ return R;
386
+ }
387
+ return 40;
388
+ }
389
+ /**
390
+ * plan lays a diagram out at the smallest radius, from a pleasant one up to
391
+ * the largest that fits, at which every part holds what it should and no
392
+ * two labels touch.
393
+ */
394
+ function plan(v) {
395
+ const most = largest(v);
396
+ let last;
397
+ for (let R = Math.min(95, most); R <= most; R += 5) {
398
+ last = planAt(v, R);
399
+ if (last.short.length === 0 && !touching(last))
400
+ return last;
401
+ }
402
+ return last ?? planAt(v, most);
403
+ }
404
+ // --- checking -------------------------------------------------------------
405
+ function checkRegion(r, path, sets, parts, seen, problems) {
406
+ if (!isObj(r)) {
407
+ problems.push(`${path}: must be a part: "in" and one of count, texts, things, ask`);
408
+ return;
409
+ }
410
+ only(r, ["in", "count", "texts", "things", "ask"], path, problems);
411
+ const before = problems.length;
412
+ const inside = list(r.in, `${path}.in`, problems, 0, sets);
413
+ inside.forEach((s, j) => {
414
+ int(s, `${path}.in[${j}]`, problems, 1, sets);
415
+ });
416
+ if (problems.length === before) {
417
+ const sorted = [...inside].sort((a, b) => a - b);
418
+ if (new Set(sorted).size !== sorted.length)
419
+ problems.push(`${path}.in: names a set twice`);
420
+ else {
421
+ const mask = maskOf(sorted);
422
+ if (!parts.some((p) => maskOf(p) === mask))
423
+ problems.push(`${path}.in: the picture has no part inside ${sorted.length === 0 ? "no circle" : `exactly the sets ${sorted.join(" and ")}`}; its parts are ${parts.map((p) => `[${p.join(", ")}]`).join(", ")}`);
424
+ else if (seen.includes(mask))
425
+ problems.push(`${path}.in: names the same part as an earlier one`);
426
+ seen.push(mask);
427
+ }
428
+ }
429
+ const contents = ["count", "texts", "things", "ask"].filter((m) => r[m] !== undefined);
430
+ if (contents.length !== 1)
431
+ problems.push(`${path}: holds exactly one of count, texts, things and ask${contents.length > 1 ? `, not ${contents.join(" and ")}` : ""}`);
432
+ if (r.count !== undefined)
433
+ int(r.count, `${path}.count`, problems, 0, 9999);
434
+ if (r.ask !== undefined && r.ask !== true)
435
+ problems.push(`${path}.ask: must be true`);
436
+ if (r.texts !== undefined)
437
+ list(r.texts, `${path}.texts`, problems, 1, mostItems).forEach((t, j) => {
438
+ if (isObj(t)) {
439
+ if (t.ask !== true || Object.keys(t).length !== 1)
440
+ problems.push(`${path}.texts[${j}]: must be a text or {"ask": true}`);
441
+ return;
442
+ }
443
+ text(t, `${path}.texts[${j}]`, problems, textMost);
444
+ if (t === "?")
445
+ problems.push(`${path}.texts[${j}]: write {"ask": true} for the place the question asks`);
446
+ });
447
+ if (r.things !== undefined)
448
+ list(r.things, `${path}.things`, problems, 1, mostItems).forEach((t, j) => {
449
+ checkThing(t, `${path}.things[${j}]`, problems);
450
+ if (isObj(t) && t.empty === true)
451
+ problems.push(`${path}.things[${j}]: an empty place is not drawn in a diagram; leave it out`);
452
+ });
453
+ }
454
+ // --- words ------------------------------------------------------------------
455
+ function an(words) {
456
+ return `${/^[aeiou]/.test(words) ? "an" : "a"} ${words}`;
457
+ }
458
+ function nameOf(v, i) {
459
+ const s = v.sets[i];
460
+ return s.label ? `"${s.label}"` : `the ${colors[colorOf(v, i)].word} circle`;
461
+ }
462
+ function circleOf(v, i) {
463
+ const s = v.sets[i];
464
+ const marked = s.thing !== undefined ? ` marked with ${an(wordOf(s.thing))}` : "";
465
+ return `${an(colors[colorOf(v, i)].word)} circle${s.label ? ` "${s.label}"` : ""}${marked}`;
466
+ }
467
+ function joinAnd(words) {
468
+ if (words.length <= 1)
469
+ return words.join("");
470
+ return `${words.slice(0, -1).join(", ")} and ${words[words.length - 1]}`;
471
+ }
472
+ function sayCircles(v) {
473
+ const k = v.sets.length;
474
+ const c = (i) => circleOf(v, i);
475
+ if (k === 1)
476
+ return `${c(0)}`;
477
+ const layout = v.layout ?? "overlap";
478
+ if (k === 2) {
479
+ if (layout === "inside")
480
+ return `${c(0)} and, inside it, ${c(1)}`;
481
+ if (layout === "apart")
482
+ return `${c(0)} and ${c(1)}, apart from each other`;
483
+ return `${c(0)} and ${c(1)}, overlapping`;
484
+ }
485
+ if (layout === "chain")
486
+ return `${c(0)}, ${c(1)} and ${c(2)} in a row; the middle one overlaps each of the others, and the first and the last do not meet`;
487
+ if (layout === "nested")
488
+ return `${c(0)}; inside it ${c(1)}; and inside that ${c(2)}`;
489
+ if (layout === "apart")
490
+ return `${c(0)}, ${c(1)} and ${c(2)}, apart from each other`;
491
+ if (layout === "inside")
492
+ return `${c(0)} and, inside it, ${c(1)} and ${c(2)}, apart from each other`;
493
+ return `${c(0)}, ${c(1)} and ${c(2)}, overlapping so that each two share a part and all three share the middle`;
494
+ }
495
+ function sayPart(v, sets) {
496
+ const k = v.sets.length;
497
+ const sorted = [...sets].sort((a, b) => a - b);
498
+ if (sorted.length === 0)
499
+ return k === 1 ? "Outside the circle, in the box" : "Outside every circle, in the box";
500
+ const ins = sorted.map((s) => nameOf(v, s - 1));
501
+ const outs = v.sets.map((_, i) => i + 1).filter((s) => !sorted.includes(s));
502
+ if (outs.length === 0)
503
+ return k === 1 ? `In ${ins[0]}` : k === 2 ? `In both ${joinAnd(ins)}` : "In all three circles";
504
+ return `In ${joinAnd(ins)} but outside ${joinAnd(outs.map((s) => nameOf(v, s - 1)))}`;
505
+ }
506
+ function sayItems(region) {
507
+ if (region.ask)
508
+ return "a question mark";
509
+ if (region.count !== undefined)
510
+ return `the number ${region.count}`;
511
+ if (region.texts)
512
+ return joinAnd(region.texts.map((t) => (typeof t === "string" ? t : "a question mark")));
513
+ const groups = [];
514
+ for (const thing of region.things ?? []) {
515
+ const seen = groups.find((g) => sameThing(g.thing, thing));
516
+ if (seen)
517
+ seen.count++;
518
+ else
519
+ groups.push({ thing, count: 1 });
520
+ }
521
+ return joinAnd(groups.map((g) => count(g.thing, g.count)));
522
+ }
523
+ export const venn = {
524
+ kind: "venn",
525
+ members: ["kind", "sets", "layout", "regions", "box"],
526
+ check(scene, problems) {
527
+ only(scene, this.members, "scene", problems);
528
+ const before = problems.length;
529
+ const sets = list(scene.sets, "sets", problems, 1, 3);
530
+ const k = sets.length;
531
+ const colours = [];
532
+ sets.forEach((s, i) => {
533
+ const path = `sets[${i}]`;
534
+ if (!isObj(s)) {
535
+ problems.push(`${path}: must be a set: a label, a thing, a colour`);
536
+ return;
537
+ }
538
+ only(s, ["label", "thing", "color"], path, problems);
539
+ if (s.label !== undefined)
540
+ text(s.label, `${path}.label`, problems, labelMost);
541
+ if (s.thing !== undefined) {
542
+ checkThing(s.thing, `${path}.thing`, problems);
543
+ if (isObj(s.thing) && (s.thing.ask === true || s.thing.empty === true))
544
+ problems.push(`${path}.thing: must be an object or a drawn thing`);
545
+ }
546
+ if (s.color !== undefined && !isColor(s.color))
547
+ problems.push(`${path}.color: must be a colour: ${colorNames.join(", ")}`);
548
+ const colour = s.color ?? defaultColors[i];
549
+ if (colours.includes(colour))
550
+ problems.push(`${path}.color: each circle has a colour of its own; ${String(colour)} is taken`);
551
+ colours.push(colour);
552
+ });
553
+ if (scene.layout !== undefined && k >= 1) {
554
+ if (k === 1)
555
+ problems.push("layout: a single circle has no layout; leave it out");
556
+ else {
557
+ const allowed = layoutsOf[k] ?? [];
558
+ const layout = oneOf(scene.layout, vennLayouts, "layout", problems);
559
+ if (!allowed.includes(layout) && problems.length === before)
560
+ problems.push(`layout: with ${k} sets it must be one of ${allowed.join(", ")}`);
561
+ }
562
+ }
563
+ if (scene.box !== undefined && scene.box !== true)
564
+ text(scene.box, "box", problems, boxMost);
565
+ if (problems.length > before || k === 0)
566
+ return;
567
+ const v = scene;
568
+ const parts = shapeOf(v).parts;
569
+ const seen = [];
570
+ if (scene.regions !== undefined)
571
+ list(scene.regions, "regions", problems, 1, parts.length).forEach((r, i) => {
572
+ checkRegion(r, `regions[${i}]`, k, parts, seen, problems);
573
+ });
574
+ if (problems.length > before)
575
+ return;
576
+ (v.regions ?? []).forEach((r, i) => {
577
+ if (r.in.length === 0 && itemsOf(r) > 0 && v.box === undefined)
578
+ problems.push(`regions[${i}]: what stands outside every circle needs the box: give box`);
579
+ });
580
+ if (problems.length > before)
581
+ return;
582
+ const p = plan(v);
583
+ for (const { region, room } of p.short) {
584
+ const r = v.regions[region];
585
+ const what = r.texts ? "texts" : r.things ? "things" : r.ask ? "ask" : "count";
586
+ problems.push(`regions[${region}].${what}: ${itemsOf(r)} do not fit in that part; it holds at most ${room}: give fewer, or shorter texts`);
587
+ }
588
+ if (touching(p))
589
+ problems.push("sets: the labels of the circles touch one another; shorten them");
590
+ },
591
+ draw(scene, pen) {
592
+ const v = scene;
593
+ const p = plan(v);
594
+ const sub = pen.sub();
595
+ if (p.box)
596
+ sub.el("rect", {
597
+ x: p.box.x0,
598
+ y: p.box.y0,
599
+ width: p.box.x1 - p.box.x0,
600
+ height: p.box.y1 - p.box.y0,
601
+ rx: 16,
602
+ fill: "#ffffff",
603
+ stroke: ink,
604
+ "stroke-width": outline,
605
+ class: "box",
606
+ });
607
+ p.circles.forEach((c, i) => {
608
+ sub.el("circle", {
609
+ cx: c.x,
610
+ cy: c.y,
611
+ r: c.r,
612
+ fill: colors[colorOf(v, i)].fill,
613
+ "fill-opacity": 0.22,
614
+ });
615
+ });
616
+ p.circles.forEach((c) => {
617
+ sub.el("circle", {
618
+ cx: c.x,
619
+ cy: c.y,
620
+ r: c.r,
621
+ fill: "none",
622
+ stroke: ink,
623
+ "stroke-width": outline,
624
+ class: "set",
625
+ });
626
+ });
627
+ (v.regions ?? []).forEach((r, i) => {
628
+ const at = p.at[i];
629
+ if (r.ask)
630
+ drawThing(sub, { ask: true }, at[0].x, at[0].y, 42);
631
+ else if (r.count !== undefined)
632
+ sub.text(at[0].x, at[0].y, String(r.count), { size: 26 });
633
+ else if (r.texts)
634
+ r.texts.forEach((t, j) => {
635
+ if (typeof t === "string")
636
+ sub.text(at[j].x, at[j].y, t, { size: 20 });
637
+ else
638
+ drawThing(sub, { ask: true }, at[j].x, at[j].y, 36);
639
+ });
640
+ else
641
+ r.things?.forEach((t, j) => {
642
+ drawThing(sub, t, at[j].x, at[j].y, thingSize);
643
+ });
644
+ });
645
+ v.sets.forEach((s, i) => {
646
+ const pill = p.pills[i];
647
+ if (!pill)
648
+ return;
649
+ const colour = colorOf(v, i);
650
+ sub.el("rect", {
651
+ x: pill.x0,
652
+ y: pill.y0,
653
+ width: pill.x1 - pill.x0,
654
+ height: pillH,
655
+ rx: pillH / 2,
656
+ fill: colors[colour].fill,
657
+ stroke: ink,
658
+ "stroke-width": 2,
659
+ class: "label",
660
+ });
661
+ let x = pill.x0 + 12;
662
+ const y = (pill.y0 + pill.y1) / 2;
663
+ if (s.thing !== undefined) {
664
+ drawThing(sub, s.thing, x + 12, y, 24);
665
+ x += 24 + 6;
666
+ }
667
+ if (s.label)
668
+ sub.text(x, y, s.label, { size: labelSize, anchor: "start", fill: textOn(colour) });
669
+ });
670
+ if (p.tab && typeof v.box === "string") {
671
+ sub.el("rect", {
672
+ x: p.tab.x0,
673
+ y: p.tab.y0,
674
+ width: p.tab.x1 - p.tab.x0,
675
+ height: p.tab.y1 - p.tab.y0,
676
+ rx: 8,
677
+ fill: soft,
678
+ stroke: ink,
679
+ "stroke-width": 2,
680
+ });
681
+ sub.text((p.tab.x0 + p.tab.x1) / 2, (p.tab.y0 + p.tab.y1) / 2, v.box, { size: labelSize });
682
+ }
683
+ const all = [extentOf(p)];
684
+ p.at.forEach((at, i) => {
685
+ const { hw, hh } = sizeOf(v.regions[i]);
686
+ for (const q of at)
687
+ all.push(around(q, hw, hh));
688
+ });
689
+ const e = union(all);
690
+ pen.place(sub, margin - e.x0, margin - e.y0);
691
+ return { width: e.x1 - e.x0 + 2 * margin, height: e.y1 - e.y0 + 2 * margin };
692
+ },
693
+ describe(scene) {
694
+ const v = scene;
695
+ const k = v.sets.length;
696
+ const box = v.box === undefined
697
+ ? ""
698
+ : typeof v.box === "string"
699
+ ? ` in a box labelled "${v.box}"`
700
+ : " in a box";
701
+ const head = `A diagram of ${k === 1 ? "a circle" : `${k} circles`}${box}: ${sayCircles(v)}.`;
702
+ const regions = v.regions ?? [];
703
+ const said = regions.map((r) => `${sayPart(v, r.in)}: ${sayItems(r)}.`);
704
+ const parts = shapeOf(v).parts.filter((part) => part.length > 0 || v.box !== undefined);
705
+ const filled = regions.filter((r) => itemsOf(r) > 0).map((r) => maskOf(r.in));
706
+ const empty = parts.some((part) => !filled.includes(maskOf(part)));
707
+ const tail = regions.length === 0 ? " Every part is empty." : empty ? " Every other part is empty." : "";
708
+ return `${head}${said.length > 0 ? ` ${said.join(" ")}` : ""}${tail}`;
709
+ },
710
+ };