@johnmorrisdotca/chikyu-earth 0.35.0 → 0.36.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 (44) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/NOTICE.md +23 -1
  3. package/README.md +20 -2
  4. package/dist/borders/layer.d.ts +75 -0
  5. package/dist/borders/layer.js +136 -0
  6. package/dist/borders/lines.d.ts +138 -0
  7. package/dist/borders/lines.js +227 -0
  8. package/dist/cities/host.d.ts +9 -0
  9. package/dist/cities/host.js +14 -2
  10. package/dist/country-names/geometry.d.ts +264 -0
  11. package/dist/country-names/geometry.js +372 -0
  12. package/dist/country-names/host.d.ts +82 -0
  13. package/dist/country-names/host.js +212 -0
  14. package/dist/grid/layer.d.ts +45 -0
  15. package/dist/grid/layer.js +66 -0
  16. package/dist/grid/lines.d.ts +85 -0
  17. package/dist/grid/lines.js +113 -0
  18. package/dist/markers/go-to-place.d.ts +27 -0
  19. package/dist/markers/go-to-place.js +35 -0
  20. package/dist/markers/index.d.ts +2 -1
  21. package/dist/markers/index.js +2 -1
  22. package/dist/markers/layer.d.ts +7 -0
  23. package/dist/markers/layer.js +7 -0
  24. package/dist/markers/place-layer.d.ts +58 -7
  25. package/dist/markers/place-layer.js +326 -64
  26. package/dist/markers/place-sprites.d.ts +33 -0
  27. package/dist/markers/place-sprites.js +161 -0
  28. package/dist/markers/places.d.ts +91 -6
  29. package/dist/markers/places.js +135 -6
  30. package/dist/realistic/earth.d.ts +11 -0
  31. package/dist/realistic/earth.js +54 -0
  32. package/dist/realistic/element.d.ts +65 -4
  33. package/dist/realistic/element.js +198 -26
  34. package/dist/realistic/immersive.d.ts +7 -0
  35. package/dist/realistic/immersive.js +17 -0
  36. package/dist/realistic/index.d.ts +6 -0
  37. package/dist/realistic/index.js +3 -0
  38. package/dist/realistic/textures.d.ts +3 -0
  39. package/dist/space/element.d.ts +81 -7
  40. package/dist/space/element.js +246 -16
  41. package/dist/space/index.d.ts +1 -1
  42. package/dist/space/scene.d.ts +53 -5
  43. package/dist/space/scene.js +88 -8
  44. package/package.json +3 -3
