mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-20 23:16:17 -05:00
A map is exported as a PDF: a 1:24,000 quadrangle, in layers, on a sheet, which says where it is (#1006)
* The map can choose a 1:24,000 quadrangle to export (#971) The first part of exporting a map as a PDF: a grid of 7.5-minute quadrangles is drawn over the map, and a click chooses one. The grid is arithmetic, so it needs no data. Exporting itself is not here yet; the button is disabled. Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * A quadrangle of the map is exported as a PDF with a layer for each map layer (#972) * A quadrangle of the map is exported as a PDF with a layer for each map layer The browser draws the quadrangle off the screen at the size of a 1:24,000 sheet, once for each layer which is on, and the API puts the images in a PDF, each in a layer of its own which a reader can show and hide. A layer in which nothing is drawn is left out. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * The exported map's canvas keeps what was drawn, and an export's memory is bounded - The drawing buffer is asked for where this MapLibre reads it (canvasContextAttributes); as an option of the map it was ignored, so the canvas could be read after it was cleared. - Each layer's pixels are compressed in the PDF as the layer is added. PyMuPDF kept them uncompressed until the PDF was written: about 90 MB a layer of a quadrangle, all at once. - The pixels of all the layers together are limited, before any image is decoded. - pymupdf is imported when a PDF is made, not when the API starts. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An exported map says where on the Earth it is (#973) * An exported map says where on the Earth it is The PDF's page has a geospatial viewport (ISO 32000-2): the page is the map in Web Mercator, with the latitude and longitude of each corner. The corners are the edges of the picture the browser drew, read from the map which drew it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A map whose edge is the antimeridian can be exported The map's arithmetic puts the east edge of the last quadrangle before the antimeridian a rounding error past 180 degrees, and the export was refused. An edge within 1e-8 of a degree of 180 is at 180 (it is not wrapped to -180); a map which is really across the antimeridian is still refused. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An exported map is on a sheet: a margin, a grid, scale bars and notes (#974) * An exported map is on a sheet: a margin, a grid, scale bars and notes The map is put on a larger page with what a topographic map has around it: a title, the latitude and longitude of its corners and of ticks between them, scale bars (kilometers, miles, feet), and notes of the projection, the grid and where the map's data is from. Over the map is a 1,000 meter UTM grid, each line named in the margin. The grid and the margin are PDF layers of their own. The PDF says where the map is, not where the page is. The picker has a box to export the map alone. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * The scale of a narrow map is written under its name, not over it A quadrangle near a pole is two inches wide, which is not room for its name and its scale on one line. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An exported map says where a compass points (#975) * An exported map says where a compass points The sheet has a diagram of the three norths (true, grid and magnetic) beside its scale bars, and a note of how far magnetic north is from true north on the day the map was made, and how fast it moves. The declination is from the World Magnetic Model 2025 (NOAA NCEI and the British Geological Survey; public domain), whose coefficient file is shipped: nothing is downloaded. The model is good until 2030; outside its years nothing is said of a compass. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A corner of an exported map is not also a tick The edges of the picture the browser draws are a hair outside the quadrangle's, so the quadrangle's own edges were taken for ticks inside the map, and each was written over the coordinate of its corner. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A compass which passes due south has moved a little, not most of the way around Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * A map can be exported at 400 DPI (#976) The picker has a choice of 300 or 400 DPI. A map is drawn less sharp than was asked for, rather than refused, when it would be more pixels than the API makes a PDF of: a quadrangle near the equator, or one with many layers on. The picker says so while it draws. Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An exported quadrangle goes by the name the USGS gives it (#977) * An exported quadrangle goes by the name the USGS gives it The picker says what the chosen quadrangle is called, and the sheet's title, the PDF's title and the file's name have it. Where the USGS has no name, which is most of the world, a quadrangle goes by where it is, as before. The names are an index of the 65,600 7.5 minute quadrangles of The National Map (U.S. Geological Survey; public domain), which is shipped: nothing is downloaded. In Alaska a USGS quadrangle is wider than 7.5 minutes, so a quadrangle of the picker's grid there is "Part of" the one which has its middle. The places the tests of the map export are of are changed for others. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * An area half of which is the last quadrangle of the land is a part of it The middle of such an area is on the quadrangle's east or north edge, with no quadrangle beyond it, and it was given no name. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * The PDF of a map is made by a Job, which the browser watches (#978) * The PDF of a map is made by a Job, which the browser watches A PDF of a quadrangle is a minute or two of work on a Raspberry Pi 4, and the request which waited for it was cut off after a minute: only the smallest quadrangles could be exported there. Now the browser describes the map, sends the image of each layer in a request of its own, and starts a Job; it watches the Job, shows how far along it is, and fetches the PDF when the Job is done. Cancel stops the Job. The images are kept on disk until the PDF is made of them, and an export is removed when it is an hour old. The credits on the sheet are no longer cut off: an attribution which names many sources is each of them. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A cancelled map export stops, and is removed - A cancelled Job is not over until the thread making the PDF has stopped, so the next Job does not start beside it; the work can also be stopped while the sheet is drawn and the PDF written. - DELETE /api/map/export/<id> stops an export at any step and removes what was sent; the browser calls it when the person exporting cancels, while layers are sent as well as while the PDF is made. - An export whose Job is waiting or running is not removed for being old; one whose Job was cancelled is removed at once. - Cancel while the map is drawn stops the drawing between two layers. - Exports are kept in a directory made for this user alone, which is refused when it is a link or is another user's; only what is an export there is removed. - A request for the finished PDF which is lost is made again. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An overlay's areas and lines go under the map's labels, and its own labels over them (#979) An overlay was drawn whole over the basemap, so an area it filled covered the names of what is in it. Labels are now always on top: the areas, lines and pictures of every overlay are under the basemap's labels, and the text, icons and points of every overlay are over them. It is so in the map, the standalone viewer, and an exported PDF, where an overlay with both is two layers ("Towers" and "Towers (labels)"). Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An overlay's ground is over the ground of every basemap file (#980) * An overlay's ground is over the ground of every basemap file On a map of several basemap files, the ground of an overlay was put before the first label of the first file, which is under the land, water and roads of every file after it: an overlay's areas and lines were hidden, and in an exported PDF its layer was just above the background. It goes where the basemap's labels begin: the first of the labels which are over all of the basemap's ground. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * The labels of every basemap file are over the ground of every file A map of several basemap files was their layers one file after another, so only the labels of the last file were on top: the labels of the others were under the land, water and roads of the files after them, and under the ground of an overlay. Both viewers now draw the ground of every file and then the labels of every file. The contour lines are drawn after the basemap's labels and are not of the basemap: an overlay's ground goes under the basemap's labels, not under the contours instead. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * Contours are drawn from as deep as the terrain file goes (#981) The map read a terrain file to zoom 8, which is how deep the terrain WROLPi offers goes, however deep the file was. It now reads a file as deep as the file says it goes, in both viewers, and draws finer contour lines from a deeper file: every 40 feet (or 20 meters) from zoom 11, as a 1:24,000 sheet has. A file which goes to zoom 8 is drawn as it was. Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An exported map names its small roads (#982) * An exported map names its small roads A quadrangle is drawn at about zoom 13. The basemap's style names small roads from zoom 15, and its tiles have no names for them below zoom 14, so the streets of a town were printed as lines with no names. Before the map is drawn, the tiles of zoom 14 which the quadrangle is in are read, and the roads in them which have a name are given to the export map as a source of its own. The layer which names small roads draws from that source, as its style says to. At the scale of a sheet most streets are shorter than their names, and a map writes a name along a line only where the line is longer. Such a road is named over its middle, turned as the road goes; a road in pieces is named once. A source whose tiles can not be read is exported as before. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * The names of small roads are placed by the export, at every latitude A quadrangle nearer the equator is drawn at a little over zoom 14, where the names were not read and the style still kept them for zoom 15: such a map had no names of small roads. They are now read wherever a layer would not name roads. Every name of a small road is now a point: over the middle of its road, turned as the road goes under it, again every 400 pixels of a long road. Before, a road long enough was left for the map to name along its line, which the map often does not (the line bends, or is in pieces), and a short piece beside it was named too. One place decides where a road is named, so a road in pieces is named once, and a piece of another kind of road does not take the name. Reading the names can be cancelled. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * A sheet has a bar of meters, its norths in mils, and how far apart its contour lines are (#983) Under the map are bars of kilometers, meters, miles and feet. How far the grid's north and a compass's north are from true north is written in mils as well as in degrees, in the diagram and in the notes: a compass may be marked in either. A map which is exported with its contour lines says how far apart they are (CONTOUR INTERVAL 40 FEET), under the bars. The browser knows: it is the interval of the tiles the lines are made for at the zoom of the sheet, in the unit the map measures in. It says so with the sheet, and what is not an interval is not written. Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * A sheet says what the quadrangles around it are called (#984) * A sheet says what the quadrangles around it are called Under the scale bars is a diagram of nine squares, the map the middle one, and beside it what the USGS calls each of the eight around it: the sheets to print to carry on off the edge of this one. The names are from the index of quadrangles which names the sheet itself. A quadrangle with no name (out to sea, or over a border) has no number; a map of where the USGS names nothing, and a map too narrow for the diagram, go without. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A sheet is never beside itself Where a quadrangle of the USGS is wider than the map (Alaska), the area the size of the map to its east or west is often more of the quadrangle the map is in, and the diagram named the sheet as its own neighbor. The quadrangle on a side is now the next one which is not the map's own. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * A sheet has a legend of the lines of its map (#985) * A sheet has a legend of the lines of its map Under the scale bars is what each kind of line of the map is: highway, major road, minor road, path, railway, boundary, contour and index contour, each a piece of the line as the map draws it, on the color of the map's land. The map's style says how a line is drawn at each zoom, and a sheet is drawn at one. The browser, which has the style, says what each line's color, width, dashes and edges are at that zoom; the API draws them. A line is in the legend when its layer is exported and draws something at that zoom. What the browser sends is made into lines before it is kept: what is not a line is left out, and the map is exported. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A legend has no line too thin to see, and no name longer than its room A style brings a line in from nothing as the map is zoomed in: a path is a few hundredths of a point wide on a quadrangle near the equator. It was in the legend, drawn several times wider than on the map. A line under a tenth of a point is now left out, by the browser and by the API. What a line is called is cut to the room beside its line, as the name of an adjoining quadrangle is. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * Fixes to the map PDF export: wrong neighbors, leftover exports, exports which outlive the map (#989) * A sheet names what is around it, and its edges, by where they are and not a hair from there The edges the browser gives of a map are a hair outside its quadrangle. The quadrangles around a map whose middle is on the edge two share (every other map of Alaska) were those around the map west of it, and one of them was the map itself. An edge a hair south of the equator was 0 degrees south, a map which ended where the UTM zones do had no grid, and a sheet dated in the last year there is could not be made. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * An export is removed when it is over, and its work stops when the API does The images and the PDF of an export were kept until the next export began, however long that was. The browser now has the export removed however it ends, and old exports are removed when a PDF is made too. The work of a Job which ended because the API was stopping went on to the end of the PDF, with the API waiting for it. What is said of an export, and each image, is written whole. Text which is no text is taken out when an export begins, not found by the Job. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * An export stops with its map, and waits for a page which can not be seen Leaving the map while it was exported left the export going, to fail or to hand a PDF to another page; so did closing the picker, which is now left open. A PDF which arrives after the export was stopped is not saved. The time a page is behind another tab is not counted against a map which is drawing. The name of a road is one line. A photograph which ends a little inside the map is not made a JPEG with a black strip. An accent in the name of a quadrangle is not a gap in the name of its file. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A PDF is not kept from who made it by a server slow to remove the export Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An exported map has its water over its parks (#990) * A sheet names what is around it, and its edges, by where they are and not a hair from there The edges the browser gives of a map are a hair outside its quadrangle. The quadrangles around a map whose middle is on the edge two share (every other map of Alaska) were those around the map west of it, and one of them was the map itself. An edge a hair south of the equator was 0 degrees south, a map which ended where the UTM zones do had no grid, and a sheet dated in the last year there is could not be made. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * An export is removed when it is over, and its work stops when the API does The images and the PDF of an export were kept until the next export began, however long that was. The browser now has the export removed however it ends, and old exports are removed when a PDF is made too. The work of a Job which ended because the API was stopping went on to the end of the PDF, with the API waiting for it. What is said of an export, and each image, is written whole. Text which is no text is taken out when an export begins, not found by the Job. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * An export stops with its map, and waits for a page which can not be seen Leaving the map while it was exported left the export going, to fail or to hand a PDF to another page; so did closing the picker, which is now left open. A PDF which arrives after the export was stopped is not saved. The time a page is behind another tab is not counted against a map which is drawing. The name of a road is one line. A photograph which ends a little inside the map is not made a JPEG with a black strip. An accent in the name of a quadrangle is not a gap in the name of its file. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * An exported map has its water over its parks A layer of the PDF was one image, drawn where the topmost of its layers is. The parks of Land Cover are under the water on the map and its piers are over it, so all of Land Cover was drawn over the water: a lake in a park, or among houses, was not on the PDF. A second basemap file put its water over the first's buildings. A layer is now as many images as it must be, each where it is on the map, in one layer of the PDF: a part which fills an area stays where it is, and a part which is only lines is drawn with the next. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A PDF is not kept from who made it by a server slow to remove the export Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A map file which is of somewhere else is not drawn when a map is exported Each basemap file is several images of an exported map, and most files of a library are of other places: each was an image of nothing, counted against how many images an export may be and how sharp it may be. A file whose own edges are outside the quadrangle is now left out before the layers are counted. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An exported map has its streams (#991) A basemap draws streams from zoom 14, and service roads and taxiways from 13. A quadrangle is drawn a little short of that (zoom 13.8 at 40 degrees, 13.2 at 61), from tiles which have them: none were on the PDF. What is drawn from a zoom no deeper than a quadrangle's detail is drawn. Names are left as they are. Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An export which is cancelled stops at once, in the middle of a request (#993) * An export which is cancelled stops at once, in the middle of a request An export was stopped between two requests. The image of a layer is tens of megabytes, which is a long request on a slow connection, and a request to a server which has stopped answering never ends: the export said it was stopping until then. Cancel, and leaving the map, now end the request. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * The requests an export makes after its layers are sent are seen to be stopped too Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * A map is exported as it is printed: on white, in dark lines (#996) * A map is exported as it is printed: on white, in dark lines The light and dark maps are made for a screen. On paper their roads are white on pale gray and their streams half a pixel of pale blue. The printed map is a third look, of the map's own: white ground, dark road edges and names, blue streams wide enough to see, paths drawn, brown contours. It is what a map is exported in unless Light or Dark is chosen where the quadrangle is, and the choice is remembered in the browser. While a quadrangle is chosen the map is shown in the look it will be exported in. The light and dark maps are as they were. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Changing the look of the map does not move it What is done when a new style is in place was asked for after the style was set. A style which only differs from the one the map has is in place before that, so it was done at the next change of style instead, with where the map had been at this one: the map went back there when a quadrangle was chosen, and again when it was not. It is asked for first, and the map is not moved at all. An export no longer waits for the map to be still, which it need not and which nothing ended. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * The colors of the printed map are chosen where its layers are (#997) * The colors of the printed map are chosen where its layers are While a quadrangle is chosen and the map is shown as it is printed, each layer of the layer control has its color beside it, to be changed: one for most, three for the land (what grows, what was built, sand and ice) and two for names (the name, and what is around it). A basemap has several colors where one is chosen, which are shades of it. The edge of a road stays dark. What is chosen is remembered in the browser, and can be put back. The map on the screen is as it was. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A ramp on a bridge is the color of a major road, as it is off one A basemap draws a ramp on a bridge in the color of a minor road on a bridge: on the printed map it was white where the rest of the ramp is yellow, and followed the color chosen for minor roads. What puts the colors back is a button, which a keyboard reaches. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * A layer with nothing in it does not make an exported map less sharp (#1001) * A layer with nothing in it does not make an exported map less sharp How sharp a map may be depends on how many images it is, and every group of layers was counted: a basemap file with no runway, highway or boundary in the quadrangle was images of nothing, drawn, sent, and counted against the rest. A map of 23 images asked for at 400 DPI was made at 330. The groups are now looked at first, on a small map, and only those with something in them are drawn, as sharp as that many may be. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * An image which arrives after its export was removed is not kept, and one mil is a mil Stopping an export while an image was on its way left the image behind it, in a directory nothing would remove for an hour. An angle of one mil was "1 mils" on the sheet. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * The map which is exported from is made as sharp as it is to be (#1002) * The map which is exported from is made as sharp as it is to be The groups of a map are looked at on a small map, which was then made larger to draw them. A browser lets a canvas be larger when it is made than it lets one be made larger afterwards: a quadrangle asked for at 400 DPI was 33 million pixels, 288 DPI at 40 degrees, less than before the groups were looked at first. The small map is now removed, and the map which is exported from is made in its place. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * A canvas the browser stopped drawing on is not a layer with nothing in it A canvas whose drawing was taken away by the browser reads as clear, and a group looked at then was left out of the PDF without a word: the export fails instead. An export stopped as the last group is looked at does not make the map it would have been drawn on. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * An exported map says where it is in a projection Adobe Acrobat knows (#1003) * An exported map says where it is in a projection Adobe Acrobat knows The page was said to be in Web Mercator, which it is drawn in. Acrobat does not know Web Mercator, in the words of the standard or in Esri's: it took the page for a map, and put every place on it at 0, 0. The page is now said to be Mercator on the WGS 84 ellipsoid, which it reads, with the same corners. Between the corners the two differ by under three centimeters on the ground. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * How well a page is said to be where it is, is measured from what the PDF says The test of it measured two formulas of its own. It now reads the corners and the projection from the PDF and does a reader's sum with them. The few centimeters are of a quadrangle: a taller page is less well said, by the square of how tall it is, which the comment now says and a test measures. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> * The help says how a map is exported as a PDF (#1004) The help of the map is five pages, one of them the PDF export. Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
d157057d81
commit
faf8e735d1
42 changed files with 8744 additions and 102 deletions
263
app/src/components/MapQuadPicker.js
Normal file
263
app/src/components/MapQuadPicker.js
Normal file
|
|
@ -0,0 +1,263 @@
|
|||
import React, {useEffect, useRef, useState} from "react";
|
||||
import {Button, Checkbox, Group, Radio} from "./ui";
|
||||
import {EXPORT_DPI, EXPORT_DPIS} from "./mapExport";
|
||||
import {EXPORT_LOOKS, PRINT_LOOK} from "./mapPrintStyle";
|
||||
import {
|
||||
EMPTY_FEATURES,
|
||||
QUAD_MIN_ZOOM,
|
||||
quadAt,
|
||||
quadGridLines,
|
||||
quadLabel,
|
||||
quadPolygon,
|
||||
quadSize,
|
||||
quadTitle,
|
||||
} from "./mapQuads";
|
||||
|
||||
// What the ids of the picker's layers and sources start with: they are of the app, not of the map.
|
||||
export const QUAD_LAYER_PREFIX = "quad-";
|
||||
const GRID_SOURCE = "quad-grid";
|
||||
const SELECTED_SOURCE = "quad-selected";
|
||||
// The picker's own layers, in the order they are drawn (all above the map's).
|
||||
const QUAD_LAYERS = [
|
||||
{
|
||||
id: "quad-grid-lines", type: "line", source: GRID_SOURCE,
|
||||
paint: {"line-color": "#e8590c", "line-width": 1.5, "line-opacity": 0.8},
|
||||
},
|
||||
{
|
||||
id: "quad-selected-fill", type: "fill", source: SELECTED_SOURCE,
|
||||
paint: {"fill-color": "#e8590c", "fill-opacity": 0.2},
|
||||
},
|
||||
{
|
||||
id: "quad-selected-outline", type: "line", source: SELECTED_SOURCE,
|
||||
paint: {"line-color": "#e8590c", "line-width": 3.5},
|
||||
},
|
||||
];
|
||||
|
||||
export function formatDistance(meters, scaleUnit) {
|
||||
return scaleUnit === "imperial"
|
||||
? `${(meters / 1609.344).toFixed(1)} mi`
|
||||
: `${(meters / 1000).toFixed(1)} km`;
|
||||
}
|
||||
|
||||
export function formatSheet(millimeters, scaleUnit) {
|
||||
return scaleUnit === "imperial"
|
||||
? `${(millimeters / 25.4).toFixed(1)} in`
|
||||
: `${(millimeters / 10).toFixed(1)} cm`;
|
||||
}
|
||||
|
||||
function selectedFeatures(quad) {
|
||||
return quad ? {type: "FeatureCollection", features: [quadPolygon(quad)]} : EMPTY_FEATURES;
|
||||
}
|
||||
|
||||
// Draws the grid of 1:24,000 quadrangles over the map while the user chooses one to export.
|
||||
//
|
||||
// The grid and the chosen quadrangle are layers of the map, which a change of its style removes; they
|
||||
// are put back whenever the style has loaded.
|
||||
//
|
||||
// onExport(quad, {sheet, dpi, name}): make the PDF; `sheet` is whether the map is to be on a sheet,
|
||||
// with a margin, a grid and scale bars, `dpi` is how sharp it is to be, and `name` is what the USGS
|
||||
// calls the quadrangle ({name, state, exact}), or null.
|
||||
//
|
||||
// fetchName(quad): asks for that name; it resolves to null where there is none.
|
||||
//
|
||||
// look, onLook(look): the look the map is exported in (see mapPrintStyle.js), and what is told when
|
||||
// another is chosen. The map is shown in it, so what is seen is what is exported.
|
||||
//
|
||||
// While the PDF is being made `status` says how far along it is, and nothing else can be chosen;
|
||||
// Cancel then stops it (onCancel()) and does not close the picker. `error` says why the last one
|
||||
// could not be made.
|
||||
export default function MapQuadPicker({
|
||||
map, scaleUnit, initialQuad = null, onExport, onCancel, onClose, fetchName, status = null, error = null,
|
||||
look = null, onLook = null,
|
||||
}) {
|
||||
const busy = status !== null;
|
||||
const busyRef = useRef(busy);
|
||||
busyRef.current = busy;
|
||||
const [selected, setSelected] = useState(initialQuad);
|
||||
const selectedRef = useRef(initialQuad);
|
||||
// Whether the map is zoomed in far enough for the grid to be drawn.
|
||||
const [gridShown, setGridShown] = useState(true);
|
||||
const [sheet, setSheet] = useState(true);
|
||||
const [dpi, setDpi] = useState(EXPORT_DPI);
|
||||
// What the chosen quadrangle is called: {id, name} once it is known, for the quadrangle it is of.
|
||||
const [named, setNamed] = useState(null);
|
||||
const name = selected && named?.id === selected.id ? named.name : null;
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected || !fetchName) return;
|
||||
let current = true;
|
||||
Promise.resolve(fetchName(selected))
|
||||
.then(found => current && setNamed({id: selected.id, name: found || null}))
|
||||
.catch(() => current && setNamed({id: selected.id, name: null}));
|
||||
// An answer for a quadrangle which is no longer the chosen one is not used.
|
||||
return () => {
|
||||
current = false;
|
||||
};
|
||||
}, [selected, fetchName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!map) return;
|
||||
|
||||
const drawGrid = () => {
|
||||
const source = map.getSource(GRID_SOURCE);
|
||||
if (!source) return;
|
||||
const bounds = map.getBounds();
|
||||
const grid = map.getZoom() >= QUAD_MIN_ZOOM
|
||||
? quadGridLines({
|
||||
west: bounds.getWest(), south: bounds.getSouth(),
|
||||
east: bounds.getEast(), north: bounds.getNorth(),
|
||||
})
|
||||
: null;
|
||||
source.setData(grid || EMPTY_FEATURES);
|
||||
setGridShown(grid !== null);
|
||||
};
|
||||
|
||||
const drawSelected = () => {
|
||||
const source = map.getSource(SELECTED_SOURCE);
|
||||
if (source) source.setData(selectedFeatures(selectedRef.current));
|
||||
};
|
||||
|
||||
const addLayers = () => {
|
||||
if (!map.getSource(GRID_SOURCE)) map.addSource(GRID_SOURCE, {type: "geojson", data: EMPTY_FEATURES});
|
||||
if (!map.getSource(SELECTED_SOURCE)) {
|
||||
map.addSource(SELECTED_SOURCE, {type: "geojson", data: EMPTY_FEATURES});
|
||||
}
|
||||
for (const layer of QUAD_LAYERS) {
|
||||
if (!map.getLayer(layer.id)) map.addLayer(layer);
|
||||
}
|
||||
drawGrid();
|
||||
drawSelected();
|
||||
};
|
||||
|
||||
const choose = (e) => {
|
||||
// The quadrangle being exported stays the chosen one.
|
||||
if (busyRef.current) return;
|
||||
const quad = quadAt(e.lngLat.lng, e.lngLat.lat);
|
||||
// Choosing the chosen quadrangle again lets go of it.
|
||||
const next = quad && selectedRef.current?.id === quad.id ? null : quad;
|
||||
selectedRef.current = next;
|
||||
setSelected(next);
|
||||
drawSelected();
|
||||
};
|
||||
|
||||
addLayers();
|
||||
map.on("style.load", addLayers);
|
||||
map.on("moveend", drawGrid);
|
||||
map.on("click", choose);
|
||||
|
||||
return () => {
|
||||
map.off("style.load", addLayers);
|
||||
map.off("moveend", drawGrid);
|
||||
map.off("click", choose);
|
||||
try {
|
||||
for (const layer of [...QUAD_LAYERS].reverse()) {
|
||||
if (map.getLayer(layer.id)) map.removeLayer(layer.id);
|
||||
}
|
||||
for (const source of [GRID_SOURCE, SELECTED_SOURCE]) {
|
||||
if (map.getSource(source)) map.removeSource(source);
|
||||
}
|
||||
} catch (e) {
|
||||
// The map itself is gone, and its layers with it.
|
||||
}
|
||||
};
|
||||
}, [map]);
|
||||
|
||||
const size = selected ? quadSize(selected) : null;
|
||||
|
||||
// Part of the app's interface over the map, like the layer control: plain, token-colored chrome.
|
||||
const panelStyle = {
|
||||
position: "absolute",
|
||||
bottom: "2.5rem",
|
||||
left: "50%",
|
||||
transform: "translateX(-50%)",
|
||||
zIndex: 1000,
|
||||
background: "var(--panel)",
|
||||
border: "1px solid var(--border)",
|
||||
color: "var(--text)",
|
||||
padding: "0.625rem 0.75rem",
|
||||
fontSize: "0.8125rem",
|
||||
width: "max-content",
|
||||
maxWidth: "calc(100% - 1.25rem)",
|
||||
};
|
||||
|
||||
return <div style={panelStyle} role="region" aria-label="Export a 1:24,000 map">
|
||||
<div style={{fontWeight: 600, paddingBottom: "0.25rem"}}>Export a 1:24,000 map</div>
|
||||
{selected
|
||||
? <div>
|
||||
{name && <div data-testid="quad-name" style={{fontWeight: 600}}>{quadTitle(name)}</div>}
|
||||
<div data-testid="quad-label">{quadLabel(selected)}</div>
|
||||
<div style={{color: "var(--muted)"}} data-testid="quad-size">
|
||||
{formatDistance(size.widthMeters, scaleUnit)} × {formatDistance(size.heightMeters, scaleUnit)}
|
||||
{" on the ground, "}
|
||||
{formatSheet(size.sheetWidthMm, scaleUnit)} × {formatSheet(size.sheetHeightMm, scaleUnit)}
|
||||
{" printed"}
|
||||
</div>
|
||||
</div>
|
||||
: <div>
|
||||
{gridShown
|
||||
? "Click a quadrangle on the map to choose it."
|
||||
: "Zoom in to see the quadrangles."}
|
||||
</div>}
|
||||
<Checkbox
|
||||
size="xs"
|
||||
style={{paddingTop: "0.5rem"}}
|
||||
label="Margins, grid and scale bars"
|
||||
checked={sheet}
|
||||
disabled={busy}
|
||||
onChange={e => setSheet(e.currentTarget.checked)}
|
||||
/>
|
||||
<Radio.Group
|
||||
size="xs"
|
||||
style={{paddingTop: "0.5rem"}}
|
||||
aria-label="Sharpness"
|
||||
value={String(dpi)}
|
||||
onChange={value => setDpi(Number(value))}
|
||||
>
|
||||
<Group gap="md">
|
||||
{EXPORT_DPIS.map(value => <Radio
|
||||
key={value}
|
||||
size="xs"
|
||||
value={String(value)}
|
||||
label={`${value} DPI`}
|
||||
disabled={busy}
|
||||
/>)}
|
||||
</Group>
|
||||
</Radio.Group>
|
||||
{look && onLook && <Radio.Group
|
||||
size="xs"
|
||||
style={{paddingTop: "0.5rem"}}
|
||||
aria-label="Colors"
|
||||
value={look}
|
||||
onChange={onLook}
|
||||
>
|
||||
<Group gap="md">
|
||||
{EXPORT_LOOKS.map(({value, label}) => <Radio
|
||||
key={value}
|
||||
size="xs"
|
||||
value={value}
|
||||
label={label}
|
||||
disabled={busy}
|
||||
/>)}
|
||||
</Group>
|
||||
</Radio.Group>}
|
||||
{look === PRINT_LOOK && onLook && <div style={{paddingTop: "0.25rem", color: "var(--muted)"}}>
|
||||
Its colors can be changed under Layers.
|
||||
</div>}
|
||||
{status && <div role="status" style={{paddingTop: "0.25rem"}}>{status}</div>}
|
||||
{error && !status && <div role="alert" style={{paddingTop: "0.25rem", color: "var(--danger, #c92a2a)"}}>
|
||||
{error}
|
||||
</div>}
|
||||
<div style={{display: "flex", gap: "0.5rem", justifyContent: "flex-end", paddingTop: "0.5rem"}}>
|
||||
<Button role="cancel" size="xs" disabled={busy && !onCancel} onClick={busy ? onCancel : onClose}>
|
||||
{error && !busy ? "Close" : "Cancel"}
|
||||
</Button>
|
||||
<Button
|
||||
role="primary"
|
||||
size="xs"
|
||||
disabled={!selected || !onExport || busy}
|
||||
loading={busy}
|
||||
onClick={() => onExport(selected, {sheet, dpi, name})}
|
||||
>Export PDF</Button>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
315
app/src/components/MapQuadPicker.test.js
Normal file
315
app/src/components/MapQuadPicker.test.js
Normal file
|
|
@ -0,0 +1,315 @@
|
|||
import React from 'react';
|
||||
import {act, fireEvent, screen, waitFor} from '@testing-library/react';
|
||||
import {renderUI} from '../test-utils';
|
||||
import MapQuadPicker, {formatDistance, formatSheet} from './MapQuadPicker';
|
||||
import {quadAt} from './mapQuads';
|
||||
|
||||
// As much of a MapLibre map as the picker uses.
|
||||
class FakeMap {
|
||||
constructor({zoom = 12, bounds = {west: -105.175, south: 40.26, east: -104.925, north: 40.4}} = {}) {
|
||||
this.zoom = zoom;
|
||||
this.bounds = bounds;
|
||||
this.sources = {};
|
||||
this.layers = [];
|
||||
this.handlers = {};
|
||||
}
|
||||
|
||||
on(event, handler) {
|
||||
(this.handlers[event] = this.handlers[event] || []).push(handler);
|
||||
}
|
||||
|
||||
off(event, handler) {
|
||||
this.handlers[event] = (this.handlers[event] || []).filter(i => i !== handler);
|
||||
}
|
||||
|
||||
fire(event, data) {
|
||||
for (const handler of [...(this.handlers[event] || [])]) handler(data);
|
||||
}
|
||||
|
||||
addSource(id, source) {
|
||||
this.sources[id] = {data: source.data, setData(data) { this.data = data; }};
|
||||
}
|
||||
|
||||
getSource(id) {
|
||||
return this.sources[id];
|
||||
}
|
||||
|
||||
removeSource(id) {
|
||||
delete this.sources[id];
|
||||
}
|
||||
|
||||
addLayer(layer) {
|
||||
this.layers.push(layer);
|
||||
}
|
||||
|
||||
getLayer(id) {
|
||||
return this.layers.find(i => i.id === id);
|
||||
}
|
||||
|
||||
removeLayer(id) {
|
||||
this.layers = this.layers.filter(i => i.id !== id);
|
||||
}
|
||||
|
||||
getZoom() {
|
||||
return this.zoom;
|
||||
}
|
||||
|
||||
getBounds() {
|
||||
const {west, south, east, north} = this.bounds;
|
||||
return {getWest: () => west, getSouth: () => south, getEast: () => east, getNorth: () => north};
|
||||
}
|
||||
|
||||
// What a style change does: every layer and source is gone, then the new style has loaded.
|
||||
changeStyle() {
|
||||
this.sources = {};
|
||||
this.layers = [];
|
||||
this.fire('style.load');
|
||||
}
|
||||
}
|
||||
|
||||
const click = (map, lng, lat) => act(() => map.fire('click', {lngLat: {lng, lat}}));
|
||||
const gridLines = map => map.getSource('quad-grid').data.features[0]?.geometry.coordinates || [];
|
||||
const selectedIds = map => map.getSource('quad-selected').data.features.map(f => f.properties.id);
|
||||
const BERTHOUD = quadAt(-105.0595, 40.31);
|
||||
|
||||
function renderPicker(map, props = {}) {
|
||||
const onClose = jest.fn();
|
||||
const result = renderUI(<MapQuadPicker map={map} scaleUnit="metric" onClose={onClose} {...props}/>);
|
||||
return {...result, onClose};
|
||||
}
|
||||
|
||||
describe('choosing a quadrangle to export', () => {
|
||||
test('the grid is drawn over the view, above the layers of the map', () => {
|
||||
const map = new FakeMap();
|
||||
map.layers.push({id: 'roads'});
|
||||
renderPicker(map);
|
||||
|
||||
expect(gridLines(map)).toHaveLength(7);
|
||||
expect(map.layers.map(l => l.id))
|
||||
.toEqual(['roads', 'quad-grid-lines', 'quad-selected-fill', 'quad-selected-outline']);
|
||||
expect(screen.getByText('Click a quadrangle on the map to choose it.')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', {name: 'Export PDF'})).toBeDisabled();
|
||||
});
|
||||
|
||||
test('the grid follows the map', () => {
|
||||
const map = new FakeMap();
|
||||
renderPicker(map);
|
||||
map.bounds = {west: -105.175, south: 40.26, east: -104.925, north: 40.6};
|
||||
act(() => map.fire('moveend'));
|
||||
expect(gridLines(map)).toHaveLength(8);
|
||||
});
|
||||
|
||||
test('there is no grid when zoomed out, and the user is told to zoom in', () => {
|
||||
const map = new FakeMap({zoom: 5});
|
||||
renderPicker(map);
|
||||
expect(gridLines(map)).toEqual([]);
|
||||
expect(screen.getByText('Zoom in to see the quadrangles.')).toBeInTheDocument();
|
||||
|
||||
map.zoom = 9;
|
||||
act(() => map.fire('moveend'));
|
||||
expect(gridLines(map)).toHaveLength(7);
|
||||
expect(screen.getByText('Click a quadrangle on the map to choose it.')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('a click chooses the quadrangle under it, and says what it is', () => {
|
||||
const map = new FakeMap();
|
||||
renderPicker(map);
|
||||
click(map, -105.0595, 40.31);
|
||||
|
||||
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
|
||||
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
|
||||
expect(screen.getByTestId('quad-size'))
|
||||
.toHaveTextContent('10.6 km × 13.9 km on the ground, 44.3 cm × 57.8 cm printed');
|
||||
|
||||
// Another click chooses another; there is one at a time.
|
||||
click(map, -104.925, 40.4);
|
||||
expect(selectedIds(map)).toEqual([quadAt(-104.925, 40.4).id]);
|
||||
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°22′30″N 105°00′W');
|
||||
});
|
||||
|
||||
test('a click on the chosen quadrangle lets go of it', () => {
|
||||
const map = new FakeMap();
|
||||
renderPicker(map);
|
||||
click(map, -105.0595, 40.31);
|
||||
click(map, -105.075, 40.3);
|
||||
expect(selectedIds(map)).toEqual([]);
|
||||
expect(screen.queryByTestId('quad-label')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('can start with a quadrangle already chosen', () => {
|
||||
const map = new FakeMap();
|
||||
renderPicker(map, {initialQuad: BERTHOUD});
|
||||
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
|
||||
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
|
||||
});
|
||||
|
||||
test('the size is in the units of the map', () => {
|
||||
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, scaleUnit: 'imperial'});
|
||||
expect(screen.getByTestId('quad-size'))
|
||||
.toHaveTextContent('6.6 mi × 8.6 mi on the ground, 17.4 in × 22.8 in printed');
|
||||
expect(formatDistance(1609.344, 'imperial')).toBe('1.0 mi');
|
||||
expect(formatSheet(254, 'metric')).toBe('25.4 cm');
|
||||
});
|
||||
|
||||
test('the grid and the choice are put back when the style of the map changes', () => {
|
||||
const map = new FakeMap();
|
||||
renderPicker(map);
|
||||
click(map, -105.0595, 40.31);
|
||||
|
||||
act(() => map.changeStyle());
|
||||
expect(map.layers.map(l => l.id)).toEqual(['quad-grid-lines', 'quad-selected-fill', 'quad-selected-outline']);
|
||||
expect(gridLines(map)).toHaveLength(7);
|
||||
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
|
||||
});
|
||||
|
||||
test('exports the chosen quadrangle', () => {
|
||||
const onExport = jest.fn();
|
||||
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport});
|
||||
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: null});
|
||||
});
|
||||
|
||||
test('while the PDF is being made, Cancel stops it and the picker stays', () => {
|
||||
const onCancel = jest.fn();
|
||||
const {onClose} = renderPicker(new FakeMap(), {
|
||||
initialQuad: BERTHOUD, onExport: jest.fn(), onCancel, status: 'Making the PDF (40%)…',
|
||||
});
|
||||
const cancel = screen.getByRole('button', {name: 'Cancel'});
|
||||
expect(cancel).toBeEnabled();
|
||||
fireEvent.click(cancel);
|
||||
expect(onCancel).toHaveBeenCalledTimes(1);
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('when nothing is being made, Cancel closes the picker', () => {
|
||||
const onCancel = jest.fn();
|
||||
const {onClose} = renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport: jest.fn(), onCancel});
|
||||
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
expect(onCancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('exports the map alone when the sheet is turned off', () => {
|
||||
const onExport = jest.fn();
|
||||
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport});
|
||||
const sheet = screen.getByRole('checkbox', {name: 'Margins, grid and scale bars'});
|
||||
expect(sheet).toBeChecked();
|
||||
fireEvent.click(sheet);
|
||||
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: false, dpi: 300, name: null});
|
||||
});
|
||||
|
||||
test('exports a sharper map when one is asked for', () => {
|
||||
const onExport = jest.fn();
|
||||
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport});
|
||||
expect(screen.getByRole('radio', {name: '300 DPI'})).toBeChecked();
|
||||
fireEvent.click(screen.getByRole('radio', {name: '400 DPI'}));
|
||||
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 400, name: null});
|
||||
});
|
||||
|
||||
test('the look the map is exported in is chosen, and not while a map is exported', () => {
|
||||
const onLook = jest.fn();
|
||||
const {unmount} = renderPicker(new FakeMap(), {initialQuad: BERTHOUD, look: 'print', onLook});
|
||||
expect(screen.getByRole('radio', {name: 'Print'})).toBeChecked();
|
||||
fireEvent.click(screen.getByRole('radio', {name: 'Dark'}));
|
||||
expect(onLook).toHaveBeenCalledWith('dark');
|
||||
unmount();
|
||||
|
||||
renderPicker(new FakeMap(), {
|
||||
initialQuad: BERTHOUD, look: 'dark', onLook, status: 'Drawing Water (1 of 12)…',
|
||||
});
|
||||
expect(screen.getByRole('radio', {name: 'Dark'})).toBeChecked();
|
||||
expect(screen.getByRole('radio', {name: 'Light'})).toBeDisabled();
|
||||
});
|
||||
|
||||
test('there is no look to choose where none is given', () => {
|
||||
renderPicker(new FakeMap(), {initialQuad: BERTHOUD});
|
||||
expect(screen.queryByRole('radio', {name: 'Print'})).toBeNull();
|
||||
});
|
||||
|
||||
test('says what the USGS calls the quadrangle, and exports it by that name', async () => {
|
||||
const named = {name: 'Berthoud', state: 'Colorado', exact: true};
|
||||
const fetchName = jest.fn().mockResolvedValue(named);
|
||||
const onExport = jest.fn();
|
||||
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport, fetchName});
|
||||
expect(await screen.findByTestId('quad-name')).toHaveTextContent('Berthoud, Colorado');
|
||||
expect(fetchName).toHaveBeenCalledWith(BERTHOUD);
|
||||
// Where it is, is still said.
|
||||
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
|
||||
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: named});
|
||||
});
|
||||
|
||||
test('a quadrangle the USGS has no name for goes by where it is', async () => {
|
||||
const fetchName = jest.fn().mockResolvedValue(null);
|
||||
const onExport = jest.fn();
|
||||
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport, fetchName});
|
||||
await waitFor(() => expect(fetchName).toHaveBeenCalled());
|
||||
expect(screen.queryByTestId('quad-name')).toBeNull();
|
||||
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: null});
|
||||
});
|
||||
|
||||
test('a name which can not be asked for is no name', async () => {
|
||||
const fetchName = jest.fn().mockRejectedValue(new Error('offline'));
|
||||
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, fetchName});
|
||||
await waitFor(() => expect(fetchName).toHaveBeenCalled());
|
||||
expect(screen.queryByTestId('quad-name')).toBeNull();
|
||||
expect(screen.getByTestId('quad-label')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('the name of one quadrangle is not shown for another', async () => {
|
||||
let answer;
|
||||
const fetchName = jest.fn()
|
||||
.mockImplementationOnce(() => new Promise(resolve => {
|
||||
answer = resolve;
|
||||
}))
|
||||
.mockResolvedValue({name: 'Windsor', state: 'Colorado', exact: true});
|
||||
const map = new FakeMap();
|
||||
renderPicker(map, {initialQuad: BERTHOUD, fetchName});
|
||||
// Another quadrangle is chosen before the first is named.
|
||||
act(() => map.fire('click', {lngLat: {lng: -104.925, lat: 40.4}}));
|
||||
expect(await screen.findByTestId('quad-name')).toHaveTextContent('Windsor, Colorado');
|
||||
await act(async () => answer({name: 'Berthoud', state: 'Colorado', exact: true}));
|
||||
expect(screen.getByTestId('quad-name')).toHaveTextContent('Windsor, Colorado');
|
||||
});
|
||||
|
||||
test('while the PDF is being made it says how far along it is, and the choice stays', () => {
|
||||
const map = new FakeMap();
|
||||
const onExport = jest.fn();
|
||||
renderPicker(map, {initialQuad: BERTHOUD, onExport, status: 'Drawing Water (2 of 13)…'});
|
||||
|
||||
expect(screen.getByRole('status')).toHaveTextContent('Drawing Water (2 of 13)…');
|
||||
expect(screen.getByRole('button', {name: 'Export PDF'})).toBeDisabled();
|
||||
// An export which can not be stopped has no way to stop it.
|
||||
expect(screen.getByRole('button', {name: 'Cancel'})).toBeDisabled();
|
||||
|
||||
// A click on the map does not choose another quadrangle.
|
||||
click(map, -104.925, 40.4);
|
||||
expect(selectedIds(map)).toEqual([BERTHOUD.id]);
|
||||
expect(screen.getByTestId('quad-label')).toHaveTextContent('40°15′N 105°07′30″W');
|
||||
});
|
||||
|
||||
test('says why the PDF could not be made, and it can be tried again', () => {
|
||||
const onExport = jest.fn();
|
||||
renderPicker(new FakeMap(), {initialQuad: BERTHOUD, onExport, error: 'Could not reach the server'});
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Could not reach the server');
|
||||
fireEvent.click(screen.getByRole('button', {name: 'Export PDF'}));
|
||||
expect(onExport).toHaveBeenCalledWith(BERTHOUD, {sheet: true, dpi: 300, name: null});
|
||||
expect(screen.getByRole('button', {name: 'Close'})).toBeEnabled();
|
||||
});
|
||||
|
||||
test('leaves nothing on the map when it is closed', () => {
|
||||
const map = new FakeMap();
|
||||
map.layers.push({id: 'roads'});
|
||||
const {onClose, unmount} = renderPicker(map);
|
||||
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
|
||||
expect(onClose).toHaveBeenCalled();
|
||||
|
||||
unmount();
|
||||
expect(map.layers.map(l => l.id)).toEqual(['roads']);
|
||||
expect(map.sources).toEqual({});
|
||||
expect(Object.values(map.handlers).flat()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
@ -5,8 +5,23 @@ import "maplibre-gl/dist/maplibre-gl.css";
|
|||
import {Protocol} from "pmtiles";
|
||||
import layers from "protomaps-themes-base";
|
||||
import mlcontour from "@acalcutt/maplibre-contour-pmtiles";
|
||||
import {addMapPin, deleteMapPin, getMapFiles, getMapPins, searchMap, setMapDefaultLocation} from "../api";
|
||||
import {
|
||||
addMapPin,
|
||||
deleteMapPin,
|
||||
exportMapPdf,
|
||||
getMapQuadName,
|
||||
getMapFiles,
|
||||
getMapPins,
|
||||
searchMap,
|
||||
setMapDefaultLocation,
|
||||
} from "../api";
|
||||
import {MAP_VIEWER_URI} from "./Vars";
|
||||
import {readTileBounds, readVectorTile} from "./mapTiles";
|
||||
import {
|
||||
lookStyle, PRINT_LOOK, PRINT_SWATCHES, printContours, printLayers, savedExportLook, savedPrintColors,
|
||||
saveExportLook, savePrintColors,
|
||||
} from "./mapPrintStyle";
|
||||
import {exportLegend} from "./mapExportLegend";
|
||||
import {Button, Checkbox, Header, Icon, Panel, TextInput, Toggle} from "./ui";
|
||||
import {SettingsContext, ThemeContext} from "../contexts/contexts";
|
||||
import {mapFlavor, mapSprite} from "../themes/names";
|
||||
|
|
@ -14,11 +29,13 @@ import {poiPopupHtml} from "./mapPoiPopup";
|
|||
import {solarCalculatorPath} from "./calculators/solar";
|
||||
import {
|
||||
addOverlaysToStyle,
|
||||
labelsOverGround,
|
||||
buildOverlayLayers,
|
||||
isOverlayEnabled,
|
||||
isOverlayLayerEnabled,
|
||||
isOverlayLayerId,
|
||||
isStyledOverlay,
|
||||
overlaySourceId,
|
||||
loadOverlayState,
|
||||
mediaUrl,
|
||||
overlayColor,
|
||||
|
|
@ -33,6 +50,23 @@ import {
|
|||
setOverlayLayerEnabled,
|
||||
} from "./mapOverlays";
|
||||
import {addMissingOverlayIcon, loadOverlayStyles, OVERLAY_ICONS_SPRITE_ID} from "./mapOverlayStyle";
|
||||
import MapQuadPicker, {QUAD_LAYER_PREFIX} from "./MapQuadPicker";
|
||||
import {contourInterval, contourThresholds, DEFAULT_TERRAIN_MAX_ZOOM, terrainMaxZoom} from "../map-shared/terrain.js";
|
||||
import {quadAt} from "./mapQuads";
|
||||
import {
|
||||
EXPORT_DPI,
|
||||
exportFileName,
|
||||
exportFrame,
|
||||
exportGroups,
|
||||
exportContours,
|
||||
exportSheet,
|
||||
exportTitle,
|
||||
maxCanvasSide,
|
||||
maxExportPixels,
|
||||
renderExport,
|
||||
sourcesOutside,
|
||||
saveBlob,
|
||||
} from "./mapExport";
|
||||
|
||||
// Layer groups matching the standalone viewer.
|
||||
const LAYER_GROUPS = {
|
||||
|
|
@ -68,13 +102,16 @@ const SKIP_SECONDARY = new Set(["background", "earth"]);
|
|||
// Set up contour DEM source (must be called once before buildStyle).
|
||||
let demSource = null;
|
||||
let terrainUrl = null;
|
||||
function initContourSource(path) {
|
||||
terrainUrl = mediaUrl(path);
|
||||
// How deep the terrain file goes: contours are drawn from as deep as it does.
|
||||
let terrainZoom = DEFAULT_TERRAIN_MAX_ZOOM;
|
||||
function initContourSource(file) {
|
||||
terrainUrl = mediaUrl(file.path);
|
||||
if (demSource) return;
|
||||
terrainZoom = terrainMaxZoom(file);
|
||||
demSource = new mlcontour.DemSource({
|
||||
url: `pmtiles://${window.location.origin}${terrainUrl}`,
|
||||
encoding: "terrarium",
|
||||
maxzoom: 8,
|
||||
maxzoom: terrainZoom,
|
||||
worker: true,
|
||||
});
|
||||
demSource.setupMaplibre(maplibregl);
|
||||
|
|
@ -86,16 +123,19 @@ function initContourSource(path) {
|
|||
// `sprite` is deliberately separate from `flavor`: we ship two sprite sets (light, dark)
|
||||
// and the monochrome themes draw a `black` basemap, which has no sprites of its own.
|
||||
// overlays: the map files which are not a basemap; overlayState: which of them (and of their
|
||||
// layers) the user turned on.
|
||||
// layers) the user turned on. printColors: the colors a person chose for the printed map.
|
||||
function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = "metric",
|
||||
sprite = "light", overlays = [], overlayState = {}) {
|
||||
sprite = "light", overlays = [], overlayState = {}, printColors = {}) {
|
||||
const styleSources = {};
|
||||
// The contour lines of the printed map, in the colors a person chose for it.
|
||||
const contours = printContours(printColors);
|
||||
const allLayers = [];
|
||||
|
||||
for (let i = 0; i < sources.length; i++) {
|
||||
const {name, url} = sources[i];
|
||||
styleSources[name] = {type: "vector", url};
|
||||
const fileLayers = layers(name, flavor);
|
||||
// The printed map is not a flavor a basemap has: it is the map's own (see mapPrintStyle.js).
|
||||
const fileLayers = flavor === PRINT_LOOK ? printLayers(name, printColors) : layers(name, flavor);
|
||||
if (i === 0) {
|
||||
// Primary source: use layer IDs as-is.
|
||||
allLayers.push(...fileLayers);
|
||||
|
|
@ -108,6 +148,9 @@ function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = "
|
|||
}
|
||||
}
|
||||
|
||||
// The labels of every basemap file are over the ground of every file.
|
||||
allLayers.splice(0, allLayers.length, ...labelsOverGround(allLayers));
|
||||
|
||||
// Add terrain sources and layers if available.
|
||||
if (hasTerrain && demSource) {
|
||||
// Read saved visibility to set initial layer state correctly.
|
||||
|
|
@ -146,27 +189,14 @@ function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = "
|
|||
elevationKey: "ele",
|
||||
levelKey: "level",
|
||||
multiplier: isImperial ? 3.28084 : 1, // meters to feet conversion
|
||||
thresholds: isImperial ? {
|
||||
// [minor, major] contour intervals in feet per zoom level.
|
||||
4: [1000, 5000],
|
||||
5: [500, 2500],
|
||||
6: [200, 1000],
|
||||
7: [200, 1000],
|
||||
8: [100, 500],
|
||||
} : {
|
||||
// [minor, major] contour intervals in meters per zoom level.
|
||||
4: [500, 2500],
|
||||
5: [200, 1000],
|
||||
6: [100, 500],
|
||||
7: [100, 500],
|
||||
8: [50, 200],
|
||||
},
|
||||
// [minor, major] contour intervals per zoom level, as fine as the terrain file can bear.
|
||||
thresholds: contourThresholds(isImperial, terrainZoom),
|
||||
});
|
||||
const elevUnit = isImperial ? "ft" : "m";
|
||||
styleSources["contours"] = {
|
||||
type: "vector",
|
||||
tiles: [contourUrl],
|
||||
maxzoom: 8,
|
||||
maxzoom: terrainZoom,
|
||||
};
|
||||
|
||||
allLayers.push(
|
||||
|
|
@ -177,7 +207,8 @@ function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = "
|
|||
"source-layer": "contours",
|
||||
filter: ["!=", ["get", "level"], 1],
|
||||
layout: {visibility: contourVis},
|
||||
paint: {"line-color": "rgba(150,100,50,0.3)", "line-width": 0.5},
|
||||
paint: flavor === PRINT_LOOK
|
||||
? contours.minor : {"line-color": "rgba(150,100,50,0.3)", "line-width": 0.5},
|
||||
},
|
||||
{
|
||||
id: "contour-lines-major",
|
||||
|
|
@ -186,7 +217,8 @@ function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = "
|
|||
"source-layer": "contours",
|
||||
filter: ["==", ["get", "level"], 1],
|
||||
layout: {visibility: contourVis},
|
||||
paint: {"line-color": "rgba(150,100,50,0.5)", "line-width": 1},
|
||||
paint: flavor === PRINT_LOOK
|
||||
? contours.major : {"line-color": "rgba(150,100,50,0.5)", "line-width": 1},
|
||||
},
|
||||
{
|
||||
id: "contour-labels",
|
||||
|
|
@ -206,6 +238,7 @@ function buildStyle(sources, flavor = "light", hasTerrain = false, scaleUnit = "
|
|||
"text-color": flavor === "light" ? "rgba(150,100,50,0.8)" : "rgba(210,180,140,0.9)",
|
||||
"text-halo-color": flavor === "light" ? "rgba(255,255,255,0.8)" : "rgba(0,0,0,0.8)",
|
||||
"text-halo-width": 1,
|
||||
...(flavor === PRINT_LOOK ? contours.label : {}),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
|
@ -327,10 +360,29 @@ function OverlayControl({file, label, state, onToggleFile, onToggleLayer, onTogg
|
|||
</div>;
|
||||
}
|
||||
|
||||
// The colors of the printed map which are of a group of the layer control, each to be chosen.
|
||||
// colors: what was chosen ({swatch id: "#rrggbb"}); onChange(colors): told what is chosen now.
|
||||
function PrintSwatches({group, colors, onChange}) {
|
||||
const swatches = PRINT_SWATCHES.filter(swatch => swatch.group === group);
|
||||
if (!swatches.length) return null;
|
||||
return <span style={{display: "inline-flex", gap: "0.25rem", marginLeft: "auto"}}>
|
||||
{swatches.map(swatch => <input
|
||||
key={swatch.id}
|
||||
type="color"
|
||||
title={`${swatch.label}: color when printed`}
|
||||
aria-label={`${swatch.label}: color when printed`}
|
||||
value={colors[swatch.id] || swatch.color}
|
||||
onChange={e => onChange({...colors, [swatch.id]: e.target.value})}
|
||||
style={{width: "1.25rem", height: "1.25rem", padding: 0, border: "1px solid var(--border)",
|
||||
background: "none", cursor: "pointer"}}
|
||||
/>)}
|
||||
</span>;
|
||||
}
|
||||
|
||||
function LayerControl({
|
||||
map, scaleUnit, onScaleUnitChange, visibilityRef,
|
||||
overlays = [], overlayState = {}, onToggleOverlay, onToggleOverlayLayer,
|
||||
onToggleAllOverlayLayers,
|
||||
onToggleAllOverlayLayers, printColors = null, onPrintColors = null,
|
||||
}) {
|
||||
const [visibility, setVisibility] = useState(() => {
|
||||
const v = getInitialVisibility();
|
||||
|
|
@ -410,14 +462,27 @@ function LayerControl({
|
|||
</div>
|
||||
{!collapsed && <div style={{padding: "0.25rem 0.75rem 0.5rem"}}>
|
||||
{Object.keys(LAYER_GROUPS).map(name =>
|
||||
<div key={name} style={{padding: "0.125rem 0"}}>
|
||||
<div key={name} style={{padding: "0.125rem 0", display: "flex", alignItems: "center", gap: "0.375rem"}}>
|
||||
<Checkbox
|
||||
label={name}
|
||||
checked={visibility[name]}
|
||||
onChange={(e) => toggleGroup(name, e.currentTarget.checked)}
|
||||
/>
|
||||
{printColors && onPrintColors && <PrintSwatches
|
||||
group={name} colors={printColors} onChange={onPrintColors}/>}
|
||||
</div>
|
||||
)}
|
||||
{printColors && onPrintColors && <div style={{paddingTop: "0.25rem", color: "var(--muted)"}}>
|
||||
Colors are of the printed map.{" "}
|
||||
{Object.keys(printColors).length > 0 && <button
|
||||
type="button"
|
||||
style={{
|
||||
cursor: "pointer", textDecoration: "underline", background: "none", border: "none",
|
||||
padding: 0, font: "inherit", color: "inherit",
|
||||
}}
|
||||
onClick={() => onPrintColors({})}
|
||||
>Reset colors</button>}
|
||||
</div>}
|
||||
{overlays.length > 0 &&
|
||||
<div style={{borderTop: "1px solid var(--border)", marginTop: "0.375rem", paddingTop: "0.375rem"}}>
|
||||
<div style={{fontWeight: 600, paddingBottom: "0.125rem"}}>Overlays</div>
|
||||
|
|
@ -659,11 +724,37 @@ export default function MapViewer() {
|
|||
const [addingPin, setAddingPin] = useState(null); // {lat, lon} when pin dialog is open
|
||||
const markersRef = useRef([]);
|
||||
const pinsVisibleRef = useRef(true);
|
||||
// Choosing a quadrangle to export: null, or {quad} (the quadrangle to start with, if any). While
|
||||
// choosing, a click on the map chooses, so the ref tells the map's own click handlers to stand by.
|
||||
const [pickingQuad, setPickingQuad] = useState(null);
|
||||
const pickingQuadRef = useRef(false);
|
||||
// The look a map is exported in. While a quadrangle is chosen the map is shown in it: what is
|
||||
// seen is what the PDF will be.
|
||||
const [exportLook, setExportLook] = useState(savedExportLook);
|
||||
const handleExportLook = useCallback(look => {
|
||||
setExportLook(look);
|
||||
saveExportLook(look);
|
||||
}, []);
|
||||
// The colors a person chose for the printed map: {swatch id: "#rrggbb"}.
|
||||
const [printColors, setPrintColors] = useState(savedPrintColors);
|
||||
const handlePrintColors = useCallback(colors => setPrintColors(savePrintColors(colors)), []);
|
||||
// Exporting the chosen quadrangle: how far along it is, or why it could not be done.
|
||||
const [exportStatus, setExportStatus] = useState(null);
|
||||
// Whether the person exporting has asked for the export which is being made to stop.
|
||||
const exportCancelledRef = useRef(false);
|
||||
// Stops the request an export is in the middle of.
|
||||
const exportAbortRef = useRef(null);
|
||||
// Whether a map is being exported, for what is asked outside of React (the map's own buttons).
|
||||
const exportingRef = useRef(false);
|
||||
const [exportError, setExportError] = useState(null);
|
||||
const [scaleUnit, setScaleUnit] = useState(() => {
|
||||
try { return localStorage.getItem(STORAGE_KEY_SCALE) || "metric"; } catch (e) { return "metric"; }
|
||||
});
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const {theme} = useContext(ThemeContext);
|
||||
const {flavor: lookFlavor, sprite: lookSprite} = lookStyle(pickingQuad ? exportLook : null);
|
||||
// The map is shown as it is printed: its colors can be chosen.
|
||||
const printing = lookFlavor === PRINT_LOOK;
|
||||
const {settings, fetchSettings} = useContext(SettingsContext);
|
||||
|
||||
// Use URL params if provided, otherwise fall back to saved default location, then 0,0,z2.
|
||||
|
|
@ -690,7 +781,7 @@ export default function MapViewer() {
|
|||
|
||||
// Fetch user's PMTiles files first to determine what base layer is needed.
|
||||
let hasTerrain = false;
|
||||
let terrainPath = null;
|
||||
let terrainFile = null;
|
||||
let overlayFiles = [];
|
||||
try {
|
||||
const data = await getMapFiles();
|
||||
|
|
@ -700,7 +791,7 @@ export default function MapViewer() {
|
|||
overlayFiles = await loadOverlayStyles(foundOverlays);
|
||||
if (terrain) {
|
||||
hasTerrain = true;
|
||||
terrainPath = terrain.path;
|
||||
terrainFile = terrain;
|
||||
}
|
||||
|
||||
if (planet) {
|
||||
|
|
@ -734,7 +825,7 @@ export default function MapViewer() {
|
|||
|
||||
// Initialize contour source if terrain data is available.
|
||||
if (hasTerrain) {
|
||||
initContourSource(terrainPath);
|
||||
initContourSource(terrainFile);
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -785,6 +876,28 @@ export default function MapViewer() {
|
|||
};
|
||||
map.addControl(pinControl, "top-right");
|
||||
|
||||
// Choose a quadrangle to export.
|
||||
const exportButton = document.createElement("button");
|
||||
exportButton.type = "button";
|
||||
exportButton.title = "Export a 1:24,000 map";
|
||||
exportButton.setAttribute("aria-label", "Export a 1:24,000 map");
|
||||
exportButton.textContent = "🖨️";
|
||||
exportButton.style.cssText = pinToggle.style.cssText;
|
||||
exportButton.addEventListener("click", () => {
|
||||
// Not while a map is being exported: what is said of it, and its Cancel, are there.
|
||||
if (destroyed || exportingRef.current) return;
|
||||
setPickingQuad(picking => (picking ? null : {quad: null}));
|
||||
});
|
||||
map.addControl({
|
||||
onAdd: () => {
|
||||
const container = document.createElement("div");
|
||||
container.className = "maplibregl-ctrl maplibregl-ctrl-group";
|
||||
container.appendChild(exportButton);
|
||||
return container;
|
||||
},
|
||||
onRemove: () => {},
|
||||
}, "top-right");
|
||||
|
||||
// Right-click context menu (desktop).
|
||||
map.on("contextmenu", (e) => {
|
||||
if (destroyed) return;
|
||||
|
|
@ -813,7 +926,7 @@ export default function MapViewer() {
|
|||
const featuresAt = (point, layers) =>
|
||||
layers.length ? map.queryRenderedFeatures(point, {layers}) : [];
|
||||
map.on("click", (e) => {
|
||||
if (destroyed) return;
|
||||
if (destroyed || pickingQuadRef.current) return;
|
||||
const html = overlayPopupHtml(featuresAt(e.point, overlayLayerIds()))
|
||||
|| poiPopupHtml(featuresAt(e.point, poiLayerIds()), e.lngLat);
|
||||
if (!html) return;
|
||||
|
|
@ -824,6 +937,10 @@ export default function MapViewer() {
|
|||
});
|
||||
map.on("mousemove", (e) => {
|
||||
if (destroyed) return;
|
||||
if (pickingQuadRef.current) {
|
||||
map.getCanvas().style.cursor = "crosshair";
|
||||
return;
|
||||
}
|
||||
const hit = featuresAt(e.point, [...overlayLayerIds(), ...poiLayerIds()]).length;
|
||||
map.getCanvas().style.cursor = hit ? "pointer" : "";
|
||||
});
|
||||
|
|
@ -885,6 +1002,9 @@ export default function MapViewer() {
|
|||
|
||||
return () => {
|
||||
destroyed = true;
|
||||
// An export of this map stops with it: nobody is here to be given the PDF.
|
||||
exportCancelledRef.current = true;
|
||||
exportAbortRef.current?.abort();
|
||||
if (map) {
|
||||
map.remove();
|
||||
}
|
||||
|
|
@ -903,23 +1023,22 @@ export default function MapViewer() {
|
|||
};
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Rebuild style when theme changes.
|
||||
// Rebuild the style when the theme changes, and when the look the map is shown in does.
|
||||
useEffect(() => {
|
||||
const map = mapRef.current;
|
||||
if (!map || !mapReady) return;
|
||||
|
||||
const center = map.getCenter();
|
||||
const zoom = map.getZoom();
|
||||
// What the user turned off is off in the new style too. Listened for before the style is
|
||||
// set: a style which only differs from the one the map has is in place, and has said so,
|
||||
// before `setStyle` returns. The map stays where it is: a style of ours says nothing of that.
|
||||
const showAsChosen = () => applyGroupVisibility(map, layerVisibilityRef.current);
|
||||
map.once("style.load", showAsChosen);
|
||||
// The overlays are part of the style, as the user last set them.
|
||||
map.setStyle(buildStyle(activeFilesRef.current, mapFlavor(theme), hasTerrainRef.current,
|
||||
scaleUnit, mapSprite(theme), overlaysRef.current, overlayStateRef.current));
|
||||
map.once("style.load", () => {
|
||||
map.setCenter(center);
|
||||
map.setZoom(zoom);
|
||||
// Re-apply layer visibility state after style rebuild.
|
||||
applyGroupVisibility(map, layerVisibilityRef.current);
|
||||
});
|
||||
}, [theme, mapReady, scaleUnit]);
|
||||
// In the look a map is exported in while one is chosen; as the theme has it otherwise.
|
||||
map.setStyle(buildStyle(activeFilesRef.current, lookFlavor || mapFlavor(theme), hasTerrainRef.current,
|
||||
scaleUnit, lookSprite || mapSprite(theme), overlaysRef.current, overlayStateRef.current, printColors));
|
||||
return () => map.off("style.load", showAsChosen);
|
||||
}, [theme, lookFlavor, lookSprite, mapReady, scaleUnit, printColors]);
|
||||
|
||||
// Remember what the user chose to see of an overlay, and show or hide its layers to match.
|
||||
const changeOverlayState = useCallback((file, next) => {
|
||||
|
|
@ -973,6 +1092,98 @@ export default function MapViewer() {
|
|||
setContextMenu(null);
|
||||
}, [contextMenu]);
|
||||
|
||||
useEffect(() => {
|
||||
pickingQuadRef.current = pickingQuad !== null;
|
||||
const map = mapRef.current;
|
||||
if (map) map.getCanvas().style.cursor = pickingQuad ? "crosshair" : "";
|
||||
}, [pickingQuad]);
|
||||
|
||||
const handleExportQuad = useCallback(() => {
|
||||
if (!contextMenu) return;
|
||||
// Start with the quadrangle which was clicked; not while another is being exported.
|
||||
if (!exportingRef.current) setPickingQuad({quad: quadAt(contextMenu.lon, contextMenu.lat)});
|
||||
setContextMenu(null);
|
||||
}, [contextMenu]);
|
||||
|
||||
// Make a PDF of a quadrangle: the layers which are on, drawn as they are on the map.
|
||||
const handleExportPdf = useCallback(async (quad, {sheet = true, dpi = EXPORT_DPI, name = null} = {}) => {
|
||||
const map = mapRef.current;
|
||||
if (!map) return;
|
||||
exportCancelledRef.current = false;
|
||||
exportingRef.current = true;
|
||||
const abort = new AbortController();
|
||||
exportAbortRef.current = abort;
|
||||
// The unit the map measures in is the unit its contour lines are apart in.
|
||||
const imperial = scaleUnit === "imperial";
|
||||
setExportError(null);
|
||||
setExportStatus("Preparing…");
|
||||
try {
|
||||
const style = map.getStyle();
|
||||
const overlayLabels = Object.fromEntries(overlaysRef.current.map(
|
||||
file => [overlaySourceId(file), overlayLabel(file, overlaysRef.current)]));
|
||||
// A map file which is of somewhere else is not drawn.
|
||||
const outside = await sourcesOutside(
|
||||
style, [quad.west, quad.south, quad.east, quad.north], readTileBounds);
|
||||
const groups = exportGroups(
|
||||
style.layers.filter(layer => !layer.id.startsWith(QUAD_LAYER_PREFIX) && !outside.has(layer.source)),
|
||||
{layerGroups: LAYER_GROUPS, overlayLabels});
|
||||
if (!groups.length) throw new Error("No layer of the map is turned on");
|
||||
// How sharp the map may be depends on how many images it is, which is not known until
|
||||
// the groups have been looked at: one with nothing in it is no image.
|
||||
const maxSide = maxCanvasSide();
|
||||
const frameFor = count => exportFrame(quad, {dpi, maxSide, maxPixels: maxExportPixels(count)});
|
||||
// The zoom of the map is the same however many images it is.
|
||||
const frame = frameFor(groups.length);
|
||||
const rendered = await renderExport({
|
||||
MapClass: maplibregl.Map,
|
||||
style,
|
||||
frameFor,
|
||||
groups,
|
||||
ignoredPrefixes: [QUAD_LAYER_PREFIX],
|
||||
readTile: readVectorTile,
|
||||
setup: exportMap => exportMap.on("styleimagemissing", e => addMissingOverlayIcon(exportMap, e.id)),
|
||||
// Stopped between two layers, as soon as the person exporting asks.
|
||||
isCancelled: () => exportCancelledRef.current,
|
||||
onLooking: () => setExportStatus("Looking at the map…"),
|
||||
// The map is less sharp than was asked for when this browser, or this many layers, can not be.
|
||||
onProgress: (name, index, count, drawn) => setExportStatus(
|
||||
`Drawing ${name} (${index + 1} of ${count})`
|
||||
+ `${Math.round(drawn.dpi) < dpi ? ` at ${Math.round(drawn.dpi)} DPI` : ""}…`),
|
||||
});
|
||||
const pdf = await exportMapPdf({
|
||||
...rendered,
|
||||
title: exportTitle(quad, name),
|
||||
// With a sheet the map has a margin, a grid and scale bars; without, it is the map alone.
|
||||
sheet: sheet ? exportSheet(quad, map, groups, new Date(), name, exportContours(
|
||||
groups, LAYER_GROUPS["Contours"], contourInterval(imperial, terrainZoom, frame.zoom), imperial,
|
||||
), exportLegend(style, groups, frame.zoom)) : undefined,
|
||||
}, {
|
||||
// Once it is being stopped, that is what is said.
|
||||
onStatus: text => !exportCancelledRef.current && setExportStatus(text),
|
||||
isCancelled: () => exportCancelledRef.current,
|
||||
signal: abort.signal,
|
||||
});
|
||||
// Stopped while the PDF was on its way: it is not wanted.
|
||||
if (!exportCancelledRef.current) saveBlob(pdf, exportFileName(quad, name));
|
||||
} catch (e) {
|
||||
// Stopped by the person exporting: nothing went wrong.
|
||||
if (!e?.cancelled) {
|
||||
console.error("Map export failed:", e);
|
||||
setExportError(e?.message || "The map could not be exported");
|
||||
}
|
||||
} finally {
|
||||
exportingRef.current = false;
|
||||
setExportStatus(null);
|
||||
}
|
||||
}, [scaleUnit]);
|
||||
|
||||
// Stop the export which is being made. It stops between two steps, and the server stops making the PDF.
|
||||
const handleCancelExport = useCallback(() => {
|
||||
exportCancelledRef.current = true;
|
||||
exportAbortRef.current?.abort();
|
||||
setExportStatus("Stopping…");
|
||||
}, []);
|
||||
|
||||
const handleExportPng = useCallback(() => {
|
||||
const map = mapRef.current;
|
||||
if (!map) return;
|
||||
|
|
@ -1099,6 +1310,8 @@ export default function MapViewer() {
|
|||
scaleUnit={scaleUnit}
|
||||
onScaleUnitChange={handleScaleUnitChange}
|
||||
visibilityRef={layerVisibilityRef}
|
||||
printColors={printing ? printColors : null}
|
||||
onPrintColors={handlePrintColors}
|
||||
overlays={overlays}
|
||||
overlayState={overlayState}
|
||||
onToggleOverlay={handleToggleOverlay}
|
||||
|
|
@ -1143,6 +1356,14 @@ export default function MapViewer() {
|
|||
>
|
||||
Export as PNG
|
||||
</div>
|
||||
<div
|
||||
style={{padding: "0.5rem 0.75rem", cursor: "pointer", userSelect: "none"}}
|
||||
onMouseEnter={e => e.target.style.background = "#f0f0f0"}
|
||||
onMouseLeave={e => e.target.style.background = "transparent"}
|
||||
onClick={handleExportQuad}
|
||||
>
|
||||
Export a 1:24,000 map
|
||||
</div>
|
||||
<div
|
||||
style={{padding: "0.5rem 0.75rem", cursor: "pointer", userSelect: "none"}}
|
||||
onMouseEnter={e => e.target.style.background = "#f0f0f0"}
|
||||
|
|
@ -1168,6 +1389,23 @@ export default function MapViewer() {
|
|||
Set as Default View
|
||||
</div>
|
||||
</div>}
|
||||
{mapReady && pickingQuad && <MapQuadPicker
|
||||
key={pickingQuad.quad?.id || "none"}
|
||||
map={mapRef.current}
|
||||
scaleUnit={scaleUnit}
|
||||
initialQuad={pickingQuad.quad}
|
||||
onExport={handleExportPdf}
|
||||
onCancel={handleCancelExport}
|
||||
fetchName={getMapQuadName}
|
||||
look={exportLook}
|
||||
onLook={handleExportLook}
|
||||
status={exportStatus}
|
||||
error={exportError}
|
||||
onClose={() => {
|
||||
setExportError(null);
|
||||
setPickingQuad(null);
|
||||
}}
|
||||
/>}
|
||||
{addingPin && <AddPinDialog
|
||||
lat={addingPin.lat}
|
||||
lon={addingPin.lon}
|
||||
|
|
|
|||
|
|
@ -19,6 +19,10 @@ jest.mock('maplibre-gl', () => {
|
|||
constructor(options) {
|
||||
this.options = options;
|
||||
this.style = options.style;
|
||||
this.center = {lat: 0, lng: 0};
|
||||
this.moves = [];
|
||||
this.listeners = [];
|
||||
this.controls = [];
|
||||
constructed.push(this);
|
||||
}
|
||||
|
||||
|
|
@ -28,7 +32,13 @@ jest.mock('maplibre-gl', () => {
|
|||
return this;
|
||||
}
|
||||
|
||||
once() {
|
||||
once(event, callback) {
|
||||
this.listeners.push({event, callback});
|
||||
return this;
|
||||
}
|
||||
|
||||
off(event, callback) {
|
||||
this.listeners = this.listeners.filter(i => i.event !== event || i.callback !== callback);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
|
@ -38,6 +48,11 @@ jest.mock('maplibre-gl', () => {
|
|||
|
||||
setStyle(style) {
|
||||
this.style = style;
|
||||
// MapLibre puts a style which only differs from the one it has in place, and says so,
|
||||
// before this returns.
|
||||
const waiting = this.listeners.filter(i => i.event === 'style.load');
|
||||
this.listeners = this.listeners.filter(i => i.event !== 'style.load');
|
||||
waiting.forEach(i => i.callback());
|
||||
}
|
||||
|
||||
getLayer(id) {
|
||||
|
|
@ -58,20 +73,26 @@ jest.mock('maplibre-gl', () => {
|
|||
}
|
||||
|
||||
getCenter() {
|
||||
return {lat: 0, lng: 0};
|
||||
return this.center;
|
||||
}
|
||||
|
||||
getZoom() {
|
||||
return 2;
|
||||
}
|
||||
|
||||
setCenter() {
|
||||
setCenter(center) {
|
||||
this.moves.push(center);
|
||||
this.center = center;
|
||||
}
|
||||
|
||||
setZoom() {
|
||||
}
|
||||
|
||||
addControl() {
|
||||
addControl(control) {
|
||||
// A control of the viewer's own (not one of MapLibre's) is put on the page.
|
||||
if (typeof control?.onAdd === 'function') {
|
||||
this.controls.push(global.document.body.appendChild(control.onAdd(this)));
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
|
|
@ -79,6 +100,7 @@ jest.mock('maplibre-gl', () => {
|
|||
}
|
||||
|
||||
remove() {
|
||||
this.controls.forEach(control => control.remove());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -108,7 +130,16 @@ jest.mock('protomaps-themes-base', () => ({
|
|||
{id: 'water', type: 'fill', source},
|
||||
{id: 'places_locality', type: 'symbol', source},
|
||||
],
|
||||
// The printed map: the same layers, in colors of its own.
|
||||
namedTheme: () => ({}),
|
||||
layersWithCustomTheme: (source) => [
|
||||
{id: 'earth', type: 'fill', source, paint: {'fill-color': 'print'}},
|
||||
{id: 'water', type: 'fill', source},
|
||||
{id: 'places_locality', type: 'symbol', source},
|
||||
],
|
||||
}));
|
||||
// Choosing a quadrangle draws on the map, which is not what is looked at here.
|
||||
jest.mock('./MapQuadPicker', () => ({onClose}) => <button onClick={onClose}>Close the picker</button>);
|
||||
// Contours are generated in the browser from the terrain file; only the URL of that source matters here.
|
||||
jest.mock('@acalcutt/maplibre-contour-pmtiles', () => ({
|
||||
__esModule: true,
|
||||
|
|
@ -407,3 +438,54 @@ describe('the text of the map', () => {
|
|||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('the look the map is exported in', () => {
|
||||
const earthColor = map => map.getLayer('earth').paint?.['fill-color'];
|
||||
|
||||
test('is how the map is shown while a quadrangle is chosen, where it is and with what is off still off', async () => {
|
||||
const map = await renderViewer([PLANET]);
|
||||
await click(screen.getByLabelText('Water'));
|
||||
expect(map.visibility('water')).toBe('none');
|
||||
// The map has been moved since it was made.
|
||||
map.center = {lat: 40.3, lng: -105.06};
|
||||
|
||||
await click(screen.getByTitle('Export a 1:24,000 map'));
|
||||
expect(earthColor(map)).toBe('print');
|
||||
expect(map.visibility('water')).toBe('none');
|
||||
// Moved again, while the quadrangle is chosen.
|
||||
map.center = {lat: 61.2, lng: -149.9};
|
||||
|
||||
await click(screen.getByText('Close the picker'));
|
||||
expect(earthColor(map)).toBeUndefined();
|
||||
expect(map.visibility('water')).toBe('none');
|
||||
// Changing the look never moves the map.
|
||||
expect(map.moves).toEqual([]);
|
||||
expect(map.center).toEqual({lat: 61.2, lng: -149.9});
|
||||
});
|
||||
|
||||
test('has colors which are chosen where its layers are, while a quadrangle is chosen', async () => {
|
||||
const map = await renderViewer([PLANET]);
|
||||
// The map on the screen has no colors to choose.
|
||||
expect(screen.queryByLabelText('Water: color when printed')).not.toBeInTheDocument();
|
||||
|
||||
await click(screen.getByTitle('Export a 1:24,000 map'));
|
||||
const water = screen.getByLabelText('Water: color when printed');
|
||||
expect(water).toHaveValue('#a9d4f2');
|
||||
expect(screen.queryByText('Reset colors')).not.toBeInTheDocument();
|
||||
await act(async () => {
|
||||
fireEvent.change(water, {target: {value: '#ff00ff'}});
|
||||
});
|
||||
expect(screen.getByLabelText('Water: color when printed')).toHaveValue('#ff00ff');
|
||||
expect(JSON.parse(localStorage.getItem('wrolpi-map-print-colors'))).toEqual({water: '#ff00ff'});
|
||||
// The map was drawn again, where it was.
|
||||
expect(earthColor(map)).toBe('print');
|
||||
expect(map.moves).toEqual([]);
|
||||
|
||||
await click(screen.getByText('Reset colors'));
|
||||
expect(screen.getByLabelText('Water: color when printed')).toHaveValue('#a9d4f2');
|
||||
expect(localStorage.getItem('wrolpi-map-print-colors')).toBeNull();
|
||||
|
||||
await click(screen.getByText('Close the picker'));
|
||||
expect(screen.queryByLabelText('Water: color when printed')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
739
app/src/components/mapExport.js
Normal file
739
app/src/components/mapExport.js
Normal file
|
|
@ -0,0 +1,739 @@
|
|||
// Exporting a quadrangle of the map as a PDF.
|
||||
//
|
||||
// The browser draws the map, because nothing else draws it as the user sees it. A second map, off
|
||||
// the screen and the size of the printed sheet, is drawn once for each layer the user has turned on,
|
||||
// with only that layer showing; the API puts the images in a PDF, each in a layer of its own, and
|
||||
// (when it is asked to) on a sheet: with a margin, a grid, scale bars and notes around the map.
|
||||
|
||||
import {QUAD_DEGREES, QUAD_SCALE, quadLabel, quadSize, quadTitle} from "./mapQuads";
|
||||
import {isOverlayLabelLayer, isOverlayLayerId} from "./mapOverlays";
|
||||
|
||||
export const EXPORT_DPI = 300;
|
||||
// How sharp a map may be asked for. More is four times the work for twice the sharpness: a
|
||||
// quadrangle at 600 is more than a browser will draw, or a Raspberry Pi will make a PDF of.
|
||||
export const EXPORT_DPIS = [300, 400];
|
||||
// The most the API makes a PDF of: the pixels of one layer, and of all the layers of a map together
|
||||
// (MAX_PIXELS and MAX_TOTAL_PIXELS in modules/map/export.py).
|
||||
const MAX_LAYER_PIXELS = 64_000_000;
|
||||
const MAX_TOTAL_PIXELS = 1_000_000_000;
|
||||
// The map's style is made for a screen, where its sizes (of text, of lines) are in CSS pixels. This
|
||||
// is how many of those are an inch of paper: fewer is larger text and less detail. At 150 a 12 pixel
|
||||
// label prints at about 6 points, which is what a topographic map uses, and a quadrangle is drawn at
|
||||
// about zoom 13 to 14.
|
||||
export const EXPORT_CSS_DPI = 150;
|
||||
// No browser makes a canvas larger than this, and few need to be asked for more.
|
||||
const MAX_CANVAS_SIDE = 16384;
|
||||
const FALLBACK_CANVAS_SIDE = 4096;
|
||||
const MILLIMETERS_PER_INCH = 25.4;
|
||||
const TILE_SIZE = 512;
|
||||
const RENDER_TIMEOUT_MS = 120_000;
|
||||
// How often it is asked whether the map has been too long in drawing.
|
||||
const RENDER_WATCH_MS = 1000;
|
||||
// How sharp the map is on which the groups are looked at, to see which have anything in them:
|
||||
// half as many pixels each way as there are CSS pixels. Anything drawn is still drawn.
|
||||
const LOOKING_PIXEL_RATIO = 0.5;
|
||||
// How many rows of a canvas are looked at at once.
|
||||
const BLANK_BAND_ROWS = 256;
|
||||
|
||||
export const BACKGROUND_GROUP = "Background";
|
||||
|
||||
// The largest canvas (in pixels a side) this browser will draw a map on.
|
||||
export function maxCanvasSide() {
|
||||
try {
|
||||
const canvas = document.createElement("canvas");
|
||||
const gl = canvas.getContext("webgl2") || canvas.getContext("webgl");
|
||||
if (!gl) return FALLBACK_CANVAS_SIDE;
|
||||
const viewport = gl.getParameter(gl.MAX_VIEWPORT_DIMS) || [];
|
||||
const side = Math.min(gl.getParameter(gl.MAX_TEXTURE_SIZE), viewport[0], viewport[1], MAX_CANVAS_SIDE);
|
||||
gl.getExtension("WEBGL_lose_context")?.loseContext();
|
||||
return Number.isFinite(side) && side > 0 ? side : FALLBACK_CANVAS_SIDE;
|
||||
} catch (e) {
|
||||
return FALLBACK_CANVAS_SIDE;
|
||||
}
|
||||
}
|
||||
|
||||
// The most pixels each layer of a map of `layerCount` layers may be.
|
||||
export function maxExportPixels(layerCount) {
|
||||
return Math.min(MAX_LAYER_PIXELS, Math.floor(MAX_TOTAL_PIXELS / Math.max(1, layerCount)));
|
||||
}
|
||||
|
||||
function mercatorY(latitude) {
|
||||
return Math.log(Math.tan(Math.PI / 4 + latitude * Math.PI / 360));
|
||||
}
|
||||
|
||||
function latitudeOfMercatorY(y) {
|
||||
return (2 * Math.atan(Math.exp(y)) - Math.PI / 2) * 180 / Math.PI;
|
||||
}
|
||||
|
||||
// How to draw a quadrangle at 1:24,000: the size of the map to make (in CSS pixels), where to put it
|
||||
// (center, zoom), and how many real pixels each CSS pixel is.
|
||||
//
|
||||
// The map is Web Mercator, in which a quadrangle is exactly a rectangle. It is as wide as the sheet
|
||||
// is at the quadrangle's middle, and as tall as Mercator makes that.
|
||||
//
|
||||
// The map is as sharp as was asked for (`dpi`), or as sharp as it can be: no side of it longer than
|
||||
// `maxSide` (the browser's largest canvas), and no more of it than `maxPixels` (what the API takes).
|
||||
export function exportFrame(quad, {
|
||||
dpi = EXPORT_DPI, cssDpi = EXPORT_CSS_DPI, maxSide = MAX_CANVAS_SIDE, maxPixels = Infinity,
|
||||
} = {}) {
|
||||
const widthInches = quadSize(quad).sheetWidthMm / MILLIMETERS_PER_INCH;
|
||||
const cssWidth = Math.round(widthInches * cssDpi);
|
||||
// The width of the whole world at the zoom where the quadrangle is `cssWidth` wide.
|
||||
const world = cssWidth * 360 / QUAD_DEGREES;
|
||||
const [south, north] = [mercatorY(quad.south), mercatorY(quad.north)];
|
||||
const cssHeight = Math.round((north - south) / (2 * Math.PI) * world);
|
||||
|
||||
// A hair under what the pixels allow: each side of the canvas is rounded to a whole pixel.
|
||||
const pixelRatio = Math.min(
|
||||
dpi / cssDpi,
|
||||
maxSide / Math.max(cssWidth, cssHeight),
|
||||
Math.sqrt(maxPixels / (cssWidth * cssHeight)) * 0.999);
|
||||
return {
|
||||
cssWidth,
|
||||
cssHeight,
|
||||
pixelRatio,
|
||||
dpi: pixelRatio * cssDpi,
|
||||
zoom: Math.log2(world / TILE_SIZE),
|
||||
bounds: [quad.west, quad.south, quad.east, quad.north],
|
||||
center: [(quad.west + quad.east) / 2, latitudeOfMercatorY((south + north) / 2)],
|
||||
};
|
||||
}
|
||||
|
||||
// The name of a basemap layer without the source it is of ("oregon.pmtiles:water" is "water").
|
||||
function basemapLayerName(layerId) {
|
||||
return layerId.includes(":") ? layerId.split(":").slice(1).join(":") : layerId;
|
||||
}
|
||||
|
||||
// The kinds of layer which are drawn over what is under them without hiding it: a line, a name.
|
||||
const THIN_LAYER_TYPES = new Set(["line", "symbol", "circle"]);
|
||||
|
||||
// The layers of the PDF: the visible layers of the map's style, gathered as the layer control
|
||||
// gathers them, from the bottom up. Each is {name, ids, raster}. An overlay is one layer, or two
|
||||
// when it has both ground and labels (see orderOverlayLayers).
|
||||
//
|
||||
// A layer of the PDF is drawn as images, and an image is in one place among the others. The layers
|
||||
// of a group are not always together in the style: the parks of Land Cover are under the water and
|
||||
// its piers are over it, and a second basemap file has all of its layers over the first's. So a
|
||||
// group is as many images as it must be, each with the name of the group (they are one layer of the
|
||||
// PDF): a part of it which fills an area stays where it is, because moved over what was above it,
|
||||
// it would hide that; a part which is only lines or names is drawn with the group's next part.
|
||||
//
|
||||
// styleLayers: the layers of the map's style, as the map has them now.
|
||||
// layerGroups: {name: [part of a layer id, ...]}, the basemap groups of the layer control.
|
||||
// overlayLabels: {source id: label} of the overlay files.
|
||||
export function exportGroups(styleLayers, {layerGroups = {}, overlayLabels = {}} = {}) {
|
||||
const groupNames = Object.keys(layerGroups);
|
||||
// What each visible layer is of: {key, name, overlay}.
|
||||
const groupOf = layer => {
|
||||
if (isOverlayLayerId(layer.id)) {
|
||||
// An overlay is drawn in two places: its ground under the basemap's labels, and its own
|
||||
// labels over them. Each is a layer of the PDF.
|
||||
const part = isOverlayLabelLayer(layer) ? "labels" : "ground";
|
||||
return {
|
||||
key: `overlay ${part} ${layer.source}`, name: overlayLabels[layer.source] || layer.source,
|
||||
overlay: {source: layer.source, part},
|
||||
};
|
||||
}
|
||||
const name = basemapLayerName(layer.id);
|
||||
// A layer in more than one group (a water label) is of the last, which is the labels.
|
||||
const group = [...groupNames].reverse().find(g => layerGroups[g].some(part => name.includes(part)));
|
||||
// What is in no group is the ground everything else is drawn on.
|
||||
return group ? {key: `group ${group}`, name: group} : {key: "background", name: BACKGROUND_GROUP};
|
||||
};
|
||||
|
||||
// The style from the bottom up, as runs of layers which are of one group and are together.
|
||||
const runs = [];
|
||||
for (const layer of styleLayers) {
|
||||
if (layer.layout?.visibility === "none") continue;
|
||||
const group = groupOf(layer);
|
||||
let run = runs[runs.length - 1];
|
||||
if (run?.key !== group.key) {
|
||||
run = {...group, ids: [], raster: true, thin: true};
|
||||
runs.push(run);
|
||||
}
|
||||
run.ids.push(layer.id);
|
||||
run.raster = run.raster && layer.type === "raster";
|
||||
run.thin = run.thin && THIN_LAYER_TYPES.has(layer.type);
|
||||
}
|
||||
// A run of lines is drawn with the next run of its group, when there is one.
|
||||
const waiting = new Map();
|
||||
const placed = [];
|
||||
for (const [index, run] of runs.entries()) {
|
||||
const ids = [...(waiting.get(run.key) || []), ...run.ids];
|
||||
waiting.delete(run.key);
|
||||
if (run.thin && runs.slice(index + 1).some(later => later.key === run.key)) {
|
||||
waiting.set(run.key, ids);
|
||||
} else {
|
||||
placed.push({...run, ids});
|
||||
}
|
||||
}
|
||||
|
||||
// The labels of an overlay are named as its labels when its ground is a layer too.
|
||||
const grounds = new Set(placed.filter(g => g.overlay?.part === "ground").map(g => g.overlay.source));
|
||||
// Two groups of one name are told apart; the images of one group have one name.
|
||||
const used = new Set();
|
||||
const names = new Map();
|
||||
return placed.map(({key, name, ids, raster, overlay}) => {
|
||||
if (!names.has(key)) {
|
||||
if (overlay?.part === "labels" && grounds.has(overlay.source)) name = `${name} (labels)`;
|
||||
let unique = name;
|
||||
for (let n = 2; used.has(unique); n++) unique = `${name} (${n})`;
|
||||
used.add(unique);
|
||||
names.set(key, unique);
|
||||
}
|
||||
return {name: names.get(key), ids, raster};
|
||||
});
|
||||
}
|
||||
|
||||
// The sources of a style whose map file has nothing of an area: a map of another state. Their
|
||||
// layers are not drawn, each of which would be an image of nothing, counted against how sharp the
|
||||
// map may be. A source is only left out when its file says where it is of, and that is elsewhere.
|
||||
//
|
||||
// bounds: the west, south, east and north edges of the area.
|
||||
// readBounds(url): the edges of the map file a source has as its `url`, or null (see mapTiles.js).
|
||||
export async function sourcesOutside(style, bounds, readBounds) {
|
||||
const [west, south, east, north] = bounds;
|
||||
const outside = new Set();
|
||||
await Promise.all(Object.entries(style.sources || {}).map(async ([id, source]) => {
|
||||
if (typeof source.url !== "string" || !source.url.startsWith("pmtiles://")) return;
|
||||
try {
|
||||
const edges = await readBounds(source.url);
|
||||
if (!edges) return;
|
||||
const [fileWest, fileSouth, fileEast, fileNorth] = edges;
|
||||
if (fileEast <= west || fileWest >= east || fileNorth <= south || fileSouth >= north) outside.add(id);
|
||||
} catch (e) {
|
||||
// A file which can not be asked is drawn, as it was going to be.
|
||||
console.warn("Could not read where a map file is of:", source.url, e);
|
||||
}
|
||||
}));
|
||||
return outside;
|
||||
}
|
||||
|
||||
// A basemap's tiles name its small roads from this zoom on. A quadrangle is drawn at about zoom 13,
|
||||
// from tiles in which the streets of a town are lines with no names.
|
||||
export const EXPORT_DETAIL_ZOOM = 14;
|
||||
// The layers of a basemap which name roads.
|
||||
const ROAD_LABELS = "roads_labels";
|
||||
const ROAD_NAMES_SOURCE = "export-road-names:";
|
||||
// More room (ems) than the name of a road is long: a name is one line.
|
||||
const ROAD_NAME_MAX_EMS = 1000;
|
||||
// Which way the name of a road is turned (degrees, clockwise), in what is said of the road.
|
||||
const NAME_ANGLE = "export:angle";
|
||||
const ROAD_TEXT_SIZE = 12;
|
||||
// About how wide a letter is, in its own height.
|
||||
const LETTER_WIDTH = 0.55;
|
||||
// A long road is named again each time it has gone this far (CSS pixels: 2.7 inches of a sheet).
|
||||
const NAME_EVERY = 400;
|
||||
// Two names of one road are never nearer than this (CSS pixels).
|
||||
const SAME_NAME_APART = 150;
|
||||
// The most tiles names are read from. A quadrangle is 20 to 40 of them, and more only where it is a
|
||||
// sliver near a pole (455 at 85 degrees); more than this is not a quadrangle.
|
||||
const MAX_DETAIL_TILES = 512;
|
||||
|
||||
// The layers of `style` which name roads, but not on a map drawn at `zoom`: their style keeps the
|
||||
// names for a zoom at which a street is inches long on a screen. On a sheet a road is found by its
|
||||
// name.
|
||||
export function unnamedRoadLayers(style, zoom) {
|
||||
return (style.layers || []).filter(layer => layer.type === "symbol" && layer["source-layer"]
|
||||
&& String(layer.id).includes(ROAD_LABELS) && layer.minzoom > zoom);
|
||||
}
|
||||
|
||||
// The tiles of `zoom` which have part of `bounds` (west, south, east, north) in them: [{z, x, y}].
|
||||
export function tilesOfBounds([west, south, east, north], zoom) {
|
||||
const count = 2 ** zoom;
|
||||
const column = longitude => (longitude + 180) / 360 * count;
|
||||
const row = latitude => (1 - mercatorY(latitude) / Math.PI) / 2 * count;
|
||||
const clamp = n => Math.min(count - 1, Math.max(0, n));
|
||||
// A tile whose edge is the edge of the bounds has nothing of them in it.
|
||||
const [left, right] = [clamp(Math.floor(column(west))), clamp(Math.ceil(column(east)) - 1)];
|
||||
const [top, bottom] = [clamp(Math.floor(row(north))), clamp(Math.ceil(row(south)) - 1)];
|
||||
const tiles = [];
|
||||
for (let x = left; x <= right; x++) {
|
||||
for (let y = top; y <= bottom; y++) tiles.push({z: zoom, x, y});
|
||||
}
|
||||
return tiles;
|
||||
}
|
||||
|
||||
// The roads of one layer of a tile which have a name, as GeoJSON features with all that the tile says
|
||||
// of them: what a layer of the style draws a name from is whatever its style asks for.
|
||||
//
|
||||
// tile: a tile as @mapbox/vector-tile reads it.
|
||||
export function namedRoads(tile, sourceLayer, {z, x, y}) {
|
||||
const layer = tile?.layers?.[sourceLayer];
|
||||
const features = [];
|
||||
for (let i = 0; layer && i < layer.length; i++) {
|
||||
const feature = layer.feature(i);
|
||||
if (!Object.keys(feature.properties).some(key => key === "name" || key.startsWith("name:"))) continue;
|
||||
const {geometry, properties} = feature.toGeoJSON(x, y, z);
|
||||
features.push({type: "Feature", geometry, properties});
|
||||
}
|
||||
return features;
|
||||
}
|
||||
|
||||
// What two pieces of one road have in common: its name, and what kind of road it is. The layers
|
||||
// which name roads each name some kinds of them, so a piece of another kind may not be named at all.
|
||||
function roadOf(properties) {
|
||||
return `${properties.kind ?? ""}\n${nameOf(properties)}`;
|
||||
}
|
||||
|
||||
function nameOf(properties) {
|
||||
return String(properties.name ?? Object.entries(properties).find(([key]) => key.startsWith("name:"))?.[1] ?? "");
|
||||
}
|
||||
|
||||
// Where a line (of points, with the length of each of its parts) is when it has gone `along`.
|
||||
function pointAlong(points, lengths, along) {
|
||||
let i = 0;
|
||||
while (i < lengths.length - 1 && along > lengths[i]) along -= lengths[i++];
|
||||
const part = lengths[i] ? Math.min(1, Math.max(0, along / lengths[i])) : 0;
|
||||
const [from, to] = [points[i], points[i + 1]];
|
||||
return [from[0] + (to[0] - from[0]) * part, from[1] + (to[1] - from[1]) * part];
|
||||
}
|
||||
|
||||
// Where named roads (of namedRoads) are named on a map drawn at `zoom` with text of `textSize` CSS
|
||||
// pixels: a GeoJSON FeatureCollection of points, each with all that is said of its road, and which
|
||||
// way the road goes there (NAME_ANGLE).
|
||||
//
|
||||
// A map writes a name along a road only where the road is longer than the name and bends little,
|
||||
// and at the scale of a sheet most streets of a town are shorter than their names. So the names
|
||||
// are placed here, as a map maker places them: over the middle of the road, turned as the road goes
|
||||
// under the name, and over its ends when it is short; again every NAME_EVERY of a long road.
|
||||
//
|
||||
// A road is in pieces where two tiles meet, and where what is said of it changes. The longest
|
||||
// pieces are named first, and a piece is not named near where its road already is.
|
||||
export function placeRoadNames(features, zoom, textSize = ROAD_TEXT_SIZE) {
|
||||
const world = TILE_SIZE * 2 ** zoom;
|
||||
const pixel = ([longitude, latitude]) => [
|
||||
(longitude + 180) / 360 * world, (1 - mercatorY(latitude) / Math.PI) / 2 * world];
|
||||
const pieces = [];
|
||||
for (const {geometry, properties} of features) {
|
||||
const parts = geometry.type === "MultiLineString" ? geometry.coordinates
|
||||
: geometry.type === "LineString" ? [geometry.coordinates] : [];
|
||||
for (const coordinates of parts) {
|
||||
if (coordinates.length < 2) continue;
|
||||
const pixels = coordinates.map(pixel);
|
||||
const lengths = pixels.slice(1).map((point, i) => Math.hypot(point[0] - pixels[i][0], point[1] - pixels[i][1]));
|
||||
const length = lengths.reduce((sum, n) => sum + n, 0);
|
||||
if (length) pieces.push({coordinates, pixels, lengths, length, properties});
|
||||
}
|
||||
}
|
||||
const named = new Map();
|
||||
const points = [];
|
||||
for (const {coordinates, pixels, lengths, length, properties} of pieces.sort((a, b) => b.length - a.length)) {
|
||||
const road = roadOf(properties);
|
||||
if (!named.has(road)) named.set(road, []);
|
||||
const places = named.get(road);
|
||||
const width = nameOf(properties).length * textSize * LETTER_WIDTH;
|
||||
const count = Math.max(1, Math.floor(length / NAME_EVERY));
|
||||
for (let n = 0; n < count; n++) {
|
||||
const along = (n + 0.5) * length / count;
|
||||
const at = pointAlong(pixels, lengths, along);
|
||||
if (places.some(other => Math.hypot(other[0] - at[0], other[1] - at[1]) < SAME_NAME_APART)) continue;
|
||||
places.push(at);
|
||||
// From where the name begins to where it ends, and never upside down.
|
||||
const first = pointAlong(pixels, lengths, Math.max(0, along - width / 2));
|
||||
const last = pointAlong(pixels, lengths, Math.min(length, along + width / 2));
|
||||
let angle = Math.atan2(last[1] - first[1], last[0] - first[0]) * 180 / Math.PI;
|
||||
if (angle > 90) angle -= 180;
|
||||
if (angle <= -90) angle += 180;
|
||||
points.push({
|
||||
type: "Feature",
|
||||
geometry: {type: "Point", coordinates: pointAlong(coordinates, lengths, along)},
|
||||
properties: {...properties, [NAME_ANGLE]: Math.round(angle * 10) / 10},
|
||||
});
|
||||
}
|
||||
}
|
||||
return {type: "FeatureCollection", features: points};
|
||||
}
|
||||
|
||||
// The names of the roads of the map which a map drawn for `frame` would not have: {source id: where
|
||||
// they are named (see placeRoadNames)}, for exportStyle. They are read from tiles of EXPORT_DETAIL_ZOOM.
|
||||
//
|
||||
// readTile(url, {z, x, y}): resolves to a tile of the source with that URL (as @mapbox/vector-tile
|
||||
// reads it), or to nothing when the source has no such tile.
|
||||
//
|
||||
// They are read wherever a layer would not name roads, whatever tiles the map itself is drawn from:
|
||||
// nearer the equator a quadrangle is drawn at a little over zoom 14, from tiles which have the names,
|
||||
// but its streets are as short there as anywhere.
|
||||
//
|
||||
// isCancelled(): asked before each source is read; when it is so no more is read.
|
||||
//
|
||||
// A source whose names can not be read is left out, and the map is exported without them.
|
||||
export async function loadRoadNames(style, frame, readTile, isCancelled) {
|
||||
const names = {};
|
||||
// Each source once: the layers which name its roads are of one layer of its tiles.
|
||||
const unnamed = new Map(unnamedRoadLayers(style, frame.zoom).map(layer => [layer.source, layer]));
|
||||
if (!readTile || !unnamed.size) return names;
|
||||
const tiles = tilesOfBounds(frame.bounds, EXPORT_DETAIL_ZOOM);
|
||||
if (tiles.length > MAX_DETAIL_TILES) return names;
|
||||
for (const [sourceId, layer] of unnamed) {
|
||||
if (isCancelled && isCancelled()) break;
|
||||
const sourceLayer = layer["source-layer"];
|
||||
const textSize = Number.isFinite(layer.layout?.["text-size"]) ? layer.layout["text-size"] : ROAD_TEXT_SIZE;
|
||||
const url = style.sources?.[sourceId]?.url;
|
||||
if (!url) continue;
|
||||
try {
|
||||
const read = await Promise.all(tiles.map(async tile => namedRoads(await readTile(url, tile), sourceLayer, tile)));
|
||||
const features = read.flat();
|
||||
if (features.length) names[sourceId] = placeRoadNames(features, frame.zoom, textSize);
|
||||
} catch (e) {
|
||||
console.warn(`The road names of ${sourceId} could not be read`, e);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
// A copy of the map's style in which nothing is drawn, for the map which is exported from; the
|
||||
// layers are shown a group at a time. Layers which are of the app and not of the map (those whose
|
||||
// id starts with one of `ignoredPrefixes`) are not in it.
|
||||
//
|
||||
// roadNames: what loadRoadNames gave for a map drawn at `zoom`. A layer which would not name roads
|
||||
// at that zoom names those instead, in its own style, where placeRoadNames put the names.
|
||||
export function exportStyle(style, ignoredPrefixes = [], {zoom = null, roadNames = {}} = {}) {
|
||||
const ignored = id => ignoredPrefixes.some(prefix => String(id).startsWith(prefix));
|
||||
const sources = Object.fromEntries(Object.entries(style.sources || {}).filter(([id]) => !ignored(id)));
|
||||
for (const [id, data] of Object.entries(roadNames)) {
|
||||
if (sources[id]) sources[ROAD_NAMES_SOURCE + id] = {type: "geojson", data};
|
||||
}
|
||||
const unnamed = new Set(zoom === null ? [] : unnamedRoadLayers(style, zoom).map(layer => layer.id));
|
||||
const layers = (style.layers || [])
|
||||
.filter(layer => !ignored(layer.id))
|
||||
.map(layer => {
|
||||
if (!unnamed.has(layer.id) || !sources[ROAD_NAMES_SOURCE + layer.source]) {
|
||||
const hidden = {...layer, layout: {...layer.layout, visibility: "none"}};
|
||||
// What a basemap draws from a zoom a little deeper than the map is drawn at (a
|
||||
// stream, a service road) is on a map of this scale, and is in the tiles it is
|
||||
// drawn from: it is drawn. Not names, of which there would be too many.
|
||||
if (zoom !== null && layer.type !== "symbol" && layer.minzoom > zoom
|
||||
&& layer.minzoom <= EXPORT_DETAIL_ZOOM) {
|
||||
hidden.minzoom = Math.floor(zoom);
|
||||
}
|
||||
return hidden;
|
||||
}
|
||||
const {minzoom, "source-layer": sourceLayer, ...named} = layer;
|
||||
return {
|
||||
...named,
|
||||
source: ROAD_NAMES_SOURCE + layer.source,
|
||||
layout: {
|
||||
...layer.layout,
|
||||
"symbol-placement": "point",
|
||||
"text-rotate": ["get", NAME_ANGLE],
|
||||
"text-rotation-alignment": "map",
|
||||
// A name along a line is one line; a name at a point is broken into several
|
||||
// unless it is told it has the room.
|
||||
"text-max-width": ROAD_NAME_MAX_EMS,
|
||||
visibility: "none",
|
||||
},
|
||||
};
|
||||
});
|
||||
return {...style, sources, layers};
|
||||
}
|
||||
|
||||
// The map's arithmetic can put the edge of the world a hair past where it is (180.00000000000125
|
||||
// degrees). Such an edge is the edge of the world; one further past it is of a map which crosses the
|
||||
// antimeridian, and is left as it is.
|
||||
const LONGITUDE_SLIVER = 1e-8;
|
||||
|
||||
function edgeLongitude(longitude) {
|
||||
if (Math.abs(longitude) > 180 && Math.abs(longitude) - 180 < LONGITUDE_SLIVER) return Math.sign(longitude) * 180;
|
||||
return longitude;
|
||||
}
|
||||
|
||||
// Only the time the page can be seen is counted: a browser does not draw a page which can not be
|
||||
// seen (another tab is in front of it), and the map is not slow for that.
|
||||
function once(map, event, timeoutMs = RENDER_TIMEOUT_MS) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let seenMs = 0;
|
||||
const timer = setInterval(() => {
|
||||
if (typeof document !== "undefined" && document.hidden) return;
|
||||
seenMs += RENDER_WATCH_MS;
|
||||
if (seenMs >= timeoutMs) {
|
||||
clearInterval(timer);
|
||||
reject(new Error("The map took too long to draw"));
|
||||
}
|
||||
}, RENDER_WATCH_MS);
|
||||
map.once(event, () => {
|
||||
clearInterval(timer);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function canvasBlob(canvas, type, quality) {
|
||||
return new Promise((resolve, reject) => canvas.toBlob(
|
||||
blob => (blob ? resolve(blob) : reject(new Error("The map could not be made into an image"))),
|
||||
type, quality));
|
||||
}
|
||||
|
||||
// Whether a canvas has no transparent part. It is reduced first: looking at every pixel of a sheet
|
||||
// is slow, and a part too small to survive the reduction is too small to matter. Its four edges are
|
||||
// looked at by themselves: a photograph which ends a little inside the map leaves a strip along an
|
||||
// edge, which is narrow enough to be lost in the reduction and wide enough to be seen.
|
||||
export function isOpaque(canvas) {
|
||||
const small = document.createElement("canvas");
|
||||
small.width = 64;
|
||||
small.height = Math.max(1, Math.round(64 * canvas.height / canvas.width));
|
||||
const context = small.getContext("2d");
|
||||
if (!context) return false;
|
||||
const {width, height} = canvas;
|
||||
const parts = [
|
||||
[0, 0, width, height],
|
||||
[0, 0, width, 1], [0, height - 1, width, 1], [0, 0, 1, height], [width - 1, 0, 1, height],
|
||||
];
|
||||
for (const [x, y, w, h] of parts) {
|
||||
context.clearRect(0, 0, small.width, small.height);
|
||||
context.drawImage(canvas, x, y, w, h, 0, 0, small.width, small.height);
|
||||
const {data} = context.getImageData(0, 0, small.width, small.height);
|
||||
for (let i = 3; i < data.length; i += 4) {
|
||||
if (data[i] !== 255) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Whether nothing is drawn on a canvas: every pixel of it is clear. Every pixel is looked at (a
|
||||
// lone well is a few of them), a band of rows at a time so that no more is in memory than a band.
|
||||
export function isBlankCanvas(canvas) {
|
||||
const band = document.createElement("canvas");
|
||||
band.width = canvas.width;
|
||||
band.height = Math.min(BLANK_BAND_ROWS, canvas.height);
|
||||
const context = band.getContext("2d", {willReadFrequently: true});
|
||||
// Not known to be blank, so it is drawn.
|
||||
if (!context) return false;
|
||||
for (let top = 0; top < canvas.height; top += band.height) {
|
||||
const rows = Math.min(band.height, canvas.height - top);
|
||||
context.clearRect(0, 0, band.width, band.height);
|
||||
context.drawImage(canvas, 0, top, canvas.width, rows, 0, 0, canvas.width, rows);
|
||||
// Only whether a pixel is seen at all: one which is not may still have a trace of a color.
|
||||
const {data} = context.getImageData(0, 0, canvas.width, rows);
|
||||
for (let i = 3; i < data.length; i += 4) {
|
||||
if (data[i] !== 0) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Whether the browser has stopped drawing on a map's canvas (it does when it has too many, or is
|
||||
// short of memory): such a canvas reads as clear.
|
||||
function contextLost(canvas) {
|
||||
if (typeof canvas.getContext !== "function") return false;
|
||||
const context = canvas.getContext("webgl2") || canvas.getContext("webgl");
|
||||
return Boolean(context && typeof context.isContextLost === "function" && context.isContextLost());
|
||||
}
|
||||
|
||||
// Draw each group of layers of `style` on a map of its own, and return the images:
|
||||
// {width, height, dpi, bounds, layers: [{name, blob}]}. `bounds` is the west, south, east and north
|
||||
// edges of the images (degrees), which is what says where the PDF is on the Earth: they are read
|
||||
// from the map which was drawn, so they are of the picture and not of what was asked for.
|
||||
//
|
||||
// MapClass: maplibregl.Map. setup(map): called with the new map before it draws anything.
|
||||
// readTile: how to read a tile of a source (see loadRoadNames); without it small roads have no names.
|
||||
// onProgress(name, index, count, frame): called before each group is drawn, with the frame it is
|
||||
// drawn in. isCancelled(): asked before each group whether to stop; when it is so nothing more is
|
||||
// drawn, and this rejects with an error whose `cancelled` is true.
|
||||
//
|
||||
// frame: how the map is drawn (see exportFrame). Or frameFor(count): the frame of a map of that
|
||||
// many images. How sharp a map may be depends on how many images it is, and a group in which
|
||||
// nothing is drawn (a basemap file with no runway in the quadrangle) is no image: so the groups are
|
||||
// first looked at on a small map, onLooking() is told, and only those with something in them are
|
||||
// drawn, as sharp as that many may be. isBlank(canvas): whether nothing is drawn on a canvas.
|
||||
export async function renderExport({
|
||||
MapClass, style, frame, frameFor, groups, setup, onProgress, onLooking, isCancelled, readTile,
|
||||
ignoredPrefixes = [], isBlank = isBlankCanvas,
|
||||
}) {
|
||||
const cancelled = () => Object.assign(new Error("The export was cancelled"), {cancelled: true});
|
||||
// The size, the middle and the zoom of the map are the same however many images it is.
|
||||
if (frameFor) frame = frameFor(groups.length);
|
||||
const roadNames = await loadRoadNames(style, frame, readTile, isCancelled);
|
||||
// Reading the names is the first of the work, and may be the slowest of it.
|
||||
if (isCancelled && isCancelled()) throw cancelled();
|
||||
const container = document.createElement("div");
|
||||
// Off the screen, but laid out and drawn as any element is.
|
||||
container.style.cssText = `position:fixed;left:-100000px;top:0;width:${frame.cssWidth}px;`
|
||||
+ `height:${frame.cssHeight}px;pointer-events:none;`;
|
||||
document.body.appendChild(container);
|
||||
|
||||
let map;
|
||||
try {
|
||||
const exported = exportStyle(style, ignoredPrefixes, {zoom: frame.zoom, roadNames});
|
||||
// A map which draws as sharp as `pixelRatio` says. A map is made as sharp as it is to be:
|
||||
// a browser lets a canvas be larger when it is made than it lets one be made larger later
|
||||
// (some 33 million pixels, less than a quadrangle at 400 DPI).
|
||||
const makeMap = async pixelRatio => {
|
||||
const side = Math.ceil(Math.max(frame.cssWidth, frame.cssHeight) * pixelRatio);
|
||||
map = new MapClass({
|
||||
container,
|
||||
style: exported,
|
||||
center: frame.center,
|
||||
zoom: frame.zoom,
|
||||
interactive: false,
|
||||
attributionControl: false,
|
||||
pixelRatio,
|
||||
maxCanvasSize: [side, side],
|
||||
// The canvas is read after it is drawn, so what was drawn must still be in it.
|
||||
canvasContextAttributes: {preserveDrawingBuffer: true},
|
||||
// A label is all there at once: nothing is caught half faded in.
|
||||
fadeDuration: 0,
|
||||
});
|
||||
if (setup) setup(map);
|
||||
await once(map, "load");
|
||||
return map.getCanvas();
|
||||
};
|
||||
let canvas = await makeMap(frameFor ? Math.min(LOOKING_PIXEL_RATIO, frame.pixelRatio) : frame.pixelRatio);
|
||||
// Draw a group alone, have `drawn()` look at the canvas, and hide the group again.
|
||||
const draw = async (group, drawn) => {
|
||||
if (isCancelled && isCancelled()) {
|
||||
throw cancelled();
|
||||
}
|
||||
const show = visibility => {
|
||||
for (const id of group.ids) {
|
||||
if (map.getLayer(id)) map.setLayoutProperty(id, "visibility", visibility);
|
||||
}
|
||||
};
|
||||
show("visible");
|
||||
const idle = once(map, "idle");
|
||||
map.triggerRepaint();
|
||||
await idle;
|
||||
const result = await drawn();
|
||||
show("none");
|
||||
return result;
|
||||
};
|
||||
|
||||
if (frameFor) {
|
||||
if (onLooking) onLooking();
|
||||
const seen = [];
|
||||
for (const group of groups) {
|
||||
const blank = await draw(group, () => isBlank(canvas));
|
||||
// A canvas the browser has stopped drawing on is clear, whatever was to be drawn:
|
||||
// that is not a group with nothing in it, to be left out and not missed.
|
||||
if (blank && contextLost(canvas)) throw new Error("The browser stopped drawing the map");
|
||||
if (!blank) seen.push(group);
|
||||
}
|
||||
if (!seen.length) throw new Error("Nothing is drawn in any layer of the map");
|
||||
// Stopped while the groups were looked at: the map to export from is not made.
|
||||
if (isCancelled && isCancelled()) throw cancelled();
|
||||
groups = seen;
|
||||
frame = frameFor(groups.length);
|
||||
// The small map is done with; the map which is exported from is made in its place.
|
||||
map.remove();
|
||||
map = null;
|
||||
canvas = await makeMap(frame.pixelRatio);
|
||||
}
|
||||
|
||||
const layers = [];
|
||||
for (const [index, group] of groups.entries()) {
|
||||
// A group is not said to be drawn when it will not be.
|
||||
if (isCancelled && isCancelled()) throw cancelled();
|
||||
if (onProgress) onProgress(group.name, index, groups.length, frame);
|
||||
const blob = await draw(group, async () => {
|
||||
// A photograph with no gaps is far smaller as a JPEG; anything else needs to be seen through.
|
||||
return group.raster && isOpaque(canvas)
|
||||
? await canvasBlob(canvas, "image/jpeg", 0.9)
|
||||
: await canvasBlob(canvas, "image/png");
|
||||
});
|
||||
layers.push({name: group.name, blob});
|
||||
}
|
||||
const edges = map.getBounds();
|
||||
return {
|
||||
width: canvas.width,
|
||||
height: canvas.height,
|
||||
bounds: [edgeLongitude(edges.getWest()), edges.getSouth(), edgeLongitude(edges.getEast()), edges.getNorth()],
|
||||
dpi: canvas.width / frame.cssWidth * (frame.dpi / frame.pixelRatio),
|
||||
layers,
|
||||
};
|
||||
} finally {
|
||||
if (map) map.remove();
|
||||
container.remove();
|
||||
}
|
||||
}
|
||||
|
||||
// Where the data of the exported layers is from: what each of their sources says of itself, once
|
||||
// each, as text.
|
||||
//
|
||||
// map: the map on the screen, whose sources have been loaded (a source may only learn its
|
||||
// attribution from its file).
|
||||
export function exportCredits(map, groups) {
|
||||
const style = map.getStyle();
|
||||
const exported = new Set(groups.flatMap(group => group.ids));
|
||||
const credits = [];
|
||||
for (const layer of style.layers || []) {
|
||||
if (!layer.source || !exported.has(layer.id)) continue;
|
||||
const attribution = map.getSource(layer.source)?.attribution || style.sources?.[layer.source]?.attribution;
|
||||
if (!attribution) continue;
|
||||
// An attribution is HTML: links, mostly. One may name many sources, with a bar between them.
|
||||
const html = new DOMParser().parseFromString(String(attribution), "text/html");
|
||||
for (const part of (html.body.textContent || "").split("|")) {
|
||||
const text = part.replace(/\s+/g, " ").trim();
|
||||
if (text && !credits.includes(text)) credits.push(text);
|
||||
}
|
||||
}
|
||||
return credits;
|
||||
}
|
||||
|
||||
// The day, as the person exporting the map has it: 2026-11-15.
|
||||
export function exportDate(now = new Date()) {
|
||||
const pad = value => String(value).padStart(2, "0");
|
||||
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
||||
}
|
||||
|
||||
// What is written on the sheet a quadrangle is printed on. `named` is what the USGS calls the
|
||||
// quadrangle ({name, state, exact}), when it calls it anything: else it goes by where it is.
|
||||
//
|
||||
// contours: {interval, unit} ("feet" or "meters"): how far apart the contour lines of the exported
|
||||
// map are, when it has them.
|
||||
//
|
||||
// legend: the lines of the map as they are drawn (of exportLegend), when it has any.
|
||||
export function exportSheet(quad, map, groups, now = new Date(), named = null, contours = null, legend = null) {
|
||||
return {
|
||||
name: quadTitle(named) || quadLabel(quad),
|
||||
credits: exportCredits(map, groups),
|
||||
date: exportDate(now),
|
||||
...(contours ? {contours} : {}),
|
||||
...(legend ? {legend} : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// How far apart the contour lines of an exported map are, for exportSheet; null when no layer of
|
||||
// `contourLayers` (parts of ids, as the layer control has them) is among the `groups` which are
|
||||
// exported, or no line is drawn at the zoom.
|
||||
//
|
||||
// interval: [minor, major] at the zoom the map is exported at (see contourInterval).
|
||||
export function exportContours(groups, contourLayers, interval, imperial) {
|
||||
const exported = groups.some(group => group.ids.some(id => contourLayers.some(part => id.includes(part))));
|
||||
if (!exported || !interval) return null;
|
||||
return {interval: interval[0], unit: imperial ? "feet" : "meters"};
|
||||
}
|
||||
|
||||
// "N40.250_W105.125": where a quadrangle's southwest corner is, in a form a file can be named.
|
||||
function quadFileStem(quad) {
|
||||
const part = (value, positive, negative) => `${value < 0 ? negative : positive}${Math.abs(value).toFixed(3)}`;
|
||||
return `${part(quad.south, "N", "S")}_${part(quad.west, "E", "W")}`;
|
||||
}
|
||||
|
||||
// A name as a part of a file's: "Berthoud".
|
||||
function fileNamePart(name) {
|
||||
// An accent is left off its letter (Cañon is Canon), not made a gap in the name.
|
||||
return String(name).normalize("NFKD").replace(/\p{M}+/gu, "").replace(/[^A-Za-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 60);
|
||||
}
|
||||
|
||||
export function exportFileName(quad, named = null) {
|
||||
const name = named?.name ? fileNamePart(named.name) : "";
|
||||
return `wrolpi-map_${QUAD_SCALE / 1000}k_${name ? `${name}_` : ""}${quadFileStem(quad)}.pdf`;
|
||||
}
|
||||
|
||||
export function exportTitle(quad, named = null) {
|
||||
return `1:${QUAD_SCALE.toLocaleString("en-US")} ${quadTitle(named) || quadLabel(quad)}`;
|
||||
}
|
||||
|
||||
// Give the user a file to keep.
|
||||
export function saveBlob(blob, filename) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.style.display = "none";
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
// Not at once: a large file is still being read when the click returns.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
1123
app/src/components/mapExport.test.js
Normal file
1123
app/src/components/mapExport.test.js
Normal file
File diff suppressed because it is too large
Load diff
117
app/src/components/mapExportLegend.js
Normal file
117
app/src/components/mapExportLegend.js
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
// The legend of an exported map: what its lines are, each as the map draws it.
|
||||
//
|
||||
// The map's style says how a road is drawn at each zoom, and a sheet is drawn at one. The lines are
|
||||
// described here, where the style can be read, and drawn on the sheet by the API.
|
||||
|
||||
import {expression, latest} from "@maplibre/maplibre-gl-style-spec";
|
||||
import {EXPORT_CSS_DPI} from "./mapExport";
|
||||
|
||||
const POINTS_PER_INCH = 72;
|
||||
const WHITE = [1, 1, 1];
|
||||
// The thinnest line (points) a legend has. A style brings a line in from nothing as the map is
|
||||
// zoomed in, and a line of a few hundredths of a point is not one anybody sees on a sheet.
|
||||
export const LEGEND_LEAST_WIDTH = 0.1;
|
||||
|
||||
// The lines a legend may have, from the top: what each is called, the layer of the basemap (or of
|
||||
// the contours) which draws it, and the layers which may draw its edges under it.
|
||||
export const LEGEND_LINES = [
|
||||
{label: "Highway", line: "roads_highway", casings: ["roads_highway_casing_late", "roads_highway_casing_early"]},
|
||||
{label: "Major road", line: "roads_major", casings: ["roads_major_casing_late", "roads_major_casing_early"]},
|
||||
{label: "Minor road", line: "roads_minor", casings: ["roads_minor_casing"]},
|
||||
{label: "Path or track", line: "roads_other"},
|
||||
{label: "Railway", line: "roads_rail"},
|
||||
{label: "Boundary", line: "boundaries"},
|
||||
{label: "Index contour", line: "contour-lines-major"},
|
||||
{label: "Contour", line: "contour-lines"},
|
||||
];
|
||||
|
||||
// The name of a basemap layer without the source it is of ("oregon.pmtiles:water" is "water").
|
||||
function layerName(layerId) {
|
||||
const id = String(layerId);
|
||||
return id.includes(":") ? id.split(":").slice(1).join(":") : id;
|
||||
}
|
||||
|
||||
// What a property of a layer is at a zoom; the style's own default when the layer does not say.
|
||||
function valueAt(layer, group, property, zoom) {
|
||||
const spec = latest[`${group}_${layer.type}`]?.[property];
|
||||
if (!spec) return undefined;
|
||||
const value = layer[group]?.[property] ?? spec.default;
|
||||
if (value === undefined) return undefined;
|
||||
try {
|
||||
return expression.normalizePropertyExpression(value, spec).evaluate({zoom});
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// A color of the style as red, green and blue from 0 to 1, and how opaque it is.
|
||||
function colorParts(color) {
|
||||
if (!color || !Number.isFinite(color.a) || color.a <= 0) return null;
|
||||
// The style keeps a color multiplied by its opacity.
|
||||
const part = n => Math.round(Math.min(1, Math.max(0, n / color.a)) * 1000) / 1000;
|
||||
return {color: [part(color.r), part(color.g), part(color.b)], opacity: color.a};
|
||||
}
|
||||
|
||||
function drawnAt(layer, zoom) {
|
||||
return (layer.minzoom === undefined || zoom >= layer.minzoom) && (layer.maxzoom === undefined || zoom < layer.maxzoom);
|
||||
}
|
||||
|
||||
const round = n => Math.round(n * 100) / 100;
|
||||
|
||||
// The legend of a map which is exported: {ground, lines}, for the sheet (see `Sheet.legend` in
|
||||
// modules/map/sheet.py), or null when the map has none of the lines a legend is of.
|
||||
//
|
||||
// style: the map's style. groups: the layers which are exported (of exportGroups). zoom: the zoom
|
||||
// the map is exported at. cssDpi: how many CSS pixels of the style are an inch of the sheet.
|
||||
//
|
||||
// A line is in the legend when its layer is exported and draws a line which can be seen at that
|
||||
// zoom: a path which the style only draws from zoom 14 is not on a sheet drawn at 13, nor in its
|
||||
// legend, and at 14.2 it is too thin to be on either.
|
||||
export function exportLegend(style, groups, zoom, cssDpi = EXPORT_CSS_DPI) {
|
||||
const exported = new Set(groups.flatMap(group => group.ids));
|
||||
const layers = (style.layers || []).filter(layer => exported.has(layer.id) && drawnAt(layer, zoom));
|
||||
const points = POINTS_PER_INCH / cssDpi;
|
||||
const find = name => layers.find(layer => layer.type === "line" && layerName(layer.id) === name);
|
||||
|
||||
const lines = [];
|
||||
for (const {label, line, casings = []} of LEGEND_LINES) {
|
||||
const layer = find(line);
|
||||
if (!layer) continue;
|
||||
const width = valueAt(layer, "paint", "line-width", zoom);
|
||||
const parts = colorParts(valueAt(layer, "paint", "line-color", zoom));
|
||||
if (!parts || !(width * points >= LEGEND_LEAST_WIDTH)) continue;
|
||||
const entry = {
|
||||
label,
|
||||
color: parts.color,
|
||||
width: round(width * points),
|
||||
opacity: round(parts.opacity * (valueAt(layer, "paint", "line-opacity", zoom) ?? 1)),
|
||||
};
|
||||
// The lengths of a dash are in widths of its line.
|
||||
const dash = valueAt(layer, "paint", "line-dasharray", zoom);
|
||||
if (Array.isArray(dash) && dash.length > 1) entry.dash = dash.map(n => round(n * width * points));
|
||||
// The edges of a road are a wider line under it, drawn as two lines with a gap between them.
|
||||
const casing = casings.map(find).find(Boolean);
|
||||
if (casing) {
|
||||
const edge = valueAt(casing, "paint", "line-width", zoom);
|
||||
const gap = valueAt(casing, "paint", "line-gap-width", zoom) ?? 0;
|
||||
const color = colorParts(valueAt(casing, "paint", "line-color", zoom));
|
||||
if (color && edge > 0) {
|
||||
entry.casing_color = color.color;
|
||||
entry.casing_width = round((gap + 2 * edge) * points);
|
||||
}
|
||||
}
|
||||
lines.push(entry);
|
||||
}
|
||||
if (!lines.length) return null;
|
||||
|
||||
// The land the lines are on: the topmost of the layers which color all of it.
|
||||
let ground = WHITE;
|
||||
for (const layer of layers) {
|
||||
const name = layerName(layer.id);
|
||||
const color = layer.type === "background" ? valueAt(layer, "paint", "background-color", zoom)
|
||||
: layer.type === "fill" && name === "earth" ? valueAt(layer, "paint", "fill-color", zoom) : null;
|
||||
const parts = colorParts(color);
|
||||
if (parts) ground = parts.color;
|
||||
}
|
||||
return {ground, lines};
|
||||
}
|
||||
133
app/src/components/mapExportLegend.test.js
Normal file
133
app/src/components/mapExportLegend.test.js
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
import {exportLegend, LEGEND_LEAST_WIDTH, LEGEND_LINES} from './mapExportLegend';
|
||||
|
||||
// A basemap as the map's style has it: roads with edges under them, at widths which change with
|
||||
// the zoom; and the contours of the terrain.
|
||||
const grows = (...stops) => ['interpolate', ['exponential', 1.6], ['zoom'], ...stops];
|
||||
const STYLE = {
|
||||
layers: [
|
||||
{id: 'background', type: 'background', paint: {'background-color': '#cccccc'}},
|
||||
{id: 'earth', type: 'fill', paint: {'fill-color': '#e2dfda'}},
|
||||
{id: 'roads_minor_casing', type: 'line', paint: {
|
||||
'line-color': '#e0e0e0', 'line-gap-width': grows(11, 0, 12.5, 0.5, 15, 2), 'line-width': grows(12, 0, 12.5, 1),
|
||||
}},
|
||||
{id: 'roads_highway_casing_late', type: 'line', minzoom: 12, paint: {
|
||||
'line-color': '#e0e0e0', 'line-gap-width': 2, 'line-width': 1,
|
||||
}},
|
||||
{id: 'roads_highway_casing_early', type: 'line', maxzoom: 12, paint: {
|
||||
'line-color': '#000000', 'line-gap-width': 1, 'line-width': 0.5,
|
||||
}},
|
||||
{id: 'roads_other', type: 'line', paint: {'line-color': '#ebebeb', 'line-dasharray': [3, 1], 'line-width': grows(14, 0, 20, 7)}},
|
||||
{id: 'roads_minor', type: 'line', paint: {
|
||||
'line-color': grows(11, '#ebebeb', 16, '#ffffff'), 'line-width': grows(11, 0, 12.5, 0.5, 15, 2),
|
||||
}},
|
||||
{id: 'roads_highway', type: 'line', paint: {'line-color': '#ffffff', 'line-width': 2}},
|
||||
{id: 'roads_rail', type: 'line', paint: {
|
||||
'line-dasharray': [0.3, 0.75], 'line-opacity': 0.5, 'line-color': '#a7b1b3', 'line-width': 1,
|
||||
}},
|
||||
{id: 'boundaries', type: 'line', paint: {
|
||||
'line-color': '#adadad', 'line-width': 0.4, 'line-dasharray': ['step', ['zoom'], ['literal', [2]], 4, ['literal', [2, 1]]],
|
||||
}},
|
||||
{id: 'roads_labels_minor', type: 'symbol'},
|
||||
{id: 'contour-lines', type: 'line', paint: {'line-color': 'rgba(150,100,50,0.3)', 'line-width': 0.5}},
|
||||
{id: 'contour-lines-major', type: 'line', paint: {'line-color': 'rgba(150,100,50,0.5)', 'line-width': 1}},
|
||||
],
|
||||
};
|
||||
const ALL = [{name: 'Everything', ids: STYLE.layers.map(layer => layer.id)}];
|
||||
const only = (...ids) => [{name: 'Some', ids}];
|
||||
const labels = legend => legend.lines.map(line => line.label);
|
||||
|
||||
describe('the legend of an exported map', () => {
|
||||
test('is of the lines which are exported and drawn at the zoom of the sheet, from the top', () => {
|
||||
const legend = exportLegend(STYLE, ALL, 13.2);
|
||||
// A path is drawn only from zoom 14: it is not on this sheet.
|
||||
expect(labels(legend)).toEqual(['Highway', 'Minor road', 'Railway', 'Boundary', 'Index contour', 'Contour']);
|
||||
expect(labels(exportLegend(STYLE, ALL, 15))).toContain('Path or track');
|
||||
// In the order they are listed, whatever order the style has them in.
|
||||
const order = LEGEND_LINES.map(line => line.label);
|
||||
expect(labels(legend)).toEqual(order.filter(label => labels(legend).includes(label)));
|
||||
});
|
||||
|
||||
test('a line is as wide on the sheet as the map draws it: 150 pixels of the style are an inch', () => {
|
||||
const {lines} = exportLegend(STYLE, ALL, 13.2);
|
||||
const highway = lines.find(line => line.label === 'Highway');
|
||||
// 2 pixels are 0.96 points; its edges are a pixel each side of it.
|
||||
expect(highway).toEqual({
|
||||
label: 'Highway', color: [1, 1, 1], width: 0.96, opacity: 1,
|
||||
casing_color: [0.878, 0.878, 0.878], casing_width: 1.92,
|
||||
});
|
||||
// At another scale of the style it is as much wider.
|
||||
expect(exportLegend(STYLE, ALL, 13.2, 75).lines[0].width).toBe(1.92);
|
||||
});
|
||||
|
||||
test('a color and a width which change with the zoom are those of the zoom', () => {
|
||||
const at = zoom => exportLegend(STYLE, ALL, zoom).lines.find(line => line.label === 'Minor road');
|
||||
expect(at(13.2).width).toBeGreaterThan(at(12.6).width);
|
||||
expect(at(13.2).width).toBeLessThan(at(15).width);
|
||||
expect(at(15).width).toBe(0.96);
|
||||
expect(at(12.6).color[0]).toBeLessThan(at(15.9).color[0]);
|
||||
// The edges of a road are those of the layer which draws them at that zoom.
|
||||
const highway = zoom => exportLegend(STYLE, ALL, zoom).lines[0];
|
||||
expect(highway(13).casing_color).toEqual([0.878, 0.878, 0.878]);
|
||||
expect(highway(11).casing_color).toEqual([0, 0, 0]);
|
||||
expect(highway(11).casing_width).toBe(0.96);
|
||||
});
|
||||
|
||||
test('a broken line has its dashes, and a faint one how faint it is', () => {
|
||||
const {lines} = exportLegend(STYLE, ALL, 13.2);
|
||||
const line = label => lines.find(i => i.label === label);
|
||||
// The dashes of a style are in widths of the line: 0.3 and 0.75 of 0.48 points.
|
||||
expect(line('Railway')).toMatchObject({dash: [0.14, 0.36], opacity: 0.5, width: 0.48});
|
||||
expect(line('Boundary').dash).toEqual([0.38, 0.19]);
|
||||
// A color which can be seen through is that color, and how much of it.
|
||||
expect(line('Contour')).toEqual({label: 'Contour', color: [0.588, 0.392, 0.196], width: 0.24, opacity: 0.3});
|
||||
expect(line('Index contour')).toMatchObject({width: 0.48, opacity: 0.5});
|
||||
expect(line('Highway')).not.toHaveProperty('dash');
|
||||
});
|
||||
|
||||
test('is on the color of the land which is exported', () => {
|
||||
expect(exportLegend(STYLE, ALL, 13.2).ground).toEqual([0.886, 0.875, 0.855]);
|
||||
// Without the land the lines are on the color under it, and without that on paper.
|
||||
expect(exportLegend(STYLE, only('background', 'roads_highway'), 13.2).ground).toEqual([0.8, 0.8, 0.8]);
|
||||
expect(exportLegend(STYLE, only('roads_highway'), 13.2).ground).toEqual([1, 1, 1]);
|
||||
});
|
||||
|
||||
test('has only what is exported', () => {
|
||||
const legend = exportLegend(STYLE, only('roads_highway', 'contour-lines'), 13.2);
|
||||
expect(labels(legend)).toEqual(['Highway', 'Contour']);
|
||||
// The road without its edges.
|
||||
expect(legend.lines[0]).not.toHaveProperty('casing_color');
|
||||
// A map with none of the lines has no legend.
|
||||
expect(exportLegend(STYLE, only('earth', 'roads_labels_minor'), 13.2)).toBeNull();
|
||||
expect(exportLegend(STYLE, [], 13.2)).toBeNull();
|
||||
expect(exportLegend({}, ALL, 13.2)).toBeNull();
|
||||
});
|
||||
|
||||
test('the layers of a second basemap file are the same lines', () => {
|
||||
const style = {layers: STYLE.layers.map(layer => ({...layer, id: `b.pmtiles:${layer.id}`}))};
|
||||
const groups = [{name: 'Everything', ids: style.layers.map(layer => layer.id)}];
|
||||
expect(labels(exportLegend(style, groups, 13.2))).toEqual(labels(exportLegend(STYLE, ALL, 13.2)));
|
||||
});
|
||||
|
||||
test('a line too thin to be seen is not in the legend', () => {
|
||||
// As the basemap draws a path: from nothing at zoom 14, where a quadrangle near the equator is drawn.
|
||||
const path = {id: 'roads_other', type: 'line', paint: {'line-color': '#ebebeb', 'line-width': grows(14, 0, 20, 7)}};
|
||||
const style = {layers: [path, {id: 'roads_highway', type: 'line', paint: {'line-width': 2}}]};
|
||||
const groups = only('roads_other', 'roads_highway');
|
||||
expect(labels(exportLegend(style, groups, 14.2))).toEqual(['Highway']);
|
||||
// Once it is a tenth of a point wide it is.
|
||||
expect(labels(exportLegend(style, groups, 15.5))).toEqual(['Highway', 'Path or track']);
|
||||
const least = {layers: [{id: 'roads_highway', type: 'line', paint: {'line-width': LEGEND_LEAST_WIDTH * 150 / 72}}]};
|
||||
expect(exportLegend(least, only('roads_highway'), 13).lines[0].width).toBe(LEGEND_LEAST_WIDTH);
|
||||
const less = {layers: [{id: 'roads_highway', type: 'line', paint: {'line-width': 0.2}}]};
|
||||
expect(exportLegend(less, only('roads_highway'), 13)).toBeNull();
|
||||
});
|
||||
|
||||
test('a layer which says nothing of its line is drawn as a style draws one', () => {
|
||||
const style = {layers: [{id: 'roads_highway', type: 'line'}]};
|
||||
expect(exportLegend(style, only('roads_highway'), 13).lines).toEqual([
|
||||
{label: 'Highway', color: [0, 0, 0], width: 0.48, opacity: 1}]);
|
||||
// What can not be made a color or a width of is left out.
|
||||
const broken = {layers: [{id: 'roads_highway', type: 'line', paint: {'line-color': ['nonsense'], 'line-width': 1}}]};
|
||||
expect(exportLegend(broken, only('roads_highway'), 13)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import {addOverlaysToMap, orderOverlayLayers} from '../map-shared/overlays.js';
|
||||
import {addOverlaysToMap, isOverlayLabelLayer, orderOverlayLayers} from '../map-shared/overlays.js';
|
||||
import {
|
||||
addOverlaysToStyle,
|
||||
basemapLabelsStart,
|
||||
labelsOverGround,
|
||||
buildOverlayLayers,
|
||||
buildOverlaySource,
|
||||
isBasemapLayer,
|
||||
|
|
@ -240,7 +242,7 @@ describe('the style of an overlay', () => {
|
|||
expect(visibility(setOverlayEnabled(state, FEATURES, true))).toEqual(['visible', 'none', 'visible']);
|
||||
});
|
||||
|
||||
test('a raster overlay goes under the basemap labels, vector overlays on top', () => {
|
||||
test('the ground of an overlay goes under the basemap labels, and what it marks goes on top', () => {
|
||||
const sources = {basemap: {}};
|
||||
const layers = [
|
||||
{id: 'earth', type: 'fill'}, {id: 'roads', type: 'line'},
|
||||
|
|
@ -250,19 +252,114 @@ describe('the style of an overlay', () => {
|
|||
expect(Object.keys(sources)).toEqual(['basemap', 'overlay:extras/features.pmtiles', 'overlay:satellite.pmtiles']);
|
||||
expect(layers.map(l => l.id)).toEqual([
|
||||
'earth', 'roads',
|
||||
// A picture under an area under a line: none of them over a name.
|
||||
'overlay:satellite.pmtiles:raster',
|
||||
'places', 'pois',
|
||||
// Fills under lines under points.
|
||||
'overlay:extras/features.pmtiles:flood_zones:fill',
|
||||
'overlay:extras/features.pmtiles:power_lines:line',
|
||||
'places', 'pois',
|
||||
'overlay:extras/features.pmtiles:towers:circle',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a raster overlay is drawn last when the basemap has no labels', () => {
|
||||
test('the ground of an overlay is over the ground of every basemap file', () => {
|
||||
// A map of two basemap files: the labels of the first are under the ground of the second.
|
||||
const layers = [
|
||||
{id: 'earth', type: 'fill'}, {id: 'roads', type: 'line'}, {id: 'places', type: 'symbol'},
|
||||
{id: 'second.pmtiles:water', type: 'fill'}, {id: 'second.pmtiles:roads', type: 'line'},
|
||||
{id: 'second.pmtiles:places', type: 'symbol'}, {id: 'second.pmtiles:pois', type: 'symbol'},
|
||||
];
|
||||
expect(basemapLabelsStart(layers)).toBe(5);
|
||||
addOverlaysToStyle({}, layers, [FEATURES, SATELLITE], {});
|
||||
expect(layers.map(l => l.id)).toEqual([
|
||||
'earth', 'roads', 'places',
|
||||
'second.pmtiles:water', 'second.pmtiles:roads',
|
||||
// Over the land, water and roads of both files; under the labels which are over them.
|
||||
'overlay:satellite.pmtiles:raster',
|
||||
'overlay:extras/features.pmtiles:flood_zones:fill',
|
||||
'overlay:extras/features.pmtiles:power_lines:line',
|
||||
'second.pmtiles:places', 'second.pmtiles:pois',
|
||||
'overlay:extras/features.pmtiles:towers:circle',
|
||||
]);
|
||||
});
|
||||
|
||||
test('the ground of an overlay is under the basemap labels when the map has contours', () => {
|
||||
const layers = [
|
||||
{id: 'earth', type: 'fill'}, {id: 'places', type: 'symbol'},
|
||||
{id: 'second.pmtiles:water', type: 'fill'}, {id: 'second.pmtiles:places', type: 'symbol'},
|
||||
{id: 'contour-lines', type: 'line', source: 'contours'},
|
||||
{id: 'contour-labels', type: 'symbol', source: 'contours'},
|
||||
];
|
||||
addOverlaysToStyle({}, layers, [FEATURES], {});
|
||||
expect(layers.map(l => l.id)).toEqual([
|
||||
'earth', 'places', 'second.pmtiles:water',
|
||||
'overlay:extras/features.pmtiles:flood_zones:fill',
|
||||
'overlay:extras/features.pmtiles:power_lines:line',
|
||||
'second.pmtiles:places',
|
||||
'contour-lines', 'contour-labels',
|
||||
'overlay:extras/features.pmtiles:towers:circle',
|
||||
]);
|
||||
});
|
||||
|
||||
test('the labels of every basemap file go over the ground of every file', () => {
|
||||
const layers = [
|
||||
{id: 'earth', type: 'fill'}, {id: 'roads', type: 'line'}, {id: 'places', type: 'symbol'},
|
||||
{id: 'second.pmtiles:water', type: 'fill'}, {id: 'second.pmtiles:places', type: 'symbol'},
|
||||
{id: 'third.pmtiles:roads', type: 'line'}, {id: 'third.pmtiles:pois', type: 'symbol'},
|
||||
];
|
||||
const ordered = labelsOverGround(layers);
|
||||
expect(ordered.map(l => l.id)).toEqual([
|
||||
'earth', 'roads', 'second.pmtiles:water', 'third.pmtiles:roads',
|
||||
'places', 'second.pmtiles:places', 'third.pmtiles:pois',
|
||||
]);
|
||||
// The same layers, and what was given is not changed.
|
||||
expect(ordered).toHaveLength(layers.length);
|
||||
expect(layers[2].id).toBe('places');
|
||||
expect(labelsOverGround(undefined)).toEqual([]);
|
||||
|
||||
// An overlay then goes under the labels of all three files, and over the ground of all three.
|
||||
addOverlaysToStyle({}, ordered, [FEATURES], {});
|
||||
expect(ordered.map(l => l.id)).toEqual([
|
||||
'earth', 'roads', 'second.pmtiles:water', 'third.pmtiles:roads',
|
||||
'overlay:extras/features.pmtiles:flood_zones:fill',
|
||||
'overlay:extras/features.pmtiles:power_lines:line',
|
||||
'places', 'second.pmtiles:places', 'third.pmtiles:pois',
|
||||
'overlay:extras/features.pmtiles:towers:circle',
|
||||
]);
|
||||
});
|
||||
|
||||
test('where the labels of a basemap begin', () => {
|
||||
const symbol = id => ({id, type: 'symbol'});
|
||||
const line = id => ({id, type: 'line'});
|
||||
expect(basemapLabelsStart([])).toBe(0);
|
||||
expect(basemapLabelsStart(undefined)).toBe(0);
|
||||
expect(basemapLabelsStart([line('roads')])).toBe(1);
|
||||
expect(basemapLabelsStart([symbol('places')])).toBe(0);
|
||||
// The contour lines are drawn after the basemap's labels, and are not of the basemap: what goes
|
||||
// under the labels does not go under the contours instead, which would be over every label.
|
||||
const contours = [
|
||||
{id: 'contour-lines', type: 'line', source: 'contours'},
|
||||
{id: 'contour-labels', type: 'symbol', source: 'contours'},
|
||||
];
|
||||
expect(basemapLabelsStart([line('roads'), symbol('places'), symbol('pois'), ...contours])).toBe(1);
|
||||
// With no label over the basemap's ground, it is over that ground and under the contours.
|
||||
expect(basemapLabelsStart([line('roads'), ...contours])).toBe(1);
|
||||
// An overlay which is already on the map is not of the basemap.
|
||||
expect(basemapLabelsStart([
|
||||
line('roads'), {id: 'overlay:a.pmtiles:x:line', type: 'line'}, symbol('places'),
|
||||
{id: 'overlay:a.pmtiles:x:circle', type: 'circle'},
|
||||
])).toBe(2);
|
||||
});
|
||||
|
||||
test('an overlay is drawn last when the basemap has no labels', () => {
|
||||
const layers = [{id: 'earth', type: 'fill'}];
|
||||
addOverlaysToStyle({}, layers, [SATELLITE], {});
|
||||
expect(layers.map(l => l.id)).toEqual(['earth', 'overlay:satellite.pmtiles:raster']);
|
||||
addOverlaysToStyle({}, layers, [SATELLITE, FEATURES], {});
|
||||
expect(layers.map(l => l.id)).toEqual([
|
||||
'earth',
|
||||
'overlay:satellite.pmtiles:raster',
|
||||
'overlay:extras/features.pmtiles:flood_zones:fill',
|
||||
'overlay:extras/features.pmtiles:power_lines:line',
|
||||
'overlay:extras/features.pmtiles:towers:circle',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -371,8 +468,11 @@ describe('adding overlays to a map a layer at a time', () => {
|
|||
const whole = BASEMAP.map(l => ({...l}));
|
||||
addOverlaysToStyle(sources, whole, [FEATURES, SATELLITE], {});
|
||||
expect(map.layers.map(l => l.id)).toEqual(whole.map(l => l.id));
|
||||
// The raster is under the basemap's labels.
|
||||
expect(map.layers.map(l => l.id).indexOf('overlay:satellite.pmtiles:raster')).toBe(1);
|
||||
// The raster, and the overlay's areas and lines, are under the basemap's labels; its points are over them.
|
||||
const ids = map.layers.map(l => l.id);
|
||||
expect(ids.indexOf('overlay:satellite.pmtiles:raster')).toBe(1);
|
||||
expect(ids.indexOf('overlay:extras/features.pmtiles:power_lines:line')).toBeLessThan(ids.indexOf('places'));
|
||||
expect(ids.indexOf('overlay:extras/features.pmtiles:towers:circle')).toBeGreaterThan(ids.indexOf('pois'));
|
||||
});
|
||||
|
||||
test('layers are added as the user last chose to see them', () => {
|
||||
|
|
@ -389,10 +489,11 @@ describe('adding overlays to a map a layer at a time', () => {
|
|||
const refused = addOverlaysToMap(map, [FEATURES, other], {}, URLS);
|
||||
expect(refused).toEqual({'extras/features.pmtiles': 1, 'other.pmtiles': 1});
|
||||
expect(map.layers.map(l => l.id)).toEqual([
|
||||
'earth', 'places', 'pois',
|
||||
'earth',
|
||||
'overlay:extras/features.pmtiles:flood_zones:fill',
|
||||
'overlay:extras/features.pmtiles:power_lines:line',
|
||||
'overlay:other.pmtiles:roads:line',
|
||||
'places', 'pois',
|
||||
]);
|
||||
});
|
||||
|
||||
|
|
@ -412,23 +513,32 @@ describe('adding overlays to a map a layer at a time', () => {
|
|||
expect(map.layers.map(l => l.id)).toEqual(before);
|
||||
});
|
||||
|
||||
test('an overlay with its own style keeps that style\'s order, under the generic ones', () => {
|
||||
test('an overlay with its own style keeps that style\'s order, under the generic ones, in each part', () => {
|
||||
const styled = {
|
||||
...FEATURES,
|
||||
map_path: 'styled.pmtiles',
|
||||
styleLayers: [
|
||||
{id: 'overlay:styled.pmtiles:towers:icons', type: 'symbol', source: 'overlay:styled.pmtiles', 'source-layer': 'towers'},
|
||||
{id: 'overlay:styled.pmtiles:flood_zones:area', type: 'fill', source: 'overlay:styled.pmtiles', 'source-layer': 'flood_zones'},
|
||||
{id: 'overlay:styled.pmtiles:towers:names', type: 'symbol', source: 'overlay:styled.pmtiles', 'source-layer': 'towers'},
|
||||
{id: 'overlay:styled.pmtiles:power_lines:wires', type: 'line', source: 'overlay:styled.pmtiles', 'source-layer': 'power_lines'},
|
||||
],
|
||||
};
|
||||
const {rasters, vectors} = orderOverlayLayers([FEATURES, styled, SATELLITE], {});
|
||||
expect(rasters.map(l => l.id)).toEqual(['overlay:satellite.pmtiles:raster']);
|
||||
expect(vectors.map(l => l.id)).toEqual([
|
||||
'overlay:styled.pmtiles:towers:icons',
|
||||
const {under, over} = orderOverlayLayers([FEATURES, styled, SATELLITE], {});
|
||||
// What goes under the basemap's labels: no text, icon or point.
|
||||
expect(under.map(l => l.id)).toEqual([
|
||||
'overlay:satellite.pmtiles:raster',
|
||||
'overlay:styled.pmtiles:flood_zones:area',
|
||||
'overlay:styled.pmtiles:power_lines:wires',
|
||||
'overlay:extras/features.pmtiles:flood_zones:fill',
|
||||
'overlay:extras/features.pmtiles:power_lines:line',
|
||||
]);
|
||||
// What goes over them: every label, whichever overlay it is of.
|
||||
expect(over.map(l => l.id)).toEqual([
|
||||
'overlay:styled.pmtiles:towers:icons',
|
||||
'overlay:styled.pmtiles:towers:names',
|
||||
'overlay:extras/features.pmtiles:towers:circle',
|
||||
]);
|
||||
expect([...under, ...over].every(l => isOverlayLabelLayer(l) === over.includes(l))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
353
app/src/components/mapPrintStyle.js
Normal file
353
app/src/components/mapPrintStyle.js
Normal file
|
|
@ -0,0 +1,353 @@
|
|||
// The map as it is printed. The light and dark maps are made for a screen, which is lit: their
|
||||
// roads are white on pale gray and their streams half a pixel of pale blue, which is nothing on
|
||||
// paper. The printed map is drawn on white, with dark lines and names, in the colors a topographic
|
||||
// sheet has: black for what was built, blue for water, green for what grows, brown for the land.
|
||||
|
||||
import {layersWithCustomTheme, namedTheme} from "protomaps-themes-base";
|
||||
|
||||
// What the map is called where a look is chosen and remembered.
|
||||
export const PRINT_LOOK = "print";
|
||||
// The looks a map may be exported in: the printed map, and the two a screen has.
|
||||
export const EXPORT_LOOKS = [
|
||||
{value: PRINT_LOOK, label: "Print"},
|
||||
{value: "light", label: "Light"},
|
||||
{value: "dark", label: "Dark"},
|
||||
];
|
||||
const STORAGE_KEY_LOOK = "wrolpi-map-export-look";
|
||||
const STORAGE_KEY_COLORS = "wrolpi-map-print-colors";
|
||||
|
||||
const BLACK = "#1a1a1a";
|
||||
const CASING = "#4d4d4d";
|
||||
const WHITE = "#ffffff";
|
||||
const WATER = "#a9d4f2";
|
||||
// Water which is a line (a stream) or a name is darker than water which is an area: a thin pale
|
||||
// line is not seen.
|
||||
const WATER_LINE = "#2f7fc4";
|
||||
const WATER_NAME = "#1b5fa3";
|
||||
const HIGHWAY = "#e2725b";
|
||||
const MAJOR = "#f2c14e";
|
||||
const TUNNEL = "#e6e6e6";
|
||||
const TUNNEL_CASING = "#9a9a9a";
|
||||
|
||||
// The colors of the printed map which are not the light map's. A basemap is drawn in some seventy
|
||||
// colors (see `namedTheme`), and these are every one which is seen at the scale of a quadrangle.
|
||||
export const PRINT_COLORS = {
|
||||
background: WHITE,
|
||||
earth: WHITE,
|
||||
park_a: "#dcefd0",
|
||||
park_b: "#c2e2b0",
|
||||
wood_a: "#d3ebc6",
|
||||
wood_b: "#b5dca4",
|
||||
scrub_a: "#e3edcd",
|
||||
scrub_b: "#cfe0b3",
|
||||
hospital: "#f3e3e0",
|
||||
school: "#f1ead9",
|
||||
industrial: "#e6e4ec",
|
||||
pedestrian: "#efefef",
|
||||
glacier: "#eef7fd",
|
||||
sand: "#f4ecd2",
|
||||
beach: "#f4ecd2",
|
||||
aerodrome: "#e7e7ee",
|
||||
runway: "#a9a9b3",
|
||||
zoo: "#d6ecd6",
|
||||
military: "#eedddd",
|
||||
water: WATER,
|
||||
pier: "#d9d9d9",
|
||||
buildings: "#6e6e6e",
|
||||
|
||||
tunnel_other_casing: TUNNEL_CASING,
|
||||
tunnel_minor_casing: TUNNEL_CASING,
|
||||
tunnel_link_casing: TUNNEL_CASING,
|
||||
tunnel_major_casing: TUNNEL_CASING,
|
||||
tunnel_highway_casing: TUNNEL_CASING,
|
||||
tunnel_other: TUNNEL,
|
||||
tunnel_minor: TUNNEL,
|
||||
tunnel_link: TUNNEL,
|
||||
tunnel_major: TUNNEL,
|
||||
tunnel_highway: TUNNEL,
|
||||
|
||||
minor_service_casing: CASING,
|
||||
minor_casing: CASING,
|
||||
link_casing: CASING,
|
||||
major_casing_late: BLACK,
|
||||
major_casing_early: BLACK,
|
||||
highway_casing_late: BLACK,
|
||||
highway_casing_early: BLACK,
|
||||
other: CASING,
|
||||
minor_service: WHITE,
|
||||
minor_a: WHITE,
|
||||
minor_b: WHITE,
|
||||
link: MAJOR,
|
||||
major: MAJOR,
|
||||
highway: HIGHWAY,
|
||||
|
||||
bridges_other_casing: CASING,
|
||||
bridges_minor_casing: CASING,
|
||||
bridges_link_casing: CASING,
|
||||
bridges_major_casing: BLACK,
|
||||
bridges_highway_casing: BLACK,
|
||||
bridges_other: CASING,
|
||||
bridges_minor: WHITE,
|
||||
bridges_link: MAJOR,
|
||||
bridges_major: MAJOR,
|
||||
bridges_highway: HIGHWAY,
|
||||
|
||||
railway: BLACK,
|
||||
boundaries: "#5b4b8a",
|
||||
|
||||
waterway_label: WATER_NAME,
|
||||
ocean_label: WATER_NAME,
|
||||
peak_label: "#6b4423",
|
||||
roads_label_minor: BLACK,
|
||||
roads_label_minor_halo: WHITE,
|
||||
roads_label_major: BLACK,
|
||||
roads_label_major_halo: WHITE,
|
||||
subplace_label: "#333333",
|
||||
subplace_label_halo: WHITE,
|
||||
city_label: "#000000",
|
||||
city_label_halo: WHITE,
|
||||
state_label: "#555555",
|
||||
state_label_halo: WHITE,
|
||||
country_label: "#555555",
|
||||
address_label: "#444444",
|
||||
address_label_halo: WHITE,
|
||||
pois: {
|
||||
blue: "#12648a",
|
||||
green: "#17643a",
|
||||
lapis: "#24449c",
|
||||
pink: "#b02f85",
|
||||
red: "#b5304f",
|
||||
slategray: "#4b3f69",
|
||||
tangerine: "#9a4e03",
|
||||
turquoise: "#00808c",
|
||||
},
|
||||
landcover: {
|
||||
grassland: "rgba(228, 242, 216, 1)",
|
||||
barren: "rgba(248, 241, 222, 1)",
|
||||
urban_area: "rgba(240, 240, 240, 1)",
|
||||
farmland: "rgba(234, 243, 216, 1)",
|
||||
glacier: "rgba(238, 247, 253, 1)",
|
||||
scrub: "rgba(229, 238, 208, 1)",
|
||||
forest: "rgba(205, 232, 194, 1)",
|
||||
},
|
||||
};
|
||||
|
||||
// What a color does not say of a layer of the printed map: how wide its line is, and how much of
|
||||
// it is seen. {layer id: paint which is the layer's on paper}.
|
||||
export const PRINT_PAINT = {
|
||||
// A stream is half a pixel on a screen, and a river is the color of a lake.
|
||||
water_stream: {"line-color": WATER_LINE, "line-width": 1.2},
|
||||
water_river: {"line-color": WATER_LINE},
|
||||
// A path is not drawn on a screen until the map is deeper than a quadrangle is drawn.
|
||||
roads_other: {"line-width": 1.2, "line-dasharray": [4, 2]},
|
||||
roads_bridges_other: {"line-width": 1.2, "line-dasharray": [4, 2]},
|
||||
// A basemap draws a ramp on a bridge in the color of a minor road on one, not in a ramp's.
|
||||
roads_bridges_link: {"line-color": MAJOR},
|
||||
roads_rail: {"line-opacity": 1},
|
||||
boundaries: {"line-width": 1.2},
|
||||
boundaries_country: {"line-width": 1.6},
|
||||
buildings: {"fill-opacity": 0.75},
|
||||
};
|
||||
|
||||
// The contour lines and their heights, which are not of a basemap: brown, and dark enough to follow.
|
||||
export const PRINT_CONTOURS = {
|
||||
minor: {"line-color": "rgba(140, 85, 35, 0.55)", "line-width": 0.6},
|
||||
major: {"line-color": "rgba(140, 85, 35, 0.9)", "line-width": 1.1},
|
||||
label: {"text-color": "rgba(110, 65, 25, 1)", "text-halo-color": "rgba(255, 255, 255, 0.9)"},
|
||||
};
|
||||
|
||||
const HEX_COLOR = /^#[0-9a-f]{6}$/i;
|
||||
|
||||
function channels(hex) {
|
||||
return [1, 3, 5].map(at => parseInt(hex.slice(at, at + 2), 16));
|
||||
}
|
||||
|
||||
// A color part of the way (0 to 1) to another: `mix("#336699", "#ffffff", 0.4)` is paler.
|
||||
export function mix(hex, toward, part) {
|
||||
const to = channels(toward);
|
||||
return "#" + channels(hex)
|
||||
.map((value, index) => Math.round(value + (to[index] - value) * part).toString(16).padStart(2, "0"))
|
||||
.join("");
|
||||
}
|
||||
|
||||
const paler = (hex, part) => mix(hex, WHITE, part);
|
||||
const darker = (hex, part) => mix(hex, "#000000", part);
|
||||
|
||||
function rgba(hex, alpha) {
|
||||
return `rgba(${channels(hex).join(", ")}, ${alpha})`;
|
||||
}
|
||||
|
||||
// The colors of the printed map which a person may choose, in the order they are offered. Each is
|
||||
// of a group of the layer control (`group`), is called `label` there, and is `color` until another
|
||||
// is chosen. A basemap has several colors where a person chooses one (a park and a wood are both
|
||||
// what grows), so a chosen color says what the others are:
|
||||
// colors(color): the colors of the basemap (see PRINT_COLORS) it stands for.
|
||||
// paint(color): the paint of layers (see PRINT_PAINT) which is of that color.
|
||||
// contours(color): the paint of the contour lines and their heights (see PRINT_CONTOURS).
|
||||
// The edge of a road is not chosen: it is what makes a road a line on paper, and stays dark.
|
||||
export const PRINT_SWATCHES = [
|
||||
{
|
||||
id: "water", group: "Water", label: "Water", color: WATER,
|
||||
colors: color => ({water: color, waterway_label: darker(color, 0.55), ocean_label: darker(color, 0.55)}),
|
||||
// A line of water is darker than an area of it: a thin pale line is not seen.
|
||||
paint: color => ({
|
||||
water_stream: {"line-color": darker(color, 0.4)},
|
||||
water_river: {"line-color": darker(color, 0.4)},
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: "vegetation", group: "Land Cover", label: "Parks and woods", color: "#c2e2b0",
|
||||
colors: color => ({
|
||||
park_a: paler(color, 0.4), park_b: color,
|
||||
wood_a: paler(color, 0.25), wood_b: darker(color, 0.06),
|
||||
scrub_a: paler(color, 0.5), scrub_b: paler(color, 0.2),
|
||||
zoo: paler(color, 0.35),
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: "built", group: "Land Cover", label: "Schools, hospitals and industry", color: "#e6e4ec",
|
||||
colors: color => ({
|
||||
hospital: color, school: color, industrial: color, military: color,
|
||||
pedestrian: paler(color, 0.3), aerodrome: color,
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: "bare", group: "Land Cover", label: "Sand and ice", color: "#f4ecd2",
|
||||
colors: color => ({sand: color, beach: color, glacier: paler(color, 0.5)}),
|
||||
},
|
||||
{
|
||||
id: "buildings", group: "Buildings", label: "Buildings", color: "#6e6e6e",
|
||||
colors: color => ({buildings: color}),
|
||||
},
|
||||
{
|
||||
id: "highway", group: "Roads - Highway", label: "Highways", color: HIGHWAY,
|
||||
colors: color => ({highway: color, bridges_highway: color}),
|
||||
},
|
||||
{
|
||||
id: "major", group: "Roads - Major", label: "Major roads", color: MAJOR,
|
||||
colors: color => ({major: color, link: color, bridges_major: color}),
|
||||
// A ramp on a bridge, which a basemap does not draw in a color of its own.
|
||||
paint: color => ({roads_bridges_link: {"line-color": color}}),
|
||||
},
|
||||
{
|
||||
id: "minor", group: "Roads - Minor", label: "Minor roads", color: WHITE,
|
||||
colors: color => ({minor_service: color, minor_a: color, minor_b: color, bridges_minor: color}),
|
||||
},
|
||||
{
|
||||
id: "rail", group: "Rail & Runways", label: "Railways", color: BLACK,
|
||||
colors: color => ({railway: color}),
|
||||
},
|
||||
{
|
||||
id: "boundaries", group: "Boundaries", label: "Boundaries", color: "#5b4b8a",
|
||||
colors: color => ({boundaries: color}),
|
||||
},
|
||||
{
|
||||
id: "contours", group: "Contours", label: "Contours", color: "#8c5523",
|
||||
contours: color => ({
|
||||
minor: {"line-color": rgba(color, 0.55)},
|
||||
major: {"line-color": rgba(color, 0.9)},
|
||||
label: {"text-color": darker(color, 0.2)},
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: "names", group: "Labels", label: "Names", color: BLACK,
|
||||
colors: color => ({
|
||||
roads_label_minor: color, roads_label_major: color, city_label: color, subplace_label: color,
|
||||
address_label: color, state_label: paler(color, 0.3), country_label: paler(color, 0.3),
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: "halo", group: "Labels", label: "Around names", color: WHITE,
|
||||
colors: color => ({
|
||||
roads_label_minor_halo: color, roads_label_major_halo: color, city_label_halo: color,
|
||||
subplace_label_halo: color, state_label_halo: color, address_label_halo: color,
|
||||
}),
|
||||
contours: color => ({label: {"text-halo-color": rgba(color, 0.9)}}),
|
||||
},
|
||||
];
|
||||
|
||||
// What was chosen ({swatch id: "#rrggbb"}) with all that is not a choice left out: a color of no
|
||||
// swatch, a color which is not one, and a color which is the swatch's own.
|
||||
export function chosenColors(chosen) {
|
||||
const colors = {};
|
||||
for (const {id, color} of PRINT_SWATCHES) {
|
||||
const value = chosen?.[id];
|
||||
if (typeof value === "string" && HEX_COLOR.test(value) && value.toLowerCase() !== color.toLowerCase()) {
|
||||
colors[id] = value.toLowerCase();
|
||||
}
|
||||
}
|
||||
return colors;
|
||||
}
|
||||
|
||||
// Each kind of thing a swatch says, with what was chosen over what the printed map has.
|
||||
function withChosen(kind, picked, base) {
|
||||
const result = {...base};
|
||||
const colors = chosenColors(picked);
|
||||
for (const swatch of PRINT_SWATCHES) {
|
||||
const color = colors[swatch.id];
|
||||
if (!color || !swatch[kind]) continue;
|
||||
for (const [key, value] of Object.entries(swatch[kind](color))) {
|
||||
result[key] = typeof value === "object" ? {...result[key], ...value} : value;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Every color of the printed map. colors: what a person chose ({swatch id: "#rrggbb"}).
|
||||
export function printTheme(colors = {}) {
|
||||
return withChosen("colors", colors, {...namedTheme("light"), ...PRINT_COLORS});
|
||||
}
|
||||
|
||||
// The paint of the contour lines and their heights on the printed map.
|
||||
export function printContours(colors = {}) {
|
||||
return withChosen("contours", colors, PRINT_CONTOURS);
|
||||
}
|
||||
|
||||
// The layers of a basemap file (a source of the map's style) as they are printed.
|
||||
export function printLayers(source, colors = {}, lang = undefined) {
|
||||
const paints = withChosen("paint", colors, PRINT_PAINT);
|
||||
return layersWithCustomTheme(source, printTheme(colors), lang).map(layer => {
|
||||
const paint = paints[layer.id];
|
||||
return paint ? {...layer, paint: {...layer.paint, ...paint}} : layer;
|
||||
});
|
||||
}
|
||||
|
||||
// The colors a person chose for the printed map, in this browser.
|
||||
export function savedPrintColors() {
|
||||
try {
|
||||
return chosenColors(JSON.parse(localStorage.getItem(STORAGE_KEY_COLORS)));
|
||||
} catch (e) {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
// Remember what was chosen; with nothing chosen, nothing is kept.
|
||||
export function savePrintColors(colors) {
|
||||
const kept = chosenColors(colors);
|
||||
try {
|
||||
if (Object.keys(kept).length) localStorage.setItem(STORAGE_KEY_COLORS, JSON.stringify(kept));
|
||||
else localStorage.removeItem(STORAGE_KEY_COLORS);
|
||||
} catch (e) { /* ignore */ }
|
||||
return kept;
|
||||
}
|
||||
|
||||
// The look a map was last exported in, in this browser: the printed map until another is chosen.
|
||||
export function savedExportLook() {
|
||||
try {
|
||||
const saved = localStorage.getItem(STORAGE_KEY_LOOK);
|
||||
if (EXPORT_LOOKS.some(look => look.value === saved)) return saved;
|
||||
} catch (e) { /* ignore */ }
|
||||
return PRINT_LOOK;
|
||||
}
|
||||
|
||||
export function saveExportLook(look) {
|
||||
try { localStorage.setItem(STORAGE_KEY_LOOK, look); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
// The flavor and the sprite of the map's style for a look: {flavor, sprite}. Nothing for no look,
|
||||
// which is the map as the screen has it.
|
||||
export function lookStyle(look) {
|
||||
if (look === PRINT_LOOK) return {flavor: PRINT_LOOK, sprite: "light"};
|
||||
if (look === "light" || look === "dark") return {flavor: look, sprite: look};
|
||||
return {};
|
||||
}
|
||||
151
app/src/components/mapPrintStyle.test.js
Normal file
151
app/src/components/mapPrintStyle.test.js
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
import layers, {namedTheme} from 'protomaps-themes-base';
|
||||
import {
|
||||
chosenColors, EXPORT_LOOKS, lookStyle, mix, PRINT_COLORS, PRINT_CONTOURS, PRINT_LOOK, PRINT_PAINT, PRINT_SWATCHES,
|
||||
printContours, printLayers, printTheme, savedExportLook, savedPrintColors, saveExportLook, savePrintColors,
|
||||
} from './mapPrintStyle';
|
||||
|
||||
describe('the printed map', () => {
|
||||
const printed = printLayers('a.pmtiles');
|
||||
const byId = Object.fromEntries(printed.map(layer => [layer.id, layer]));
|
||||
|
||||
test('has every layer the light map has, of the same source', () => {
|
||||
const light = layers('a.pmtiles', 'light');
|
||||
expect(printed.map(layer => layer.id)).toEqual(light.map(layer => layer.id));
|
||||
expect(new Set(printed.map(layer => layer.source).filter(Boolean))).toEqual(new Set(['a.pmtiles']));
|
||||
});
|
||||
|
||||
test('is drawn on white, in dark lines', () => {
|
||||
expect(byId.background.paint['background-color']).toBe('#ffffff');
|
||||
expect(byId.earth.paint['fill-color']).toBe('#ffffff');
|
||||
// The edge of a road is what is seen of it on paper.
|
||||
expect(byId.roads_minor_casing.paint['line-color']).toBe('#4d4d4d');
|
||||
expect(byId.roads_highway.paint['line-color']).toBe(PRINT_COLORS.highway);
|
||||
expect(byId.roads_labels_minor.paint['text-color']).toBe('#1a1a1a');
|
||||
expect(byId.roads_labels_minor.paint['text-halo-color']).toBe('#ffffff');
|
||||
});
|
||||
|
||||
test('has lines which are wide enough to see', () => {
|
||||
// A stream is not the color of a lake, nor half a pixel.
|
||||
expect(byId.water_stream.paint['line-width']).toBeGreaterThan(1);
|
||||
expect(byId.water_stream.paint['line-color']).not.toBe(byId.water.paint['fill-color']);
|
||||
// A path is drawn however deep the map is, and is still a broken line.
|
||||
expect(byId.roads_other.paint['line-width']).toBe(1.2);
|
||||
expect(byId.roads_other.paint['line-dasharray']).toEqual([4, 2]);
|
||||
expect(byId.roads_rail.paint['line-opacity']).toBe(1);
|
||||
});
|
||||
|
||||
test('changes only layers a basemap has, and colors it has', () => {
|
||||
for (const id of Object.keys(PRINT_PAINT)) expect(Object.keys(byId)).toContain(id);
|
||||
const light = namedTheme('light');
|
||||
for (const color of Object.keys(PRINT_COLORS)) expect(Object.keys(light)).toContain(color);
|
||||
expect(Object.keys(printTheme()).sort()).toEqual(Object.keys(light).sort());
|
||||
expect(Object.keys(PRINT_COLORS.pois).sort()).toEqual(Object.keys(light.pois).sort());
|
||||
expect(Object.keys(PRINT_COLORS.landcover).sort()).toEqual(Object.keys(light.landcover).sort());
|
||||
});
|
||||
});
|
||||
|
||||
describe('the look a map is exported in', () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
test('is the printed map until another is chosen, and is remembered', () => {
|
||||
expect(savedExportLook()).toBe(PRINT_LOOK);
|
||||
saveExportLook('dark');
|
||||
expect(savedExportLook()).toBe('dark');
|
||||
// What is not a look is not remembered as one.
|
||||
localStorage.setItem('wrolpi-map-export-look', 'sepia');
|
||||
expect(savedExportLook()).toBe(PRINT_LOOK);
|
||||
expect(EXPORT_LOOKS.map(look => look.value)).toEqual([PRINT_LOOK, 'light', 'dark']);
|
||||
});
|
||||
|
||||
test('says how the map is drawn', () => {
|
||||
// The printed map has the icons of the light one.
|
||||
expect(lookStyle(PRINT_LOOK)).toEqual({flavor: PRINT_LOOK, sprite: 'light'});
|
||||
expect(lookStyle('light')).toEqual({flavor: 'light', sprite: 'light'});
|
||||
expect(lookStyle('dark')).toEqual({flavor: 'dark', sprite: 'dark'});
|
||||
// With no look chosen, the map is as the screen has it: nothing is said.
|
||||
expect(lookStyle(null)).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('the colors a person chooses for the printed map', () => {
|
||||
beforeEach(() => localStorage.clear());
|
||||
|
||||
test('each is a color the printed map has until another is chosen', () => {
|
||||
const theme = printTheme();
|
||||
const paints = Object.fromEntries(printLayers('a.pmtiles').map(layer => [layer.id, layer.paint]));
|
||||
for (const swatch of PRINT_SWATCHES) {
|
||||
// Choosing the color it has changes nothing: what it stands for is what the map has.
|
||||
const same = {[swatch.id]: swatch.color};
|
||||
expect(chosenColors(same)).toEqual({});
|
||||
// Every color and layer it speaks of is one a basemap has.
|
||||
for (const key of Object.keys(swatch.colors?.(swatch.color) || {})) expect(Object.keys(theme)).toContain(key);
|
||||
for (const id of Object.keys(swatch.paint?.(swatch.color) || {})) expect(Object.keys(paints)).toContain(id);
|
||||
for (const key of Object.keys(swatch.contours?.(swatch.color) || {})) {
|
||||
expect(Object.keys(PRINT_CONTOURS)).toContain(key);
|
||||
}
|
||||
}
|
||||
// No two have one name, and none speaks of a color another does.
|
||||
expect(new Set(PRINT_SWATCHES.map(swatch => swatch.id)).size).toBe(PRINT_SWATCHES.length);
|
||||
const spoken = PRINT_SWATCHES.flatMap(swatch => Object.keys(swatch.colors?.(swatch.color) || {}));
|
||||
expect(new Set(spoken).size).toBe(spoken.length);
|
||||
});
|
||||
|
||||
test('a chosen color is the color of all it stands for', () => {
|
||||
const byId = Object.fromEntries(
|
||||
printLayers('a.pmtiles', {water: '#ff00ff', minor: '#00ff00'}).map(layer => [layer.id, layer]));
|
||||
expect(byId.water.paint['fill-color']).toBe('#ff00ff');
|
||||
// A line of water is darker than an area of it, and as wide as the printed map has it.
|
||||
expect(byId.water_stream.paint['line-color']).toBe(mix('#ff00ff', '#000000', 0.4));
|
||||
expect(byId.water_stream.paint['line-width']).toBe(PRINT_PAINT.water_stream['line-width']);
|
||||
expect(JSON.stringify(byId.roads_minor.paint['line-color'])).toContain('#00ff00');
|
||||
// The edge of a road is not chosen.
|
||||
expect(byId.roads_bridges_link.paint['line-color']).toBe(PRINT_COLORS.major);
|
||||
expect(byId.roads_minor_casing.paint['line-color']).toBe('#4d4d4d');
|
||||
// What was not chosen is as it was.
|
||||
expect(byId.roads_highway.paint['line-color']).toBe(PRINT_COLORS.highway);
|
||||
});
|
||||
|
||||
test('a ramp is the color of a major road, on a bridge as off one', () => {
|
||||
const ramps = colors => {
|
||||
const byId = Object.fromEntries(printLayers('a.pmtiles', colors).map(layer => [layer.id, layer]));
|
||||
return [byId.roads_link.paint['line-color'], byId.roads_bridges_link.paint['line-color']];
|
||||
};
|
||||
expect(ramps({})).toEqual([PRINT_COLORS.major, PRINT_COLORS.major]);
|
||||
expect(ramps({major: '#123456'})).toEqual(['#123456', '#123456']);
|
||||
// The color of a minor road is not a ramp's.
|
||||
expect(ramps({minor: '#00ff00'})).toEqual([PRINT_COLORS.major, PRINT_COLORS.major]);
|
||||
});
|
||||
|
||||
test('several colors of a basemap are shades of the one chosen', () => {
|
||||
const theme = printTheme({vegetation: '#008000'});
|
||||
expect(theme.park_b).toBe('#008000');
|
||||
expect(theme.park_a).toBe(mix('#008000', '#ffffff', 0.4));
|
||||
expect(theme.wood_b).not.toBe(theme.park_b);
|
||||
expect(mix('#000000', '#ffffff', 0.5)).toBe('#808080');
|
||||
});
|
||||
|
||||
test('contours are the color chosen for them, and their heights have the halo of names', () => {
|
||||
expect(printContours()).toEqual(PRINT_CONTOURS);
|
||||
const contours = printContours({contours: '#102030', halo: '#fffacd'});
|
||||
expect(contours.minor).toEqual({'line-color': 'rgba(16, 32, 48, 0.55)', 'line-width': 0.6});
|
||||
expect(contours.major['line-color']).toBe('rgba(16, 32, 48, 0.9)');
|
||||
expect(contours.label['text-halo-color']).toBe('rgba(255, 250, 205, 0.9)');
|
||||
});
|
||||
|
||||
test('what is not a choice is not kept', () => {
|
||||
expect(chosenColors({water: '#FF00FF', sky: '#0000ff', minor: 'green', highway: 7, major: '#fff'}))
|
||||
.toEqual({water: '#ff00ff'});
|
||||
expect(chosenColors(null)).toEqual({});
|
||||
});
|
||||
|
||||
test('are remembered in the browser, and forgotten when there are none', () => {
|
||||
expect(savedPrintColors()).toEqual({});
|
||||
expect(savePrintColors({water: '#ff00ff', sky: '#0000ff'})).toEqual({water: '#ff00ff'});
|
||||
expect(savedPrintColors()).toEqual({water: '#ff00ff'});
|
||||
savePrintColors({});
|
||||
expect(localStorage.getItem('wrolpi-map-print-colors')).toBeNull();
|
||||
// What was kept is not what this keeps.
|
||||
localStorage.setItem('wrolpi-map-print-colors', 'not JSON');
|
||||
expect(savedPrintColors()).toEqual({});
|
||||
});
|
||||
});
|
||||
128
app/src/components/mapQuads.js
Normal file
128
app/src/components/mapQuads.js
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
// The areas a map can be exported by: the 7.5-minute quadrangles of a 1:24,000 topographic map.
|
||||
//
|
||||
// A quadrangle is 7.5 minutes of latitude by 7.5 minutes of longitude, its edges on whole multiples
|
||||
// of that. The grid is arithmetic, so it needs no data and covers the whole world.
|
||||
|
||||
export const QUAD_DEGREES = 0.125;
|
||||
export const QUAD_SCALE = 24000;
|
||||
// The grid is not drawn below this zoom: its cells would be too small to choose between.
|
||||
export const QUAD_MIN_ZOOM = 8;
|
||||
|
||||
const QUADS_PER_DEGREE = 1 / QUAD_DEGREES;
|
||||
// Web Mercator draws no further north or south than this.
|
||||
const MAX_LATITUDE = 85;
|
||||
const MAX_GRID_LINES = 400;
|
||||
|
||||
function wrapLongitude(lng) {
|
||||
return ((lng + 180) % 360 + 360) % 360 - 180;
|
||||
}
|
||||
|
||||
function quadOf(row, col) {
|
||||
return {
|
||||
id: `${row}:${col}`,
|
||||
row,
|
||||
col,
|
||||
west: col * QUAD_DEGREES,
|
||||
south: row * QUAD_DEGREES,
|
||||
east: (col + 1) * QUAD_DEGREES,
|
||||
north: (row + 1) * QUAD_DEGREES,
|
||||
};
|
||||
}
|
||||
|
||||
// The quadrangle a point is in, or null where there is none (off the map, or not a place).
|
||||
export function quadAt(lng, lat) {
|
||||
if (!Number.isFinite(lng) || !Number.isFinite(lat) || Math.abs(lat) >= MAX_LATITUDE) return null;
|
||||
return quadOf(Math.floor(lat * QUADS_PER_DEGREE), Math.floor(wrapLongitude(lng) * QUADS_PER_DEGREE));
|
||||
}
|
||||
|
||||
// The outline of a quadrangle, as GeoJSON.
|
||||
export function quadPolygon(quad) {
|
||||
const {west, south, east, north} = quad;
|
||||
return {
|
||||
type: "Feature",
|
||||
properties: {id: quad.id},
|
||||
geometry: {
|
||||
type: "Polygon",
|
||||
coordinates: [[[west, south], [east, south], [east, north], [west, north], [west, south]]],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const EMPTY_FEATURES = {type: "FeatureCollection", features: []};
|
||||
|
||||
// The lines of the grid across `bounds` ({west, south, east, north}, as the map gives them; east may
|
||||
// be past 180), as GeoJSON. Null when there would be too many lines to be of use.
|
||||
export function quadGridLines(bounds) {
|
||||
const south = Math.max(bounds.south, -MAX_LATITUDE);
|
||||
const north = Math.min(bounds.north, MAX_LATITUDE);
|
||||
const firstRow = Math.floor(south * QUADS_PER_DEGREE);
|
||||
const lastRow = Math.ceil(north * QUADS_PER_DEGREE);
|
||||
const firstCol = Math.floor(bounds.west * QUADS_PER_DEGREE);
|
||||
const lastCol = Math.ceil(bounds.east * QUADS_PER_DEGREE);
|
||||
if (!(lastRow > firstRow) || !(lastCol > firstCol)) return EMPTY_FEATURES;
|
||||
if ((lastRow - firstRow) + (lastCol - firstCol) > MAX_GRID_LINES) return null;
|
||||
|
||||
const [west, east] = [firstCol * QUAD_DEGREES, lastCol * QUAD_DEGREES];
|
||||
const [bottom, top] = [firstRow * QUAD_DEGREES, lastRow * QUAD_DEGREES];
|
||||
const lines = [];
|
||||
for (let row = firstRow; row <= lastRow; row++) {
|
||||
lines.push([[west, row * QUAD_DEGREES], [east, row * QUAD_DEGREES]]);
|
||||
}
|
||||
for (let col = firstCol; col <= lastCol; col++) {
|
||||
lines.push([[col * QUAD_DEGREES, bottom], [col * QUAD_DEGREES, top]]);
|
||||
}
|
||||
return {
|
||||
type: "FeatureCollection",
|
||||
features: [{type: "Feature", properties: {}, geometry: {type: "MultiLineString", coordinates: lines}}],
|
||||
};
|
||||
}
|
||||
|
||||
// 37.875 -> 37°52′30″
|
||||
function degreesMinutesSeconds(value) {
|
||||
const seconds = Math.round(Math.abs(value) * 3600);
|
||||
const d = Math.floor(seconds / 3600);
|
||||
const m = Math.floor((seconds % 3600) / 60);
|
||||
const s = seconds % 60;
|
||||
const pad = n => String(n).padStart(2, "0");
|
||||
return s ? `${d}°${pad(m)}′${pad(s)}″` : `${d}°${pad(m)}′`;
|
||||
}
|
||||
|
||||
export function formatLatitude(lat) {
|
||||
return `${degreesMinutesSeconds(lat)}${lat < 0 ? "S" : "N"}`;
|
||||
}
|
||||
|
||||
export function formatLongitude(lng) {
|
||||
return `${degreesMinutesSeconds(lng)}${lng < 0 ? "W" : "E"}`;
|
||||
}
|
||||
|
||||
// What to call a quadrangle: where its southwest corner is.
|
||||
export function quadLabel(quad) {
|
||||
return `${formatLatitude(quad.south)} ${formatLongitude(quad.west)}`;
|
||||
}
|
||||
|
||||
// What the USGS calls a quadrangle, from what the API says of it ({name, state, exact}): "Berthoud,
|
||||
// Colorado". A quadrangle of the grid which is not all of the named one (they are wider in
|
||||
// Alaska) is a part of it.
|
||||
export function quadTitle(named) {
|
||||
if (!named?.name) return null;
|
||||
const title = named.state ? `${named.name}, ${named.state}` : named.name;
|
||||
return named.exact === false ? `Part of ${title}` : title;
|
||||
}
|
||||
|
||||
// How far it is across and up a quadrangle on the ground (meters, along its middle), and on a sheet
|
||||
// printed at 1:24,000 (millimeters).
|
||||
export function quadSize(quad) {
|
||||
const latitude = (quad.south + quad.north) / 2 * Math.PI / 180;
|
||||
// The length of a degree on the WGS84 ellipsoid.
|
||||
const metersPerDegreeLatitude = 111132.92 - 559.82 * Math.cos(2 * latitude) + 1.175 * Math.cos(4 * latitude);
|
||||
const metersPerDegreeLongitude = 111412.84 * Math.cos(latitude) - 93.5 * Math.cos(3 * latitude)
|
||||
+ 0.118 * Math.cos(5 * latitude);
|
||||
const widthMeters = metersPerDegreeLongitude * QUAD_DEGREES;
|
||||
const heightMeters = metersPerDegreeLatitude * QUAD_DEGREES;
|
||||
return {
|
||||
widthMeters,
|
||||
heightMeters,
|
||||
sheetWidthMm: widthMeters * 1000 / QUAD_SCALE,
|
||||
sheetHeightMm: heightMeters * 1000 / QUAD_SCALE,
|
||||
};
|
||||
}
|
||||
111
app/src/components/mapQuads.test.js
Normal file
111
app/src/components/mapQuads.test.js
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
import {
|
||||
EMPTY_FEATURES,
|
||||
formatLatitude,
|
||||
formatLongitude,
|
||||
quadAt,
|
||||
quadGridLines,
|
||||
quadLabel,
|
||||
quadPolygon,
|
||||
quadSize,
|
||||
} from './mapQuads';
|
||||
|
||||
describe('the quadrangle a point is in', () => {
|
||||
test('has its edges on whole multiples of 7.5 minutes', () => {
|
||||
expect(quadAt(-105.0595, 40.31)).toEqual({
|
||||
id: '322:-841', row: 322, col: -841, west: -105.125, south: 40.25, east: -105, north: 40.375,
|
||||
});
|
||||
// South and east of the origin.
|
||||
expect(quadAt(151.21, -33.87)).toMatchObject({west: 151.125, south: -33.875, east: 151.25, north: -33.75});
|
||||
});
|
||||
|
||||
test('a point on an edge belongs to the quadrangle north and east of it', () => {
|
||||
expect(quadAt(-105.125, 40.25)).toMatchObject({west: -105.125, south: 40.25});
|
||||
expect(quadAt(-105.1250001, 40.2499999)).toMatchObject({west: -105.25, south: 40.125});
|
||||
});
|
||||
|
||||
test('is the same wherever around the world the map has been dragged to', () => {
|
||||
expect(quadAt(-105.0595 + 360, 40.31)).toEqual(quadAt(-105.0595, 40.31));
|
||||
expect(quadAt(-105.0595 - 720, 40.31)).toEqual(quadAt(-105.0595, 40.31));
|
||||
expect(quadAt(180, 0)).toMatchObject({west: -180, east: -179.875});
|
||||
});
|
||||
|
||||
test('is nothing off the map', () => {
|
||||
expect(quadAt(0, 86)).toBeNull();
|
||||
expect(quadAt(0, -85)).toBeNull();
|
||||
expect(quadAt(NaN, 0)).toBeNull();
|
||||
expect(quadAt(0, undefined)).toBeNull();
|
||||
});
|
||||
|
||||
test('has an outline which closes', () => {
|
||||
const ring = quadPolygon(quadAt(-105.0595, 40.31)).geometry.coordinates[0];
|
||||
expect(ring).toEqual([[-105.125, 40.25], [-105, 40.25], [-105, 40.375], [-105.125, 40.375], [-105.125, 40.25]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the grid across the map', () => {
|
||||
const lines = bounds => quadGridLines(bounds).features[0].geometry.coordinates;
|
||||
|
||||
test('covers the view, out to the edges of the quadrangles it shows part of', () => {
|
||||
const grid = lines({west: -105.175, south: 40.26, east: -104.925, north: 40.4});
|
||||
// Parallels at 40.25, 40.375, 40.5; meridians at -105.25, -105.125, -105, -104.875.
|
||||
expect(grid).toHaveLength(7);
|
||||
expect(grid.slice(0, 3)).toEqual([
|
||||
[[-105.25, 40.25], [-104.875, 40.25]],
|
||||
[[-105.25, 40.375], [-104.875, 40.375]],
|
||||
[[-105.25, 40.5], [-104.875, 40.5]],
|
||||
]);
|
||||
expect(grid[3]).toEqual([[-105.25, 40.25], [-105.25, 40.5]]);
|
||||
expect(grid[6]).toEqual([[-104.875, 40.25], [-104.875, 40.5]]);
|
||||
});
|
||||
|
||||
test('is not made when the view is of too many quadrangles', () => {
|
||||
expect(quadGridLines({west: -125, south: 25, east: -66, north: 50})).toBeNull();
|
||||
});
|
||||
|
||||
test('stops where the map does', () => {
|
||||
const grid = lines({west: 0, south: 84.9, east: 0.1, north: 89});
|
||||
expect(Math.max(...grid.flat().map(point => point[1]))).toBe(85);
|
||||
});
|
||||
|
||||
test('is empty for a view of nothing', () => {
|
||||
expect(quadGridLines({west: 0, south: 88, east: 1, north: 89})).toBe(EMPTY_FEATURES);
|
||||
});
|
||||
});
|
||||
|
||||
describe('what a quadrangle is called', () => {
|
||||
test('is where its southwest corner is', () => {
|
||||
expect(quadLabel(quadAt(-105.0595, 40.31))).toBe('40°15′N 105°07′30″W');
|
||||
expect(quadLabel(quadAt(-104.925, 40.4))).toBe('40°22′30″N 105°00′W');
|
||||
expect(quadLabel(quadAt(151.21, -33.87))).toBe('33°52′30″S 151°07′30″E');
|
||||
});
|
||||
|
||||
test('a coordinate is written in degrees, minutes and seconds', () => {
|
||||
expect(formatLatitude(0)).toBe('0°00′N');
|
||||
expect(formatLatitude(-0.125)).toBe('0°07′30″S');
|
||||
expect(formatLongitude(-179.875)).toBe('179°52′30″W');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the size of a quadrangle', () => {
|
||||
test('is narrower further from the equator, and about as tall everywhere', () => {
|
||||
const equator = quadSize(quadAt(0, 0));
|
||||
const colorado = quadSize(quadAt(-105.0595, 40.31));
|
||||
const alaska = quadSize(quadAt(-150, 64.8));
|
||||
expect(equator.widthMeters).toBeGreaterThan(colorado.widthMeters);
|
||||
expect(colorado.widthMeters).toBeGreaterThan(alaska.widthMeters);
|
||||
for (const size of [equator, colorado, alaska]) {
|
||||
expect(size.heightMeters).toBeGreaterThan(13800);
|
||||
expect(size.heightMeters).toBeLessThan(14000);
|
||||
}
|
||||
});
|
||||
|
||||
test('is that of a 1:24,000 sheet', () => {
|
||||
// A quadrangle at 40 degrees north is about 10.6 km by 13.9 km: about 17.4 by 22.8 inches of paper.
|
||||
const {widthMeters, heightMeters, sheetWidthMm, sheetHeightMm} = quadSize(quadAt(-105.0595, 40.31));
|
||||
expect(widthMeters / 1000).toBeCloseTo(10.62, 1);
|
||||
expect(heightMeters / 1000).toBeCloseTo(13.88, 1);
|
||||
expect(sheetWidthMm / 25.4).toBeCloseTo(17.4, 0);
|
||||
expect(sheetHeightMm / 25.4).toBeCloseTo(22.8, 0);
|
||||
expect(sheetWidthMm).toBeCloseTo(widthMeters / 24, 6);
|
||||
});
|
||||
});
|
||||
29
app/src/components/mapTiles.js
Normal file
29
app/src/components/mapTiles.js
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
// Reading the tiles of a map file, as the map does not: one at a time, for what is in them.
|
||||
|
||||
import {PMTiles} from "pmtiles";
|
||||
import {VectorTile} from "@mapbox/vector-tile";
|
||||
import Pbf from "pbf";
|
||||
|
||||
const PROTOCOL = "pmtiles://";
|
||||
const archives = new Map();
|
||||
|
||||
function archive(url) {
|
||||
const address = url.startsWith(PROTOCOL) ? url.slice(PROTOCOL.length) : url;
|
||||
if (!archives.has(address)) archives.set(address, new PMTiles(address));
|
||||
return archives.get(address);
|
||||
}
|
||||
|
||||
// A tile of the vector map file which a source of the map's style has as its `url`, or null when
|
||||
// the file has no such tile (it is not of that place, or does not go that deep).
|
||||
export async function readVectorTile(url, {z, x, y}) {
|
||||
const tile = await archive(url).getZxy(z, x, y);
|
||||
return tile?.data ? new VectorTile(new Pbf(new Uint8Array(tile.data))) : null;
|
||||
}
|
||||
|
||||
// The west, south, east and north edges (degrees) of what a map file is of, as the file says; null
|
||||
// when it does not say.
|
||||
export async function readTileBounds(url) {
|
||||
const {minLon, minLat, maxLon, maxLat} = await archive(url).getHeader();
|
||||
const edges = [minLon, minLat, maxLon, maxLat];
|
||||
return edges.every(Number.isFinite) && minLon < maxLon && minLat < maxLat ? edges : null;
|
||||
}
|
||||
51
app/src/components/mapTiles.test.js
Normal file
51
app/src/components/mapTiles.test.js
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import {readTileBounds, readVectorTile} from './mapTiles';
|
||||
|
||||
const mockOpened = [];
|
||||
const mockTiles = {};
|
||||
const mockHeaders = {};
|
||||
|
||||
jest.mock('pmtiles', () => ({
|
||||
PMTiles: class {
|
||||
constructor(address) {
|
||||
this.address = address;
|
||||
mockOpened.push(address);
|
||||
}
|
||||
|
||||
async getHeader() {
|
||||
return mockHeaders[this.address] || {};
|
||||
}
|
||||
|
||||
async getZxy(z, x, y) {
|
||||
return mockTiles[`${this.address} ${z}/${x}/${y}`];
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
describe('reading a tile of a map file', () => {
|
||||
test('is of the file a source of the map has as its URL, which is opened once', async () => {
|
||||
// A tile with nothing in it.
|
||||
mockTiles['https://example.com/a.pmtiles 14/3/5'] = {data: new ArrayBuffer(0)};
|
||||
const tile = await readVectorTile('pmtiles://https://example.com/a.pmtiles', {z: 14, x: 3, y: 5});
|
||||
expect(tile.layers).toEqual({});
|
||||
await readVectorTile('pmtiles://https://example.com/a.pmtiles', {z: 14, x: 3, y: 6});
|
||||
expect(mockOpened).toEqual(['https://example.com/a.pmtiles']);
|
||||
});
|
||||
|
||||
test('is nothing when the file has no such tile', async () => {
|
||||
expect(await readVectorTile('pmtiles:///media/b.pmtiles', {z: 14, x: 0, y: 0})).toBeNull();
|
||||
expect(mockOpened).toContain('/media/b.pmtiles');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the edges of a map file', () => {
|
||||
test('are what the file says: west, south, east and north', async () => {
|
||||
mockHeaders['/media/c.pmtiles'] = {minLon: -150, minLat: 61, maxLon: -149, maxLat: 62, maxZoom: 15};
|
||||
expect(await readTileBounds('pmtiles:///media/c.pmtiles')).toEqual([-150, 61, -149, 62]);
|
||||
});
|
||||
|
||||
test('are not known when the file does not say', async () => {
|
||||
mockHeaders['/media/d.pmtiles'] = {minLon: 0, minLat: 0, maxLon: 0, maxLat: 0};
|
||||
expect(await readTileBounds('pmtiles:///media/d.pmtiles')).toBeNull();
|
||||
expect(await readTileBounds('pmtiles:///media/e.pmtiles')).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue