@johnmorrisdotca/wakusei-planets 0.23.0 → 0.25.0

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 (45) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +41 -14
  3. package/dist/blackbody.d.ts +2 -0
  4. package/dist/blackbody.js +10 -0
  5. package/dist/element.d.ts +12 -0
  6. package/dist/element.js +160 -23
  7. package/dist/embed.d.ts +5 -0
  8. package/dist/embed.js +32 -8
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +2 -0
  11. package/dist/kids/data.d.ts +109 -0
  12. package/dist/kids/data.js +164 -0
  13. package/dist/kids/index.d.ts +4 -0
  14. package/dist/kids/index.js +5 -0
  15. package/dist/kids/land.d.ts +3 -0
  16. package/dist/kids/land.js +29 -0
  17. package/dist/kids/picture.d.ts +39 -0
  18. package/dist/kids/picture.js +255 -0
  19. package/dist/kids/sheet.d.ts +60 -0
  20. package/dist/kids/sheet.js +79 -0
  21. package/dist/kids/svg.d.ts +46 -0
  22. package/dist/kids/svg.js +193 -0
  23. package/dist/line.d.ts +9 -1
  24. package/dist/line.js +3 -4
  25. package/dist/portrait/element.d.ts +9 -0
  26. package/dist/portrait/element.js +39 -5
  27. package/dist/scene/body.d.ts +8 -1
  28. package/dist/scene/body.js +33 -9
  29. package/dist/scene/glsl.d.ts +7 -2
  30. package/dist/scene/glsl.js +49 -3
  31. package/dist/scene/look.d.ts +43 -0
  32. package/dist/scene/look.js +39 -1
  33. package/dist/scene/store.d.ts +3 -0
  34. package/dist/scene/store.js +3 -1
  35. package/dist/scene/textures.d.ts +2 -2
  36. package/dist/space/element.d.ts +6 -0
  37. package/dist/space/element.js +18 -0
  38. package/dist/star-line.d.ts +20 -0
  39. package/dist/star-line.js +59 -0
  40. package/dist/star.d.ts +193 -0
  41. package/dist/star.js +261 -0
  42. package/dist/stars.js +3 -5
  43. package/dist/version.d.ts +1 -1
  44. package/dist/version.js +1 -1
  45. package/package.json +9 -2
@@ -0,0 +1,255 @@
1
+ // The pictures of the colouring sheets: a body as thick black outlines on white, drawn in millimetres from the package's own numbers (facts, tilt, rings). Big shapes only: a feature too small
2
+ // to colour is made bigger or left out, and two never overlap. Pure: an SVG string, no DOM.
3
+ import { BODIES } from "../facts.js";
4
+ import { cross, RAD, DEG } from "../vec.js";
5
+ import { facing, portrait, silhouette, surfacePoint } from "../pose.js";
6
+ import { OWN_FEATURES } from "./land.js";
7
+ /** The thickness of the outline of a body and of every line inside it, in millimetres. */
8
+ export const OUTLINE_MM = 3;
9
+ export const LINE_MM = 2.5;
10
+ /** The smallest radius of a shape to colour, in millimetres, and the least between two lines. */
11
+ const MIN_SHAPE_MM = 8;
12
+ const MIN_GAP_MM = 12;
13
+ const INK = "#000";
14
+ const n = (v) => (Math.round(v * 100) / 100).toString();
15
+ const polyline = (pts, close = false) => `M${pts.map((p) => `${n(p[0])} ${n(p[1])}`).join("L")}${close ? "Z" : ""}`;
16
+ const stroke = (d, width) => `<path d="${d}" fill="none" stroke="${INK}" stroke-width="${width}" stroke-linecap="round" stroke-linejoin="round"/>`;
17
+ /** The edges of the rings a child colours, in kilometres from the planet's centre: the main rings of Saturn and the outer and inner rings of Uranus. */
18
+ const RING_EDGES = { saturn: [74658, 136775], uranus: [41800, 51100] };
19
+ /** How far a body is turned to face the viewer, degrees east, where the body's own default is not the best side for a sheet. */
20
+ const PITCH = { saturn: 20, uranus: 35 };
21
+ const TILT = { saturn: 0 };
22
+ const SPIN = { earth: 100 };
23
+ const screen = (frame, p) => [frame.cx + p[0] * frame.r, frame.cy - p[1] * frame.r];
24
+ /** The pose a sheet draws: the body's own tilt, looked at a little from above, full face. */
25
+ export function sheetPose(id) {
26
+ return portrait(id, { pitch: PITCH[id] ?? 18, tilt: TILT[id], phase: 0, spin: SPIN[id] });
27
+ }
28
+ const axesOf = (id) => {
29
+ const km = BODIES[id].axesKm;
30
+ return km === undefined ? undefined : [km[0] / BODIES[id].radiusKm, km[1] / BODIES[id].radiusKm, km[2] / BODIES[id].radiusKm];
31
+ };
32
+ /** The ring's edge as points of the plane of the rings, unit radius ρ, at angle t. */
33
+ const ringPoint = (pose, rho, t) => {
34
+ const e1 = pose.meridian;
35
+ const e2 = cross(pose.pole, pose.meridian);
36
+ return [rho * (Math.cos(t) * e1[0] + Math.sin(t) * e2[0]), rho * (Math.cos(t) * e1[1] + Math.sin(t) * e2[1]), rho * (Math.cos(t) * e1[2] + Math.sin(t) * e2[2])];
37
+ };
38
+ /** How far a body reaches from its centre, in units of its radius: its outline, its rings and, for the Sun, its rays. */
39
+ export function reach(id, pose = sheetPose(id)) {
40
+ const facts = BODIES[id];
41
+ const sil = silhouette(pose, facts.flattening, axesOf(id));
42
+ const a = sil.angle * RAD;
43
+ let x = Math.hypot(sil.a * Math.cos(a), sil.b * Math.sin(a));
44
+ let y = Math.hypot(sil.a * Math.sin(a), sil.b * Math.cos(a));
45
+ const edges = RING_EDGES[id];
46
+ if (edges !== undefined) {
47
+ for (let k = 0; k < 72; k += 1) {
48
+ const p = ringPoint(pose, edges[1] / facts.radiusKm, (k / 72) * 2 * Math.PI);
49
+ x = Math.max(x, Math.abs(p[0]));
50
+ y = Math.max(y, Math.abs(p[1]));
51
+ }
52
+ }
53
+ if (id === "sun") {
54
+ x = Math.max(x, 1.3);
55
+ y = Math.max(y, 1.3);
56
+ }
57
+ return { x, y };
58
+ }
59
+ /** The longer side of the box round some points. */
60
+ const size = (pts) => {
61
+ const xs = pts.map((p) => p[0]);
62
+ const ys = pts.map((p) => p[1]);
63
+ return Math.max(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));
64
+ };
65
+ /** A circle or oval of angular radii (degrees) round a longitude and latitude, as points on the body. */
66
+ function around(lon, lat, rx, ry) {
67
+ const out = [];
68
+ for (let k = 0; k < 32; k += 1) {
69
+ const t = (k / 32) * 2 * Math.PI;
70
+ const dlat = ry * Math.sin(t);
71
+ out.push([lon + (rx * Math.cos(t)) / Math.max(0.2, Math.cos((lat + dlat) * RAD)), Math.max(-89.9, Math.min(89.9, lat + dlat))]);
72
+ }
73
+ return out;
74
+ }
75
+ const between = (a, b) => {
76
+ const cosine = Math.sin(a[1] * RAD) * Math.sin(b[1] * RAD) + Math.cos(a[1] * RAD) * Math.cos(b[1] * RAD) * Math.cos((a[0] - b[0]) * RAD);
77
+ return Math.acos(Math.max(-1, Math.min(1, cosine))) * DEG;
78
+ };
79
+ /** Break a line of samples into the runs that face the viewer. */
80
+ function runs(samples, visible) {
81
+ const out = [];
82
+ let current = [];
83
+ for (const sample of samples) {
84
+ if (visible(sample))
85
+ current.push(sample);
86
+ else if (current.length > 0) {
87
+ out.push(current);
88
+ current = [];
89
+ }
90
+ }
91
+ if (current.length > 0)
92
+ out.push(current);
93
+ return out;
94
+ }
95
+ /** The lines inside the body: bands, big round shapes, and lines (cracks, lands) that are long enough to colour between. */
96
+ function inside(id, pose, frame, line) {
97
+ const facts = BODIES[id];
98
+ const f = facts.flattening;
99
+ const axes = axesOf(id);
100
+ const spin = SPIN[id] ?? facts.showLon ?? 0;
101
+ const out = [];
102
+ if (frame.r < 18)
103
+ return out;
104
+ const face = (lon, lat) => facing(pose, lon, lat, f, axes);
105
+ const at = (lon, lat) => screen(frame, surfacePoint(pose, lon, lat, f, axes));
106
+ const features = OWN_FEATURES[id] ?? facts.features ?? [];
107
+ // round shapes and ovals: made no smaller than MIN_SHAPE_MM across the radius, kept whole, never overlapping
108
+ const minDeg = (MIN_SHAPE_MM / frame.r) * DEG;
109
+ const shapes = features
110
+ .map((one) => (one.kind === "circle" ? { lon: one.lon, lat: one.lat, rx: one.radius, ry: one.radius } : one.kind === "oval" ? { lon: one.lon, lat: one.lat, rx: one.rx, ry: one.ry } : undefined))
111
+ .filter((one) => one !== undefined)
112
+ .sort((a, b) => b.rx * b.ry - a.rx * a.ry);
113
+ const placed = [];
114
+ const heights = [];
115
+ for (const shape of shapes) {
116
+ if (placed.length >= 6)
117
+ break;
118
+ const rx = Math.min(45, Math.max(shape.rx, minDeg));
119
+ const ry = Math.min(45, Math.max(shape.ry, minDeg));
120
+ const size = Math.max(rx, ry);
121
+ const ring = around(shape.lon, shape.lat, rx, ry);
122
+ if (!ring.every(([lon, lat]) => face(lon, lat) > 0.35))
123
+ continue;
124
+ if (placed.some((p) => between([p.lon, p.lat], [shape.lon, shape.lat]) < (p.size + size) * 1.15))
125
+ continue;
126
+ placed.push({ lon: shape.lon, lat: shape.lat, size });
127
+ heights.push([shape.lat, ry]);
128
+ out.push(stroke(polyline(ring.map(([lon, lat]) => at(lon, lat)), true), line));
129
+ }
130
+ // bands of latitude: each at least MIN_GAP_MM from the last, and not so near the edge that the strip beyond is too thin to colour
131
+ const kept = [];
132
+ const bands = features.filter((one) => one.kind === "band").sort((a, b) => Math.abs(a.lat) - Math.abs(b.lat));
133
+ for (const band of bands) {
134
+ if (kept.length >= 7 || face(spin, band.lat) < 0.5)
135
+ continue;
136
+ if (heights.some(([lat, ry]) => Math.abs(lat - band.lat) < ry + 2))
137
+ continue;
138
+ const here = at(spin, band.lat);
139
+ if (kept.some((p) => Math.hypot(p[0] - here[0], p[1] - here[1]) < MIN_GAP_MM))
140
+ continue;
141
+ const samples = [];
142
+ for (let lon = 0; lon <= 360; lon += 3)
143
+ samples.push([lon, band.lat]);
144
+ const parts = runs(samples, ([lon, lat]) => face(lon, lat) > 0.01).map((part) => part.map(([lon, lat]) => at(lon, lat)));
145
+ if (!parts.some((part) => size(part) >= 2 * MIN_SHAPE_MM))
146
+ continue;
147
+ kept.push(here);
148
+ for (const part of parts)
149
+ out.push(stroke(polyline(part), line));
150
+ }
151
+ // lines: whole (closed) or in the runs that face us, long enough to see
152
+ for (const one of features) {
153
+ if (one.kind !== "line")
154
+ continue;
155
+ const count = one.points.length;
156
+ const samples = [];
157
+ for (let k = 0; k < (one.close === true ? count : count - 1); k += 1) {
158
+ const a = one.points[k];
159
+ const b = one.points[(k + 1) % count];
160
+ const steps = Math.max(1, Math.ceil(Math.hypot(b[0] - a[0], b[1] - a[1]) / 2));
161
+ for (let s = 0; s < steps; s += 1)
162
+ samples.push([a[0] + ((b[0] - a[0]) * s) / steps, a[1] + ((b[1] - a[1]) * s) / steps]);
163
+ }
164
+ const last = one.points[one.close === true ? 0 : count - 1];
165
+ samples.push([last[0], last[1]]);
166
+ const parts = runs(samples, ([lon, lat]) => face(lon, lat) > 0.01);
167
+ const whole = one.close === true && parts.length === 1 && parts[0].length === samples.length;
168
+ for (const part of parts) {
169
+ if (part.length < 3)
170
+ continue;
171
+ const pts = part.map(([lon, lat]) => at(lon, lat));
172
+ if (size(pts) < 2 * MIN_SHAPE_MM)
173
+ continue;
174
+ out.push(stroke(polyline(pts, whole), line));
175
+ }
176
+ }
177
+ return out;
178
+ }
179
+ /** The rings as thick edges: the back parts first (the planet will cover them), and the front parts as a white band with its edges, to go over the planet. */
180
+ function ringParts(id, pose, frame, line) {
181
+ const edges = RING_EDGES[id];
182
+ if (edges === undefined)
183
+ return { back: "", front: "" };
184
+ const radius = BODIES[id].radiusKm;
185
+ const e1 = pose.meridian[2];
186
+ const e2 = cross(pose.pole, pose.meridian)[2];
187
+ const phi = Math.atan2(e2, e1);
188
+ const arc = (rho, from, to) => Array.from({ length: 61 }, (_, k) => screen(frame, ringPoint(pose, rho, from + ((to - from) * k) / 60)));
189
+ const front0 = phi - Math.PI / 2;
190
+ const back0 = phi + Math.PI / 2;
191
+ const back = [];
192
+ const outer = edges[1] / radius;
193
+ const inner = edges[0] / radius;
194
+ for (const rho of [inner, outer])
195
+ back.push(stroke(polyline(arc(rho, back0, back0 + Math.PI)), line));
196
+ const band = [...arc(outer, front0, front0 + Math.PI), ...arc(inner, front0 + Math.PI, front0).slice()];
197
+ const front = [`<path d="${polyline(band, true)}" fill="#fff"/>`, ...[inner, outer].map((rho) => stroke(polyline(arc(rho, front0, front0 + Math.PI)), line))];
198
+ return { back: back.join(""), front: front.join("") };
199
+ }
200
+ /** The Sun's rays: short thick strokes all round, long and short in turn. */
201
+ function rays(frame, line) {
202
+ const parts = [];
203
+ for (let k = 0; k < 16; k += 1) {
204
+ const a = (k / 16) * 2 * Math.PI;
205
+ const r1 = 1.1;
206
+ const r2 = k % 2 === 0 ? 1.3 : 1.2;
207
+ parts.push(`M${n(frame.cx + Math.cos(a) * r1 * frame.r)} ${n(frame.cy + Math.sin(a) * r1 * frame.r)}L${n(frame.cx + Math.cos(a) * r2 * frame.r)} ${n(frame.cy + Math.sin(a) * r2 * frame.r)}`);
208
+ }
209
+ return stroke(parts.join(""), line);
210
+ }
211
+ /**
212
+ * A body as a colouring picture: thick black outlines on white (the outline 3 mm, every line inside 2.5 mm), its big features, its rings, and the Sun's rays. The picture is drawn at its centre `(cx, cy)` with `r`
213
+ * millimetres for the body's radius. `outline` is the outline's thickness; the lines inside are 2.5 mm or, for a thinner outline, a little less.
214
+ * @param id - The body's name.
215
+ * @param cx - The centre's place, in millimetres.
216
+ * @param cy - The centre's place, in millimetres.
217
+ * @param r - The body's radius, in millimetres.
218
+ * @param outline - The outline's thickness in millimetres. Default 3.
219
+ * @returns The SVG markup of the body, to put inside an `<svg>` measured in millimetres.
220
+ *
221
+ * @example
222
+ * ```ts
223
+ * import { colouringArt } from "@johnmorrisdotca/wakusei-planets/sheets";
224
+ *
225
+ * console.log(colouringArt("mars", 50, 50, 40).startsWith("<g"));
226
+ * ```
227
+ */
228
+ export function colouringArt(id, cx, cy, r, outline = OUTLINE_MM) {
229
+ const facts = BODIES[id];
230
+ const pose = sheetPose(id);
231
+ const frame = { cx, cy, r };
232
+ const sil = silhouette(pose, facts.flattening, axesOf(id));
233
+ const disc = `<ellipse cx="${n(cx)}" cy="${n(cy)}" rx="${n(r * sil.a)}" ry="${n(r * sil.b)}" transform="rotate(${n(sil.angle)} ${n(cx)} ${n(cy)})"`;
234
+ const line = Math.min(LINE_MM, outline * 0.84);
235
+ const rings = ringParts(id, pose, frame, line);
236
+ const clip = `kids-${id}-clip`;
237
+ return [
238
+ `<g data-body="${id}">`,
239
+ rings.back,
240
+ `${disc} fill="#fff" stroke="${INK}" stroke-width="${outline}"/>`,
241
+ `<clipPath id="${clip}">${disc}/></clipPath>`,
242
+ `<g clip-path="url(#${clip})">${inside(id, pose, frame, line).join("")}</g>`,
243
+ id === "sun" ? rays(frame, line) : "",
244
+ rings.front,
245
+ `</g>`,
246
+ ].join("");
247
+ }
248
+ /** A body's picture made as large as fits a box `width` by `height` millimetres, in the middle of it. */
249
+ export function colouringPicture(id, width, height, top = 0) {
250
+ const pose = sheetPose(id);
251
+ const extent = reach(id, pose);
252
+ const pad = OUTLINE_MM;
253
+ const r = Math.min((width - 2 * pad) / (2 * extent.x), (height - 2 * pad) / (2 * extent.y));
254
+ return { markup: colouringArt(id, width / 2, top + height / 2, r), halfWidth: extent.x * r, halfHeight: extent.y * r };
255
+ }
@@ -0,0 +1,60 @@
1
+ import { type Layout, type PageName } from "@johnmorrisdotca/kazoku-ui/print";
2
+ import { type KidsSheet, type Lang } from "./data.ts";
3
+ /** Where the sheets are on the web: the demo's address, and the QR code on each sheet leads to its own. */
4
+ export declare const KIDS_ADDRESS = "https://johnmorrisdotca.github.io/wakusei-planets/kids.html";
5
+ /**
6
+ * What to build a sheet with: the paper, the language, the date and the address for the QR code.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { type KidsOptions } from "@johnmorrisdotca/wakusei-planets/sheets";
11
+ *
12
+ * const options: KidsOptions = { page: "letter", language: "ja" };
13
+ * console.log(options.page);
14
+ * ```
15
+ */
16
+ export interface KidsOptions {
17
+ /** `a4`, `letter`, `a3` or `tabloid`. Default `a4`. */
18
+ page?: PageName;
19
+ language?: Lang;
20
+ /** Written in the footer; a `Date` as `YYYY-MM-DD`. Default: today. */
21
+ date?: Date | string;
22
+ /** The address printed in the footer as a QR code. Default: this sheet's place in the demo. */
23
+ address?: string;
24
+ }
25
+ /**
26
+ * The layout of a sheet, to give kazoku-ui's `printCss`: its paper, its turn (the lineup lies on its side), large type for children and the language.
27
+ * @param id - A body with a sheet, or `lineup`.
28
+ * @param options - The paper and the language.
29
+ * @returns The layout.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * import { kidsLayout } from "@johnmorrisdotca/wakusei-planets/sheets";
34
+ *
35
+ * console.log(kidsLayout("lineup", { page: "letter" }));
36
+ * ```
37
+ */
38
+ export declare const kidsLayout: (id: KidsSheet, options?: KidsOptions) => Partial<Layout>;
39
+ /** A sheet's title: the body's name, or for the lineup its own. */
40
+ export declare const kidsTitle: (id: KidsSheet, lang: Lang) => string;
41
+ /**
42
+ * A printable colouring sheet: one `.kazoku-sheet` with one page holding the sheet's SVG, in kazoku-ui's print layout (add `printCss(kidsLayout(id, options))` to the page, and print with `printSheet`).
43
+ * @param id - A body with a sheet, or `lineup`.
44
+ * @param options - The paper, the language, the date and the address for the QR code.
45
+ * @returns The sheet's element.
46
+ *
47
+ * @example
48
+ * ```ts no-run
49
+ * import { printCss, printSheet } from "@johnmorrisdotca/kazoku-ui/print";
50
+ * import { kidsLayout, kidsSheet } from "@johnmorrisdotca/wakusei-planets/sheets";
51
+ *
52
+ * const style = document.createElement("style");
53
+ * style.textContent = printCss(kidsLayout("saturn", { page: "letter" }));
54
+ * document.head.append(style);
55
+ * const sheet = kidsSheet("saturn", { page: "letter" });
56
+ * document.body.append(sheet);
57
+ * printSheet(sheet);
58
+ * ```
59
+ */
60
+ export declare function kidsSheet(id: KidsSheet, options?: KidsOptions): HTMLElement;
@@ -0,0 +1,79 @@
1
+ // The printable page of a colouring sheet: kazoku-ui's print sheet (header with the brand, the package, the title and a Name box; footer with credits, version and a QR code back to the demo)
2
+ // around the sheet's one SVG. Needs a DOM; the picture itself (`kidsSvg`) does not.
3
+ import { buildSheet, printCss } from "@johnmorrisdotca/kazoku-ui/print";
4
+ import { VERSION } from "../version.js";
5
+ import { SAY, kidsName } from "./data.js";
6
+ import { kidsOrientation, kidsRoom, kidsSvg } from "./svg.js";
7
+ /** Where the sheets are on the web: the demo's address, and the QR code on each sheet leads to its own. */
8
+ export const KIDS_ADDRESS = "https://johnmorrisdotca.github.io/wakusei-planets/kids.html";
9
+ /**
10
+ * The layout of a sheet, to give kazoku-ui's `printCss`: its paper, its turn (the lineup lies on its side), large type for children and the language.
11
+ * @param id - A body with a sheet, or `lineup`.
12
+ * @param options - The paper and the language.
13
+ * @returns The layout.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { kidsLayout } from "@johnmorrisdotca/wakusei-planets/sheets";
18
+ *
19
+ * console.log(kidsLayout("lineup", { page: "letter" }));
20
+ * ```
21
+ */
22
+ export const kidsLayout = (id, options = {}) => ({ page: options.page ?? "a4", orientation: kidsOrientation(id), type: "kid", language: options.language ?? "en" });
23
+ /** A sheet's title: the body's name, or for the lineup its own. */
24
+ export const kidsTitle = (id, lang) => (id === "lineup" ? SAY[lang].lineup : kidsName(id, lang));
25
+ /**
26
+ * A printable colouring sheet: one `.kazoku-sheet` with one page holding the sheet's SVG, in kazoku-ui's print layout (add `printCss(kidsLayout(id, options))` to the page, and print with `printSheet`).
27
+ * @param id - A body with a sheet, or `lineup`.
28
+ * @param options - The paper, the language, the date and the address for the QR code.
29
+ * @returns The sheet's element.
30
+ *
31
+ * @example
32
+ * ```ts no-run
33
+ * import { printCss, printSheet } from "@johnmorrisdotca/kazoku-ui/print";
34
+ * import { kidsLayout, kidsSheet } from "@johnmorrisdotca/wakusei-planets/sheets";
35
+ *
36
+ * const style = document.createElement("style");
37
+ * style.textContent = printCss(kidsLayout("saturn", { page: "letter" }));
38
+ * document.head.append(style);
39
+ * const sheet = kidsSheet("saturn", { page: "letter" });
40
+ * document.body.append(sheet);
41
+ * printSheet(sheet);
42
+ * ```
43
+ */
44
+ export function kidsSheet(id, options = {}) {
45
+ const layout = kidsLayout(id, options);
46
+ const lang = options.language ?? "en";
47
+ const holder = document.createElement("div");
48
+ holder.style.cssText = "position:absolute;inset:0";
49
+ const sheet = buildSheet({
50
+ ...layout,
51
+ brand: SAY[lang].brand,
52
+ packageName: SAY[lang].pack,
53
+ title: kidsTitle(id, lang),
54
+ credits: SAY[lang].credits,
55
+ version: VERSION,
56
+ date: options.date ?? new Date(),
57
+ address: options.address ?? `${KIDS_ADDRESS}?sheet=${id}`,
58
+ pages: [holder],
59
+ });
60
+ holder.innerHTML = kidsSvg(id, { ...roomOf(sheet, layout, kidsRoom(layout.page, layout.orientation)), lang });
61
+ return sheet;
62
+ }
63
+ /** The room the page's body really has: the sheet is laid out out of sight for a moment, with the print rules, and measured, so the picture is drawn at the size it will print. */
64
+ function roomOf(sheet, layout, estimate) {
65
+ const style = document.createElement("style");
66
+ style.textContent = printCss(layout);
67
+ const host = document.createElement("div");
68
+ host.style.cssText = "position:fixed;left:-10000px;top:0;visibility:hidden";
69
+ host.append(sheet);
70
+ document.head.append(style);
71
+ document.body.append(host);
72
+ const body = sheet.querySelector(".kazoku-body")?.getBoundingClientRect();
73
+ host.remove();
74
+ style.remove();
75
+ if (body === undefined || body.height === 0)
76
+ return estimate;
77
+ const mm = 25.4 / 96;
78
+ return { widthMm: Math.floor(body.width * mm * 10) / 10, heightMm: Math.floor(body.height * mm * 10) / 10 };
79
+ }
@@ -0,0 +1,46 @@
1
+ import { type Orientation, type PageName } from "@johnmorrisdotca/kazoku-ui/print";
2
+ import { KIDS_BODIES, type KidsSheet, type Lang } from "./data.ts";
3
+ /** The lineup is wide, so it is printed on its side. */
4
+ export declare const kidsOrientation: (id: KidsSheet) => Orientation;
5
+ /**
6
+ * The room a sheet's picture has on a page, in millimetres: the page inside its margins, less the header and the footer.
7
+ * @param page - `a4`, `letter`, `a3` or `tabloid`.
8
+ * @param orientation - `portrait` or `landscape`.
9
+ * @returns The width and height.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { kidsRoom } from "@johnmorrisdotca/wakusei-planets/sheets";
14
+ *
15
+ * console.log(kidsRoom("a4", "portrait"));
16
+ * ```
17
+ */
18
+ export declare function kidsRoom(page: PageName, orientation?: Orientation): {
19
+ widthMm: number;
20
+ heightMm: number;
21
+ };
22
+ /** The width of a text in millimetres, estimated on the wide side so a font that is wider than the rounded ones (a fallback on a server) still fits: a full-width character is as wide as the type is tall, a Latin capital or a digit 0.82 of it, a small letter 0.7 (DejaVu Sans Bold, the usual fallback on a server, is that wide), a space or a stop 0.38. */
23
+ export declare function textWidth(text: string, sizeMm: number): number;
24
+ /** Break a sentence into lines no wider than `maxMm`: at spaces for English, after a full stop (or anywhere) for Japanese. */
25
+ export declare function wrap(text: string, maxMm: number, sizeMm: number): string[];
26
+ /**
27
+ * One sheet as an SVG string measured in millimetres: the picture of the body, the colours to colour it with and three facts, in English or Japanese; or the lineup of all the planets at one scale. `widthMm` and
28
+ * `heightMm` are the room it is drawn for (`kidsRoom`), and the viewBox is that room, so a millimetre is a millimetre on paper.
29
+ * @param id - A body with a sheet, or `lineup`.
30
+ * @param options - The room, and the language.
31
+ * @returns The `<svg>` markup.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * import { kidsRoom, kidsSvg } from "@johnmorrisdotca/wakusei-planets/sheets";
36
+ *
37
+ * const room = kidsRoom("a4");
38
+ * console.log(kidsSvg("saturn", { ...room, lang: "en" }).includes("Colour me!"));
39
+ * ```
40
+ */
41
+ export declare function kidsSvg(id: KidsSheet, options: {
42
+ widthMm: number;
43
+ heightMm: number;
44
+ lang?: Lang;
45
+ }): string;
46
+ export { KIDS_BODIES };
@@ -0,0 +1,193 @@
1
+ // One colouring sheet as one SVG measured in millimetres: the picture, the colours to colour with and the three facts (or, for the lineup, all the planets in a row at one scale). Pure: a string.
2
+ import { TYPE_PRESETS, DEFAULT_MARGIN_MM, printableSize } from "@johnmorrisdotca/kazoku-ui/print";
3
+ import { BODIES } from "../facts.js";
4
+ import { KIDS_BODIES, LINEUP_IDS, SAY, SWATCHES, kidsFacts, kidsName, kidsSay, lineupFacts } from "./data.js";
5
+ import { colouringArt, colouringPicture, LINE_MM, OUTLINE_MM, reach, sheetPose } from "./picture.js";
6
+ const PT = 25.4 / 72;
7
+ const KID = TYPE_PRESETS.kid;
8
+ const BODY_MM = KID.bodyPt * PT;
9
+ const NAME_MM = KID.namePt * PT;
10
+ /** The planets' names on the lineup: the least size the kid type allows for a name, 24 pt. */
11
+ const LABEL_MM = 24 * PT;
12
+ /** What the sheet's header, footer and gaps take from the page's height, in millimetres, as measured (a narrow page's footer is taller, for its address wraps); a browser measures the real room (`kidsSheet`). */
13
+ const FRAME_MM = 89;
14
+ const WIDE_FRAME_MM = 77;
15
+ /** The lineup is wide, so it is printed on its side. */
16
+ export const kidsOrientation = (id) => (id === "lineup" ? "landscape" : "portrait");
17
+ /**
18
+ * The room a sheet's picture has on a page, in millimetres: the page inside its margins, less the header and the footer.
19
+ * @param page - `a4`, `letter`, `a3` or `tabloid`.
20
+ * @param orientation - `portrait` or `landscape`.
21
+ * @returns The width and height.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { kidsRoom } from "@johnmorrisdotca/wakusei-planets/sheets";
26
+ *
27
+ * console.log(kidsRoom("a4", "portrait"));
28
+ * ```
29
+ */
30
+ export function kidsRoom(page, orientation = "portrait") {
31
+ const size = printableSize(page, orientation, DEFAULT_MARGIN_MM);
32
+ return { widthMm: size.widthMm, heightMm: size.heightMm - (size.widthMm >= 240 ? WIDE_FRAME_MM : FRAME_MM) };
33
+ }
34
+ const esc = (text) => text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
35
+ const n = (v) => (Math.round(v * 100) / 100).toString();
36
+ /** The width of a text in millimetres, estimated on the wide side so a font that is wider than the rounded ones (a fallback on a server) still fits: a full-width character is as wide as the type is tall, a Latin capital or a digit 0.82 of it, a small letter 0.7 (DejaVu Sans Bold, the usual fallback on a server, is that wide), a space or a stop 0.38. */
37
+ export function textWidth(text, sizeMm) {
38
+ let total = 0;
39
+ for (const ch of text)
40
+ total += /[\u3000-\u30ff\u4e00-\u9fff\uff00-\uffef]/.test(ch) ? sizeMm : /[ .,:;!'|]/.test(ch) ? 0.38 * sizeMm : /[A-Z0-9]/.test(ch) ? 0.82 * sizeMm : 0.7 * sizeMm;
41
+ return total;
42
+ }
43
+ /** Break a sentence into lines no wider than `maxMm`: at spaces for English, after a full stop (or anywhere) for Japanese. */
44
+ export function wrap(text, maxMm, sizeMm) {
45
+ const japanese = /[぀-ヿ一-鿿]/.test(text);
46
+ const pieces = japanese ? (text.match(/[^。]+。?/g) ?? [text]) : text.split(" ");
47
+ const joiner = japanese ? "" : " ";
48
+ const lines = [];
49
+ let line = "";
50
+ for (const piece of pieces) {
51
+ const next = line === "" ? piece : line + joiner + piece;
52
+ if (line !== "" && textWidth(next, sizeMm) > maxMm) {
53
+ lines.push(line);
54
+ line = piece;
55
+ }
56
+ else
57
+ line = next;
58
+ }
59
+ if (line !== "")
60
+ lines.push(line);
61
+ return japanese ? lines.flatMap((one) => cut(one, maxMm, sizeMm)) : lines;
62
+ }
63
+ ;
64
+ function cut(line, maxMm, sizeMm) {
65
+ const out = [];
66
+ let current = "";
67
+ for (const ch of line) {
68
+ if (current !== "" && textWidth(current + ch, sizeMm) > maxMm) {
69
+ out.push(current);
70
+ current = ch;
71
+ }
72
+ else
73
+ current += ch;
74
+ }
75
+ return current === "" ? out : [...out, current];
76
+ }
77
+ const text = (x, y, size, body, extra = "") => `<text x="${n(x)}" y="${n(y)}" font-size="${n(size)}" font-weight="700" fill="#000"${extra}>${esc(body)}</text>`;
78
+ /** The facts as numbered dots and lines of words. */
79
+ function facts(list, width, y, numbered = true) {
80
+ const dot = 4.6;
81
+ const left = 2 * dot + 4;
82
+ const lineHeight = BODY_MM * 1.3;
83
+ const out = [];
84
+ let at = y;
85
+ list.forEach((fact, i) => {
86
+ const lines = wrap(fact, width - left, BODY_MM);
87
+ const rowHeight = Math.max(2 * dot, lines.length * lineHeight);
88
+ const mid = at + rowHeight / 2;
89
+ out.push(`<circle cx="${n(dot)}" cy="${n(mid)}" r="${dot}" fill="#000"/>`, numbered ? `<text x="${n(dot)}" y="${n(mid + BODY_MM * 0.36)}" font-size="${n(BODY_MM)}" font-weight="700" fill="#fff" text-anchor="middle">${i + 1}</text>` : "");
90
+ lines.forEach((line, k) => out.push(text(left, mid - (lines.length * lineHeight) / 2 + lineHeight * (k + 0.72), BODY_MM, line, ' data-fact=""')));
91
+ at += rowHeight + 3.5;
92
+ });
93
+ return { markup: `<g data-facts="">${out.join("")}</g>`, height: at - y - 3.5 };
94
+ }
95
+ /** The colours to colour with: the heading at the left, then a square of each real colour with its name under it. */
96
+ function swatches(id, lang, width, y) {
97
+ const list = SWATCHES[id];
98
+ const head = NAME_MM * 0.9;
99
+ const headWidth = 52;
100
+ const cell = (width - headWidth) / list.length;
101
+ const square = 14;
102
+ const out = [text(1.2, y + square / 2 + head * 0.35, head, SAY[lang].colour, ' data-colour-head=""')];
103
+ list.forEach((one, i) => {
104
+ const cx = headWidth + cell * i + cell / 2;
105
+ out.push(`<rect x="${n(cx - square / 2 - 1)}" y="${n(y)}" width="${n(square + 2)}" height="${n(square)}" rx="3" fill="${one.hex}" stroke="#000" stroke-width="${LINE_MM}" data-swatch="${one.hex}"/>`);
106
+ out.push(text(cx, y + square + 2 + BODY_MM * 0.85, BODY_MM, one[lang], ' text-anchor="middle" data-swatch-name=""'));
107
+ });
108
+ return { markup: `<g data-swatches="">${out.join("")}</g>`, height: square + 2 + BODY_MM * 1.2 };
109
+ }
110
+ /** The sheet of one body: the picture on top, then the colours, then the facts. */
111
+ function bodySheet(id, lang, width, height) {
112
+ const list = kidsFacts(id, lang);
113
+ const probe = facts(list, width, 0);
114
+ const colours = swatches(id, lang, width, 0);
115
+ const gap = 7;
116
+ const art = colouringPicture(id, width, height - probe.height - colours.height - 2 * gap);
117
+ const top = height - probe.height - colours.height - 2 * gap;
118
+ const parts = [art.markup, `<g transform="translate(0 ${n(top + gap)})">${colours.markup}</g>`, `<g transform="translate(0 ${n(top + colours.height + 2 * gap)})">${facts(list, width, 0).markup}</g>`];
119
+ return parts.join("");
120
+ }
121
+ /** What a planet takes of the row: its width, or its rings'. */
122
+ const extentKm = (id) => 2 * reach(id, sheetPose(id)).x * BODIES[id].radiusKm;
123
+ /** The lineup: every planet on one line at one scale, each with a number under it and a line to the number; below, the numbers with the names in the order from the Sun; and three facts. */
124
+ function lineupSheet(lang, width, height) {
125
+ const ext = LINEUP_IDS.map((id) => extentKm(id));
126
+ const badge = 4.4;
127
+ const reachKm = ext.reduce((total, e) => total + e, 0);
128
+ const rows = 2;
129
+ const pitch = LABEL_MM * 1.5;
130
+ const factsFor = (k) => facts(lineupFacts(lang, k), width, 0, false);
131
+ const tall = (k) => 2 * BODIES.jupiter.radiusKm * k;
132
+ // the gaps keep the numbers apart, then the rest of the width is shared
133
+ const gapsAt = (k) => ext.slice(1).map((e, i) => Math.max(3, 2 * badge + 2 - ((ext[i] + e) * k) / 2));
134
+ let k = (width - 2 * badge - 3 * (ext.length - 1)) / reachKm;
135
+ for (let pass = 0; pass < 6; pass += 1) {
136
+ const spare = width - 2 * badge - reachKm * k - gapsAt(k).reduce((t, g) => t + g, 0);
137
+ if (spare < 0)
138
+ k += spare / reachKm;
139
+ }
140
+ k = Math.min(k, (height - factsFor(k).height - rows * pitch - 2 * badge - 12) / tall(1));
141
+ const gaps = gapsAt(k);
142
+ const extra = (width - 2 * badge - reachKm * k - gaps.reduce((t, g) => t + g, 0)) / gaps.length;
143
+ const axis = tall(k) / 2 + OUTLINE_MM / 2;
144
+ const badgeY = axis + tall(k) / 2 + 3 + badge;
145
+ const out = [];
146
+ let x = badge;
147
+ LINEUP_IDS.forEach((id, i) => {
148
+ const extent = ext[i] * k;
149
+ const cx = x + extent / 2;
150
+ const r = BODIES[id].radiusKm * k;
151
+ const thick = r * 2 >= 24 ? OUTLINE_MM : Math.max(1, Math.min(OUTLINE_MM, r / 4));
152
+ out.push(colouringArt(id, cx, axis, r, thick));
153
+ out.push(`<path d="M${n(cx)} ${n(axis + (reach(id, sheetPose(id)).y * BODIES[id].radiusKm * k) + 1.5)}L${n(cx)} ${n(badgeY - badge)}" fill="none" stroke="#000" stroke-width="0.8" stroke-linecap="round" data-leader=""/>`);
154
+ out.push(`<circle cx="${n(cx)}" cy="${n(badgeY)}" r="${badge}" fill="#000" data-badge="${i + 1}"/>`, `<text x="${n(cx)}" y="${n(badgeY + BODY_MM * 0.36)}" font-size="${n(BODY_MM)}" font-weight="700" fill="#fff" text-anchor="middle">${i + 1}</text>`);
155
+ x += extent + (gaps[i] ?? 0) + extra;
156
+ });
157
+ const legendTop = badgeY + badge + 8;
158
+ const columns = LINEUP_IDS.length / rows;
159
+ const cell = width / columns;
160
+ LINEUP_IDS.forEach((id, i) => {
161
+ const column = i % columns;
162
+ const row = Math.floor(i / columns);
163
+ const y = legendTop + row * pitch + LABEL_MM;
164
+ out.push(`<circle cx="${n(column * cell + badge)}" cy="${n(y - LABEL_MM * 0.33)}" r="${badge}" fill="#000"/>`, `<text x="${n(column * cell + badge)}" y="${n(y - LABEL_MM * 0.33 + BODY_MM * 0.36)}" font-size="${n(BODY_MM)}" font-weight="700" fill="#fff" text-anchor="middle">${i + 1}</text>`);
165
+ out.push(text(column * cell + 2 * badge + 2, y, LABEL_MM, kidsSay(id, lang), ' data-planet-name=""'));
166
+ });
167
+ const block = factsFor(k);
168
+ out.push(`<g transform="translate(0 ${n(height - block.height)})">${block.markup}</g>`);
169
+ return out.join("");
170
+ }
171
+ /**
172
+ * One sheet as an SVG string measured in millimetres: the picture of the body, the colours to colour it with and three facts, in English or Japanese; or the lineup of all the planets at one scale. `widthMm` and
173
+ * `heightMm` are the room it is drawn for (`kidsRoom`), and the viewBox is that room, so a millimetre is a millimetre on paper.
174
+ * @param id - A body with a sheet, or `lineup`.
175
+ * @param options - The room, and the language.
176
+ * @returns The `<svg>` markup.
177
+ *
178
+ * @example
179
+ * ```ts
180
+ * import { kidsRoom, kidsSvg } from "@johnmorrisdotca/wakusei-planets/sheets";
181
+ *
182
+ * const room = kidsRoom("a4");
183
+ * console.log(kidsSvg("saturn", { ...room, lang: "en" }).includes("Colour me!"));
184
+ * ```
185
+ */
186
+ export function kidsSvg(id, options) {
187
+ const lang = options.lang ?? "en";
188
+ const { widthMm: w, heightMm: h } = options;
189
+ const label = id === "lineup" ? SAY[lang].lineup : kidsName(id, lang);
190
+ const inner = id === "lineup" ? lineupSheet(lang, w, h) : bodySheet(id, lang, w, h);
191
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n(w)} ${n(h)}" width="100%" height="100%" preserveAspectRatio="xMidYMid meet" role="img" aria-label="${esc(label)}" data-kids-sheet="${id}" font-family="inherit"><title>${esc(label)}</title>${inner}</svg>`;
192
+ }
193
+ export { KIDS_BODIES };
package/dist/line.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type Pose } from "./ephemeris.ts";
2
- import { type BodyId, type MoonId } from "./facts.ts";
2
+ import { type BodyFacts, type BodyId, type MoonId } from "./facts.ts";
3
3
  import { type PortraitOptions } from "./pose.ts";
