mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
vectorBase: evaluate as the style specification does; leave out features with no value
- A legacy function without a type is exponential only on a property that interpolates and interval on any other (line-join, text-transform, ...); a property function with string outputs is no longer categorical. - step over what is not a number fails, leaving the feature out. - has, get and legacy filters see a feature's own properties, never inherited names such as toString. - A value that comes to null, undefined or NaN leaves the feature out instead of being written to the canvas, which ignored it and drew the last feature's colour or width. - A layer's labels are placed in their features' order, as MapLibre places them, not reversed.
This commit is contained in:
1 parent
72d8dd606d
commit
09d1133d90
5 files changed
+402
-78
No files matched your search
@@ -315,13 +315,18 @@ What it draws of the style specification:
|
||||
`text-color`, `text-opacity`, `text-halo-color`, `text-halo-width`,
|
||||
`text-transform`, `text-anchor`, `text-offset`, `text-max-width`).
|
||||
Layer `minzoom`, `maxzoom`, `filter` and `visibility` hold.
|
||||
- Labels are painted into the tiles: top layer first, each clear of those
|
||||
placed before it and wholly inside its tile (one across a tile edge is
|
||||
- Labels are painted into the tiles: top layer first (within a layer, its
|
||||
features in their order in the tile), each clear of those placed before
|
||||
it and wholly inside its tile (one across a tile edge is
|
||||
left out). A point labels at itself, a line halfway along it (level, not
|
||||
along the line), a polygon at its outer ring's bounding-box centre.
|
||||
- Filters in both syntaxes (legacy, with `$type` and `$id`, and
|
||||
expressions). Legacy `{stops, base, property, type}` functions
|
||||
(exponential, interval, categorical, identity; not zoom-and-property).
|
||||
(exponential, interval, categorical, identity; not zoom-and-property);
|
||||
one without a `type` is exponential on a property that interpolates (a
|
||||
number or colour) and interval on any other (`line-cap`, `line-join`,
|
||||
`text-font`, `text-transform`, `text-anchor`, ...), as the specification
|
||||
says. `has`, `get` and legacy filters see a feature's own properties only.
|
||||
- Expressions: `literal`, `get`, `has`, `id`, `geometry-type`, `zoom`,
|
||||
`properties`, `!`, `all`, `any`, `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`,
|
||||
`case`, `match`, `coalesce`, `step`, `interpolate` (`linear` and
|
||||
@@ -335,7 +340,9 @@ What it draws of the style specification:
|
||||
(`fill-pattern`, `line-pattern`, `background-pattern`), `line-offset`,
|
||||
`line-gradient` or a translation; layers whose values use an expression
|
||||
not listed (or are malformed). A feature whose values cannot be evaluated
|
||||
(a type that does not fit) is left out. Nothing unsupported throws.
|
||||
(a type that does not fit, a `step` or `interpolate` over what is not a
|
||||
number, or a value that comes to nothing: null, or not a finite number
|
||||
where one is needed) is left out. Nothing unsupported throws.
|
||||
- Ignored: icons (`icon-image`, sprites: a symbol layer draws its text
|
||||
alone), text along lines (drawn level), `glyphs` (system fonts), and any
|
||||
other paint or layout property not listed above.
|
||||
|
||||
@@ -19,6 +19,10 @@ const unsupported = (what) => {
|
||||
/** A feature with no properties, at a zoom: what a zoom-only value sees. */
|
||||
const constant = (value) => () => value;
|
||||
|
||||
/** A feature's own property `key` (never an inherited name), or undefined. */
|
||||
const propertyOf = (properties, key) =>
|
||||
properties && Object.hasOwn(properties, key) ? properties[key] : undefined;
|
||||
|
||||
const COMPARE = {
|
||||
'==': (a, b) => a === b,
|
||||
'!=': (a, b) => a !== b,
|
||||
@@ -211,7 +215,7 @@ export function isExpressionFilter(filter) {
|
||||
const legacyKey = (key) => {
|
||||
if (key === '$type') return (f) => f.type;
|
||||
if (key === '$id') return (f) => f.id;
|
||||
return (f) => f.properties[key];
|
||||
return (f) => propertyOf(f.properties, key);
|
||||
};
|
||||
|
||||
/** A legacy filter, compiled. */
|
||||
@@ -232,7 +236,7 @@ function compileLegacyFilter(filter) {
|
||||
const has = (f) =>
|
||||
args[0] === '$type' || args[0] === '$id'
|
||||
? legacyKey(args[0])(f) !== undefined
|
||||
: args[0] in f.properties;
|
||||
: propertyOf(f.properties, args[0]) !== undefined;
|
||||
return op === 'has' ? has : (f) => !has(f);
|
||||
}
|
||||
case 'in':
|
||||
@@ -271,18 +275,18 @@ export function compileFilter(filter) {
|
||||
return (f) => fn(f) === true;
|
||||
}
|
||||
|
||||
/** A legacy `{stops, base, property, type, default}` function, compiled. */
|
||||
function compileFunction(fn) {
|
||||
/**
|
||||
* A legacy `{stops, base, property, type, default}` function, compiled.
|
||||
* Without a `type` it is `exponential` for a property that interpolates and
|
||||
* `interval` for one that does not, as the style specification says.
|
||||
*/
|
||||
function compileFunction(fn, interpolated) {
|
||||
const stops = fn.stops;
|
||||
const base = fn.base ?? 1;
|
||||
const type =
|
||||
fn.type ??
|
||||
(fn.property !== undefined && typeof stops?.[0]?.[1] === 'string'
|
||||
? 'categorical'
|
||||
: 'exponential');
|
||||
const type = fn.type ?? (interpolated ? 'exponential' : 'interval');
|
||||
if (type === 'identity') {
|
||||
if (fn.property === undefined) return unsupported('identity of zoom');
|
||||
return (f) => f.properties[fn.property] ?? fn.default;
|
||||
return (f) => propertyOf(f.properties, fn.property) ?? fn.default;
|
||||
}
|
||||
if (!Array.isArray(stops) || stops.length === 0)
|
||||
return unsupported('a function without stops');
|
||||
@@ -291,7 +295,7 @@ function compileFunction(fn) {
|
||||
const input =
|
||||
fn.property === undefined
|
||||
? (f) => f.zoom
|
||||
: (f) => f.properties[fn.property];
|
||||
: (f) => propertyOf(f.properties, fn.property);
|
||||
if (type === 'categorical') {
|
||||
const map = new Map(stops.map(([k, v]) => [k, v]));
|
||||
return (f) => {
|
||||
@@ -310,11 +314,17 @@ function compileFunction(fn) {
|
||||
|
||||
/**
|
||||
* A layout or paint value, compiled: a constant, a legacy function, or an
|
||||
* expression.
|
||||
* expression. `interpolated`: whether the property interpolates (a number
|
||||
* or colour), which a legacy function without a `type` steps between its
|
||||
* stops (`interval`) where it does not.
|
||||
* @param {unknown} value
|
||||
* @param {{array?: boolean, interpolated?: boolean}} [options]
|
||||
* @returns {(feature: object) => unknown}
|
||||
*/
|
||||
export function compileValue(value, { array = false } = {}) {
|
||||
export function compileValue(
|
||||
value,
|
||||
{ array = false, interpolated = true } = {},
|
||||
) {
|
||||
// An array property's own value (`text-font`, `line-dasharray`): a
|
||||
// literal unless it names an operator.
|
||||
if (
|
||||
@@ -326,7 +336,7 @@ export function compileValue(value, { array = false } = {}) {
|
||||
return constant(value);
|
||||
if (isExpression(value)) return compileExpression(value);
|
||||
if (value && typeof value === 'object' && !Array.isArray(value))
|
||||
return compileFunction(value);
|
||||
return compileFunction(value, interpolated);
|
||||
return constant(value);
|
||||
}
|
||||
|
||||
@@ -398,12 +408,12 @@ export function compileExpression(expr) {
|
||||
case 'get': {
|
||||
if (raw.length !== 1) return unsupported('get from an object');
|
||||
const [key] = args();
|
||||
return (f) => f.properties[key(f)] ?? null;
|
||||
return (f) => propertyOf(f.properties, key(f)) ?? null;
|
||||
}
|
||||
case 'has': {
|
||||
if (raw.length !== 1) return unsupported('has in an object');
|
||||
const [key] = args();
|
||||
return (f) => key(f) in f.properties;
|
||||
return (f) => propertyOf(f.properties, key(f)) !== undefined;
|
||||
}
|
||||
case '!': {
|
||||
const [a] = args();
|
||||
@@ -483,6 +493,8 @@ export function compileExpression(expr) {
|
||||
steps.push([raw[i], compileExpression(raw[i + 1])]);
|
||||
return (f) => {
|
||||
const x = input(f);
|
||||
// A step over what is not a number fails, as interpolate does.
|
||||
if (typeof x !== 'number') return unsupported('step a non-number');
|
||||
let out = first;
|
||||
for (const [at, value] of steps) if (x >= at) out = value;
|
||||
return out(f);
|
||||
@@ -614,5 +626,7 @@ function textOf(v) {
|
||||
* feature.
|
||||
*/
|
||||
export function fillTokens(text, properties) {
|
||||
return text.replace(/{([^{}]+)}/g, (_, key) => textOf(properties[key]));
|
||||
return text.replace(/{([^{}]+)}/g, (_, key) =>
|
||||
textOf(propertyOf(properties, key)),
|
||||
);
|
||||
}
|
||||
+110
-52
@@ -12,7 +12,8 @@
|
||||
* zoomed); below its `minzoom` it draws nothing. A feature whose filter or
|
||||
* values cannot be evaluated is left out.
|
||||
*
|
||||
* Labels are placed top layer first, each kept clear of those placed
|
||||
* Labels are placed top layer first (a layer's own in their features' order
|
||||
* in the tile), each kept clear of those placed
|
||||
* before it and wholly inside its tile (a label across a tile edge is left
|
||||
* out, never cut); a point labels at itself, a line at the point halfway
|
||||
* along it, a polygon at its outer ring's bounding-box centre. Text wraps at
|
||||
@@ -21,7 +22,7 @@
|
||||
*/
|
||||
import { PbfReader } from 'pbf';
|
||||
import { VectorTile } from '@mapbox/vector-tile';
|
||||
import { fillTokens } from './expressions.js';
|
||||
import { cssOf, fillTokens, Unsupported } from './expressions.js';
|
||||
|
||||
/** The tile size style zooms are given for, pixels. */
|
||||
export const STYLE_TILE_SIZE = 512;
|
||||
@@ -95,6 +96,34 @@ function sourceTile(style, url, fetchImpl) {
|
||||
/** A value of a layer for a feature; throws where it cannot be evaluated. */
|
||||
const valueOf = (layer, key, f) => layer.values[key]?.(f);
|
||||
|
||||
/**
|
||||
* A number value; throws (the feature is left out) for null, undefined or
|
||||
* what is not a finite number, which a canvas would ignore, keeping the
|
||||
* last feature's.
|
||||
*/
|
||||
function numberOf(layer, key, f) {
|
||||
const v = valueOf(layer, key, f);
|
||||
const n = v === null || v === undefined || v === '' ? NaN : Number(v);
|
||||
if (!Number.isFinite(n)) throw new Unsupported(`${key} is ${v}`);
|
||||
return n;
|
||||
}
|
||||
|
||||
/** A colour value as CSS; throws, as {@link numberOf}, for no colour. */
|
||||
function colorOf(layer, key, f) {
|
||||
const v = valueOf(layer, key, f);
|
||||
if (typeof v === 'string' && v.trim()) return v;
|
||||
if (Array.isArray(v) && v.length === 4 && v.every(Number.isFinite))
|
||||
return cssOf(v);
|
||||
throw new Unsupported(`${key} is ${v}`);
|
||||
}
|
||||
|
||||
/** A keyword value (`line-cap`, `line-join`); throws for no string. */
|
||||
function keywordOf(layer, key, f) {
|
||||
const v = valueOf(layer, key, f);
|
||||
if (typeof v !== 'string' || !v) throw new Unsupported(`${key} is ${v}`);
|
||||
return v;
|
||||
}
|
||||
|
||||
/** Paths a feature's rings or lines in tile pixels. */
|
||||
function tracePath(ctx, rings, at) {
|
||||
ctx.beginPath();
|
||||
@@ -212,12 +241,14 @@ export async function paintVectorTile(
|
||||
ctx.clearRect(0, 0, size, size);
|
||||
const labels = [];
|
||||
|
||||
for (const layer of shown) {
|
||||
for (const [order, layer] of shown.entries()) {
|
||||
if (layer.type === 'background') {
|
||||
const f = { zoom, properties: {}, type: 'Polygon' };
|
||||
try {
|
||||
ctx.globalAlpha = Number(valueOf(layer, 'background-opacity', f));
|
||||
ctx.fillStyle = String(valueOf(layer, 'background-color', f));
|
||||
const opacity = numberOf(layer, 'background-opacity', f);
|
||||
const color = colorOf(layer, 'background-color', f);
|
||||
ctx.globalAlpha = opacity;
|
||||
ctx.fillStyle = color;
|
||||
ctx.fillRect(0, 0, size, size);
|
||||
} catch {
|
||||
// Not evaluated: no background from this layer.
|
||||
@@ -240,7 +271,7 @@ export async function paintVectorTile(
|
||||
};
|
||||
try {
|
||||
if (!f.type || !layer.filter(f)) continue;
|
||||
drawFeature(ctx, layer, feature, f, at, labels);
|
||||
drawFeature(ctx, layer, feature, f, at, labels, order);
|
||||
} catch {
|
||||
// A filter or value not evaluated: the feature is left out.
|
||||
}
|
||||
@@ -252,19 +283,29 @@ export async function paintVectorTile(
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Draw a feature of a fill, line or circle layer; queue a symbol's label. */
|
||||
function drawFeature(ctx, layer, feature, f, at, labels) {
|
||||
/**
|
||||
* Draw a feature of a fill, line or circle layer; queue a symbol's label.
|
||||
* Every value is evaluated before anything is drawn, so a feature with one
|
||||
* that cannot be is left out whole.
|
||||
*/
|
||||
function drawFeature(ctx, layer, feature, f, at, labels, order) {
|
||||
const v = (key) => valueOf(layer, key, f);
|
||||
const num = (key) => numberOf(layer, key, f);
|
||||
const color = (key) => colorOf(layer, key, f);
|
||||
switch (layer.type) {
|
||||
case 'fill': {
|
||||
if (f.type !== 'Polygon') return;
|
||||
const rings = feature.loadGeometry();
|
||||
tracePath(ctx, rings, at);
|
||||
ctx.globalAlpha = Number(v('fill-opacity'));
|
||||
ctx.fillStyle = String(v('fill-color'));
|
||||
const opacity = num('fill-opacity');
|
||||
const fill = color('fill-color');
|
||||
const outline = layer.values['fill-outline-color']
|
||||
? color('fill-outline-color')
|
||||
: null;
|
||||
tracePath(ctx, feature.loadGeometry(), at);
|
||||
ctx.globalAlpha = opacity;
|
||||
ctx.fillStyle = fill;
|
||||
ctx.fill('evenodd');
|
||||
if (layer.values['fill-outline-color']) {
|
||||
ctx.strokeStyle = String(v('fill-outline-color'));
|
||||
if (outline) {
|
||||
ctx.strokeStyle = outline;
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
}
|
||||
@@ -272,39 +313,52 @@ function drawFeature(ctx, layer, feature, f, at, labels) {
|
||||
}
|
||||
case 'line': {
|
||||
if (f.type === 'Point') return;
|
||||
const width = Number(v('line-width'));
|
||||
const gap = Number(v('line-gap-width'));
|
||||
const width = num('line-width');
|
||||
const gap = num('line-gap-width');
|
||||
// A cased line (a gap between two lines) as one line its full width,
|
||||
// under what fills the gap.
|
||||
const drawn = gap > 0 ? gap + 2 * width : width;
|
||||
if (!(drawn > 0)) return;
|
||||
tracePath(ctx, feature.loadGeometry(), at);
|
||||
ctx.globalAlpha = Number(v('line-opacity'));
|
||||
ctx.strokeStyle = String(v('line-color'));
|
||||
ctx.lineWidth = drawn;
|
||||
ctx.lineCap = String(v('line-cap'));
|
||||
ctx.lineJoin = String(v('line-join'));
|
||||
const opacity = num('line-opacity');
|
||||
const stroke = color('line-color');
|
||||
const cap = keywordOf(layer, 'line-cap', f);
|
||||
const join = keywordOf(layer, 'line-join', f);
|
||||
const dashes = layer.values['line-dasharray'] && v('line-dasharray');
|
||||
if (Array.isArray(dashes) && gap <= 0)
|
||||
ctx.setLineDash(dashes.map((d) => Number(d) * width));
|
||||
const dash =
|
||||
Array.isArray(dashes) && gap <= 0
|
||||
? dashes.map((d) => Number(d) * width)
|
||||
: null;
|
||||
if (dash && !dash.every(Number.isFinite))
|
||||
throw new Unsupported(`line-dasharray is ${dashes}`);
|
||||
tracePath(ctx, feature.loadGeometry(), at);
|
||||
ctx.globalAlpha = opacity;
|
||||
ctx.strokeStyle = stroke;
|
||||
ctx.lineWidth = drawn;
|
||||
ctx.lineCap = cap;
|
||||
ctx.lineJoin = join;
|
||||
if (dash) ctx.setLineDash(dash);
|
||||
ctx.stroke();
|
||||
return;
|
||||
}
|
||||
case 'circle': {
|
||||
if (f.type !== 'Point') return;
|
||||
const radius = Number(v('circle-radius'));
|
||||
const stroke = Number(v('circle-stroke-width'));
|
||||
const radius = num('circle-radius');
|
||||
const stroke = num('circle-stroke-width');
|
||||
const opacity = num('circle-opacity');
|
||||
const fill = color('circle-color');
|
||||
const strokeOpacity = stroke > 0 ? num('circle-stroke-opacity') : 0;
|
||||
const strokeColor = stroke > 0 ? color('circle-stroke-color') : null;
|
||||
for (const part of feature.loadGeometry())
|
||||
for (const p of part) {
|
||||
const [px, py] = at(p);
|
||||
ctx.beginPath();
|
||||
ctx.arc(px, py, radius, 0, Math.PI * 2);
|
||||
ctx.globalAlpha = Number(v('circle-opacity'));
|
||||
ctx.fillStyle = String(v('circle-color'));
|
||||
ctx.globalAlpha = opacity;
|
||||
ctx.fillStyle = fill;
|
||||
ctx.fill();
|
||||
if (stroke > 0) {
|
||||
ctx.globalAlpha = Number(v('circle-stroke-opacity'));
|
||||
ctx.strokeStyle = String(v('circle-stroke-color'));
|
||||
ctx.globalAlpha = strokeOpacity;
|
||||
ctx.strokeStyle = strokeColor;
|
||||
ctx.lineWidth = stroke;
|
||||
ctx.stroke();
|
||||
}
|
||||
@@ -337,27 +391,30 @@ function drawFeature(ctx, layer, feature, f, at, labels) {
|
||||
(Math.min(...ys) + Math.max(...ys)) / 2,
|
||||
]);
|
||||
}
|
||||
const px = Number(v('text-size'));
|
||||
const px = num('text-size');
|
||||
const offset = layer.values['text-offset'] ? v('text-offset') : [0, 0];
|
||||
const dx = Number(offset?.[0] ?? 0) * px;
|
||||
const dy = Number(offset?.[1] ?? 0) * px;
|
||||
const maxWidth =
|
||||
(layer.values['text-max-width'] ? num('text-max-width') : 10) * px;
|
||||
if (!Number.isFinite(dx) || !Number.isFinite(dy))
|
||||
throw new Unsupported(`text-offset is ${offset}`);
|
||||
const label = {
|
||||
text,
|
||||
px,
|
||||
font: fontOf(v('text-font'), px),
|
||||
color: color('text-color'),
|
||||
opacity: num('text-opacity'),
|
||||
halo: color('text-halo-color'),
|
||||
haloWidth: num('text-halo-width'),
|
||||
anchor: String(
|
||||
(layer.values['text-anchor'] && v('text-anchor')) ?? 'center',
|
||||
),
|
||||
maxWidth,
|
||||
order,
|
||||
};
|
||||
for (const anchor of anchors)
|
||||
labels.push({
|
||||
text,
|
||||
x: anchor[0] + Number(offset?.[0] ?? 0) * px,
|
||||
y: anchor[1] + Number(offset?.[1] ?? 0) * px,
|
||||
px,
|
||||
font: fontOf(v('text-font'), px),
|
||||
color: String(v('text-color')),
|
||||
opacity: Number(v('text-opacity')),
|
||||
halo: String(v('text-halo-color')),
|
||||
haloWidth: Number(v('text-halo-width')),
|
||||
anchor: String(
|
||||
(layer.values['text-anchor'] && v('text-anchor')) ?? 'center',
|
||||
),
|
||||
maxWidth:
|
||||
Number(
|
||||
(layer.values['text-max-width'] && v('text-max-width')) ?? 10,
|
||||
) * px,
|
||||
});
|
||||
labels.push({ ...label, x: anchor[0] + dx, y: anchor[1] + dy });
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -366,11 +423,12 @@ function drawFeature(ctx, layer, feature, f, at, labels) {
|
||||
/** Place the labels top layer first, clear of each other, and draw them. */
|
||||
function placeLabels(ctx, labels, size) {
|
||||
const placed = [];
|
||||
// Later in the style is on top, and placed first.
|
||||
const order = labels.map((label, i) => [label, i]).reverse();
|
||||
// Later in the style is on top, and placed first; within a layer, its
|
||||
// features in their order in the tile, as MapLibre places them.
|
||||
const order = labels.slice().sort((a, b) => b.order - a.order);
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
for (const [label] of order) {
|
||||
for (const label of order) {
|
||||
ctx.font = label.font;
|
||||
const lines = wrap(ctx, label.text, label.maxWidth);
|
||||
if (!lines.length) continue;
|
||||
|
||||
@@ -40,6 +40,46 @@ const ARRAY_VALUES = new Set([
|
||||
'circle-translate',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Properties that interpolate (numbers, colours, number arrays the
|
||||
* specification marks interpolated): a legacy function without a `type` is
|
||||
* `exponential` on these and `interval` on every other (`line-cap`,
|
||||
* `line-join`, `line-dasharray`, `text-field`, `text-font`,
|
||||
* `text-transform`, `text-anchor`, ...).
|
||||
*/
|
||||
const INTERPOLATED = new Set([
|
||||
'background-color',
|
||||
'background-opacity',
|
||||
'fill-color',
|
||||
'fill-opacity',
|
||||
'fill-outline-color',
|
||||
'line-color',
|
||||
'line-opacity',
|
||||
'line-width',
|
||||
'line-gap-width',
|
||||
'line-blur',
|
||||
'circle-radius',
|
||||
'circle-color',
|
||||
'circle-opacity',
|
||||
'circle-blur',
|
||||
'circle-stroke-width',
|
||||
'circle-stroke-color',
|
||||
'circle-stroke-opacity',
|
||||
'text-size',
|
||||
'text-color',
|
||||
'text-opacity',
|
||||
'text-halo-color',
|
||||
'text-halo-width',
|
||||
'text-halo-blur',
|
||||
'text-offset',
|
||||
'text-max-width',
|
||||
'text-letter-spacing',
|
||||
'text-line-height',
|
||||
'text-rotate',
|
||||
'text-padding',
|
||||
'text-radial-offset',
|
||||
]);
|
||||
|
||||
/** Defaults the painter reads for each layer type, as the specification's. */
|
||||
const DEFAULTS = {
|
||||
background: { 'background-color': '#000000', 'background-opacity': 1 },
|
||||
@@ -117,7 +157,10 @@ function compileLayer(layer, sources) {
|
||||
...paint,
|
||||
}))
|
||||
if (key !== 'visibility')
|
||||
values[key] = compileValue(value, { array: ARRAY_VALUES.has(key) });
|
||||
values[key] = compileValue(value, {
|
||||
array: ARRAY_VALUES.has(key),
|
||||
interpolated: INTERPOLATED.has(key),
|
||||
});
|
||||
return {
|
||||
layer: {
|
||||
id: layer.id,
|
||||
@@ -199,10 +242,12 @@ export async function loadVectorStyle(
|
||||
if (layer.type === 'background' && !background)
|
||||
try {
|
||||
const at = { zoom: 0, properties: {}, type: 'Polygon' };
|
||||
background = {
|
||||
color: String(layer.values['background-color'](at)),
|
||||
opacity: Number(layer.values['background-opacity'](at)),
|
||||
};
|
||||
const color = layer.values['background-color'](at);
|
||||
const opacity = layer.values['background-opacity'](at);
|
||||
background =
|
||||
typeof color === 'string' && Number.isFinite(opacity)
|
||||
? { color, opacity }
|
||||
: null;
|
||||
} catch {
|
||||
background = null;
|
||||
}
|
||||
|
||||
@@ -330,3 +330,203 @@ test('a feature whose value cannot be evaluated is left out, the rest drawn', as
|
||||
[0.3],
|
||||
);
|
||||
});
|
||||
|
||||
test('a legacy function without a type steps on a property that cannot interpolate', () => {
|
||||
const zoomStops = {
|
||||
stops: [
|
||||
[10, 'butt'],
|
||||
[14, 'round'],
|
||||
],
|
||||
};
|
||||
const join = compileValue(zoomStops, { interpolated: false });
|
||||
assert.deepEqual(
|
||||
[9, 12, 14].map((zoom) => join(feature({}, { zoom }))),
|
||||
['butt', 'butt', 'round'],
|
||||
);
|
||||
// A number property interpolates, exponentially by default.
|
||||
const width = compileValue(
|
||||
{
|
||||
stops: [
|
||||
[10, 1],
|
||||
[12, 5],
|
||||
],
|
||||
},
|
||||
{ interpolated: true },
|
||||
);
|
||||
assert.equal(width(feature({}, { zoom: 11 })), 3);
|
||||
// A property function with string outputs is not categorical by default:
|
||||
// interval over a number input, the default over any other.
|
||||
const byRank = compileValue(
|
||||
{
|
||||
property: 'rank',
|
||||
default: 'Sans',
|
||||
stops: [
|
||||
[1, 'Bold'],
|
||||
[5, 'Regular'],
|
||||
],
|
||||
},
|
||||
{ interpolated: false },
|
||||
);
|
||||
assert.deepEqual(
|
||||
[1, 3, 7, 'x'].map((rank) => byRank(feature({ rank }))),
|
||||
['Bold', 'Bold', 'Regular', 'Sans'],
|
||||
);
|
||||
});
|
||||
|
||||
test('a style’s legacy string stops are stepped where the property does not interpolate', async () => {
|
||||
const { fetch } = fetchOver({
|
||||
'https://example.test/s.json': {
|
||||
version: 8,
|
||||
sources: { base: { type: 'vector', tiles: ['/{z}/{x}/{y}'] } },
|
||||
layers: [
|
||||
{
|
||||
id: 'roads',
|
||||
type: 'line',
|
||||
source: 'base',
|
||||
'source-layer': 'roads',
|
||||
layout: {
|
||||
'line-join': {
|
||||
stops: [
|
||||
[0, 'bevel'],
|
||||
[20, 'round'],
|
||||
],
|
||||
},
|
||||
'text-transform': {
|
||||
stops: [
|
||||
[0, 'none'],
|
||||
[20, 'uppercase'],
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const style = await loadVectorStyle('https://example.test/s.json', fetch);
|
||||
assert.deepEqual(style.skipped, []);
|
||||
const [roads] = style.layers;
|
||||
const at = feature({}, { zoom: 10, type: 'LineString' });
|
||||
assert.equal(roads.values['line-join'](at), 'bevel');
|
||||
assert.equal(roads.values['text-transform'](at), 'none');
|
||||
});
|
||||
|
||||
test('step and has follow the specification on missing and inherited names', () => {
|
||||
const step = compileExpression(['step', ['get', 'rank'], 'low', 0, 'high']);
|
||||
assert.equal(step(feature({ rank: 2 })), 'high');
|
||||
assert.throws(() => step(feature({})), Unsupported, 'a missing input fails');
|
||||
for (const name of ['toString', 'constructor', '__proto__']) {
|
||||
assert.equal(compileExpression(['has', name])(feature({})), false, name);
|
||||
assert.equal(compileExpression(['get', name])(feature({})), null, name);
|
||||
assert.equal(compileFilter(['has', name])(feature({})), false, name);
|
||||
assert.equal(compileFilter(['==', name, 'x'])(feature({})), false, name);
|
||||
}
|
||||
});
|
||||
|
||||
/** A one-layer style over one tile, painted on a recording canvas. */
|
||||
async function paintOne(layer, features) {
|
||||
const tile = encodeVectorTile(features);
|
||||
const { fetch } = fetchOver({
|
||||
'https://example.test/s.json': {
|
||||
version: 8,
|
||||
sources: { base: { type: 'vector', tiles: ['/{z}/{x}/{y}'] } },
|
||||
layers: [{ source: 'base', ...layer }],
|
||||
},
|
||||
'https://example.test/0/0/0': tile,
|
||||
});
|
||||
const style = await loadVectorStyle('https://example.test/s.json', fetch);
|
||||
const { canvas, calls } = recordingCanvas();
|
||||
await paintVectorTile(style, 0, 0, 0, { fetch, canvas });
|
||||
return calls;
|
||||
}
|
||||
|
||||
test('a feature whose colour or width evaluates to nothing is left out, not drawn in the last one’s', async () => {
|
||||
const fills = await paintOne(
|
||||
{
|
||||
id: 'water',
|
||||
type: 'fill',
|
||||
'source-layer': 'water',
|
||||
paint: { 'fill-color': ['get', 'colour'] },
|
||||
},
|
||||
{
|
||||
water: [
|
||||
{ type: 'Polygon', geometry: FULL, properties: { colour: '#00f' } },
|
||||
{ type: 'Polygon', geometry: FULL, properties: {} },
|
||||
],
|
||||
},
|
||||
);
|
||||
assert.equal(fills.filter(([k]) => k === 'fill').length, 1);
|
||||
assert.deepEqual(
|
||||
fills.filter(([k]) => k === '=fillStyle').map(([, v]) => v),
|
||||
['#00f'],
|
||||
);
|
||||
const line = [
|
||||
[
|
||||
[0, 2048],
|
||||
[4096, 2048],
|
||||
],
|
||||
];
|
||||
const lines = await paintOne(
|
||||
{
|
||||
id: 'roads',
|
||||
type: 'line',
|
||||
'source-layer': 'roads',
|
||||
paint: { 'line-width': ['get', 'w'], 'line-color': ['get', 'c'] },
|
||||
},
|
||||
{
|
||||
roads: [
|
||||
{ type: 'LineString', geometry: line, properties: { w: 3, c: '#f00' } },
|
||||
{ type: 'LineString', geometry: line, properties: { w: 2 } },
|
||||
{ type: 'LineString', geometry: line, properties: { c: '#0f0' } },
|
||||
],
|
||||
},
|
||||
);
|
||||
assert.equal(lines.filter(([k]) => k === 'stroke').length, 1);
|
||||
assert.deepEqual(
|
||||
lines.filter(([k]) => k === '=strokeStyle').map(([, v]) => v),
|
||||
['#f00'],
|
||||
);
|
||||
const circles = await paintOne(
|
||||
{
|
||||
id: 'dots',
|
||||
type: 'circle',
|
||||
'source-layer': 'dots',
|
||||
paint: { 'circle-radius': ['get', 'r'], 'circle-color': '#fff' },
|
||||
},
|
||||
{
|
||||
dots: [
|
||||
{ type: 'Point', geometry: [[[100, 100]]], properties: { r: 4 } },
|
||||
{ type: 'Point', geometry: [[[200, 200]]], properties: {} },
|
||||
],
|
||||
},
|
||||
);
|
||||
assert.equal(circles.filter(([k]) => k === 'arc').length, 1);
|
||||
});
|
||||
|
||||
test('labels of one layer are placed in their features’ order, the first winning', async () => {
|
||||
const calls = await paintOne(
|
||||
{
|
||||
id: 'places',
|
||||
type: 'symbol',
|
||||
'source-layer': 'places',
|
||||
layout: { 'text-field': '{name}', 'text-size': 12 },
|
||||
},
|
||||
{
|
||||
places: [
|
||||
{
|
||||
type: 'Point',
|
||||
geometry: [[[2048, 2048]]],
|
||||
properties: { name: 'First' },
|
||||
},
|
||||
{
|
||||
type: 'Point',
|
||||
geometry: [[[2048, 2048]]],
|
||||
properties: { name: 'Second' },
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
calls.filter(([k]) => k === 'fillText').map(([, text]) => text),
|
||||
['First'],
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user