-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
index.js
366 lines (306 loc) · 12.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
// @flow
import assert from 'assert';
import extend from '../util/extend';
import ParsingError from './parsing_error';
import ParsingContext from './parsing_context';
import EvaluationContext from './evaluation_context';
import CompoundExpression from './compound_expression';
import Step from './definitions/step';
import Interpolate from './definitions/interpolate';
import Coalesce from './definitions/coalesce';
import Let from './definitions/let';
import definitions from './definitions';
import * as isConstant from './is_constant';
import RuntimeError from './runtime_error';
import { success, error } from '../util/result';
import type {Type} from './types';
import type {Value} from './values';
import type {Expression} from './expression';
import type {StylePropertySpecification} from '../style-spec';
import type {Result} from '../util/result';
import type {InterpolationType} from './definitions/interpolate';
export type Feature = {
+type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon',
+id?: any,
+properties: {[string]: any}
};
export type GlobalProperties = {
zoom: number,
heatmapDensity?: number
};
export class StyleExpression {
expression: Expression;
_evaluator: EvaluationContext;
_defaultValue: Value;
_warningHistory: {[key: string]: boolean};
_enumValues: {[string]: any};
constructor(expression: Expression, propertySpec: StylePropertySpecification) {
this.expression = expression;
this._warningHistory = {};
this._defaultValue = getDefaultValue(propertySpec);
if (propertySpec.type === 'enum') {
this._enumValues = propertySpec.values;
}
}
evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature): any {
if (!this._evaluator) {
this._evaluator = new EvaluationContext();
}
this._evaluator.globals = globals;
this._evaluator.feature = feature;
return this.expression.evaluate(this._evaluator);
}
evaluate(globals: GlobalProperties, feature?: Feature): any {
if (!this._evaluator) {
this._evaluator = new EvaluationContext();
}
this._evaluator.globals = globals;
this._evaluator.feature = feature;
try {
const val = this.expression.evaluate(this._evaluator);
if (val === null || val === undefined) {
return this._defaultValue;
}
if (this._enumValues && !(val in this._enumValues)) {
throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ')}, but found ${JSON.stringify(val)} instead.`);
}
return val;
} catch (e) {
if (!this._warningHistory[e.message]) {
this._warningHistory[e.message] = true;
if (typeof console !== 'undefined') {
console.warn(e.message);
}
}
return this._defaultValue;
}
}
}
export function isExpression(expression: mixed) {
return Array.isArray(expression) && expression.length > 0 &&
typeof expression[0] === 'string' && expression[0] in definitions;
}
/**
* Parse and typecheck the given style spec JSON expression. If
* options.defaultValue is provided, then the resulting StyleExpression's
* `evaluate()` method will handle errors by logging a warning (once per
* message) and returning the default value. Otherwise, it will throw
* evaluation errors.
*
* @private
*/
export function createExpression(expression: mixed, propertySpec: StylePropertySpecification): Result<StyleExpression, Array<ParsingError>> {
const parser = new ParsingContext(definitions, [], getExpectedType(propertySpec));
const parsed = parser.parse(expression);
if (!parsed) {
assert(parser.errors.length > 0);
return error(parser.errors);
}
return success(new StyleExpression(parsed, propertySpec));
}
export class ZoomConstantExpression<Kind> {
kind: Kind;
_styleExpression: StyleExpression;
constructor(kind: Kind, expression: StyleExpression) {
this.kind = kind;
this._styleExpression = expression;
}
evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature): any {
return this._styleExpression.evaluateWithoutErrorHandling(globals, feature);
}
evaluate(globals: GlobalProperties, feature?: Feature): any {
return this._styleExpression.evaluate(globals, feature);
}
}
export class ZoomDependentExpression<Kind> {
kind: Kind;
zoomStops: Array<number>;
_styleExpression: StyleExpression;
_interpolationType: ?InterpolationType;
constructor(kind: Kind, expression: StyleExpression, zoomCurve: Step | Interpolate) {
this.kind = kind;
this.zoomStops = zoomCurve.labels;
this._styleExpression = expression;
if (zoomCurve instanceof Interpolate) {
this._interpolationType = zoomCurve.interpolation;
}
}
evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature): any {
return this._styleExpression.evaluateWithoutErrorHandling(globals, feature);
}
evaluate(globals: GlobalProperties, feature?: Feature): any {
return this._styleExpression.evaluate(globals, feature);
}
interpolationFactor(input: number, lower: number, upper: number): number {
if (this._interpolationType) {
return Interpolate.interpolationFactor(this._interpolationType, input, lower, upper);
} else {
return 0;
}
}
}
export type ConstantExpression = {
kind: 'constant',
+evaluate: (globals: GlobalProperties, feature?: Feature) => any,
}
export type SourceExpression = {
kind: 'source',
+evaluate: (globals: GlobalProperties, feature?: Feature) => any,
};
export type CameraExpression = {
kind: 'camera',
+evaluate: (globals: GlobalProperties, feature?: Feature) => any,
+interpolationFactor: (input: number, lower: number, upper: number) => number,
zoomStops: Array<number>
};
export type CompositeExpression = {
kind: 'composite',
+evaluate: (globals: GlobalProperties, feature?: Feature) => any,
+interpolationFactor: (input: number, lower: number, upper: number) => number,
zoomStops: Array<number>
};
export type StylePropertyExpression =
| ConstantExpression
| SourceExpression
| CameraExpression
| CompositeExpression;
export function createPropertyExpression(expression: mixed, propertySpec: StylePropertySpecification): Result<StylePropertyExpression, Array<ParsingError>> {
expression = createExpression(expression, propertySpec);
if (expression.result === 'error') {
return expression;
}
const parsed = expression.value.expression;
const isFeatureConstant = isConstant.isFeatureConstant(parsed);
if (!isFeatureConstant && !propertySpec['property-function']) {
return error([new ParsingError('', 'property expressions not supported')]);
}
const isZoomConstant = isConstant.isGlobalPropertyConstant(parsed, ['zoom']);
if (!isZoomConstant && propertySpec['zoom-function'] === false) {
return error([new ParsingError('', 'zoom expressions not supported')]);
}
const zoomCurve = findZoomCurve(parsed);
if (!zoomCurve && !isZoomConstant) {
return error([new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.')]);
} else if (zoomCurve instanceof ParsingError) {
return error([zoomCurve]);
} else if (zoomCurve instanceof Interpolate && propertySpec['function'] === 'piecewise-constant') {
return error([new ParsingError('', '"interpolate" expressions cannot be used with this property')]);
}
if (!zoomCurve) {
return success(isFeatureConstant ?
(new ZoomConstantExpression('constant', expression.value): ConstantExpression) :
(new ZoomConstantExpression('source', expression.value): SourceExpression));
}
return success(isFeatureConstant ?
(new ZoomDependentExpression('camera', expression.value, zoomCurve): CameraExpression) :
(new ZoomDependentExpression('composite', expression.value, zoomCurve): CompositeExpression));
}
import { isFunction, createFunction } from '../function';
import { Color } from './values';
// serialization wrapper for old-style stop functions normalized to the
// expression interface
export class StylePropertyFunction<T> {
_parameters: PropertyValueSpecification<T>;
_specification: StylePropertySpecification;
kind: 'constant' | 'source' | 'camera' | 'composite';
evaluate: (globals: GlobalProperties, feature?: Feature) => any;
interpolationFactor: ?(input: number, lower: number, upper: number) => number;
zoomStops: ?Array<number>;
constructor(parameters: PropertyValueSpecification<T>, specification: StylePropertySpecification) {
this._parameters = parameters;
this._specification = specification;
extend(this, createFunction(this._parameters, this._specification));
}
static deserialize(serialized: {_parameters: PropertyValueSpecification<T>, _specification: StylePropertySpecification}) {
return ((new StylePropertyFunction(serialized._parameters, serialized._specification)): StylePropertyFunction<T>);
}
static serialize(input: StylePropertyFunction<T>) {
return {
_parameters: input._parameters,
_specification: input._specification
};
}
}
export function normalizePropertyExpression<T>(value: PropertyValueSpecification<T>, specification: StylePropertySpecification): StylePropertyExpression {
if (isFunction(value)) {
return (new StylePropertyFunction(value, specification): any);
} else if (isExpression(value)) {
const expression = createPropertyExpression(value, specification);
if (expression.result === 'error') {
// this should have been caught in validation
throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', '));
}
return expression.value;
} else {
let constant: any = value;
if (typeof value === 'string' && specification.type === 'color') {
constant = Color.parse(value);
}
return {
kind: 'constant',
evaluate: () => constant
};
}
}
// Zoom-dependent expressions may only use ["zoom"] as the input to a top-level "step" or "interpolate"
// expression (collectively referred to as a "curve"). The curve may be wrapped in one or more "let" or
// "coalesce" expressions.
function findZoomCurve(expression: Expression): Step | Interpolate | ParsingError | null {
let result = null;
if (expression instanceof Let) {
result = findZoomCurve(expression.result);
} else if (expression instanceof Coalesce) {
for (const arg of expression.args) {
result = findZoomCurve(arg);
if (result) {
break;
}
}
} else if ((expression instanceof Step || expression instanceof Interpolate) &&
expression.input instanceof CompoundExpression &&
expression.input.name === 'zoom') {
result = expression;
}
if (result instanceof ParsingError) {
return result;
}
expression.eachChild((child) => {
const childResult = findZoomCurve(child);
if (childResult instanceof ParsingError) {
result = childResult;
} else if (!result && childResult) {
result = new ParsingError('', '"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression.');
} else if (result && childResult && result !== childResult) {
result = new ParsingError('', 'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.');
}
});
return result;
}
import { ColorType, StringType, NumberType, BooleanType, ValueType, array } from './types';
function getExpectedType(spec: StylePropertySpecification): Type | null {
const types = {
color: ColorType,
string: StringType,
number: NumberType,
enum: StringType,
boolean: BooleanType
};
if (spec.type === 'array') {
return array(types[spec.value] || ValueType, spec.length);
}
return types[spec.type] || null;
}
function getDefaultValue(spec: StylePropertySpecification): Value {
if (spec.type === 'color' && isFunction(spec.default)) {
// Special case for heatmap-color: it uses the 'default:' to define a
// default color ramp, but createExpression expects a simple value to fall
// back to in case of runtime errors
return new Color(0, 0, 0, 0);
} else if (spec.type === 'color') {
return Color.parse(spec.default) || null;
} else if (spec.default === undefined) {
return null;
} else {
return spec.default;
}
}