4
4
  /**
5
5
  * Options for `lineSvg`: the size, a pose (`tilt`, `pitch`, `phase`, `spin`, a `time` or a `pose`), `moons`, `range`, `fill`, the language and the colours.
@@ -48,6 +48,7 @@ export interface LineOptions extends PortraitOptions {
48
48
  /** The colour of the disc. Default: a dark tint of the body's colour. */
49
49
  paper?: string;
50
50
  }
51
+ export declare const NAVY = "#0b1424";
51
52
  /**
52
53
  * Mix two `#rrggbb` colours: `t` is how much of `b` (0 to 1).
53
54
  * @param a - The first colour.
@@ -63,6 +64,13 @@ export interface LineOptions extends PortraitOptions {
63
64
  * ```
64
65
  */
65
66
  export declare function mix(a: string, b: string, t: number): string;
67
+ export interface Frame {
68
+ cx: number;
69
+ cy: number;
70
+ r: number;
71
+ }
72
+ /** The body's outline, features, rings and dark side as SVG, centred in `frame`. `facts` and `clip` stand in for the table's entry and the clip path's name when a star that is not in the table is drawn. */
73
+ export declare function bodyGroup(id: BodyId, pose: Pose, frame: Frame, o: Required<Pick<LineOptions, "stroke" | "paper">>, hair: number, ringScale: number, facts?: BodyFacts, clipId?: string): string;
66
74
  /**
67
75
  * A body as a line drawing, as an SVG string: the outline (squeezed by its flattening and leaning at its axial tilt), bands and features, rings with their gaps, and the dark side
68
76
  * dashed off. Give it a `time` to draw the body as the Earth sees it then; leave it out for a portrait. `moons: true` draws a planet with its moons on their orbits.