509 lines
23 KiB
JavaScript
509 lines
23 KiB
JavaScript
// The base map's look: OpenFreeMap Liberty recolored after the National Park
|
||
// Service's Park Tiles "Standard" style. Colors sampled from the Park Tiles
|
||
// legend swatches (nps.gov/maps/web/img/legend/*-standard.png) and their
|
||
// public Imagery style JSON (docs/nps-resources.adoc) — only the colors,
|
||
// none of their data or tiles. Line widths stay Liberty's own. Applied
|
||
// identically to the online style and the offline one (offline.pmtiles is
|
||
// built with Planetiler's OpenMapTiles profile, the schema Liberty expects).
|
||
// map.js styles the map with it and /symbols.html draws its legend from the
|
||
// same patched style, so the two can't drift apart.
|
||
|
||
export function patchOnlineStyle(style) {
|
||
return insertTrackOnlyLayer(protectedAreasAndTextures(parkTilesStyle(style)));
|
||
}
|
||
|
||
const PARK_TILES_PATCH = {
|
||
background: { "background-color": "#f7eee8" },
|
||
natural_earth: { "raster-opacity": 0 },
|
||
landuse_residential: { "fill-color": "#f7eee8" },
|
||
landcover_wood: { "fill-color": "#dfe0c9", "fill-opacity": 0.6 },
|
||
landcover_grass: { "fill-color": "#e9e7d6", "fill-opacity": 0.5 },
|
||
landcover_wetland: { "fill-color": "#d5dcc9", "fill-opacity": 0.6 },
|
||
landcover_ice: { "fill-color": "#ffffff" },
|
||
landcover_sand: { "fill-color": "#f1e7d0" },
|
||
water: { "fill-color": "#b5d0de" },
|
||
waterway_river: { "line-color": "#b5d0de" },
|
||
waterway_other: { "line-color": "#b5d0de" },
|
||
// Park Tiles' area fill is this muted sage (#b3e378 is their park *point* color).
|
||
park: { "fill-color": "#ced2b7", "fill-opacity": 1, "fill-outline-color": "#ced2b7" },
|
||
park_outline: { "line-color": "#8ba35a", "line-width": 1.3, "line-opacity": 1 },
|
||
building: { "fill-color": "#e7e4d5", "fill-outline-color": "#b8b1a0" },
|
||
boundary_2: { "line-color": "#bdb8b0" },
|
||
boundary_3: { "line-color": "#d6d0c8" },
|
||
road_motorway: { "line-color": "#f8ecbe" },
|
||
road_trunk_primary: { "line-color": "#f8ecbe" },
|
||
road_secondary_tertiary: { "line-color": "#f9f9f6" },
|
||
road_link: { "line-color": "#f9f9f6" },
|
||
road_motorway_link: { "line-color": "#f9f9f6" },
|
||
road_minor: { "line-color": "#f5f3e5" },
|
||
road_service_track: { "line-color": "#f5f3e5" },
|
||
road_motorway_casing: { "line-color": "#8f867a" },
|
||
road_trunk_primary_casing: { "line-color": "#8f867a" },
|
||
road_secondary_tertiary_casing: { "line-color": "#857f7a" },
|
||
road_link_casing: { "line-color": "#857f7a" },
|
||
road_motorway_link_casing: { "line-color": "#857f7a" },
|
||
road_minor_casing: { "line-color": "#a5a197" },
|
||
road_service_track_casing: { "line-color": "#a5a197" },
|
||
road_path_pedestrian: { "line-color": "#8e827b", "line-width": 1, "line-dasharray": [2, 1.5] },
|
||
water_name_point_label: { "text-color": "#31505f", "text-halo-color": "#ffffff" },
|
||
water_name_line_label: { "text-color": "#31505f", "text-halo-color": "#ffffff" },
|
||
waterway_line_label: { "text-color": "#31505f", "text-halo-color": "#ffffff" },
|
||
"highway-name-major": { "text-color": "#636363", "text-halo-color": "#ffffff" },
|
||
"highway-name-minor": { "text-color": "#636363", "text-halo-color": "#ffffff" },
|
||
"highway-name-path": { "text-color": "#636363", "text-halo-color": "#ffffff" },
|
||
};
|
||
|
||
// tunnel_*/bridge_* layers reuse their surface road's colors.
|
||
function parkTilesPatchFor(id) {
|
||
const match = id.match(/^(tunnel|bridge)_(.+)$/);
|
||
if (!match) return PARK_TILES_PATCH[id];
|
||
const alias = { street: "minor", street_casing: "minor_casing" }[match[2]] ?? match[2];
|
||
return PARK_TILES_PATCH[`road_${alias}`];
|
||
}
|
||
|
||
function parkTilesStyle(style) {
|
||
for (const layer of style.layers) {
|
||
const patch = parkTilesPatchFor(layer.id);
|
||
if (patch) Object.assign((layer.paint ??= {}), patch);
|
||
}
|
||
const take = (id) => {
|
||
const index = style.layers.findIndex((layer) => layer.id === id);
|
||
return index === -1 ? null : style.layers.splice(index, 1)[0];
|
||
};
|
||
const park = take("park");
|
||
const outline = take("park_outline");
|
||
if (!park || !outline) return style;
|
||
delete outline.paint["line-dasharray"];
|
||
// Park Tiles paints a whole NPS unit one flat sage, so the park fill moves
|
||
// above landcover (wood/grass would mottle it), just below water — with a
|
||
// light-green tint band inside the boundary line, like theirs.
|
||
const band = {
|
||
...outline,
|
||
id: "park_tintband",
|
||
paint: { "line-color": "#b2c294", "line-width": 5, "line-offset": 2.5, "line-opacity": 0.8 },
|
||
};
|
||
const index = style.layers.findIndex((layer) => layer.id === "waterway_tunnel");
|
||
style.layers.splice(index === -1 ? style.layers.length : index, 0, park, band, outline);
|
||
return style;
|
||
}
|
||
|
||
// OpenMapTiles' park `class` is the OSM protection_title lowercased when
|
||
// there is one ("národný_park", "nationalpark", …), else the boundary/leisure
|
||
// tag ("national_park", "nature_reserve", "protected_area"), so national
|
||
// parks are told apart by substring.
|
||
// ponytail: a handful of languages; add a word when a park shows up gray.
|
||
const NATIONAL_PARK = ["any", ...["nation", "národn", "narodn", "nemzeti", "nazional", "nacional"].map((word) => ["in", word, ["coalesce", ["get", "class"], ""]])];
|
||
|
||
// National parks keep the flat Park Tiles sage; other protected areas
|
||
// (nature reserves, landscape areas, Natura 2000, …) get a translucent
|
||
// gray-green with a dashed edge, so the map tells "national park rules"
|
||
// from "some protection" at a glance; strict reserves and monuments (where
|
||
// you mostly can't leave the marked trail) a step darker than landscape
|
||
// areas / Natura 2000. Military areas red-hatched. Meadows get a grass
|
||
// texture from zoom 13, scrub / dwarf pine its own bushes from 11 (no forest texture: OSM rarely says what kind, and
|
||
// trees everywhere were too busy).
|
||
// The pattern images are drawn at runtime (patternImage below, on
|
||
// MapLibre's styleimagemissing), so there's no sprite sheet to extend and
|
||
// they work offline alike.
|
||
// ponytail: same substring trick as NATIONAL_PARK, a word per language.
|
||
const STRICT_RESERVE = ["any", ...["rezerv", "reserv", "wilderness", "wildnis", "pamiatk", "památk", "monument", "denkmal"].map((word) => ["in", word, ["coalesce", ["get", "class"], ""]])];
|
||
const protectedFill = (strict, other, nationalPark) => ["case", NATIONAL_PARK, nationalPark, STRICT_RESERVE, strict, other];
|
||
const PROTECTED_LINE = "#7d9468";
|
||
|
||
function protectedAreasAndTextures(style) {
|
||
const find = (id) => style.layers.find((layer) => layer.id === id);
|
||
const park = find("park");
|
||
const outline = find("park_outline");
|
||
const band = find("park_tintband");
|
||
if (!park || !outline) return style;
|
||
const sage = park.paint["fill-color"];
|
||
park.paint["fill-color"] = protectedFill("rgba(130, 160, 110, 0.32)", "rgba(140, 165, 120, 0.14)", sage);
|
||
park.paint["fill-outline-color"] = ["case", ["!", NATIONAL_PARK], "rgba(0, 0, 0, 0)", sage];
|
||
const protectedOutline = {
|
||
...outline,
|
||
id: "park_outline_protected",
|
||
filter: ["all", outline.filter, ["!", NATIONAL_PARK]],
|
||
paint: { "line-color": PROTECTED_LINE, "line-width": 1.2, "line-dasharray": [3, 2] },
|
||
};
|
||
outline.filter = ["all", outline.filter, NATIONAL_PARK];
|
||
if (band) band.filter = ["all", band.filter, NATIONAL_PARK];
|
||
|
||
const textures = [
|
||
{ id: "landcover_grass_pattern", source: "landcover", class: "grass", pattern: "grass", minzoom: 13, not: "scrub" },
|
||
{ id: "landcover_scrub_pattern", source: "landcover", class: "grass", pattern: "scrub", minzoom: 11, only: "scrub" },
|
||
{ id: "landuse_military", source: "landuse", class: "military", pattern: "military", minzoom: 8 },
|
||
].map((t) => ({
|
||
id: t.id,
|
||
type: "fill",
|
||
source: park.source,
|
||
"source-layer": t.source,
|
||
minzoom: t.minzoom,
|
||
filter: ["all", ["==", ["get", "class"], t.class],
|
||
...(t.not ? [["!=", ["get", "subclass"], t.not]] : []),
|
||
...(t.only ? [["==", ["get", "subclass"], t.only]] : [])],
|
||
paint: { "fill-pattern": `maptool-pattern-${t.pattern}` },
|
||
}));
|
||
const military = {
|
||
...textures.find((t) => t.id === "landuse_military"),
|
||
id: "landuse_military_outline",
|
||
type: "line",
|
||
paint: { "line-color": "#c0392b", "line-width": 1.2, "line-opacity": 0.7 },
|
||
};
|
||
// Above the park group (a national park's sage is opaque), below water.
|
||
const index = style.layers.indexOf(outline) + 1;
|
||
style.layers.splice(index, 0, protectedOutline, ...textures, military);
|
||
|
||
// Park names while zoomed out (as OsmAnd does); from z11 village, peak
|
||
// and other local names take over. Before the place labels, so towns win
|
||
// a collision. The OpenMapTiles park layer carries a label point per area.
|
||
const label = {
|
||
id: "park_label",
|
||
type: "symbol",
|
||
source: park.source,
|
||
"source-layer": "park",
|
||
minzoom: 6,
|
||
maxzoom: 11,
|
||
filter: ["==", ["geometry-type"], "Point"],
|
||
layout: {
|
||
"text-field": ["coalesce", ["get", "name"], ["get", "name_en"]],
|
||
"text-font": ["Noto Sans Italic"],
|
||
"text-size": ["interpolate", ["linear"], ["zoom"], 6, 10, 10, 13],
|
||
"text-max-width": 8,
|
||
"text-letter-spacing": 0.05,
|
||
"symbol-sort-key": ["coalesce", ["get", "rank"], 99],
|
||
},
|
||
paint: { "text-color": "#3f5a2e", "text-halo-color": "#ffffff", "text-halo-width": 1.5 },
|
||
};
|
||
// Peaks from z7, great for orientation zoomed out (Liberty has none):
|
||
// the highest win a collision, names and towns take precedence.
|
||
const peaks = {
|
||
id: "mountain_peak_label",
|
||
type: "symbol",
|
||
source: park.source,
|
||
"source-layer": "mountain_peak",
|
||
minzoom: 7,
|
||
filter: ["match", ["get", "class"], ["peak", "volcano"], true, false],
|
||
layout: {
|
||
"icon-image": "maptool-pattern-peak",
|
||
"text-field": ["case", ["has", "ele"],
|
||
["format", ["coalesce", ["get", "name"], ""], {}, "\n", {}, ["concat", ["get", "ele"], " m"], { "font-scale": 0.8 }],
|
||
["coalesce", ["get", "name"], ""]],
|
||
"text-font": ["Noto Sans Regular"],
|
||
"text-size": ["interpolate", ["linear"], ["zoom"], 7, 10, 12, 12],
|
||
"text-anchor": "top",
|
||
"text-offset": [0, 0.5],
|
||
"text-max-width": 8,
|
||
"text-optional": true,
|
||
"text-padding": 6,
|
||
"symbol-sort-key": ["-", 0, ["coalesce", ["get", "ele"], 0]],
|
||
},
|
||
paint: { "icon-color": "#6b4f3a", "text-color": "#6b4f3a", "text-halo-color": "#ffffff", "text-halo-width": 1.5 },
|
||
};
|
||
// Ski lifts and cable cars (Liberty draws none): a thin line with the
|
||
// topo map's cross ticks, the lift's name along it.
|
||
const aerialway = ["==", ["get", "class"], "aerialway"];
|
||
const lift = { type: "line", source: park.source, "source-layer": "transportation", minzoom: 12, filter: aerialway };
|
||
const lifts = [
|
||
{ ...lift, id: "aerialway", paint: { "line-color": "#4a4a4a", "line-width": 1.2 } },
|
||
{ ...lift, id: "aerialway_ticks", paint: { "line-color": "#4a4a4a", "line-width": 6, "line-dasharray": [0.2, 8] } },
|
||
{
|
||
id: "aerialway_name", type: "symbol", source: park.source, "source-layer": "transportation_name", minzoom: 13, filter: aerialway,
|
||
layout: { "symbol-placement": "line", "text-field": ["get", "name"], "text-font": ["Noto Sans Regular"], "text-size": 11, "text-offset": [0, 0.8] },
|
||
paint: { "text-color": "#4a4a4a", "text-halo-color": "#ffffff", "text-halo-width": 1.5 },
|
||
},
|
||
];
|
||
const firstSymbol = style.layers.findIndex((layer) => layer.type === "symbol");
|
||
style.layers.splice(firstSymbol === -1 ? style.layers.length : firstSymbol, 0, ...lifts.slice(0, 2));
|
||
const placeIndex = style.layers.findIndex((layer) => layer["source-layer"] === "place");
|
||
style.layers.splice(placeIndex === -1 ? style.layers.length : placeIndex, 0, lifts[2], peaks, label);
|
||
return style;
|
||
}
|
||
|
||
const PATTERNS = {
|
||
// Not a pattern: the peak triangle, drawn by the same on-demand path as
|
||
// an SDF so night mode recolors it with icon-color.
|
||
peak: { day: "#000000", sdf: true },
|
||
grass: { day: "rgba(130, 140, 95, 0.45)", night: "rgba(120, 140, 105, 0.3)" },
|
||
// Scrub, incl. dwarf pine (kosodrevina) above the tree line: its own
|
||
// tint (bg) plus bushes, so it reads apart from both meadow and forest.
|
||
scrub: { day: "rgba(95, 125, 80, 0.55)", night: "rgba(110, 140, 100, 0.4)", bg: "rgba(150, 170, 120, 0.3)", bgNight: "rgba(60, 80, 55, 0.35)" },
|
||
military: { day: "rgba(192, 57, 43, 0.4)", night: "rgba(192, 57, 43, 0.35)" },
|
||
};
|
||
|
||
// "maptool-pattern-<name>[-night]" → { width, height, data } for
|
||
// map.addImage, drawn on a canvas at 2× (pixelRatio 2); null for other ids.
|
||
export function patternImage(id) {
|
||
const match = id.match(/^maptool-pattern-(\w+?)(-night)?$/);
|
||
const colors = match && PATTERNS[match[1]];
|
||
if (!colors) return null;
|
||
const size = match[1] === "peak" ? 20 : 48;
|
||
const ctx = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
|
||
ctx.canvas.width = ctx.canvas.height = size;
|
||
ctx.strokeStyle = ctx.fillStyle = match[2] ? colors.night : colors.day;
|
||
ctx.lineWidth = 2;
|
||
ctx.lineCap = "round";
|
||
if (colors.bg) {
|
||
ctx.fillStyle = match[2] ? colors.bgNight : colors.bg;
|
||
ctx.fillRect(0, 0, size, size);
|
||
ctx.fillStyle = match[2] ? colors.night : colors.day;
|
||
}
|
||
if (match[1] === "peak") {
|
||
ctx.beginPath();
|
||
ctx.moveTo(10, 3);
|
||
ctx.lineTo(18, 17);
|
||
ctx.lineTo(2, 17);
|
||
ctx.fill();
|
||
} else if (match[1] === "scrub") {
|
||
// Low bushes: three overlapping dots each, staggered.
|
||
for (const [x, y] of [[12, 16], [36, 40], [34, 14], [10, 38]]) {
|
||
for (const dx of [-3, 0, 3]) {
|
||
ctx.beginPath();
|
||
ctx.arc(x + dx, y - (dx ? 0 : 2), 3, 0, 2 * Math.PI);
|
||
ctx.fill();
|
||
}
|
||
}
|
||
} else if (match[1] === "grass") {
|
||
for (const [x, y] of [[10, 16], [34, 40], [30, 12]]) {
|
||
ctx.beginPath();
|
||
for (const dx of [-4, 0, 4]) {
|
||
ctx.moveTo(x + dx * 0.4, y);
|
||
ctx.lineTo(x + dx, y - 6);
|
||
}
|
||
ctx.stroke();
|
||
}
|
||
} else {
|
||
// Diagonal hatch, seamless across tile edges.
|
||
ctx.lineWidth = 3;
|
||
ctx.beginPath();
|
||
for (const offset of [-size, 0, size]) {
|
||
ctx.moveTo(offset, size);
|
||
ctx.lineTo(offset + size, 0);
|
||
}
|
||
ctx.stroke();
|
||
}
|
||
return { image: ctx.getImageData(0, 0, size, size), options: { pixelRatio: 2, sdf: !!colors.sdf } };
|
||
}
|
||
|
||
// Liberty's own "road_service_track" layer paints service roads (paved
|
||
// driveways/parking aisles) and actual unpaved tracks the same color —
|
||
// fine for a general-purpose map, not for this app's "can the camper get
|
||
// there" use case. The underlying OpenMapTiles data does carry `class:
|
||
// "track"` separately from `"service"` (see the filter below), so rather
|
||
// than recoloring the merged layer (which would mislabel paved driveways
|
||
// as unpaved), this clones it into a second layer scoped to `class ==
|
||
// "track"` only, dashed and dirt-brown.
|
||
// Surface-level only (excludes tunnel_/bridge_ variants): an unpaved track
|
||
// in a tunnel or on a bridge is rare enough not to be worth a third layer.
|
||
function insertTrackOnlyLayer(style) {
|
||
const index = style.layers.findIndex((layer) => layer.id === "road_service_track");
|
||
if (index === -1) return style;
|
||
|
||
const base = style.layers[index];
|
||
const trackOnly = {
|
||
...base,
|
||
id: "road_track_only",
|
||
filter: ["all", base.filter, ["==", ["get", "class"], "track"]],
|
||
paint: { ...base.paint, "line-color": "#c9a66b", "line-dasharray": [2, 2] },
|
||
};
|
||
style.layers.splice(index + 1, 0, trackOnly);
|
||
return style;
|
||
}
|
||
|
||
// --- Night palette ----------------------------------------------------------
|
||
// What car navigations do instead of inverting: a dark blue-gray ground (not
|
||
// black), low contrast, roads a step lighter than the ground, motorways a
|
||
// muted ochre, light-gray labels on dark halos; rasters dimmed, not inverted.
|
||
// Switched live with setPaintProperty (no setStyle), so overlays stay put.
|
||
// The main layers have hand-picked colors; every other base-style color goes
|
||
// through nightColor(), and overlays only get their rasters dimmed and their
|
||
// labels' halos darkened — their own colors are the point of them.
|
||
|
||
const NIGHT_GROUND = "#1d2329";
|
||
const NIGHT_LABEL = { "text-color": "#a8b0b8", "text-halo-color": NIGHT_GROUND };
|
||
const NIGHT_WATER_LABEL = { "text-color": "#6f8fa3", "text-halo-color": NIGHT_GROUND };
|
||
const NIGHT_CASING = { "line-color": "#121619" };
|
||
|
||
const NIGHT_PATCH = {
|
||
background: { "background-color": NIGHT_GROUND },
|
||
landuse_residential: { "fill-color": "#20262c" },
|
||
landcover_wood: { "fill-color": "#1f2a24" },
|
||
landcover_grass: { "fill-color": "#222a25" },
|
||
landcover_wetland: { "fill-color": "#1f2a2a" },
|
||
landcover_ice: { "fill-color": "#2a3036" },
|
||
landcover_sand: { "fill-color": "#2a2823" },
|
||
water: { "fill-color": "#12202b" },
|
||
waterway_river: { "line-color": "#1a3040" },
|
||
waterway_other: { "line-color": "#1a3040" },
|
||
park: {
|
||
"fill-color": protectedFill("rgba(120, 150, 110, 0.2)", "rgba(120, 150, 110, 0.09)", "#1f2b22"),
|
||
"fill-outline-color": ["case", ["!", NATIONAL_PARK], "rgba(0, 0, 0, 0)", "#1f2b22"],
|
||
},
|
||
park_outline: { "line-color": "#4f6b3a" },
|
||
park_outline_protected: { "line-color": "#46593a" },
|
||
landcover_grass_pattern: { "fill-pattern": "maptool-pattern-grass-night" },
|
||
landcover_scrub_pattern: { "fill-pattern": "maptool-pattern-scrub-night" },
|
||
landuse_military: { "fill-pattern": "maptool-pattern-military-night" },
|
||
landuse_military_outline: { "line-color": "#8a3a30" },
|
||
park_tintband: { "line-color": "#2b3a26" },
|
||
park_label: { "text-color": "#8fae7a", "text-halo-color": NIGHT_GROUND },
|
||
aerialway: { "line-color": "#8a8f96" },
|
||
aerialway_ticks: { "line-color": "#8a8f96" },
|
||
aerialway_name: NIGHT_LABEL,
|
||
mountain_peak_label: { "icon-color": "#b8a48c", "text-color": "#b8a48c", "text-halo-color": NIGHT_GROUND },
|
||
building: { "fill-color": "#262c32", "fill-outline-color": "#30373e" },
|
||
boundary_2: { "line-color": "#4a4f55" },
|
||
boundary_3: { "line-color": "#3a3f45" },
|
||
road_motorway: { "line-color": "#6b5a35" },
|
||
road_trunk_primary: { "line-color": "#6b5a35" },
|
||
road_secondary_tertiary: { "line-color": "#4a5058" },
|
||
road_link: { "line-color": "#4a5058" },
|
||
road_motorway_link: { "line-color": "#4a5058" },
|
||
road_minor: { "line-color": "#3a4047" },
|
||
road_service_track: { "line-color": "#343a40" },
|
||
road_track_only: { "line-color": "#7a6440" },
|
||
road_path_pedestrian: { "line-color": "#5a5650" },
|
||
road_motorway_casing: NIGHT_CASING,
|
||
road_trunk_primary_casing: NIGHT_CASING,
|
||
road_secondary_tertiary_casing: NIGHT_CASING,
|
||
road_link_casing: NIGHT_CASING,
|
||
road_motorway_link_casing: NIGHT_CASING,
|
||
road_minor_casing: NIGHT_CASING,
|
||
road_service_track_casing: NIGHT_CASING,
|
||
water_name_point_label: NIGHT_WATER_LABEL,
|
||
water_name_line_label: NIGHT_WATER_LABEL,
|
||
waterway_line_label: NIGHT_WATER_LABEL,
|
||
"highway-name-major": NIGHT_LABEL,
|
||
"highway-name-minor": NIGHT_LABEL,
|
||
"highway-name-path": NIGHT_LABEL,
|
||
};
|
||
|
||
// tunnel_*/bridge_* layers reuse their surface road's colors.
|
||
function nightPatchFor(id) {
|
||
const match = id.match(/^(tunnel|bridge)_(.+)$/);
|
||
if (!match) return NIGHT_PATCH[id];
|
||
const alias = { street: "minor", street_casing: "minor_casing" }[match[2]] ?? match[2];
|
||
return NIGHT_PATCH[`road_${alias}`];
|
||
}
|
||
|
||
// The color paint properties per layer type, and how each darkens.
|
||
const COLOR_PROPS = {
|
||
background: { "background-color": "area" },
|
||
fill: { "fill-color": "area", "fill-outline-color": "area" },
|
||
line: { "line-color": "area" },
|
||
"fill-extrusion": { "fill-extrusion-color": "area" },
|
||
circle: { "circle-color": "area", "circle-stroke-color": "area" },
|
||
symbol: { "text-color": "text", "text-halo-color": "halo" },
|
||
"color-relief": { "color-relief-color": "area" },
|
||
};
|
||
|
||
let probe = null;
|
||
|
||
// Any CSS color → [r, g, b, a] (the browser parses it), null if not a color.
|
||
function parseColor(value) {
|
||
probe ??= document.createElement("canvas").getContext("2d");
|
||
probe.fillStyle = "#010203";
|
||
probe.fillStyle = value;
|
||
const out = probe.fillStyle;
|
||
if (out === "#010203" && value.toLowerCase() !== "#010203") return null;
|
||
const hex = out.match(/^#(..)(..)(..)$/);
|
||
if (hex) return [...hex.slice(1).map((h) => parseInt(h, 16)), 1];
|
||
const [r, g, b, a = 1] = out.match(/\(([^)]+)\)/)[1].split(",").map(Number);
|
||
return [r, g, b, a];
|
||
}
|
||
|
||
function toHsl([r, g, b]) {
|
||
[r, g, b] = [r / 255, g / 255, b / 255];
|
||
const max = Math.max(r, g, b);
|
||
const min = Math.min(r, g, b);
|
||
const l = (max + min) / 2;
|
||
if (max === min) return [0, 0, l];
|
||
const d = max - min;
|
||
const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
|
||
const h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
|
||
return [h * 60, s, l];
|
||
}
|
||
|
||
// The fallback for layers NIGHT_PATCH doesn't list: lightness flipped and
|
||
// squeezed into the dark end, colors desaturated; dark text goes light,
|
||
// halos become the ground. (Roads need the hand-picked colors: flipping
|
||
// would draw white roads darker than a cream ground.)
|
||
export function nightColor(value, role) {
|
||
const rgba = typeof value === "string" && parseColor(value);
|
||
if (!rgba) return value;
|
||
const alpha = rgba[3];
|
||
if (role === "halo") return `rgba(29, 35, 41, ${alpha})`;
|
||
const [h, s, l] = toHsl(rgba);
|
||
const night = role === "text" ? [s * 0.5, 0.55 + (1 - l) * 0.25] : [s * 0.55, 0.08 + (1 - l) * 0.3];
|
||
return `hsla(${h.toFixed(1)}, ${(night[0] * 100).toFixed(1)}%, ${(night[1] * 100).toFixed(1)}%, ${alpha})`;
|
||
}
|
||
|
||
// Colors inside expressions too (interpolate stops, match outputs) and in
|
||
// legacy {stops: [[zoom, color], …]} functions, which Liberty still uses.
|
||
function nightValue(value, role) {
|
||
if (Array.isArray(value)) return value.map((v) => nightValue(v, role));
|
||
if (value?.stops) return { ...value, stops: value.stops.map(([zoom, v]) => [zoom, nightValue(v, role)]) };
|
||
return nightColor(value, role);
|
||
}
|
||
|
||
export class NightMap {
|
||
constructor(map) {
|
||
this._map = map;
|
||
this._on = false;
|
||
this._base = new Set();
|
||
this._day = new Map(); // layer id -> its day values of what night changed
|
||
map.on("styledata", () => this._on && this._apply());
|
||
}
|
||
|
||
// The base style's layers (passed through on its way to setStyle).
|
||
base(style) {
|
||
this._base = new Set(style.layers.map((layer) => layer.id));
|
||
this._day.clear();
|
||
return style;
|
||
}
|
||
|
||
set(on) {
|
||
if (on === this._on) return;
|
||
this._on = on;
|
||
if (on) this._apply();
|
||
else this._restore();
|
||
}
|
||
|
||
_apply() {
|
||
const ids = this._map.getLayersOrder();
|
||
for (const id of this._day.keys()) if (!ids.includes(id)) this._day.delete(id); // removed overlays
|
||
for (const id of ids) {
|
||
if (this._day.has(id)) continue;
|
||
const night = this._nightFor(id);
|
||
const day = Object.fromEntries(Object.keys(night).map((prop) => [prop, this._map.getPaintProperty(id, prop)]));
|
||
try {
|
||
for (const [prop, value] of Object.entries(night)) this._map.setPaintProperty(id, prop, value);
|
||
} catch {
|
||
return; // a style still loading: its own styledata comes once it's done
|
||
}
|
||
this._day.set(id, day);
|
||
}
|
||
}
|
||
|
||
_restore() {
|
||
for (const [id, props] of this._day) {
|
||
if (this._map.getLayer(id)) for (const [prop, value] of Object.entries(props)) this._map.setPaintProperty(id, prop, value);
|
||
}
|
||
this._day.clear();
|
||
}
|
||
|
||
_nightFor(id) {
|
||
const type = this._map.getLayer(id).type;
|
||
if (type === "raster") return { "raster-brightness-max": 0.6, "raster-saturation": -0.3 };
|
||
if (type === "hillshade") return { "hillshade-highlight-color": "rgba(255, 255, 255, 0.06)" };
|
||
const base = this._base.has(id);
|
||
if (!base && type !== "symbol" && type !== "color-relief") return {};
|
||
const night = { ...(base && nightPatchFor(id)) };
|
||
for (const [prop, role] of Object.entries(COLOR_PROPS[type] || {})) {
|
||
if (prop in night) continue;
|
||
const day = this._map.getPaintProperty(id, prop);
|
||
if (day !== undefined) night[prop] = nightValue(day, role);
|
||
}
|
||
return night;
|
||
}
|
||
}
|