@mark1russell7/cartography 0.1.0 → 0.1.2

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.
package/dist/index.js CHANGED
@@ -15,71 +15,6 @@ var MapError = class extends Error {
15
15
  this.code = code;
16
16
  }
17
17
  };
18
- // src/filter.ts
19
- /** This function gives the kind of a geometry. */
20
- function geometryKind(geometry) {
21
- switch (geometry.type) {
22
- case "Point":
23
- case "MultiPoint": return "point";
24
- case "LineString":
25
- case "MultiLineString": return "line";
26
- case "Polygon":
27
- case "MultiPolygon": return "area";
28
- case "GeometryCollection": {
29
- const kinds = new Set(geometry.geometries.map(geometryKind));
30
- return kinds.size === 1 ? [...kinds][0] : "mixed";
31
- }
32
- }
33
- }
34
- /** This function tells if a feature matches a filter. A feature with no geometry matches no `{ geometry }` filter. */
35
- function matchesFilter(filter, feature) {
36
- if ("all" in filter) return filter.all.every((item) => matchesFilter(item, feature));
37
- if ("any" in filter) return filter.any.some((item) => matchesFilter(item, feature));
38
- if ("not" in filter) return !matchesFilter(filter.not, feature);
39
- if ("geometry" in filter) return feature.geometry !== null && geometryKind(feature.geometry) === filter.geometry;
40
- const properties = feature.properties ?? {};
41
- const has = Object.hasOwn(properties, filter.property);
42
- if ("exists" in filter) return has === filter.exists;
43
- return has && filter.in.includes(properties[filter.property]);
44
- }
45
- const KINDS = [
46
- "point",
47
- "line",
48
- "area",
49
- "mixed"
50
- ];
51
- /**
52
- * This function refuses a value that is not a `Filter`, for example a filter from JSON.
53
- *
54
- * @throws MapError - The code is `filter`.
55
- */
56
- function checkFilter(filter, path = "filter") {
57
- const fail = (reason) => {
58
- throw new MapError("filter", `${path}: ${reason}`);
59
- };
60
- if (typeof filter !== "object" || filter === null || Array.isArray(filter)) fail("a filter must be an object");
61
- const value = filter;
62
- const keys = Object.keys(value).toSorted().join(",");
63
- if (keys === "all" || keys === "any") {
64
- const items = value[keys];
65
- if (!Array.isArray(items)) fail(`the member ${keys} must be an array`);
66
- items.forEach((item, i) => checkFilter(item, `${path}.${keys}[${i}]`));
67
- } else if (keys === "not") checkFilter(value["not"], `${path}.not`);
68
- else if (keys === "geometry") {
69
- if (!KINDS.includes(value["geometry"])) fail(`the geometry must be one of ${KINDS.join(", ")}`);
70
- } else if (keys === "in,property" || keys === "exists,property") {
71
- if (typeof value["property"] !== "string") fail("the property must be a string");
72
- if (keys === "exists,property" && typeof value["exists"] !== "boolean") fail("the member exists must be true or false");
73
- if (keys === "in,property") {
74
- const items = value["in"];
75
- if (!Array.isArray(items) || !items.every((item) => [
76
- "string",
77
- "number",
78
- "boolean"
79
- ].includes(typeof item))) fail("the member in must be an array of strings, numbers and booleans");
80
- }
81
- } else fail(`the members ${keys === "" ? "(none)" : keys} are not a form of a filter`);
82
- }
83
18
  // src/frame.ts
84
19
  /**
85
20
  * The frame of a map: the part of the Earth that the map shows, its scale and its size on the paper.
@@ -165,6 +100,237 @@ function frameBBox(frame) {
165
100
  }
166
101
  return bboxOfPoints(points);
167
102
  }
103
+ // src/atlas.ts
104
+ /** The default width of the overlap of neighbor pages, in millimetres. */
105
+ const ATLAS_OVERLAP_MM = 10;
106
+ /**
107
+ * This function gives the name of a column: A to Z, then AA, AB and the next names.
108
+ *
109
+ * @throws MapError - The code is `atlas`. The index is not an integer of 0 or more.
110
+ */
111
+ function columnName(index) {
112
+ if (!(Number.isInteger(index) && index >= 0)) throw new MapError("atlas", `The column ${index} is not an integer of 0 or more`);
113
+ let name = "";
114
+ for (let rest = index + 1; rest > 0; rest = Math.floor((rest - 1) / 26)) name = String.fromCharCode(65 + (rest - 1) % 26) + name;
115
+ return name;
116
+ }
117
+ /**
118
+ * This function gives the pages of an atlas: a grid of frames on the plane of the projection.
119
+ * The middle of the grid is at the center of the area.
120
+ *
121
+ * - Neighbor pages share a strip of `overlapMm` at their common edge.
122
+ * - The grid has the smallest number of columns and rows that shows the full circle.
123
+ * - Each page has the scale of the plan at its own center. For `azimuthalEquidistant` over 50 km, the edges of neighbor pages agree to 0.01 mm.
124
+ *
125
+ * @throws MapError - The code is `frame` or `atlas`.
126
+ */
127
+ function atlasPages(plan) {
128
+ const overlapMm = plan.overlapMm ?? 10;
129
+ checkFrame(plan);
130
+ if (!(Number.isFinite(plan.radiusMeters) && plan.radiusMeters > 0)) throw new MapError("atlas", `The radius ${plan.radiusMeters} of the atlas is not a finite number more than 0`);
131
+ if (!(Number.isFinite(overlapMm) && overlapMm >= 0 && overlapMm < Math.min(plan.widthMm, plan.heightMm) / 2)) throw new MapError("atlas", `The overlap ${overlapMm} of the atlas is not from 0 to less than half of the smaller side of the page`);
132
+ const middle = frameView(plan);
133
+ const origin = plan.projection.toPlane(plan.center);
134
+ const radiusMm = plan.radiusMeters * middle.mmPerMeter;
135
+ const stepX = plan.widthMm - overlapMm;
136
+ const stepY = plan.heightMm - overlapMm;
137
+ const columns = Math.max(1, Math.ceil((2 * radiusMm - plan.widthMm) / stepX) + 1);
138
+ const rows = Math.max(1, Math.ceil((2 * radiusMm - plan.heightMm) / stepY) + 1);
139
+ const offsetX = (column) => (column - (columns - 1) / 2) * stepX;
140
+ const offsetY = (row) => ((rows - 1) / 2 - row) * stepY;
141
+ const shows = (column, row) => {
142
+ if (column < 0 || column >= columns || row < 0 || row >= rows) return false;
143
+ const dx = Math.max(Math.abs(offsetX(column)) - plan.widthMm / 2, 0);
144
+ const dy = Math.max(Math.abs(offsetY(row)) - plan.heightMm / 2, 0);
145
+ return dx * dx + dy * dy < radiusMm * radiusMm;
146
+ };
147
+ const name = (column, row) => `${columnName(column)}${row + 1}`;
148
+ const pages = [];
149
+ for (let row = 0; row < rows; row += 1) for (let column = 0; column < columns; column += 1) {
150
+ if (!shows(column, row)) continue;
151
+ const center = plan.projection.fromPlane({
152
+ x: origin.x + offsetX(column) / middle.mmPerPlaneMeter,
153
+ y: origin.y + offsetY(row) / middle.mmPerPlaneMeter
154
+ });
155
+ const neighbors = {};
156
+ for (const [edge, dc, dr] of [
157
+ [
158
+ "top",
159
+ 0,
160
+ -1
161
+ ],
162
+ [
163
+ "right",
164
+ 1,
165
+ 0
166
+ ],
167
+ [
168
+ "bottom",
169
+ 0,
170
+ 1
171
+ ],
172
+ [
173
+ "left",
174
+ -1,
175
+ 0
176
+ ]
177
+ ]) if (shows(column + dc, row + dr)) neighbors[edge] = name(column + dc, row + dr);
178
+ const frame = {
179
+ projection: plan.projection,
180
+ center,
181
+ scale: plan.scale,
182
+ widthMm: plan.widthMm,
183
+ heightMm: plan.heightMm
184
+ };
185
+ pages.push({
186
+ id: name(column, row),
187
+ column,
188
+ row,
189
+ frame,
190
+ neighbors
191
+ });
192
+ }
193
+ return {
194
+ plan,
195
+ columns,
196
+ rows,
197
+ pages
198
+ };
199
+ }
200
+ /**
201
+ * This function gives the outline of each page of an atlas as a polygon feature, with the name of the page in the property `id`.
202
+ * A layer of an index map draws them. Each edge has `pointsPerEdge` points, because the edges of the pages are curves on the Earth.
203
+ *
204
+ * @throws MapError - The code is `atlas`. The number of points is not an integer of 1 or more.
205
+ */
206
+ function atlasOutlines(atlas, pointsPerEdge = 16) {
207
+ if (!(Number.isInteger(pointsPerEdge) && pointsPerEdge >= 1)) throw new MapError("atlas", `The number of points ${pointsPerEdge} of an edge is not an integer of 1 or more`);
208
+ return atlas.pages.map((page) => {
209
+ const view = frameView(page.frame);
210
+ const { widthMm: w, heightMm: h } = page.frame;
211
+ const ring = [];
212
+ for (let i = 0; i < pointsPerEdge; i += 1) ring.push(lonLat(view.fromPaper({
213
+ x: i / pointsPerEdge * w,
214
+ y: 0
215
+ })));
216
+ for (let i = 0; i < pointsPerEdge; i += 1) ring.push(lonLat(view.fromPaper({
217
+ x: w,
218
+ y: i / pointsPerEdge * h
219
+ })));
220
+ for (let i = 0; i < pointsPerEdge; i += 1) ring.push(lonLat(view.fromPaper({
221
+ x: w - i / pointsPerEdge * w,
222
+ y: h
223
+ })));
224
+ for (let i = 0; i < pointsPerEdge; i += 1) ring.push(lonLat(view.fromPaper({
225
+ x: 0,
226
+ y: h - i / pointsPerEdge * h
227
+ })));
228
+ ring.reverse();
229
+ ring.push(ring[0]);
230
+ return {
231
+ type: "Feature",
232
+ geometry: {
233
+ type: "Polygon",
234
+ coordinates: [ring]
235
+ },
236
+ properties: { id: page.id }
237
+ };
238
+ });
239
+ }
240
+ /**
241
+ * This function gives the frame of an index map of an atlas. The frame shows all the pages of the grid in the space, at the largest scale.
242
+ * Its center is the middle of the grid.
243
+ *
244
+ * @throws MapError - The code is `frame`.
245
+ */
246
+ function atlasIndexFrame(atlas, widthMm, heightMm) {
247
+ const { plan } = atlas;
248
+ checkFrame({
249
+ ...plan,
250
+ widthMm,
251
+ heightMm
252
+ });
253
+ const overlapMm = plan.overlapMm ?? 10;
254
+ const gridWidthMm = (atlas.columns - 1) * (plan.widthMm - overlapMm) + plan.widthMm;
255
+ const gridHeightMm = (atlas.rows - 1) * (plan.heightMm - overlapMm) + plan.heightMm;
256
+ const scale = plan.scale * Math.max(gridWidthMm / widthMm, gridHeightMm / heightMm);
257
+ return {
258
+ projection: plan.projection,
259
+ center: plan.center,
260
+ scale,
261
+ widthMm,
262
+ heightMm
263
+ };
264
+ }
265
+ /** This function gives the GeoJSON position `[lon, lat]` of a point. */
266
+ function lonLat(point) {
267
+ return [point.lon, point.lat];
268
+ }
269
+ // src/filter.ts
270
+ /** This function gives the kind of a geometry. */
271
+ function geometryKind(geometry) {
272
+ switch (geometry.type) {
273
+ case "Point":
274
+ case "MultiPoint": return "point";
275
+ case "LineString":
276
+ case "MultiLineString": return "line";
277
+ case "Polygon":
278
+ case "MultiPolygon": return "area";
279
+ case "GeometryCollection": {
280
+ const kinds = new Set(geometry.geometries.map(geometryKind));
281
+ return kinds.size === 1 ? [...kinds][0] : "mixed";
282
+ }
283
+ }
284
+ }
285
+ /** This function tells if a feature matches a filter. A feature with no geometry matches no `{ geometry }` filter. */
286
+ function matchesFilter(filter, feature) {
287
+ if ("all" in filter) return filter.all.every((item) => matchesFilter(item, feature));
288
+ if ("any" in filter) return filter.any.some((item) => matchesFilter(item, feature));
289
+ if ("not" in filter) return !matchesFilter(filter.not, feature);
290
+ if ("geometry" in filter) return feature.geometry !== null && geometryKind(feature.geometry) === filter.geometry;
291
+ const properties = feature.properties ?? {};
292
+ const has = Object.hasOwn(properties, filter.property);
293
+ if ("exists" in filter) return has === filter.exists;
294
+ return has && filter.in.includes(properties[filter.property]);
295
+ }
296
+ const KINDS = [
297
+ "point",
298
+ "line",
299
+ "area",
300
+ "mixed"
301
+ ];
302
+ /**
303
+ * This function refuses a value that is not a `Filter`, for example a filter from JSON.
304
+ *
305
+ * @throws MapError - The code is `filter`.
306
+ */
307
+ function checkFilter(filter, path = "filter") {
308
+ const fail = (reason) => {
309
+ throw new MapError("filter", `${path}: ${reason}`);
310
+ };
311
+ if (typeof filter !== "object" || filter === null || Array.isArray(filter)) fail("a filter must be an object");
312
+ const value = filter;
313
+ const keys = Object.keys(value).toSorted().join(",");
314
+ if (keys === "all" || keys === "any") {
315
+ const items = value[keys];
316
+ if (!Array.isArray(items)) fail(`the member ${keys} must be an array`);
317
+ items.forEach((item, i) => checkFilter(item, `${path}.${keys}[${i}]`));
318
+ } else if (keys === "not") checkFilter(value["not"], `${path}.not`);
319
+ else if (keys === "geometry") {
320
+ if (!KINDS.includes(value["geometry"])) fail(`the geometry must be one of ${KINDS.join(", ")}`);
321
+ } else if (keys === "in,property" || keys === "exists,property") {
322
+ if (typeof value["property"] !== "string") fail("the property must be a string");
323
+ if (keys === "exists,property" && typeof value["exists"] !== "boolean") fail("the member exists must be true or false");
324
+ if (keys === "in,property") {
325
+ const items = value["in"];
326
+ if (!Array.isArray(items) || !items.every((item) => [
327
+ "string",
328
+ "number",
329
+ "boolean"
330
+ ].includes(typeof item))) fail("the member in must be an array of strings, numbers and booleans");
331
+ }
332
+ } else fail(`the members ${keys === "" ? "(none)" : keys} are not a form of a filter`);
333
+ }
168
334
  // src/style.ts
169
335
  /**
170
336
  * The black and white styles of the layers: lines with dashes, areas with gray levels and hatches, and point symbols.
@@ -525,7 +691,7 @@ function areaOnFrame(area, view) {
525
691
  * - Each point symbol of the layers and the north arrow are obstacles too.
526
692
  * - A text with a part on the frame and no free place is in `skipped`. A text with no part on the frame is in neither list.
527
693
  *
528
- * @param obstacles - The boxes on the paper that no label covers, as the middle and the half size in millimetres.
694
+ * @param obstacles - The boxes on the paper that no label covers, as the middle and the half size in millimetres. A box with `halfHeight` has the half width `half`.
529
695
  * @throws MapError - The code is `label`: the width of a text from `measure` is not a finite number of 0 or more.
530
696
  */
531
697
  function placeLabels(layers, view, font, obstacles = []) {
@@ -534,7 +700,7 @@ function placeLabels(layers, view, font, obstacles = []) {
534
700
  x: o.x,
535
701
  y: o.y,
536
702
  hw: o.half,
537
- hh: o.half,
703
+ hh: o.halfHeight ?? o.half,
538
704
  angle: 0
539
705
  });
540
706
  for (const layer of layers) {
@@ -650,7 +816,7 @@ function labelsSvg(placement, font) {
650
816
  }
651
817
  // src/marks.ts
652
818
  /**
653
- * The marks of a map: the scale bar and the north arrow.
819
+ * The marks of a map: the scale bar, the north arrow and the texts at the edges of the frame.
654
820
  *
655
821
  * @packageDocumentation
656
822
  */
@@ -711,12 +877,64 @@ function scaleBarSvg(x, y, length, mmPerMeter) {
711
877
  function northArrowSvg(x, y, northDegrees) {
712
878
  return `<g class="north-arrow" transform="translate(${mm(x)} ${mm(y)}) rotate(${mm(northDegrees)})"><circle r="4.5" fill="#ffffff" stroke="#000000" stroke-width="0.2"/><path d="M0 -3.6L1.6 1.2L0 0.4L-1.6 1.2Z" fill="#000000"/><text y="3.9" font-size="2.2" text-anchor="middle">N</text></g>`;
713
879
  }
880
+ /** The four edges of a frame, in the sequence of the marks. */
881
+ const FRAME_EDGES = [
882
+ "top",
883
+ "right",
884
+ "bottom",
885
+ "left"
886
+ ];
887
+ /** The size of the font of a text at an edge of the frame, in millimetres. */
888
+ const EDGE_TEXT_MM = 2.6;
889
+ /** The space in the box of an edge text around the arrow and the text, and the size of the arrow, in millimetres. */
890
+ const EDGE = {
891
+ pad: .8,
892
+ arrow: 1.8,
893
+ gap: .7
894
+ };
895
+ /** The angle of the arrow of each edge. The arrow points out of the frame. */
896
+ const EDGE_TURN = {
897
+ top: 0,
898
+ right: 90,
899
+ bottom: 180,
900
+ left: 270
901
+ };
902
+ /**
903
+ * This function gives the marks of the texts at the middle of the edges of a frame, in the sequence top, right, bottom and left.
904
+ * An edge with no text has no mark.
905
+ *
906
+ * @param measure - This function gives the width of a text in millimetres at the size `EDGE_TEXT_MM`.
907
+ */
908
+ function edgeMarks(widthMm, heightMm, texts, measure) {
909
+ return FRAME_EDGES.flatMap((edge) => {
910
+ const text = texts[edge];
911
+ if (text === void 0) return [];
912
+ const boxWidth = 2 * EDGE.pad + EDGE.arrow + EDGE.gap + measure(text);
913
+ const boxHeight = 2 * EDGE.pad + EDGE_TEXT_MM;
914
+ const x = edge === "left" ? boxWidth / 2 : edge === "right" ? widthMm - boxWidth / 2 : widthMm / 2;
915
+ const y = edge === "top" ? boxHeight / 2 : edge === "bottom" ? heightMm - boxHeight / 2 : heightMm / 2;
916
+ const left = x - boxWidth / 2;
917
+ const top = y - boxHeight / 2;
918
+ const arrowX = left + EDGE.pad + EDGE.arrow / 2;
919
+ const half = EDGE.arrow / 2;
920
+ const svg = `<g class="edge-${edge}"><rect x="${mm(left)}" y="${mm(top)}" width="${mm(boxWidth)}" height="${mm(boxHeight)}" fill="#ffffff" stroke="#000000" stroke-width="0.2"/><path transform="translate(${mm(arrowX)} ${mm(y)}) rotate(${EDGE_TURN[edge]})" d="M0 ${mm(-half)}L${mm(half)} ${mm(half)}L${mm(-half)} ${mm(half)}Z" fill="#000000"/><text x="${mm(arrowX + half + EDGE.gap)}" y="${mm(y + EDGE_TEXT_MM * .35)}" font-size="${EDGE_TEXT_MM}" font-weight="bold">${escapeHtml(text)}</text></g>`;
921
+ return [{
922
+ edge,
923
+ x,
924
+ y,
925
+ halfWidth: boxWidth / 2,
926
+ halfHeight: boxHeight / 2,
927
+ svg
928
+ }];
929
+ });
930
+ }
714
931
  // src/render.ts
715
932
  /**
716
933
  * A map as data, and its render to SVG.
717
934
  *
718
935
  * @packageDocumentation
719
936
  */
937
+ const LEGEND_PLACES = ["below", "side"];
720
938
  const ID = /^[a-z][a-z0-9-]*$/;
721
939
  function checkId(id, what) {
722
940
  if (!ID.test(id)) throw new MapError("id", `The identifier "${id}" of the ${what} is not lower case letters, digits and hyphens that start with a letter`);
@@ -735,6 +953,7 @@ function checkSource(source, layer) {
735
953
  function checkMap(map) {
736
954
  checkId(map.id, "map");
737
955
  frameView(map.frame);
956
+ if (map.legendPlace !== void 0 && !LEGEND_PLACES.includes(map.legendPlace)) throw new MapError("style", `The place of the legend "${String(map.legendPlace)}" is not "below" or "side"`);
738
957
  const ids = /* @__PURE__ */ new Set();
739
958
  for (const layer of map.layers) {
740
959
  checkId(layer.id, "layer");
@@ -746,6 +965,13 @@ function checkMap(map) {
746
965
  if (layer.label !== void 0) checkLabelRule(layer.label, layer.id);
747
966
  if (layer.simplifyMm !== void 0 && !(Number.isFinite(layer.simplifyMm) && layer.simplifyMm > 0)) throw new MapError("style", `The layer "${layer.id}": the tolerance ${layer.simplifyMm} is not a finite number more than 0`);
748
967
  }
968
+ if (map.edges !== void 0) {
969
+ if (typeof map.edges !== "object" || map.edges === null) throw new MapError("label", "The edge texts of the map are not an object");
970
+ for (const [edge, text] of Object.entries(map.edges)) {
971
+ if (!FRAME_EDGES.includes(edge)) throw new MapError("label", `The edge "${edge}" is not top, right, bottom or left`);
972
+ if (text !== void 0 && (typeof text !== "string" || text.trim() === "")) throw new MapError("label", `The text of the edge "${edge}" is not a text that is not empty`);
973
+ }
974
+ }
749
975
  }
750
976
  /** The box of the points on the paper that a feature uses. */
751
977
  var PaperBox = class {
@@ -830,12 +1056,22 @@ const NORTH_ARROW = {
830
1056
  inset: 6.5,
831
1057
  half: 4.7
832
1058
  };
1059
+ /** This function gives the marks of the edge texts of a map. Without a font, the width of a text is an estimate. */
1060
+ function edgeMarksOf(map, font) {
1061
+ const measure = (text) => font === void 0 ? text.length * EDGE_TEXT_MM * CHARACTER_WIDTH : font.measure(text, EDGE_TEXT_MM);
1062
+ return edgeMarks(map.frame.widthMm, map.frame.heightMm, map.edges ?? {}, measure);
1063
+ }
833
1064
  function placementOf(map, features, view, font) {
834
- const obstacles = map.northArrow === false ? [] : [{
1065
+ const obstacles = [...map.northArrow === false ? [] : [{
835
1066
  x: map.frame.widthMm - NORTH_ARROW.inset,
836
1067
  y: NORTH_ARROW.inset,
837
1068
  half: NORTH_ARROW.half
838
- }];
1069
+ }], ...edgeMarksOf(map, font).map((mark) => ({
1070
+ x: mark.x,
1071
+ y: mark.y,
1072
+ half: mark.halfWidth,
1073
+ halfHeight: mark.halfHeight
1074
+ }))];
839
1075
  return placeLabels(map.layers.map((layer, i) => ({
840
1076
  id: layer.id,
841
1077
  features: features[i],
@@ -877,6 +1113,110 @@ function swatch(style, x, y, fill) {
877
1113
  function thousands(value) {
878
1114
  return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
879
1115
  }
1116
+ /** The space between the frame and the column of the legend at the side, in millimetres. */
1117
+ const SIDE_GAP_MM = 3;
1118
+ /** The space above the first row of the column of the legend at the side, in millimetres. */
1119
+ const SIDE_TOP_MM = 1;
1120
+ /** The least width of the column of the legend at the side, in millimetres. */
1121
+ const SIDE_LEAST_WIDTH_MM = 30;
1122
+ /** The space between the scale bars and the legend in the column at the side, in millimetres. */
1123
+ const SIDE_GROUP_GAP_MM = 1.5;
1124
+ /** The space at the right of a scale bar in the column at the side for its label, in millimetres. */
1125
+ const SCALE_LABEL_MM = 12;
1126
+ /** The size of the font of the legend texts, in millimetres. */
1127
+ const LEGEND_TEXT_MM = 2.4;
1128
+ /** The distance from the left side of a swatch to its text, in millimetres. */
1129
+ const LEGEND_TEXT_X_MM = 7.5;
1130
+ /** The width of a character of a legend text, as a part of the size of the font, when the options have no font. */
1131
+ const CHARACTER_WIDTH = .6;
1132
+ /** This function gives the font that measures the legend texts: the label font of the options, if it has a measure. */
1133
+ function measureFontOf(options) {
1134
+ const font = options.labelFont;
1135
+ return font !== void 0 && typeof font.measure === "function" ? font : void 0;
1136
+ }
1137
+ function legendLayout(map, font) {
1138
+ const units = map.scaleBar ?? "both";
1139
+ const bars = units === "none" ? [] : units === "both" ? ["metric", "imperial"] : [units];
1140
+ const texts = map.layers.flatMap((layer) => layer.legend === void 0 ? [] : [layer.legend]);
1141
+ const lines = attributionLines(map);
1142
+ const place = map.legendPlace ?? "below";
1143
+ if (place === "below" || bars.length + texts.length === 0) return {
1144
+ bars,
1145
+ lines,
1146
+ columnMm: 0,
1147
+ columnHeightMm: 0,
1148
+ blockMm: place === "below" ? Math.max(bars.length, Math.ceil(texts.length / 2)) * SCALE_BAR_ROW_MM : 0
1149
+ };
1150
+ const width = (text) => font === void 0 ? text.length * LEGEND_TEXT_MM * CHARACTER_WIDTH : font.measure(text, LEGEND_TEXT_MM);
1151
+ const widest = Math.max(0, ...texts.map(width));
1152
+ const columnMm = Math.max(SIDE_LEAST_WIDTH_MM, LEGEND_TEXT_X_MM + widest + 1);
1153
+ const gap = bars.length > 0 && texts.length > 0 ? SIDE_GROUP_GAP_MM : 0;
1154
+ return {
1155
+ bars,
1156
+ lines,
1157
+ columnMm,
1158
+ columnHeightMm: SIDE_TOP_MM + (bars.length + texts.length) * SCALE_BAR_ROW_MM + gap,
1159
+ blockMm: 0
1160
+ };
1161
+ }
1162
+ function marginsOf(layout) {
1163
+ return {
1164
+ rightMm: layout.columnMm === 0 ? 0 : SIDE_GAP_MM + layout.columnMm,
1165
+ belowMm: 2 + layout.blockMm + 2.5 + (layout.lines.length - 1) * 3 + 1.5,
1166
+ leastHeightMm: layout.columnHeightMm
1167
+ };
1168
+ }
1169
+ /**
1170
+ * This function gives the space of the SVG of a map around its frame, for the place of the legend of the map. The
1171
+ * size of the frame does not change it.
1172
+ *
1173
+ * - The label font of the options measures the legend texts. With no font, each character is 0.6 of the size of the font.
1174
+ * - The SVG of the map is `rightMm` wider and `belowMm` taller than its frame.
1175
+ *
1176
+ * @throws MapError - The map is not correct, as `checkMap` tells.
1177
+ */
1178
+ function mapMargins(map, options = {}) {
1179
+ checkMap(map);
1180
+ return marginsOf(legendLayout(map, measureFontOf(options)));
1181
+ }
1182
+ /**
1183
+ * This function gives the frame with the largest area for a map in one of a list of spaces, and the place of its
1184
+ * legend. The SVG of the map with that frame and that place fits that space.
1185
+ *
1186
+ * - Give one space for each choice of the caller, for example a paper upright and the same paper in landscape.
1187
+ * - The scale of the map does not change, so a larger frame shows more ground.
1188
+ * - The size of the frame of the map does not change the result.
1189
+ * - With two choices of equal area, the first place of the options wins, and then the first space.
1190
+ *
1191
+ * @throws MapError - The map is not correct, a place or a space is not correct, or no choice leaves space for a frame.
1192
+ */
1193
+ function fitFrame(map, spaces, options = {}) {
1194
+ checkMap(map);
1195
+ for (const { widthMm, heightMm } of spaces) if (![widthMm, heightMm].every((value) => Number.isFinite(value) && value > 0)) throw new MapError("frame", `The space ${widthMm} by ${heightMm} mm is not two finite numbers more than 0`);
1196
+ const places = options.places ?? LEGEND_PLACES;
1197
+ const font = measureFontOf(options);
1198
+ let best;
1199
+ for (const place of places) {
1200
+ if (!LEGEND_PLACES.includes(place)) throw new MapError("style", `The place of the legend "${String(place)}" is not "below" or "side"`);
1201
+ const margins = marginsOf(legendLayout({
1202
+ ...map,
1203
+ legendPlace: place
1204
+ }, font));
1205
+ for (const [index, { widthMm, heightMm }] of spaces.entries()) {
1206
+ const frameWidth = widthMm - margins.rightMm;
1207
+ const frameHeight = heightMm - margins.belowMm;
1208
+ if (!(frameWidth > 0 && frameHeight > 0 && frameHeight >= margins.leastHeightMm)) continue;
1209
+ if (best === void 0 || frameWidth * frameHeight > best.widthMm * best.heightMm) best = {
1210
+ widthMm: frameWidth,
1211
+ heightMm: frameHeight,
1212
+ legendPlace: place,
1213
+ space: index
1214
+ };
1215
+ }
1216
+ }
1217
+ if (best === void 0) throw new MapError("frame", "No space of the list has space for a frame after the legend");
1218
+ return best;
1219
+ }
880
1220
  /** This function gives the lines of the attribution block: the scale, the projection and each source one time. */
881
1221
  function attributionLines(map) {
882
1222
  const lines = [`Scale 1:${thousands(map.frame.scale)} at the center. Projection: ${map.frame.projection.name}.`];
@@ -893,6 +1233,8 @@ function attributionLines(map) {
893
1233
  * This function gives the SVG of a map. The units of the SVG are millimetres, for a print at the scale of the frame.
894
1234
  *
895
1235
  * - The map is at the top. Below it are the scale bars, the legend and the attribution block.
1236
+ * - With the place `side`, the scale bars and the legend are in a column at the right of the frame. The attribution
1237
+ * block stays below.
896
1238
  * - The layers are in their sequence, from the bottom to the top. The frame clips each layer.
897
1239
  * - A feature that is not on the frame is not in the SVG.
898
1240
  * - Each identifier in the SVG starts with the identifier of the map. Thus two maps can be in one HTML page.
@@ -921,29 +1263,35 @@ function renderMap(map, options = {}) {
921
1263
  return `<g id="${map.id}-${layer.id}">${body}</g>`;
922
1264
  });
923
1265
  const labels = font === void 0 ? "" : labelsSvg(placementOf(map, features, view, font), font);
924
- const top = h + 2;
925
- const units = map.scaleBar ?? "both";
926
- const bars = units === "none" ? [] : units === "both" ? ["metric", "imperial"] : [units];
927
- const maxMeters = .3 * w / view.mmPerMeter;
928
- const scaleBars = bars.map((unit, i) => scaleBarSvg(.5, top + i * SCALE_BAR_ROW_MM, scaleBarLength(maxMeters, unit), view.mmPerMeter)).join("");
1266
+ const layout = legendLayout(map, measureFontOf(options));
1267
+ const side = layout.columnMm > 0;
1268
+ const { bars, lines } = layout;
1269
+ const top = (side ? Math.max(h, layout.columnHeightMm) : h) + 2;
1270
+ const sideX = w + SIDE_GAP_MM;
1271
+ const maxMeters = (side ? layout.columnMm - SCALE_LABEL_MM : .3 * w) / view.mmPerMeter;
1272
+ const scaleBars = bars.map((unit, i) => {
1273
+ const length = scaleBarLength(maxMeters, unit);
1274
+ return side ? scaleBarSvg(sideX, SIDE_TOP_MM + i * SCALE_BAR_ROW_MM, length, view.mmPerMeter) : scaleBarSvg(.5, top + i * SCALE_BAR_ROW_MM, length, view.mmPerMeter);
1275
+ }).join("");
929
1276
  const legendLayers = map.layers.flatMap((layer, i) => layer.legend === void 0 ? [] : [{
930
1277
  layer,
931
1278
  fill: fills[i]
932
1279
  }]);
933
1280
  const columnWidth = w * .275;
1281
+ const sideTop = SIDE_TOP_MM + bars.length * SCALE_BAR_ROW_MM + (bars.length > 0 ? SIDE_GROUP_GAP_MM : 0);
934
1282
  const legend = legendLayers.map(({ layer, fill }, i) => {
935
- const x = w * .45 + i % 2 * columnWidth;
936
- const y = top + Math.floor(i / 2) * SCALE_BAR_ROW_MM - 1;
937
- return `${swatch(layer.style, x, y, fill)}<text x="${mm(x + 7.5)}" y="${mm(y + 2.9)}" font-size="2.4">${escapeHtml(layer.legend)}</text>`;
1283
+ const x = side ? sideX : w * .45 + i % 2 * columnWidth;
1284
+ const y = side ? sideTop + i * SCALE_BAR_ROW_MM : top + Math.floor(i / 2) * SCALE_BAR_ROW_MM - 1;
1285
+ return `${swatch(layer.style, x, y, fill)}<text x="${mm(x + LEGEND_TEXT_X_MM)}" y="${mm(y + 2.9)}" font-size="${LEGEND_TEXT_MM}">${escapeHtml(layer.legend)}</text>`;
938
1286
  }).join("");
939
- const blockHeight = Math.max(bars.length, Math.ceil(legendLayers.length / 2)) * SCALE_BAR_ROW_MM;
940
- const lines = attributionLines(map);
941
- const firstLine = top + blockHeight + 2.5;
1287
+ const firstLine = top + layout.blockMm + 2.5;
942
1288
  const attribution = lines.map((line, i) => `<text x="0.5" y="${mm(firstLine + i * 3)}" font-size="2.2">${escapeHtml(line)}</text>`).join("");
943
1289
  const total = firstLine + (lines.length - 1) * 3 + 1.5;
1290
+ const width = side ? sideX + layout.columnMm : w;
944
1291
  const arrow = map.northArrow === false ? "" : northArrowSvg(w - 6.5, 6.5, view.northDegrees);
945
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${mm(w)}mm" height="${mm(total)}mm" viewBox="0 0 ${mm(w)} ${mm(total)}" role="img" aria-label="${escapeAttribute(map.title)}" font-family="sans-serif"><title>${escapeHtml(map.title)}</title><defs>${defs.join("")}</defs><rect width="${mm(w)}" height="${mm(total)}" fill="#ffffff"/><g clip-path="url(#${map.id}-clip)">${layers.join("")}</g>${labels}<rect width="${mm(w)}" height="${mm(h)}" fill="none" stroke="#000000" stroke-width="0.3"/>${arrow}<g class="legend">${scaleBars}${legend}</g><g class="attribution">${attribution}</g></svg>`;
1292
+ const edges = edgeMarksOf(map, measureFontOf(options)).map((mark) => mark.svg).join("");
1293
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${mm(width)}mm" height="${mm(total)}mm" viewBox="0 0 ${mm(width)} ${mm(total)}" role="img" aria-label="${escapeAttribute(map.title)}" font-family="sans-serif"><title>${escapeHtml(map.title)}</title><defs>${defs.join("")}</defs><rect width="${mm(width)}" height="${mm(total)}" fill="#ffffff"/><g clip-path="url(#${map.id}-clip)">${layers.join("")}</g>${labels}<rect width="${mm(w)}" height="${mm(h)}" fill="none" stroke="#000000" stroke-width="0.3"/>${arrow}${edges}<g class="legend">${scaleBars}${legend}</g><g class="attribution">${attribution}</g></svg>`;
946
1294
  }
947
- export { MapError, SCALE_BAR_ROW_MM, attributionLines, checkFilter, checkFrame, checkLabelRule, checkMap, checkStyle, frameBBox, frameView, geometryKind, grayColor, hatchPattern, labelText, labelsSvg, mapLabels, matchesFilter, mm, niceNumber, northArrowSvg, placeLabels, pointSymbol, renderMap, scaleBarLength, scaleBarSvg, strokeAttributes };
1295
+ export { ATLAS_OVERLAP_MM, EDGE_TEXT_MM, FRAME_EDGES, MapError, SCALE_BAR_ROW_MM, atlasIndexFrame, atlasOutlines, atlasPages, attributionLines, checkFilter, checkFrame, checkLabelRule, checkMap, checkStyle, columnName, edgeMarks, fitFrame, frameBBox, frameView, geometryKind, grayColor, hatchPattern, labelText, labelsSvg, mapLabels, mapMargins, matchesFilter, mm, niceNumber, northArrowSvg, placeLabels, pointSymbol, renderMap, scaleBarLength, scaleBarSvg, strokeAttributes };
948
1296
 
949
1297
  //# sourceMappingURL=index.js.map