@@ -0,0 +1,372 @@
1
+ const RAD = Math.PI / 180;
2
+ /** How many of a country's points, the nearest to the middle of the part in view first, its name is tried at. */
3
+ const SPOTS_TRIED = 6;
4
+ /** Points that face the viewer less squarely than this are too foreshortened to count. */
5
+ const FACING = 0.2;
6
+ /** About this many points are spread over each country, more for none and at least one for each polygon. */
7
+ const POINTS_EACH = 48;
8
+ /**
9
+ * The space between the letters of a country's name, as a share of the text's size (the style sheet's `letter-spacing` in `em`).
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { COUNTRY_LETTER_SPACING } from "@johnmorrisdotca/chikyu-earth/realistic";
14
+ *
15
+ * console.log(COUNTRY_LETTER_SPACING * 12);
16
+ * ```
17
+ */
18
+ export const COUNTRY_LETTER_SPACING = 0.06;
19
+ const ringsOf = (geometry) => {
20
+ if (!geometry || !Array.isArray(geometry.coordinates))
21
+ return [];
22
+ if (geometry.type === "Polygon")
23
+ return [geometry.coordinates];
24
+ if (geometry.type === "MultiPolygon")
25
+ return geometry.coordinates;
26
+ return [];
27
+ };
28
+ const inside = (rings, lon, lat) => {
29
+ let odd = false;
30
+ for (const ring of rings) {
31
+ for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
32
+ const [xi, yi] = ring[i];
33
+ const [xj, yj] = ring[j];
34
+ if (yi > lat !== yj > lat && lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi)
35
+ odd = !odd;
36
+ }
37
+ }
38
+ return odd;
39
+ };
40
+ /**
41
+ * Spreads points over each named country's land, about 48 to a country on an even grid of longitude and latitude, so that a view can find the middle of the part of it in sight and how large
42
+ * that part is. A polygon too small for the grid gets one point, at the middle of its outline. Made once, when the outlines arrive.
43
+ *
44
+ * @param shapes - The outlines, as chizu's `world-geo` has them.
45
+ * @returns The countries and their points.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * import { countrySpots } from "@johnmorrisdotca/chikyu-earth/realistic";
50
+ *
51
+ * const square = { properties: { code: "A", name: "Square" }, geometry: { type: "Polygon", coordinates: [[[0, 0], [10, 0], [10, 10], [0, 10], [0, 0]]] } };
52
+ * const spots = countrySpots({ features: [square] });
53
+ * console.log(spots.countries[0]?.points.length! / 4);
54
+ * ```
55
+ */
56
+ export function countrySpots(shapes) {
57
+ const countries = [];
58
+ for (const feature of shapes.features) {
59
+ const name = feature.properties?.name;
60
+ if (!name)
61
+ continue;
62
+ const polygons = ringsOf(feature.geometry).filter((rings) => rings.length > 0 && rings[0].length >= 4);
63
+ if (polygons.length === 0)
64
+ continue;
65
+ const boxes = polygons.map((rings) => {
66
+ let west = 180;
67
+ let east = -180;
68
+ let south = 90;
69
+ let north = -90;
70
+ for (const point of rings[0]) {
71
+ west = Math.min(west, point[0]);
72
+ east = Math.max(east, point[0]);
73
+ south = Math.min(south, point[1]);
74
+ north = Math.max(north, point[1]);
75
+ }
76
+ return { west, east, south, north };
77
+ });
78
+ // the grid's step: the country's outline boxes, on the plane of longitude and latitude, shared among about POINTS_EACH points
79
+ const plane = boxes.reduce((sum, box) => sum + (box.east - box.west) * (box.north - box.south), 0);
80
+ const step = Math.min(8, Math.max(0.1, Math.sqrt(plane / POINTS_EACH)));
81
+ const out = [];
82
+ polygons.forEach((rings, polygon) => {
83
+ const box = boxes[polygon];
84
+ const before = out.length;
85
+ for (let lat = box.south + step / 2; lat < box.north; lat += step) {
86
+ for (let lon = box.west + step / 2; lon < box.east; lon += step) {
87
+ if (inside(rings, lon, lat))
88
+ out.push(lon, lat, Math.cos(lat * RAD) * step * step, polygon);
89
+ }
90
+ }
91
+ if (out.length === before) {
92
+ // too small for the grid: one point at the middle of its outline, standing for the box's area at most
93
+ const ring = rings[0];
94
+ let lon = 0;
95
+ let lat = 0;
96
+ for (const point of ring) {
97
+ lon += point[0];
98
+ lat += point[1];
99
+ }
100
+ lon /= ring.length;
101
+ lat /= ring.length;
102
+ out.push(lon, lat, Math.cos(lat * RAD) * Math.max(0.0001, (box.east - box.west) * (box.north - box.south)) * 0.5, polygon);
103
+ }
104
+ });
105
+ // the cap: the middle of the points on the sphere, and the farthest point from it
106
+ let x = 0;
107
+ let y = 0;
108
+ let z = 0;
109
+ for (let i = 0; i < out.length; i += 4) {
110
+ const phi = out[i + 1] * RAD;
111
+ const lambda = out[i] * RAD;
112
+ x += Math.cos(phi) * Math.sin(lambda);
113
+ y += Math.sin(phi);
114
+ z += Math.cos(phi) * Math.cos(lambda);
115
+ }
116
+ const length = Math.hypot(x, y, z) || 1;
117
+ x /= length;
118
+ y /= length;
119
+ z /= length;
120
+ let reach = 0;
121
+ for (let i = 0; i < out.length; i += 4) {
122
+ const phi = out[i + 1] * RAD;
123
+ const lambda = out[i] * RAD;
124
+ const dot = x * Math.cos(phi) * Math.sin(lambda) + y * Math.sin(phi) + z * Math.cos(phi) * Math.cos(lambda);
125
+ reach = Math.max(reach, Math.acos(Math.max(-1, Math.min(1, dot))) / RAD);
126
+ }
127
+ const ja = feature.properties?.nameJa;
128
+ countries.push({
129
+ code: feature.properties?.code ?? name,
130
+ name: ja ? { en: name, ja } : { en: name },
131
+ points: new Float32Array(out),
132
+ cap: { lon: Math.atan2(x, z) / RAD, lat: Math.asin(Math.max(-1, Math.min(1, y))) / RAD, reach: reach + step },
133
+ });
134
+ }
135
+ return { countries };
136
+ }
137
+ /**
138
+ * The name to write for a country: its Japanese name on a page in Japanese where there is one, else its English name in capitals.
139
+ *
140
+ * @param country - The country's names.
141
+ * @param lang - The page's language, `en` or `ja`.
142
+ * @returns The text.
143
+ *
144
+ * @example
145
+ * ```ts
146
+ * import { countryNameText } from "@johnmorrisdotca/chikyu-earth/realistic";
147
+ *
148
+ * const japan = { name: { en: "Japan", ja: "日本" } };
149
+ * console.log(countryNameText(japan, "en"), countryNameText(japan, "ja"));
150
+ * ```
151
+ */
152
+ export function countryNameText(country, lang) {
153
+ return lang === "ja" && country.name.ja ? country.name.ja : country.name.en.toUpperCase();
154
+ }
155
+ /**
156
+ * About how wide and tall a country's name is, in pixels, without reading any layout: a Japanese character as wide as the text is tall, a capital about 0.7 of it, with the letters' spacing.
157
+ *
158
+ * @param text - The name.
159
+ * @param size - The text size in pixels.
160
+ * @returns The width and height.
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * import { countryNameBox } from "@johnmorrisdotca/chikyu-earth/realistic";
165
+ *
166
+ * console.log(countryNameBox("JAPAN", 12), countryNameBox("日本", 12));
167
+ * ```
168
+ */
169
+ export function countryNameBox(text, size) {
170
+ let width = 0;
171
+ for (const char of text)
172
+ width += ((char.codePointAt(0) ?? 0) >= 0x2e80 ? size : size * 0.7) + size * COUNTRY_LETTER_SPACING;
173
+ return { width: Math.ceil(width) + 4, height: Math.ceil(size * 1.3) };
174
+ }
175
+ const GAP = 2;
176
+ /**
177
+ * Lays the names out for one draw. Each country in sight is named at the middle of the largest part of it the view shows (snapped to a point of its own land, so a crescent's name is not out at
178
+ * sea), the largest on the screen first, its text sized by that part, only where the text fits within it, inside the Earth's disc, and free of the names already placed and of `taken`
179
+ * (tried at the middle, a line above and below, then at the next points of its land out from the middle). A country on the far side, or too small for its name, is left out: fewer names when the Earth is small, more as it grows.
180
+ *
181
+ * @param spots - The countries' points (see {@link countrySpots}).
182
+ * @param frame - Where the Earth is on the screen.
183
+ * @param lang - The page's language, `en` or `ja`.
184
+ * @param options - The most names, the text sizes, the boxes taken and how to measure.
185
+ * @returns The names to show, the largest first.
186
+ *
187
+ * @example
188
+ * ```ts
189
+ * import { countrySpots, layoutCountryNames } from "@johnmorrisdotca/chikyu-earth/realistic";
190
+ *
191
+ * const square = { properties: { code: "A", name: "Square", nameJa: "四角" }, geometry: { type: "Polygon", coordinates: [[[-20, -20], [20, -20], [20, 20], [-20, 20], [-20, -20]]] } };
192
+ * const frame = {
193
+ * width: 400, height: 400, radius: 180, disc: { x: 200, y: 200, radius: 180 },
194
+ * project: (lon: number, lat: number, out: { x: number; y: number }) => { out.x = 200 + lon * 3; out.y = 200 - lat * 3; return 1; },
195
+ * };
196
+ * console.log(layoutCountryNames(countrySpots({ features: [square] }), frame, "en", { max: 10, smallest: 10, largest: 16 }).map((one) => one.text));
197
+ * ```
198
+ */
199
+ export function layoutCountryNames(spots, frame, lang, options) {
200
+ const out = { x: 0, y: 0 };
201
+ const margin = 2;
202
+ const pixelsPerArea = (RAD * frame.radius) ** 2;
203
+ const disc = frame.disc;
204
+ const seen = [];
205
+ const sums = new Map();
206
+ const xs = [];
207
+ const ys = [];
208
+ const owners = [];
209
+ for (const country of spots.countries) {
210
+ // the whole cap on the far side: nothing of it in sight
211
+ const middle = frame.project(country.cap.lon, country.cap.lat, out);
212
+ if (Math.acos(Math.max(-1, Math.min(1, middle))) / RAD - country.cap.reach > 95)
213
+ continue;
214
+ sums.clear();
215
+ xs.length = 0;
216
+ ys.length = 0;
217
+ owners.length = 0;
218
+ const points = country.points;
219
+ for (let i = 0; i < points.length; i += 4) {
220
+ const facing = frame.project(points[i], points[i + 1], out);
221
+ if (facing < FACING)
222
+ continue;
223
+ if (out.x < margin || out.y < margin || out.x > frame.width - margin || out.y > frame.height - margin)
224
+ continue;
225
+ if (disc && Math.hypot(out.x - disc.x, out.y - disc.y) > disc.radius)
226
+ continue;
227
+ const polygon = points[i + 3];
228
+ const weight = points[i + 2] * facing;
229
+ const sum = sums.get(polygon);
230
+ if (sum) {
231
+ sum.w += weight;
232
+ sum.x += out.x * weight;
233
+ sum.y += out.y * weight;
234
+ }
235
+ else
236
+ sums.set(polygon, { w: weight, x: out.x * weight, y: out.y * weight });
237
+ xs.push(out.x);
238
+ ys.push(out.y);
239
+ owners.push(polygon);
240
+ }
241
+ let best = -1;
242
+ let most = 0;
243
+ for (const [polygon, sum] of sums) {
244
+ if (sum.w > most) {
245
+ most = sum.w;
246
+ best = polygon;
247
+ }
248
+ }
249
+ if (best < 0)
250
+ continue;
251
+ const sum = sums.get(best);
252
+ const cx = sum.x / sum.w;
253
+ const cy = sum.y / sum.w;
254
+ // snapped to the points of that polygon's own land in view, the nearest to the middle first: the next ones are tried when another name is in the way
255
+ const near = [];
256
+ for (let k = 0; k < xs.length; k += 1) {
257
+ if (owners[k] !== best)
258
+ continue;
259
+ near.push({ x: xs[k], y: ys[k], d: (xs[k] - cx) ** 2 + (ys[k] - cy) ** 2 });
260
+ }
261
+ near.sort((a, b) => a.d - b.d);
262
+ seen.push({ code: country.code, text: countryNameText(country, lang), spots: near.slice(0, SPOTS_TRIED), area: most * pixelsPerArea });
263
+ }
264
+ seen.sort((a, b) => b.area - a.area);
265
+ const placed = [];
266
+ const blocked = (options.taken ?? []).map((box) => ({ l: box.left, t: box.top, r: box.left + box.width, b: box.top + box.height }));
267
+ const free = (box) => {
268
+ for (const other of placed)
269
+ if (box.l < other.r + GAP && box.r + GAP > other.l && box.t < other.b + GAP && box.b + GAP > other.t)
270
+ return false;
271
+ for (const other of blocked)
272
+ if (box.l < other.r && box.r > other.l && box.t < other.b && box.b > other.t)
273
+ return false;
274
+ return true;
275
+ };
276
+ const inDisc = (box) => {
277
+ if (!disc)
278
+ return true;
279
+ const reach = disc.radius - 2;
280
+ for (const [x, y] of [
281
+ [box.l, box.t],
282
+ [box.r, box.t],
283
+ [box.l, box.b],
284
+ [box.r, box.b],
285
+ ]) {
286
+ if (Math.hypot(x - disc.x, y - disc.y) > reach)
287
+ return false;
288
+ }
289
+ return true;
290
+ };
291
+ const names = [];
292
+ for (const one of seen) {
293
+ if (names.length >= options.max)
294
+ break;
295
+ const across = Math.sqrt(one.area);
296
+ const size = Math.round(Math.min(options.largest, Math.max(options.smallest, options.smallest - 1 + across / 30)));
297
+ const guess = countryNameBox(one.text, size);
298
+ const measured = options.measure?.(one.text, size);
299
+ const width = Math.max(guess.width, measured ? Math.ceil(measured.width) + 4 : 0);
300
+ const height = Math.max(guess.height, measured ? Math.ceil(measured.height) : 0);
301
+ // the name must fit the part of the country in view: a country much narrower than its name is left out
302
+ if (across < width * 0.45)
303
+ continue;
304
+ tries: for (const spot of one.spots) {
305
+ for (const shift of [0, -0.8, 0.8]) {
306
+ const left = spot.x - width / 2;
307
+ const top = spot.y - height / 2 + shift * height;
308
+ const box = { l: left, t: top, r: left + width, b: top + height };
309
+ if (box.l < 0 || box.t < 0 || box.r > frame.width || box.b > frame.height || !inDisc(box) || !free(box))
310
+ continue;
311
+ placed.push(box);
312
+ names.push({ code: one.code, text: one.text, x: spot.x, y: spot.y, left, top, width, height, size });
313
+ break tries;
314
+ }
315
+ }
316
+ }
317
+ return names;
318
+ }
319
+ /**
320
+ * The most names `country-names` may ask for at once.
321
+ *
322
+ * @example
323
+ * ```ts
324
+ * import { COUNTRY_NAMES_MAX } from "@johnmorrisdotca/chikyu-earth/realistic";
325
+ *
326
+ * console.log(COUNTRY_NAMES_MAX);
327
+ * ```
328
+ */
329
+ export const COUNTRY_NAMES_MAX = 120;
330
+ /**
331
+ * How many names a bare `country-names` asks for.
332
+ *
333
+ * @example
334
+ * ```ts
335
+ * import { COUNTRY_NAMES_DEFAULT } from "@johnmorrisdotca/chikyu-earth/realistic";
336
+ *
337
+ * console.log(COUNTRY_NAMES_DEFAULT);
338
+ * ```
339
+ */
340
+ export const COUNTRY_NAMES_DEFAULT = 40;
341
+ /**
342
+ * Reads the `country-names` attribute: absent (or `off`) is none, bare is 40 names at most, a number is that many at most (1 to 120).
343
+ *
344
+ * @param value - The attribute's value, or `null` when it is absent.
345
+ * @returns How many names at most, or `null` for none.
346
+ *
347
+ * @example
348
+ * ```ts
349
+ * import { readCountryNames } from "@johnmorrisdotca/chikyu-earth/realistic";
350
+ *
351
+ * console.log(readCountryNames(null), readCountryNames(""), readCountryNames("12"), readCountryNames("500"), readCountryNames("off"));
352
+ * ```
353
+ */
354
+ export function readCountryNames(value) {
355
+ if (value === null || value.trim().toLowerCase() === "off")
356
+ return null;
357
+ const count = Number(value.trim());
358
+ if (value.trim() === "" || !Number.isFinite(count))
359
+ return COUNTRY_NAMES_DEFAULT;
360
+ return Math.min(COUNTRY_NAMES_MAX, Math.max(1, Math.round(count)));
361
+ }
362
+ /**
363
+ * The attributes the country names read: `country-names`.
364
+ *
365
+ * @example
366
+ * ```ts
367
+ * import { COUNTRY_NAMES_ATTRIBUTES } from "@johnmorrisdotca/chikyu-earth/realistic";
368
+ *
369
+ * console.log(COUNTRY_NAMES_ATTRIBUTES.join(" "));
370
+ * ```
371
+ */
372
+ export const COUNTRY_NAMES_ATTRIBUTES = ["country-names"];
@@ -0,0 +1,82 @@
1
+ import { type CountryFrame, type CountryName, type NamedShape } from "./geometry.ts";
2
+ /**
3
+ * The look of the country names, all optional: the text's font, weight and colour, the outline round it, and the smallest and largest size in pixels.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import type { CountryNamesStyle } from "@johnmorrisdotca/chikyu-earth/realistic";
8
+ *
9
+ * const look: CountryNamesStyle = { font: "Georgia, serif", colour: "#fff3d6", halo: "#1a1000", smallest: 11, largest: 18 };
10
+ * console.log(Object.keys(look).join(" "));
11
+ * ```
12
+ */
13
+ export interface CountryNamesStyle {
14
+ font?: string;
15
+ weight?: number | string;
16
+ colour?: string;
17
+ halo?: string;
18
+ haloWidth?: number;
19
+ smallest?: number;
20
+ largest?: number;
21
+ }
22
+ /** The styles of the layer, for an element to add to its own (`#co-names` and the names in its shadow root). */
23
+ export declare const COUNTRY_NAMES_STYLE: string;
24
+ /** What an element tells the layer about the page. */
25
+ export interface CountryHostOptions {
26
+ /** Reads one of the element's attributes. */
27
+ attribute(name: string): string | null;
28
+ /** The page's language, `en` or `ja`. */
29
+ language(): "en" | "ja";
30
+ /** The shadow root the layer is made in. */
31
+ root: ShadowRoot;
32
+ /** Told when the outlines could not be loaded. */
33
+ onError(error: unknown): void;
34
+ /** Loads the outlines with their names: chizu's `world-geo` by default. */
35
+ load?(): Promise<{
36
+ features: readonly NamedShape[];
37
+ }>;
38
+ }
39
+ /**
40
+ * What the country names did: whether `country-names` is set and the most it asks for, the countries loaded, the names shown at the last draw, how many times the layer was laid out, and
41
+ * whether the outlines could not be loaded.
42
+ *
43
+ * @example
44
+ * ```ts no-run
45
+ * import type { CountryNamesStats } from "@johnmorrisdotca/chikyu-earth/realistic";
46
+ *
47
+ * const none: CountryNamesStats = { on: false, max: 0, countries: 0, names: 0, renders: 0, failed: false };
48
+ * console.log(none);
49
+ * ```
50
+ */
51
+ export interface CountryNamesStats {
52
+ on: boolean;
53
+ max: number;
54
+ countries: number;
55
+ names: number;
56
+ renders: number;
57
+ failed: boolean;
58
+ }
59
+ export interface CountryHost {
60
+ /** Tells where the Earth is in the picture just drawn (or `null` when there is no Earth to name), and the boxes other names use there. */
61
+ frame(frame: CountryFrame | null, taken?: readonly {
62
+ left: number;
63
+ top: number;
64
+ width: number;
65
+ height: number;
66
+ }[]): void;
67
+ /** Reads the attribute and the language again after either changed. */
68
+ refresh(): void;
69
+ /** The look of the names (the property `countryNamesStyle`). */
70
+ setStyle(style: CountryNamesStyle): void;
71
+ /** The names shown at the last draw. */
72
+ readonly shown: readonly CountryName[];
73
+ readonly stats: CountryNamesStats;
74
+ dispose(): void;
75
+ }
76
+ /**
77
+ * Makes the layer of one element, inside its shadow root. Nothing is loaded, and nothing is added to the root, until `country-names` is there.
78
+ *
79
+ * @param options - The attribute reader, the language and the shadow root.
80
+ * @returns The host.
81
+ */
82
+ export declare function createCountryHost(options: CountryHostOptions): CountryHost;
@@ -0,0 +1,212 @@
1
+ // The names of the countries on the Earth, over the picture of an element (chizu's `world-geo`, loaded only when `country-names` is set). The element tells this where the Earth is at each draw
2
+ // and which boxes other names use (`frame`); it lays the names out as a few labels and draws nothing at rest.
3
+ import { COUNTRY_LETTER_SPACING, COUNTRY_NAMES_MAX, countrySpots, layoutCountryNames, readCountryNames } from "./geometry.js";
4
+ /** The styles of the layer, for an element to add to its own (`#co-names` and the names in its shadow root). */
5
+ export const COUNTRY_NAMES_STYLE = "#co-names{position:absolute;inset:0;overflow:hidden;pointer-events:none}" +
6
+ `.co-name{position:absolute;left:0;top:0;margin:0;white-space:nowrap;text-align:center;pointer-events:none;will-change:transform;letter-spacing:${COUNTRY_LETTER_SPACING}em;` +
7
+ "font-family:var(--chikyu-country-font,system-ui,-apple-system,'Segoe UI',sans-serif);font-weight:var(--chikyu-country-weight,600);color:var(--chikyu-country-colour,rgba(255,244,214,.92));" +
8
+ "text-shadow:0 0 calc(var(--chikyu-country-halo-width,3) * 1px) var(--chikyu-country-halo,#140c00),0 0 calc(var(--chikyu-country-halo-width,3) * 1px) var(--chikyu-country-halo,#140c00)}.co-name[hidden]{display:none}";
9
+ const DEFAULTS = { smallest: 10, largest: 16 };
10
+ const worldGeo = async () => (await import("@johnmorrisdotca/chizu/world-geo")).default;
11
+ /**
12
+ * Makes the layer of one element, inside its shadow root. Nothing is loaded, and nothing is added to the root, until `country-names` is there.
13
+ *
14
+ * @param options - The attribute reader, the language and the shadow root.
15
+ * @returns The host.
16
+ */
17
+ export function createCountryHost(options) {
18
+ const { root } = options;
19
+ const doc = root.ownerDocument;
20
+ let spots = null;
21
+ let asked = false;
22
+ let failed = false;
23
+ let last = null;
24
+ let taken = [];
25
+ let shown = [];
26
+ let renders = 0;
27
+ let style = {};
28
+ let box;
29
+ const pool = [];
30
+ let max = readCountryNames(options.attribute("country-names"));
31
+ let usedLang;
32
+ // set by `dispose`: an outline load that finishes after it is ignored, so it makes no box and tells no one
33
+ let disposed = false;
34
+ const attach = () => {
35
+ if (box)
36
+ return;
37
+ box = doc.createElement("div");
38
+ box.id = "co-names";
39
+ box.setAttribute("aria-hidden", "true");
40
+ // under the other names: the city names' box, when it is there, comes after this one
41
+ const cities = root.getElementById("cn-canvas");
42
+ if (cities)
43
+ root.insertBefore(box, cities);
44
+ else
45
+ root.append(box);
46
+ vars();
47
+ };
48
+ const clear = () => {
49
+ for (const name of pool)
50
+ name.hidden = true;
51
+ shown = [];
52
+ };
53
+ function vars() {
54
+ if (!box)
55
+ return;
56
+ const set = (name, value) => {
57
+ if (value === undefined)
58
+ box.style.removeProperty(name);
59
+ else
60
+ box.style.setProperty(name, String(value));
61
+ };
62
+ set("--chikyu-country-font", style.font);
63
+ set("--chikyu-country-weight", style.weight);
64
+ set("--chikyu-country-colour", style.colour);
65
+ set("--chikyu-country-halo", style.halo);
66
+ set("--chikyu-country-halo-width", style.haloWidth);
67
+ }
68
+ /** The width and height of a name in the font it is drawn in: a canvas set to the layer's own font and weight, so a fallback font with wider letters or taller lines is measured as it is. */
69
+ let ruler;
70
+ const measurer = () => {
71
+ if (ruler === undefined)
72
+ ruler = doc.createElement("canvas").getContext?.("2d") ?? null;
73
+ const context = ruler;
74
+ if (!context || typeof context.measureText !== "function")
75
+ return undefined;
76
+ const host = root.host ? getComputedStyle(root.host) : undefined;
77
+ const family = style.font ?? (host?.getPropertyValue("--chikyu-country-font").trim() || "system-ui, -apple-system, 'Segoe UI', sans-serif");
78
+ const weight = style.weight ?? (host?.getPropertyValue("--chikyu-country-weight").trim() || 600);
79
+ return (text, size) => {
80
+ context.font = `${weight} ${size}px ${family}`;
81
+ const metrics = context.measureText(text);
82
+ const ink = (metrics.actualBoundingBoxAscent ?? 0) + (metrics.actualBoundingBoxDescent ?? 0);
83
+ const line = (metrics.fontBoundingBoxAscent ?? 0) + (metrics.fontBoundingBoxDescent ?? 0);
84
+ return { width: metrics.width + [...text].length * size * COUNTRY_LETTER_SPACING, height: Math.max(ink + 2, line) };
85
+ };
86
+ };
87
+ const ensure = () => {
88
+ if (asked)
89
+ return;
90
+ asked = true;
91
+ let loading;
92
+ try {
93
+ loading = (options.load ?? worldGeo)();
94
+ }
95
+ catch (error) {
96
+ failed = true;
97
+ options.onError(error);
98
+ return;
99
+ }
100
+ loading.then((shapes) => {
101
+ if (disposed)
102
+ return;
103
+ spots = countrySpots(shapes);
104
+ compute();
105
+ }, (error) => {
106
+ if (disposed)
107
+ return;
108
+ failed = true;
109
+ options.onError(error);
110
+ });
111
+ };
112
+ function compute() {
113
+ const frame = last;
114
+ if (max === null || !frame)
115
+ return;
116
+ ensure();
117
+ if (!spots)
118
+ return;
119
+ attach();
120
+ usedLang = options.language();
121
+ shown = layoutCountryNames(spots, frame, usedLang, { max, smallest: style.smallest ?? DEFAULTS.smallest, largest: style.largest ?? DEFAULTS.largest, taken, measure: measurer() });
122
+ place();
123
+ }
124
+ function place() {
125
+ if (!box)
126
+ return;
127
+ renders += 1;
128
+ while (pool.length < Math.min(COUNTRY_NAMES_MAX, shown.length)) {
129
+ const name = doc.createElement("span");
130
+ name.className = "co-name";
131
+ box.append(name);
132
+ pool.push(name);
133
+ }
134
+ for (let i = 0; i < pool.length; i += 1) {
135
+ const name = pool[i];
136
+ const one = shown[i];
137
+ if (!one) {
138
+ if (!name.hidden)
139
+ name.hidden = true;
140
+ continue;
141
+ }
142
+ if (name.textContent !== one.text)
143
+ name.textContent = one.text;
144
+ const font = `${one.size}px`;
145
+ if (name.style.fontSize !== font)
146
+ name.style.fontSize = font;
147
+ const line = `${one.height}px`;
148
+ if (name.style.lineHeight !== line) {
149
+ name.style.lineHeight = line;
150
+ name.style.height = line;
151
+ }
152
+ const wide = `${Math.ceil(one.width)}px`;
153
+ if (name.style.width !== wide)
154
+ name.style.width = wide;
155
+ name.hidden = false;
156
+ name.style.transform = `translate(${Math.round(one.left)}px,${Math.round(one.top)}px)`;
157
+ }
158
+ }
159
+ // the family's chooser tells the document when the page's language changes: the names are written again, though nothing else is drawn
160
+ const onLanguage = () => queueMicrotask(() => {
161
+ if (max !== null && last && usedLang !== undefined && usedLang !== options.language())
162
+ compute();
163
+ });
164
+ doc.addEventListener("kazoku-languagechange", onLanguage);
165
+ // a font arrives: the names are measured in the font they are drawn in, so they are laid out again
166
+ const onFonts = () => {
167
+ if (max !== null && last)
168
+ compute();
169
+ };
170
+ doc.fonts?.addEventListener?.("loadingdone", onFonts);
171
+ return {
172
+ frame(next, boxes = []) {
173
+ last = next;
174
+ taken = boxes;
175
+ if (max === null)
176
+ return;
177
+ if (!next) {
178
+ clear();
179
+ return;
180
+ }
181
+ compute();
182
+ },
183
+ refresh() {
184
+ max = readCountryNames(options.attribute("country-names"));
185
+ if (max === null) {
186
+ clear();
187
+ return;
188
+ }
189
+ compute();
190
+ },
191
+ setStyle(next) {
192
+ style = { ...next };
193
+ vars();
194
+ compute();
195
+ },
196
+ get shown() {
197
+ return shown;
198
+ },
199
+ get stats() {
200
+ return { on: max !== null, max: max ?? 0, countries: spots?.countries.length ?? 0, names: shown.length, renders, failed };
201
+ },
202
+ dispose() {
203
+ disposed = true;
204
+ doc.removeEventListener("kazoku-languagechange", onLanguage);
205
+ doc.fonts?.removeEventListener?.("loadingdone", onFonts);
206
+ box?.remove();
207
+ box = undefined;
208
+ pool.length = 0;
209
+ shown = [];
210
+ },
211
+ };
212
+ }