-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
395 lines (369 loc) · 12.3 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/// A prefix that uniquely identifies this plugin, prepended onto the name of any variable generated by this plugin.
const variablePrefix = 'maplibre_gl_dates';
/**
* Filters the map’s features by a date.
*
* @param map The MapboxGL map object to filter the style of.
* @param date The date object or date string to filter by.
*/
function filterByDate(map, date) {
let dateRange = dateRangeFromDate(date);
map.getStyle().layers.map(function (layer) {
if (!('source-layer' in layer)) return;
let filter = constrainFilterByDateRange(map.getFilter(layer.id), dateRange);
map.setFilter(layer.id, filter);
});
}
/**
* Converts the given date to a date range object.
*
* @param date A date object or date string in ISO 8601-1 format.
* @returns A date range object.
*/
function dateRangeFromDate(date) {
let dateRange;
if (typeof date === 'string') {
dateRange = dateRangeFromISODate(date);
} else if (date instanceof Date && !isNaN(date)) {
let decimalYear = decimalYearFromDate(date);
let isoDate = date.toISOString().split('T')[0];
dateRange = {
startDate: date,
startDecimalYear: decimalYear,
startISODate: isoDate,
endDate: date,
endDecimalYear: decimalYear,
endISODate: isoDate,
};
}
return dateRange;
}
/**
* Converts the given ISO 8601-1 date to a date range object.
*
* @param isoDate A date string in ISO 8601-1 format.
* @returns A date range object indicating the minimum (inclusive) and maximum
* (exclusive) possible dates represented by the given date string.
*/
function dateRangeFromISODate(isoDate) {
// Require a valid YYYY, YYYY-MM, or YYYY-MM-DD date, but allow the year
// to be a variable number of digits or negative, unlike ISO 8601-1.
if (!isoDate || !/^-?\d{1,4}(?:-\d\d){0,2}$/.test(isoDate)) return;
let ymd = isoDate.split('-');
// A negative year results in an extra element at the beginning.
let isBCE = ymd[0] === '';
if (isBCE) {
ymd.shift();
ymd[0] *= -1;
}
let startYear = +ymd[0];
let endYear = +ymd[0];
let startMonth, endMonth;
if (ymd[1]) {
// Date.UTC() uses zero-based months.
startMonth = endMonth = +ymd[1] - 1;
} else {
endYear++;
startMonth = endMonth = 0;
}
let startDay, endDay;
if (ymd[2]) {
startDay = endDay = +ymd[2];
} else if (ymd[1]) {
// Months still count forwards in BCE.
endMonth++;
startDay = endDay = 1;
}
let startDate = dateFromUTC(startYear, startMonth, startDay);
let endDate = dateFromUTC(endYear, endMonth, endDay);
return {
startDate: !isNaN(startDate) && startDate,
startDecimalYear: !isNaN(startDate) && decimalYearFromDate(startDate),
startISODate: !isNaN(startDate) && startDate.toISOString().split('T')[0],
endDate: !isNaN(endDate) && endDate,
endDecimalYear: !isNaN(endDate) && decimalYearFromDate(endDate),
endISODate: !isNaN(endDate) && endDate.toISOString().split('T')[0],
};
}
/**
* Returns a `Date` object representing the given UTC date components.
*
* @param year A one-based year in the proleptic Gregorian calendar.
* @param month A zero-based month.
* @param day A one-based day.
* @returns A date object.
*/
function dateFromUTC(year, month, day) {
let date = new Date(Date.UTC(year, month, day));
// Date.UTC() treats a two-digit year as an offset from 1900.
date.setUTCFullYear(year);
return date;
}
/**
* Converts the given date to a decimal year.
*
* @param date A date object.
* @returns A floating point number of years since year 0.
*/
function decimalYearFromDate(date) {
// Add the year and the fraction of the date between two New Year’s Days.
let year = date.getUTCFullYear();
let nextNewYear = dateFromUTC(year + 1, 0, 1).getTime();
let lastNewYear = dateFromUTC(year, 0, 1).getTime();
if (year < 0) {
// New Year’s 1 BCE is closer to -2 than -1.
year--;
}
return year + (date.getTime() - lastNewYear) / (nextNewYear - lastNewYear);
}
/**
* Returns a modified version of the given filter that only evaluates to
* true if the feature overlaps with the given date range.
*
* @param filter The original layer filter.
* @param dateRange The date range to filter by.
* @returns A filter similar to the given filter, but with added conditions
* that require the feature to overlap with the date range.
*/
function constrainFilterByDateRange(filter, dateRange) {
if (typeof filter !== 'undefined' && isLegacyFilter(filter)) {
return constrainLegacyFilterByDateRange(filter, dateRange);
} else {
return constrainExpressionFilterByDateRange(filter, dateRange);
}
}
/**
* Returns a modified version of the given legacy filter that only evaluates to
* true if the feature overlaps with the given date range.
*
* @param filter The original layer filter using the legacy syntax.
* @param dateRange The date range to filter by.
* @returns A filter similar to the given filter, but with added conditions
* that require the feature to overlap with the date range. If the filter has
* previously been passed into this function, it surgically updates the filter.
*/
function constrainLegacyFilterByDateRange(filter, dateRange) {
if (filter[0] === 'all' &&
filter[2] && filter[1][0] === 'any' && filter[2][0] === 'any') {
if (filter[1][1] && filter[1][1][0] === 'all' &&
filter[1][1][2] && filter[1][1][2][0] === '<' &&
filter[1][1][2][1] === 'start_decdate') {
filter[1][1][2][2] = dateRange.endDecimalYear;
}
if (filter[1][2] && filter[1][2][0] === 'all' &&
filter[1][2][2] && filter[1][2][2][0] === '<' &&
filter[1][2][2][2] === 'start_date') {
filter[1][2][2][3] = dateRange.endISODate;
}
if (filter[2][1] && filter[2][1][0] === 'all' &&
filter[2][1][2] && filter[2][1][2][0] === '>=' &&
filter[2][1][2][1] === 'end_decdate') {
filter[2][1][2][2] = dateRange.startDecimalYear;
}
if (filter[2][2] && filter[2][2][0] === 'all' &&
filter[2][2][2] && filter[2][2][2][0] === '>=' &&
filter[2][2][2][2] === 'end_date') {
filter[2][2][2][3] = dateRange.startISODate;
}
return filter;
}
return [
'all',
[
'any',
[
'all',
['has', 'start_decdate'],
['<', 'start_decdate', dateRange.endDecimalYear],
],
[
'all',
['!has', 'start_decdate'],
['has', 'start_date'],
['<', 'start_date', dateRange.endISODate],
],
[
'all',
['!has', 'start_decdate'],
['!has', 'start_date'],
],
],
[
'any',
[
'all',
['has', 'end_decdate'],
['>=', 'end_decdate', dateRange.startDecimalYear],
],
[
'all',
['!has', 'end_decdate'],
['has', 'end_date'],
['>=', 'end_date', dateRange.startISODate],
],
[
'all',
['!has', 'end_decdate'],
['!has', 'end_date'],
],
],
filter,
];
}
/**
* Returns a modified version of the given expression-based filter that only
* evaluates to true if the feature overlaps with the given date range.
*
* @param filter The original layer filter using the expression syntax.
* @param dateRange The date range to filter by.
* @returns A filter similar to the given filter, but with added conditions
* that require the feature to overlap with the date range. If the filter has
* previously been passed into this function, or if it already has a `let`
* expression at the top level, it merely updates a variable.
*/
function constrainExpressionFilterByDateRange(filter, dateRange) {
const startDecimalYearVariable = `${variablePrefix}__startDecimalYear`;
const startISODateVariable = `${variablePrefix}__startISODate`;
const endDecimalYearVariable = `${variablePrefix}__endDecimalYear`;
const endISODateVariable = `${variablePrefix}__endISODate`;
if (Array.isArray(filter) && filter[0] === 'let') {
updateVariable(filter, startDecimalYearVariable, dateRange.startDecimalYear);
updateVariable(filter, startISODateVariable, dateRange.startISODate);
updateVariable(filter, endDecimalYearVariable, dateRange.endDecimalYear);
updateVariable(filter, endISODateVariable, dateRange.endISODate);
return filter;
}
let allExpression = [
'all',
[
'any',
[
'all',
['has', 'start_decdate'],
['<', ['get', 'start_decdate'], ['var', endDecimalYearVariable]],
],
[
'all',
['!', ['has', 'start_decdate']],
['has', 'start_date'],
['<', ['get', 'start_date'], ['var', endISODateVariable]],
],
[
'all',
['!', ['has', 'start_decdate']],
['!', ['has', 'start_date']]
],
],
[
'any',
[
'all',
['has', 'end_decdate'],
['>=', ['get', 'end_decdate'], ['var', startDecimalYearVariable]],
],
[
'all',
['!', ['has', 'end_decdate']],
['has', 'end_date'],
['>=', ['get', 'end_date'], ['var', startISODateVariable]],
],
[
'all',
['!', ['has', 'end_decdate']],
['!', ['has', 'end_date']]
],
],
];
if (filter) {
allExpression.push(filter);
}
return [
'let',
startDecimalYearVariable, dateRange.startDecimalYear,
startISODateVariable, dateRange.startISODate,
endDecimalYearVariable, dateRange.endDecimalYear,
endISODateVariable, dateRange.endISODate,
allExpression,
];
}
/**
* Returns a Boolean indicating whether the given filter is definitely based on [the deprecated legacy filter syntax](https://maplibre.org/maplibre-style-spec/deprecations/#other-filter) and thus incompatible with an expression.
*
* @param filter A filter that is either based on the legacy syntax or an expression.
* @returns True if the filter is definitely based on the legacy syntax; false if it might be an expression.
*/
function isLegacyFilter(filter) {
if (!Array.isArray(filter) || filter.length < 2) {
return false;
}
let args = filter.slice(1);
switch (filter[0]) {
case '!has':
case '!in':
case 'none':
// These are filters but not expression operators.
return true;
case 'has':
// These are unlikely feature properties but are built-in legacy keys.
return args[0] === '$id' || args[0] === '$type';
case 'in':
return (// The legacy syntax includes all the possible matches inline.
args.length > 2 ||
// These are unlikely feature properties but are built-in legacy keys.
args[0] === '$id' || args[0] === '$type' ||
// The `in` expression only allows searching within a string or array.
typeof args[1] === 'number' || typeof args[1] === 'boolean' ||
// It would be pointless to search for a string literal inside another string literal.
(typeof args[0] === 'string' && typeof args[1] === 'string'));
case '==':
case '!=':
case '>':
case '>=':
case '<':
case '<=':
// An expression would require the string literal to be compared to another string literal, but it would be pointless to do so.
return typeof args[0] === 'string' && !Array.isArray(args[1]);
case 'all':
case 'any':
// If any of the arguments is definitely a legacy filter, the whole thing is too.
return args.some(isLegacyFilter);
default:
return false;
}
}
/**
* Mutates a `let` expression to have a new value for the variable by the given
* name.
*
* @param letExpression A `let` expression.
* @param name The name of the variable to mutate.
* @param newValue The variable’s new value.
*/
function updateVariable(letExpression, name, newValue) {
if (letExpression[0] !== 'let') {
return;
}
let variableIndex = letExpression.indexOf(name);
if (variableIndex !== -1 && variableIndex % 2 === 1) {
letExpression[variableIndex + 1] = newValue;
} else {
letExpression.splice(-1, 0, name, newValue);
}
}
if (typeof window !== 'undefined' && 'maplibregl' in window) {
maplibregl.Map.prototype.filterByDate = function (date) {
filterByDate(this, date);
};
} else if (typeof module !== 'undefined') {
module.exports = {
filterByDate,
dateRangeFromDate,
decimalYearFromDate,
dateRangeFromISODate,
constrainFilterByDateRange,
constrainLegacyFilterByDateRange,
constrainExpressionFilterByDateRange,
isLegacyFilter,
updateVariable,
};
}