@superrouteca/smap 1.1.5 → 1.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +104 -3
- package/dist/SOURCE.json +8 -8
- package/dist/smap-client.cjs +2 -2
- package/dist/smap-client.js +2 -2
- package/dist/smap-client.mjs +2 -2
- package/dist/smap.cjs +1770 -16
- package/dist/smap.css +61 -1
- package/dist/smap.js +1759 -13
- package/dist/smap.mjs +1768 -17
- package/package.json +1 -1
- package/types/smap.d.cts +382 -5
- package/types/smap.d.mts +382 -5
package/dist/smap.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! sMap Web SDK 1.1.
|
|
1
|
+
/*! sMap Web SDK 1.1.6. Bundles maplibre-gl 6.16.0 (BSD-3-Clause), see vendor-licenses.txt. */
|
|
2
2
|
(function () {
|
|
3
3
|
function smapCreateEngine() {
|
|
4
4
|
var SMAP_BASE_URL = (typeof document !== 'undefined' && document.baseURI) || (typeof location !== 'undefined' && location.href) || 'about:blank';
|
|
@@ -28325,12 +28325,1634 @@ function smapCreateInterop() {
|
|
|
28325
28325
|
|
|
28326
28326
|
return module.exports;
|
|
28327
28327
|
}
|
|
28328
|
-
function
|
|
28328
|
+
function smapCreatePlan() {
|
|
28329
|
+
var module = { exports: {} };
|
|
28330
|
+
var exports = module.exports;
|
|
28331
|
+
var define;
|
|
28332
|
+
var self = {};
|
|
28333
|
+
/*!
|
|
28334
|
+
* sMap plan editor (OPEN-ROUTE-EDIT E10): edits a plan the caller holds through the Open Platform's plan.* calls.
|
|
28335
|
+
*
|
|
28336
|
+
* // /plan-token on your own server calls POST /v1/plan/token with its API token and hands the answer on.
|
|
28337
|
+
* const editor = map.planEditor({ credentials: { token: () => fetch('/plan-token').then((r) => r.json()) }, plan });
|
|
28338
|
+
* editor.on('change', (e) => save(e.plan));
|
|
28339
|
+
*
|
|
28340
|
+
* The editor keeps no plan on any server: every call carries the whole plan and the answer replaces the plan drawn.
|
|
28341
|
+
* It opens a distance snapshot (POST /v1/plan/matrix) and names it in every call, opening a new one by itself when
|
|
28342
|
+
* the snapshot expired. Three parts, each usable alone:
|
|
28343
|
+
* PlanEditor the state, the calls, undo / redo and the events; needs no map and no page
|
|
28344
|
+
* attachToMap draws the plan on an sMap map and lets stops be dragged within and between routes
|
|
28345
|
+
* createPanel the ready-made panel (routes, totals, violations, undo / redo, insert choices) in 14 languages
|
|
28346
|
+
*/
|
|
28347
|
+
(function (root, factory) {
|
|
28348
|
+
if (typeof module === 'object' && module.exports) {
|
|
28349
|
+
module.exports = factory();
|
|
28350
|
+
} else {
|
|
28351
|
+
root.smapPlan = factory();
|
|
28352
|
+
}
|
|
28353
|
+
})(typeof self !== 'undefined' ? self : this, function () {
|
|
28354
|
+
'use strict';
|
|
28355
|
+
|
|
28356
|
+
// ------------------------------------------------------------------ credentials and transport
|
|
28357
|
+
//
|
|
28358
|
+
// The one place that knows where plan calls go and how they are authorised (Superroute OPEN-ROUTE-EDIT §2e): a
|
|
28359
|
+
// short-lived plan editor token (`sr_pet_…`) that the customer's own server mints with POST /v1/plan/token, or a
|
|
28360
|
+
// map key (`smk_…`) with plan editing switched on. Both are sent as `Authorization: Bearer …`. A browser is known by
|
|
28361
|
+
// its Origin; a native app also names itself with X-SMap-App (and X-SMap-App-Cert on Android).
|
|
28362
|
+
|
|
28363
|
+
var DEFAULT_BASE = 'https://open.superroute.ca';
|
|
28364
|
+
// A token whose expiry can be read is renewed this many seconds before it ends.
|
|
28365
|
+
var RENEW_BEFORE = 30;
|
|
28366
|
+
var TOKEN_PREFIX = 'sr_pet_';
|
|
28367
|
+
|
|
28368
|
+
function base64Json(part) {
|
|
28369
|
+
var b64 = String(part).replace(/-/g, '+').replace(/_/g, '/');
|
|
28370
|
+
while (b64.length % 4) { b64 += '='; }
|
|
28371
|
+
return JSON.parse(atob(b64));
|
|
28372
|
+
}
|
|
28373
|
+
|
|
28374
|
+
/** The expiry (Unix seconds) of a plan editor token (`sr_pet_<payload>.<signature>`) or a JWT-shaped token; 0 if unreadable. */
|
|
28375
|
+
function tokenExpiry(token) {
|
|
28376
|
+
try {
|
|
28377
|
+
var t = String(token);
|
|
28378
|
+
var payload = t.indexOf(TOKEN_PREFIX) === 0 ? t.slice(TOKEN_PREFIX.length).split('.')[0] : t.split('.')[1];
|
|
28379
|
+
return Number(base64Json(payload).exp) || 0;
|
|
28380
|
+
} catch (e) { return 0; }
|
|
28381
|
+
}
|
|
28382
|
+
|
|
28383
|
+
/**
|
|
28384
|
+
* What a token provider gave: the token string, or the token answer of POST /v1/plan/token
|
|
28385
|
+
* ({ access_token, token_type, expires_in, expires_at, scopes, origins }, or that answer's `{ data }` envelope).
|
|
28386
|
+
* Returns { token, exp } with exp in Unix seconds (0 when it cannot be told).
|
|
28387
|
+
*/
|
|
28388
|
+
function readToken(t) {
|
|
28389
|
+
if (t && typeof t === 'object' && t.data && typeof t.data === 'object' && !t.access_token) { t = t.data; }
|
|
28390
|
+
if (typeof t === 'string' && t) { return { token: t, exp: tokenExpiry(t) }; }
|
|
28391
|
+
if (t && typeof t === 'object' && typeof t.access_token === 'string' && t.access_token) {
|
|
28392
|
+
var exp = t.expires_at ? Date.parse(t.expires_at) / 1000 : 0;
|
|
28393
|
+
if (!exp && typeof t.expires_in === 'number') { exp = Date.now() / 1000 + t.expires_in; }
|
|
28394
|
+
return { token: t.access_token, exp: exp || tokenExpiry(t.access_token) };
|
|
28395
|
+
}
|
|
28396
|
+
return null;
|
|
28397
|
+
}
|
|
28398
|
+
|
|
28399
|
+
/** The app headers of a native app: options.app is 'android:<package>' / 'apple:<bundle id>' / 'windows:<id>', or { id, cert }. */
|
|
28400
|
+
function appHeaders(app) {
|
|
28401
|
+
var h = {};
|
|
28402
|
+
if (!app) { return h; }
|
|
28403
|
+
var id = typeof app === 'string' ? app : app.id;
|
|
28404
|
+
if (id) { h['X-SMap-App'] = String(id); }
|
|
28405
|
+
if (app && typeof app === 'object' && app.cert) { h['X-SMap-App-Cert'] = String(app.cert); }
|
|
28406
|
+
return h;
|
|
28407
|
+
}
|
|
28408
|
+
|
|
28409
|
+
/**
|
|
28410
|
+
* Credentials: { token: () => Promise<string | TokenAnswer> } (called at first use, again before the expiry it
|
|
28411
|
+
* gives and after a 401 SESSION_EXPIRED), or { key: 'smk_…' } (a map key with plan editing switched on).
|
|
28412
|
+
*/
|
|
28413
|
+
function credentialsOf(c) {
|
|
28414
|
+
if (c && typeof c.token === 'function') {
|
|
28415
|
+
var token = null;
|
|
28416
|
+
var exp = 0;
|
|
28417
|
+
var pending = null;
|
|
28418
|
+
var fetchToken = function () {
|
|
28419
|
+
if (!pending) {
|
|
28420
|
+
pending = Promise.resolve().then(function () { return c.token(); }).then(function (t) {
|
|
28421
|
+
pending = null;
|
|
28422
|
+
var read = readToken(t);
|
|
28423
|
+
if (!read) { throw new Error('sMap plan editor: the token provider gave no token'); }
|
|
28424
|
+
token = read.token;
|
|
28425
|
+
exp = read.exp;
|
|
28426
|
+
return token;
|
|
28427
|
+
}, function (e) { pending = null; throw e; });
|
|
28428
|
+
}
|
|
28429
|
+
return pending;
|
|
28430
|
+
};
|
|
28431
|
+
return {
|
|
28432
|
+
kind: 'token',
|
|
28433
|
+
headers: function () {
|
|
28434
|
+
var fresh = token && (!exp || exp - Date.now() / 1000 > RENEW_BEFORE);
|
|
28435
|
+
return (fresh ? Promise.resolve(token) : fetchToken()).then(function (t) { return { Authorization: 'Bearer ' + t }; });
|
|
28436
|
+
},
|
|
28437
|
+
// After a 401 SESSION_EXPIRED: forget the token so the next call asks the provider again. True when a retry may help.
|
|
28438
|
+
renew: function () { token = null; exp = 0; return true; },
|
|
28439
|
+
};
|
|
28440
|
+
}
|
|
28441
|
+
if (c && typeof c.key === 'string' && c.key) {
|
|
28442
|
+
return {
|
|
28443
|
+
kind: 'key',
|
|
28444
|
+
headers: function () { return Promise.resolve({ Authorization: 'Bearer ' + c.key }); },
|
|
28445
|
+
renew: function () { return false; },
|
|
28446
|
+
};
|
|
28447
|
+
}
|
|
28448
|
+
throw new Error('sMap plan editor: credentials are { token: () => Promise<string | TokenAnswer> } or { key: string }');
|
|
28449
|
+
}
|
|
28450
|
+
|
|
28451
|
+
/** An error answered by the Open Platform (status, code, reason, details) or raised on the way. */
|
|
28452
|
+
function PlanError(message, o) {
|
|
28453
|
+
var e = new Error(message);
|
|
28454
|
+
e.name = 'PlanError';
|
|
28455
|
+
o = o || {};
|
|
28456
|
+
e.status = o.status || 0;
|
|
28457
|
+
e.code = o.code || null;
|
|
28458
|
+
e.details = o.details || null;
|
|
28459
|
+
e.reason = o.reason || null;
|
|
28460
|
+
e.path = o.path || null;
|
|
28461
|
+
return e;
|
|
28462
|
+
}
|
|
28463
|
+
|
|
28464
|
+
function isAbort(e) { return !!e && (e.name === 'AbortError' || e.cancelled === true); }
|
|
28465
|
+
function cancelled() { var e = new Error('cancelled'); e.name = 'AbortError'; e.cancelled = true; return e; }
|
|
28466
|
+
|
|
28467
|
+
/**
|
|
28468
|
+
* The transport: send(method, path, body, signal) resolves { status, body, data, matrix } (matrix: the X-Plan-Matrix
|
|
28469
|
+
* header) or rejects with a PlanError. A 401 SESSION_EXPIRED with a token provider asks for a new token and repeats
|
|
28470
|
+
* the call once; every other refusal (SESSION_REVOKED, TOKEN_INVALID, 403 NOT_AUTHORIZED with its reason) is raised.
|
|
28471
|
+
*/
|
|
28472
|
+
function createTransport(o) {
|
|
28473
|
+
o = o || {};
|
|
28474
|
+
var base = String(o.baseUrl || DEFAULT_BASE).replace(/\/$/, '');
|
|
28475
|
+
var creds = credentialsOf(o.credentials);
|
|
28476
|
+
var app = appHeaders(o.app);
|
|
28477
|
+
var fetchFn = o.fetch || (typeof fetch === 'function' ? function (url, init) { return fetch(url, init); } : null);
|
|
28478
|
+
if (!fetchFn) { throw new Error('sMap plan editor: no fetch; pass options.fetch'); }
|
|
28479
|
+
|
|
28480
|
+
function send(method, path, body, signal, retried) {
|
|
28481
|
+
return creds.headers().then(function (h) {
|
|
28482
|
+
var headers = { Accept: 'application/json' };
|
|
28483
|
+
Object.keys(app).forEach(function (k) { headers[k] = app[k]; });
|
|
28484
|
+
Object.keys(h).forEach(function (k) { headers[k] = h[k]; });
|
|
28485
|
+
var init = { method: method, headers: headers };
|
|
28486
|
+
if (body !== undefined) { headers['Content-Type'] = 'application/json'; init.body = JSON.stringify(body); }
|
|
28487
|
+
if (signal) { init.signal = signal; }
|
|
28488
|
+
return fetchFn(base + path, init);
|
|
28489
|
+
}).then(function (res) {
|
|
28490
|
+
return res.text().then(function (text) {
|
|
28491
|
+
var json = null;
|
|
28492
|
+
try { json = text ? JSON.parse(text) : null; } catch (e) { json = null; }
|
|
28493
|
+
var matrix = res.headers && typeof res.headers.get === 'function' ? res.headers.get('X-Plan-Matrix') : null;
|
|
28494
|
+
if (!res.ok) {
|
|
28495
|
+
var err = (json && json.error) || {};
|
|
28496
|
+
if (res.status === 401 && err.code === 'SESSION_EXPIRED' && !retried && creds.renew()) { return send(method, path, body, signal, true); }
|
|
28497
|
+
throw PlanError(err.message || ('HTTP ' + res.status), {
|
|
28498
|
+
status: res.status, code: err.code || null, details: err.details || null, reason: err.reason || (json && json.reason) || null, path: path,
|
|
28499
|
+
});
|
|
28500
|
+
}
|
|
28501
|
+
return { status: res.status, body: json, data: json && json.data, matrix: matrix };
|
|
28502
|
+
});
|
|
28503
|
+
});
|
|
28504
|
+
}
|
|
28505
|
+
return { send: send, kind: creds.kind, baseUrl: base };
|
|
28506
|
+
}
|
|
28507
|
+
|
|
28508
|
+
// ------------------------------------------------------------------ plans
|
|
28509
|
+
|
|
28510
|
+
function clone(v) { return v === undefined ? undefined : JSON.parse(JSON.stringify(v)); }
|
|
28511
|
+
|
|
28512
|
+
function routesOf(routes) {
|
|
28513
|
+
return (routes || []).map(function (r) {
|
|
28514
|
+
var stops = (r.stops || []).map(String);
|
|
28515
|
+
// A route sent with `reverse` is held in driving order, as the plan calls answer it.
|
|
28516
|
+
if (r.reverse) { stops.reverse(); }
|
|
28517
|
+
return { vehicle_id: String(r.vehicle_id), stops: stops };
|
|
28518
|
+
});
|
|
28519
|
+
}
|
|
28520
|
+
|
|
28521
|
+
// Every vehicle keeps a route to drop stops on: an empty one, last, where the plan gives none.
|
|
28522
|
+
function withAllVehicles(routes, vehicles) {
|
|
28523
|
+
var out = routes.slice();
|
|
28524
|
+
vehicles.forEach(function (v) {
|
|
28525
|
+
if (!out.some(function (r) { return r.vehicle_id === String(v.id); })) { out.push({ vehicle_id: String(v.id), stops: [] }); }
|
|
28526
|
+
});
|
|
28527
|
+
return out;
|
|
28528
|
+
}
|
|
28529
|
+
|
|
28530
|
+
function unassignedOf(jobs, routes) {
|
|
28531
|
+
var on = {};
|
|
28532
|
+
routes.forEach(function (r) { r.stops.forEach(function (s) { on[s] = true; }); });
|
|
28533
|
+
return jobs.filter(function (j) { return !on[String(j.id)]; }).map(function (j) { return String(j.id); });
|
|
28534
|
+
}
|
|
28535
|
+
|
|
28536
|
+
function findStop(routes, id) {
|
|
28537
|
+
for (var i = 0; i < routes.length; i++) {
|
|
28538
|
+
var k = routes[i].stops.indexOf(id);
|
|
28539
|
+
if (k >= 0) { return { route: i, vehicle_id: routes[i].vehicle_id, position: k + 1 }; }
|
|
28540
|
+
}
|
|
28541
|
+
return null;
|
|
28542
|
+
}
|
|
28543
|
+
|
|
28544
|
+
function idList(v) { return (Array.isArray(v) ? v : [v]).map(String); }
|
|
28545
|
+
|
|
28546
|
+
/** The routes after giving vehicleId's route the stops in `stops` (every stop of the route once, no other). */
|
|
28547
|
+
function applyResequence(routes, vehicleId, stops) {
|
|
28548
|
+
var out = clone(routes);
|
|
28549
|
+
var r = out.filter(function (x) { return x.vehicle_id === vehicleId; })[0];
|
|
28550
|
+
if (!r) { throw PlanError('sMap plan editor: no route of vehicle ' + vehicleId); }
|
|
28551
|
+
var want = idList(stops);
|
|
28552
|
+
if (want.length !== r.stops.length || want.slice().sort().join('\u0000') !== r.stops.slice().sort().join('\u0000')) {
|
|
28553
|
+
throw PlanError('sMap plan editor: a new order holds every stop of the route once, and no other');
|
|
28554
|
+
}
|
|
28555
|
+
r.stops = want;
|
|
28556
|
+
return out;
|
|
28557
|
+
}
|
|
28558
|
+
|
|
28559
|
+
/** The routes after moving `stops` to vehicleId's route at `position` (from 1, counted without them; none: last). */
|
|
28560
|
+
function applyMove(routes, stops, vehicleId, position) {
|
|
28561
|
+
var out = clone(routes);
|
|
28562
|
+
var ids = idList(stops);
|
|
28563
|
+
out.forEach(function (r) { r.stops = r.stops.filter(function (s) { return ids.indexOf(s) < 0; }); });
|
|
28564
|
+
var target = out.filter(function (x) { return x.vehicle_id === vehicleId; })[0];
|
|
28565
|
+
if (!target) { target = { vehicle_id: vehicleId, stops: [] }; out.push(target); }
|
|
28566
|
+
var at = position === undefined || position === null ? target.stops.length : Math.max(0, Math.min(target.stops.length, position - 1));
|
|
28567
|
+
Array.prototype.splice.apply(target.stops, [at, 0].concat(ids));
|
|
28568
|
+
return out;
|
|
28569
|
+
}
|
|
28570
|
+
|
|
28571
|
+
/** The routes after taking `stops` off their routes (each must be on a route). */
|
|
28572
|
+
function applyRemove(routes, stops) {
|
|
28573
|
+
var ids = idList(stops);
|
|
28574
|
+
ids.forEach(function (id) { if (!findStop(routes, id)) { throw PlanError('sMap plan editor: ' + id + ' is on no route'); } });
|
|
28575
|
+
var out = clone(routes);
|
|
28576
|
+
out.forEach(function (r) { r.stops = r.stops.filter(function (s) { return ids.indexOf(s) < 0; }); });
|
|
28577
|
+
return out;
|
|
28578
|
+
}
|
|
28579
|
+
|
|
28580
|
+
/**
|
|
28581
|
+
* Where a stop dropped before the stop at `position` of vehicleId's route (as drawn, the stop itself included; past
|
|
28582
|
+
* the last stop = after it) ends up: { kind: 'resequence', vehicle_id, stops } within its route, { kind: 'move',
|
|
28583
|
+
* vehicle_id, position } to another route or from the unassigned, or null when nothing changes.
|
|
28584
|
+
*/
|
|
28585
|
+
function dropEdit(routes, stopId, vehicleId, position) {
|
|
28586
|
+
var from = findStop(routes, stopId);
|
|
28587
|
+
var target = routes.filter(function (r) { return r.vehicle_id === vehicleId; })[0];
|
|
28588
|
+
var length = target ? target.stops.length : 0;
|
|
28589
|
+
if (from && from.vehicle_id === vehicleId) {
|
|
28590
|
+
var stops = target.stops.slice();
|
|
28591
|
+
stops.splice(from.position - 1, 1);
|
|
28592
|
+
var at = Math.max(1, Math.min(position, length + 1));
|
|
28593
|
+
if (from.position < at) { at -= 1; }
|
|
28594
|
+
stops.splice(at - 1, 0, stopId);
|
|
28595
|
+
if (stops.join('\u0000') === target.stops.join('\u0000')) { return null; }
|
|
28596
|
+
return { kind: 'resequence', vehicle_id: vehicleId, stops: stops };
|
|
28597
|
+
}
|
|
28598
|
+
var p = Math.max(1, position);
|
|
28599
|
+
return { kind: 'move', vehicle_id: vehicleId, position: p > length ? null : p };
|
|
28600
|
+
}
|
|
28601
|
+
|
|
28602
|
+
/** [lng, lat] of a location given as { lng, lat } / { lon, lat } / [lng, lat]; null when unreadable. */
|
|
28603
|
+
function lngLat(v) {
|
|
28604
|
+
if (!v) { return null; }
|
|
28605
|
+
if (Array.isArray(v)) { return v.length >= 2 ? [Number(v[0]), Number(v[1])] : null; }
|
|
28606
|
+
var lng = v.lng !== undefined ? v.lng : (v.lon !== undefined ? v.lon : v.longitude);
|
|
28607
|
+
var lat = v.lat !== undefined ? v.lat : v.latitude;
|
|
28608
|
+
return lng === undefined || lat === undefined ? null : [Number(lng), Number(lat)];
|
|
28609
|
+
}
|
|
28610
|
+
|
|
28611
|
+
/** An encoded polyline (precision 5, as plan.recost answers legs) as [[lng, lat], …]. */
|
|
28612
|
+
function decodePolyline(text, precision) {
|
|
28613
|
+
var factor = Math.pow(10, precision || 5);
|
|
28614
|
+
var out = [];
|
|
28615
|
+
var index = 0;
|
|
28616
|
+
var lat = 0;
|
|
28617
|
+
var lng = 0;
|
|
28618
|
+
text = String(text);
|
|
28619
|
+
while (index < text.length) {
|
|
28620
|
+
var values = [0, 0];
|
|
28621
|
+
for (var n = 0; n < 2; n++) {
|
|
28622
|
+
var shift = 0;
|
|
28623
|
+
var result = 0;
|
|
28624
|
+
var b;
|
|
28625
|
+
do {
|
|
28626
|
+
b = text.charCodeAt(index++) - 63;
|
|
28627
|
+
result |= (b & 0x1f) << shift;
|
|
28628
|
+
shift += 5;
|
|
28629
|
+
} while (b >= 0x20 && index <= text.length);
|
|
28630
|
+
values[n] = (result & 1) ? ~(result >> 1) : (result >> 1);
|
|
28631
|
+
}
|
|
28632
|
+
lat += values[0];
|
|
28633
|
+
lng += values[1];
|
|
28634
|
+
out.push([lng / factor, lat / factor]);
|
|
28635
|
+
}
|
|
28636
|
+
return out;
|
|
28637
|
+
}
|
|
28638
|
+
|
|
28639
|
+
// ------------------------------------------------------------------ the editor
|
|
28640
|
+
|
|
28641
|
+
var EVENTS = ['change', 'busy', 'error', 'snapshot', 'preview', 'destroy'];
|
|
28642
|
+
var PATHS = {
|
|
28643
|
+
recost: '/v1/plan/recost', resequence: '/v1/plan/resequence', move: '/v1/plan/move', remove: '/v1/plan/remove',
|
|
28644
|
+
insert: '/v1/plan/insert', refine: '/v1/plan/refine', matrix: '/v1/plan/matrix',
|
|
28645
|
+
};
|
|
28646
|
+
// Answer fields that describe the edit itself, beside routes, summary and plan.
|
|
28647
|
+
var ANSWERS = { resequence: 'resequence', move: 'move', remove: 'removed', insert: 'insert', refine: 'refine' };
|
|
28648
|
+
// A snapshot that could not be opened is asked for again after this long; calls go on without one meanwhile.
|
|
28649
|
+
var SNAPSHOT_RETRY_MS = 60000;
|
|
28650
|
+
|
|
28651
|
+
function newController() { return typeof AbortController === 'function' ? new AbortController() : null; }
|
|
28652
|
+
|
|
28653
|
+
/**
|
|
28654
|
+
* The plan editor's state and calls, without a map.
|
|
28655
|
+
* @param {Object} options
|
|
28656
|
+
* @param {Object} options.credentials { token: () => Promise<string | TokenAnswer> } or { key: string }
|
|
28657
|
+
* @param {string|Object} [options.app] a native app's identity: 'android:<package>' / 'apple:<bundle id>' / 'windows:<id>', or { id, cert }
|
|
28658
|
+
* @param {string} [options.baseUrl] the Open Platform (default https://open.superroute.ca)
|
|
28659
|
+
* @param {Function} [options.fetch] fetch to use (default the page's)
|
|
28660
|
+
* @param {Object} [options.plan] the starting plan: { vehicles, jobs, routes, region?, profile?, departed_at? }
|
|
28661
|
+
* @param {string} [options.region] used when the plan names none
|
|
28662
|
+
* @param {string} [options.profile] used when the plan names none
|
|
28663
|
+
* @param {boolean} [options.snapshot=true] open and use a distance snapshot
|
|
28664
|
+
* @param {boolean} [options.geometry=true] ask for each leg's line (for drawing)
|
|
28665
|
+
* @param {number} [options.insertLimit=3] positions offered per inserted job (1-10)
|
|
28666
|
+
* @param {'duration'|'distance'} [options.objective] what insert ranks by (the server's default: duration)
|
|
28667
|
+
*/
|
|
28668
|
+
function PlanEditor(options) {
|
|
28669
|
+
if (!(this instanceof PlanEditor)) { return new PlanEditor(options); }
|
|
28670
|
+
options = options || {};
|
|
28671
|
+
this._transport = createTransport(options);
|
|
28672
|
+
this._options = options;
|
|
28673
|
+
this._snapshotOn = options.snapshot !== false;
|
|
28674
|
+
this._geometry = options.geometry !== false;
|
|
28675
|
+
this._handlers = {};
|
|
28676
|
+
EVENTS.forEach(function (t) { this._handlers[t] = []; }, this);
|
|
28677
|
+
this._history = [];
|
|
28678
|
+
this._at = -1;
|
|
28679
|
+
this._vehicles = [];
|
|
28680
|
+
this._context = {};
|
|
28681
|
+
this._locked = {};
|
|
28682
|
+
this._choices = null;
|
|
28683
|
+
this._last = null;
|
|
28684
|
+
this._inflight = null;
|
|
28685
|
+
this._previewing = null;
|
|
28686
|
+
this._previewResult = null;
|
|
28687
|
+
this._busy = false;
|
|
28688
|
+
this._error = null;
|
|
28689
|
+
this._matrix = null;
|
|
28690
|
+
this._matrixKey = null;
|
|
28691
|
+
this._opening = null;
|
|
28692
|
+
this._openingKey = null;
|
|
28693
|
+
this._matrixRetryAt = 0;
|
|
28694
|
+
this._destroyed = false;
|
|
28695
|
+
if (options.plan) { this.setPlan(options.plan).catch(function () {}); }
|
|
28696
|
+
}
|
|
28697
|
+
|
|
28698
|
+
PlanEditor.prototype.on = function (type, fn) {
|
|
28699
|
+
if (!this._handlers[type]) { throw new Error('sMap plan editor: unknown event "' + type + '"'); }
|
|
28700
|
+
this._handlers[type].push(fn);
|
|
28701
|
+
return this;
|
|
28702
|
+
};
|
|
28703
|
+
PlanEditor.prototype.off = function (type, fn) {
|
|
28704
|
+
if (this._handlers[type]) { this._handlers[type] = this._handlers[type].filter(function (h) { return h !== fn; }); }
|
|
28705
|
+
return this;
|
|
28706
|
+
};
|
|
28707
|
+
PlanEditor.prototype._emit = function (type, payload) {
|
|
28708
|
+
(this._handlers[type] || []).slice().forEach(function (h) {
|
|
28709
|
+
try { h(payload); } catch (e) { if (typeof console !== 'undefined') { console.error(e); } }
|
|
28710
|
+
});
|
|
28711
|
+
};
|
|
28712
|
+
|
|
28713
|
+
/** Replaces the plan: the history starts again from it, and it is priced (plan.recost). */
|
|
28714
|
+
PlanEditor.prototype.setPlan = function (plan) {
|
|
28715
|
+
if (!plan || !Array.isArray(plan.vehicles) || !Array.isArray(plan.jobs)) {
|
|
28716
|
+
return Promise.reject(PlanError('sMap plan editor: a plan has vehicles and jobs'));
|
|
28717
|
+
}
|
|
28718
|
+
this._supersede();
|
|
28719
|
+
this.clearPreview();
|
|
28720
|
+
this._vehicles = clone(plan.vehicles);
|
|
28721
|
+
this._context = {};
|
|
28722
|
+
var o = this._options;
|
|
28723
|
+
var region = plan.region || o.region;
|
|
28724
|
+
var profile = plan.profile || o.profile;
|
|
28725
|
+
if (region) { this._context.region = region; }
|
|
28726
|
+
if (profile) { this._context.profile = profile; }
|
|
28727
|
+
if (plan.departed_at) { this._context.departed_at = plan.departed_at; }
|
|
28728
|
+
var routes = withAllVehicles(routesOf(plan.routes), this._vehicles);
|
|
28729
|
+
var jobs = clone(plan.jobs);
|
|
28730
|
+
var known = {};
|
|
28731
|
+
jobs.forEach(function (j) { known[String(j.id)] = true; });
|
|
28732
|
+
Object.keys(this._locked).forEach(function (id) { if (!known[id]) { delete this._locked[id]; } }, this);
|
|
28733
|
+
this._history = [{ kind: 'set', routes: routes, jobs: jobs, result: null, answer: null }];
|
|
28734
|
+
this._at = 0;
|
|
28735
|
+
this._choices = null;
|
|
28736
|
+
this._last = null;
|
|
28737
|
+
this._error = null;
|
|
28738
|
+
this._changed('set');
|
|
28739
|
+
return this._price(this._history[0]);
|
|
28740
|
+
};
|
|
28741
|
+
|
|
28742
|
+
/** The plan in the shape it is sent: vehicles, jobs, routes (stops in driving order), unassigned and its context. */
|
|
28743
|
+
PlanEditor.prototype.getPlan = function () {
|
|
28744
|
+
var e = this._history[this._at];
|
|
28745
|
+
if (!e) { return null; }
|
|
28746
|
+
var plan = { vehicles: clone(this._vehicles), jobs: clone(e.jobs), routes: clone(e.routes), unassigned: unassignedOf(e.jobs, e.routes) };
|
|
28747
|
+
Object.keys(this._context).forEach(function (k) { plan[k] = this._context[k]; }, this);
|
|
28748
|
+
return plan;
|
|
28749
|
+
};
|
|
28750
|
+
|
|
28751
|
+
/** The plan's prices and judgement as the last answer gave them ({ routes, summary }), or null before one. */
|
|
28752
|
+
PlanEditor.prototype.getResult = function () {
|
|
28753
|
+
var e = this._history[this._at];
|
|
28754
|
+
return e && e.result ? clone(e.result) : null;
|
|
28755
|
+
};
|
|
28756
|
+
|
|
28757
|
+
/** Everything a panel shows, in one object. */
|
|
28758
|
+
PlanEditor.prototype.state = function () {
|
|
28759
|
+
return {
|
|
28760
|
+
plan: this.getPlan(), result: this.getResult(), busy: this._busy, error: this._error, canUndo: this.canUndo(),
|
|
28761
|
+
canRedo: this.canRedo(), choices: clone(this._choices), locked: this.locked(), last: clone(this._last),
|
|
28762
|
+
preview: this._previewResult ? clone(this._previewResult) : null,
|
|
28763
|
+
};
|
|
28764
|
+
};
|
|
28765
|
+
|
|
28766
|
+
PlanEditor.prototype.canUndo = function () { return this._at > 0; };
|
|
28767
|
+
PlanEditor.prototype.canRedo = function () { return this._at >= 0 && this._at < this._history.length - 1; };
|
|
28768
|
+
PlanEditor.prototype.isBusy = function () { return this._busy; };
|
|
28769
|
+
|
|
28770
|
+
/** Gives vehicleId's route the stops in a new driving order (plan.resequence). */
|
|
28771
|
+
PlanEditor.prototype.resequence = function (vehicleId, stops) {
|
|
28772
|
+
vehicleId = String(vehicleId);
|
|
28773
|
+
var order = idList(stops);
|
|
28774
|
+
return this._run('resequence', { vehicle_id: vehicleId, stops: order }, function (routes) { return applyResequence(routes, vehicleId, order); });
|
|
28775
|
+
};
|
|
28776
|
+
|
|
28777
|
+
/** Moves stops to vehicleId's route at `position` (from 1, counted without them; omitted: last) (plan.move). */
|
|
28778
|
+
PlanEditor.prototype.move = function (stops, vehicleId, position) {
|
|
28779
|
+
vehicleId = String(vehicleId);
|
|
28780
|
+
var ids = idList(stops);
|
|
28781
|
+
var body = { vehicle_id: vehicleId, stops: ids };
|
|
28782
|
+
if (position !== undefined && position !== null) { body.position = position; }
|
|
28783
|
+
return this._run('move', body, function (routes) { return applyMove(routes, ids, vehicleId, position); });
|
|
28784
|
+
};
|
|
28785
|
+
|
|
28786
|
+
/** Takes stops off their routes; they become unassigned (plan.remove). */
|
|
28787
|
+
PlanEditor.prototype.remove = function (stops) {
|
|
28788
|
+
var ids = idList(stops);
|
|
28789
|
+
return this._run('remove', { stops: ids }, function (routes) { return applyRemove(routes, ids); });
|
|
28790
|
+
};
|
|
28791
|
+
|
|
28792
|
+
/**
|
|
28793
|
+
* Places a stop where it was dropped: before the stop at `position` of vehicleId's route as drawn (past the last
|
|
28794
|
+
* stop: after it). Within its route this is a resequence, otherwise a move. Resolves null when nothing changes.
|
|
28795
|
+
*/
|
|
28796
|
+
PlanEditor.prototype.dropStop = function (stopId, vehicleId, position) {
|
|
28797
|
+
var e = this._history[this._at];
|
|
28798
|
+
if (!e) { return Promise.resolve(null); }
|
|
28799
|
+
var edit = dropEdit(e.routes, String(stopId), String(vehicleId), position);
|
|
28800
|
+
if (!edit) { return Promise.resolve(null); }
|
|
28801
|
+
return edit.kind === 'resequence' ? this.resequence(edit.vehicle_id, edit.stops) : this.move([String(stopId)], edit.vehicle_id, edit.position);
|
|
28802
|
+
};
|
|
28803
|
+
|
|
28804
|
+
/**
|
|
28805
|
+
* Inserts new jobs (each like a job of the plan, with an id the plan does not have) at their cheapest positions, or
|
|
28806
|
+
* places jobs of the plan that are on no route (given by id) (plan.insert). The ranked positions answered are kept
|
|
28807
|
+
* in choices(); choose() takes another one.
|
|
28808
|
+
* @param {Object|string|Array} jobs
|
|
28809
|
+
* @param {Object} [o] limit (1-10), objective ('duration' | 'distance'), nearest (1-50)
|
|
28810
|
+
*/
|
|
28811
|
+
PlanEditor.prototype.insert = function (jobs, o) {
|
|
28812
|
+
try { return this._insert(jobs, o || {}); } catch (err) { return Promise.reject(err); }
|
|
28813
|
+
};
|
|
28814
|
+
PlanEditor.prototype._insert = function (jobs, o) {
|
|
28815
|
+
var e = this._history[this._at];
|
|
28816
|
+
if (!e) { return Promise.reject(PlanError('sMap plan editor: no plan; call setPlan first')); }
|
|
28817
|
+
var list = Array.isArray(jobs) ? jobs : [jobs];
|
|
28818
|
+
var byId = {};
|
|
28819
|
+
e.jobs.forEach(function (j) { byId[String(j.id)] = j; });
|
|
28820
|
+
var placing = list.map(function (j) {
|
|
28821
|
+
if (typeof j === 'string' || typeof j === 'number') {
|
|
28822
|
+
var known = byId[String(j)];
|
|
28823
|
+
if (!known) { throw PlanError('sMap plan editor: no job ' + j); }
|
|
28824
|
+
if (findStop(e.routes, String(j))) { throw PlanError('sMap plan editor: ' + j + ' is already on a route'); }
|
|
28825
|
+
return clone(known);
|
|
28826
|
+
}
|
|
28827
|
+
return clone(j);
|
|
28828
|
+
});
|
|
28829
|
+
var ids = placing.map(function (j) { return String(j.id); });
|
|
28830
|
+
var rest = e.jobs.filter(function (j) { return ids.indexOf(String(j.id)) < 0; });
|
|
28831
|
+
var body = { insert: placing, limit: o.limit || this._options.insertLimit || 3 };
|
|
28832
|
+
var objective = o.objective || this._options.objective;
|
|
28833
|
+
if (objective) { body.objective = objective; }
|
|
28834
|
+
if (o.nearest) { body.nearest = o.nearest; }
|
|
28835
|
+
return this._run('insert', body, null, { jobs: rest, after: rest.concat(placing) });
|
|
28836
|
+
};
|
|
28837
|
+
|
|
28838
|
+
/** The positions the last insert answered: [{ job, placed, reason?, choices: […], chosen }]; null when none. */
|
|
28839
|
+
PlanEditor.prototype.choices = function () { return clone(this._choices); };
|
|
28840
|
+
PlanEditor.prototype.clearChoices = function () { this._choices = null; this._changed('choices'); return this; };
|
|
28841
|
+
|
|
28842
|
+
/** Puts an inserted job at another of its answered positions (plan.move). */
|
|
28843
|
+
PlanEditor.prototype.choose = function (jobId, index) {
|
|
28844
|
+
jobId = String(jobId);
|
|
28845
|
+
var item = (this._choices || []).filter(function (c) { return c.job === jobId; })[0];
|
|
28846
|
+
var choice = item && item.choices[index];
|
|
28847
|
+
if (!choice) { return Promise.reject(PlanError('sMap plan editor: no such position for ' + jobId)); }
|
|
28848
|
+
var self = this;
|
|
28849
|
+
var kept = this._choices;
|
|
28850
|
+
var before = item.chosen;
|
|
28851
|
+
var moving = this.move([jobId], choice.vehicle_id, choice.position);
|
|
28852
|
+
item.chosen = index;
|
|
28853
|
+
this._choices = kept;
|
|
28854
|
+
this._changed('choices');
|
|
28855
|
+
return moving.then(function (answer) {
|
|
28856
|
+
if (answer) { self._choices = kept; self._changed('choices'); }
|
|
28857
|
+
return answer;
|
|
28858
|
+
}, function (e) { item.chosen = before; self._choices = kept; self._changed('choices'); throw e; });
|
|
28859
|
+
};
|
|
28860
|
+
|
|
28861
|
+
/**
|
|
28862
|
+
* Re-orders the stops of chosen routes around the locked stops (plan.refine). The new order is kept only when the
|
|
28863
|
+
* service finds it better; otherwise the plan stays and `last.answer.changed` is false.
|
|
28864
|
+
* @param {Object} [o] vehicleIds (default every route), freeze (default the locked stops on those routes)
|
|
28865
|
+
*/
|
|
28866
|
+
PlanEditor.prototype.refine = function (o) {
|
|
28867
|
+
o = o || {};
|
|
28868
|
+
var e = this._history[this._at];
|
|
28869
|
+
if (!e) { return Promise.reject(PlanError('sMap plan editor: no plan; call setPlan first')); }
|
|
28870
|
+
var body = {};
|
|
28871
|
+
var vehicles = o.vehicleIds ? idList(o.vehicleIds) : null;
|
|
28872
|
+
if (vehicles) { body.vehicle_ids = vehicles; }
|
|
28873
|
+
var freeze = o.freeze ? idList(o.freeze) : this.locked().filter(function (id) {
|
|
28874
|
+
var at = findStop(e.routes, id);
|
|
28875
|
+
return at && (!vehicles || vehicles.indexOf(at.vehicle_id) >= 0);
|
|
28876
|
+
});
|
|
28877
|
+
if (freeze.length) { body.freeze = freeze; }
|
|
28878
|
+
return this._run('refine', body, null, {});
|
|
28879
|
+
};
|
|
28880
|
+
|
|
28881
|
+
/** Prices the plan again as it is (plan.recost). */
|
|
28882
|
+
PlanEditor.prototype.recost = function () {
|
|
28883
|
+
var e = this._history[this._at];
|
|
28884
|
+
if (!e) { return Promise.resolve(null); }
|
|
28885
|
+
this._supersede();
|
|
28886
|
+
return this._price(e);
|
|
28887
|
+
};
|
|
28888
|
+
|
|
28889
|
+
/** Locks stops so that refine keeps them on their route, in their order. */
|
|
28890
|
+
PlanEditor.prototype.lock = function (stops) { idList(stops).forEach(function (id) { this._locked[id] = true; }, this); this._changed('lock'); return this; };
|
|
28891
|
+
PlanEditor.prototype.unlock = function (stops) { idList(stops).forEach(function (id) { delete this._locked[id]; }, this); this._changed('lock'); return this; };
|
|
28892
|
+
PlanEditor.prototype.locked = function () { return Object.keys(this._locked); };
|
|
28893
|
+
PlanEditor.prototype.isLocked = function (id) { return !!this._locked[String(id)]; };
|
|
28894
|
+
|
|
28895
|
+
/** Goes back one edit. The plan drawn is the one answered then; a plan never priced is priced again. */
|
|
28896
|
+
PlanEditor.prototype.undo = function () {
|
|
28897
|
+
if (!this.canUndo()) { return Promise.resolve(null); }
|
|
28898
|
+
return this._step(-1);
|
|
28899
|
+
};
|
|
28900
|
+
PlanEditor.prototype.redo = function () {
|
|
28901
|
+
if (!this.canRedo()) { return Promise.resolve(null); }
|
|
28902
|
+
return this._step(1);
|
|
28903
|
+
};
|
|
28904
|
+
PlanEditor.prototype._step = function (by) {
|
|
28905
|
+
this._supersede();
|
|
28906
|
+
this.clearPreview();
|
|
28907
|
+
this._at += by;
|
|
28908
|
+
this._choices = null;
|
|
28909
|
+
this._last = null;
|
|
28910
|
+
this._error = null;
|
|
28911
|
+
var e = this._history[this._at];
|
|
28912
|
+
this._changed(by < 0 ? 'undo' : 'redo');
|
|
28913
|
+
return e.result ? Promise.resolve(this.getResult()) : this._price(e);
|
|
28914
|
+
};
|
|
28915
|
+
|
|
28916
|
+
/**
|
|
28917
|
+
* Prices other routes for the current jobs without changing the plan (plan.recost, no geometry), e.g. while a stop
|
|
28918
|
+
* is dragged; a newer preview cancels the one before. Reported as the `preview` event.
|
|
28919
|
+
*/
|
|
28920
|
+
PlanEditor.prototype.preview = function (routes) {
|
|
28921
|
+
var e = this._history[this._at];
|
|
28922
|
+
if (!e || this._destroyed) { return Promise.resolve(null); }
|
|
28923
|
+
this._cancelPreview();
|
|
28924
|
+
var controller = newController();
|
|
28925
|
+
var ticket = { controller: controller };
|
|
28926
|
+
this._previewing = ticket;
|
|
28927
|
+
var body = this._body({ routes: routesOf(routes), jobs: e.jobs }, {}, false);
|
|
28928
|
+
var self = this;
|
|
28929
|
+
return this._call(PATHS.recost, body, controller && controller.signal).then(function (res) {
|
|
28930
|
+
if (self._previewing !== ticket) { return null; }
|
|
28931
|
+
self._previewing = null;
|
|
28932
|
+
self._previewResult = { routes: routesOf(routes), result: { routes: (res.data || {}).routes || [], summary: (res.data || {}).summary || null } };
|
|
28933
|
+
self._emit('preview', clone(self._previewResult));
|
|
28934
|
+
return clone(self._previewResult);
|
|
28935
|
+
}, function (err) {
|
|
28936
|
+
if (self._previewing === ticket) { self._previewing = null; }
|
|
28937
|
+
if (!isAbort(err) && self._previewing === null && !self._destroyed) { self._emit('error', { error: err, kind: 'preview' }); }
|
|
28938
|
+
return null;
|
|
28939
|
+
});
|
|
28940
|
+
};
|
|
28941
|
+
PlanEditor.prototype.clearPreview = function () {
|
|
28942
|
+
var had = this._previewing || this._previewResult;
|
|
28943
|
+
this._cancelPreview();
|
|
28944
|
+
this._previewResult = null;
|
|
28945
|
+
if (had) { this._emit('preview', null); }
|
|
28946
|
+
return this;
|
|
28947
|
+
};
|
|
28948
|
+
PlanEditor.prototype._cancelPreview = function () {
|
|
28949
|
+
if (this._previewing && this._previewing.controller) { this._previewing.controller.abort(); }
|
|
28950
|
+
this._previewing = null;
|
|
28951
|
+
};
|
|
28952
|
+
|
|
28953
|
+
/** Ends the editor: cancels its calls, closes its snapshot, and tells its map layer and panel to leave. */
|
|
28954
|
+
PlanEditor.prototype.destroy = function () {
|
|
28955
|
+
if (this._destroyed) { return; }
|
|
28956
|
+
this._supersede();
|
|
28957
|
+
this._cancelPreview();
|
|
28958
|
+
this._destroyed = true;
|
|
28959
|
+
var matrix = this._matrix;
|
|
28960
|
+
this._matrix = null;
|
|
28961
|
+
if (matrix) { this._transport.send('DELETE', PATHS.matrix + '/' + encodeURIComponent(matrix)).catch(function () {}); }
|
|
28962
|
+
this._emit('destroy', null);
|
|
28963
|
+
EVENTS.forEach(function (t) { this._handlers[t] = []; }, this);
|
|
28964
|
+
};
|
|
28965
|
+
|
|
28966
|
+
// --- internals
|
|
28967
|
+
|
|
28968
|
+
PlanEditor.prototype._changed = function (kind) {
|
|
28969
|
+
var e = this._history[this._at] || {};
|
|
28970
|
+
this._emit('change', {
|
|
28971
|
+
kind: kind, plan: this.getPlan(), result: this.getResult(), answer: this._last ? clone(this._last.answer) : null,
|
|
28972
|
+
pending: !e.result, canUndo: this.canUndo(), canRedo: this.canRedo(),
|
|
28973
|
+
});
|
|
28974
|
+
};
|
|
28975
|
+
|
|
28976
|
+
PlanEditor.prototype._setBusy = function (on) {
|
|
28977
|
+
if (this._busy === on) { return; }
|
|
28978
|
+
this._busy = on;
|
|
28979
|
+
this._emit('busy', { busy: on });
|
|
28980
|
+
};
|
|
28981
|
+
|
|
28982
|
+
// Cancels the call in flight. An edit drawn ahead of its answer stays in the history unpriced, and is priced when
|
|
28983
|
+
// it is shown again; a search (insert, refine) that was cancelled never happened.
|
|
28984
|
+
PlanEditor.prototype._supersede = function () {
|
|
28985
|
+
var t = this._inflight;
|
|
28986
|
+
if (!t) { return; }
|
|
28987
|
+
this._inflight = null;
|
|
28988
|
+
if (t.controller) { t.controller.abort(); }
|
|
28989
|
+
this._setBusy(false);
|
|
28990
|
+
};
|
|
28991
|
+
|
|
28992
|
+
PlanEditor.prototype._body = function (entry, extra, geometry) {
|
|
28993
|
+
// Routes without stops are kept here as drop targets and not sent (an empty route would be priced start to end).
|
|
28994
|
+
var routes = entry.routes.filter(function (r) { return r.stops.length; });
|
|
28995
|
+
if (!routes.length) { routes = entry.routes.slice(0, 1); }
|
|
28996
|
+
var body = { vehicles: this._vehicles, jobs: entry.jobs, routes: routes };
|
|
28997
|
+
Object.keys(this._context).forEach(function (k) { body[k] = this._context[k]; }, this);
|
|
28998
|
+
body.options = { geometry: geometry === undefined ? this._geometry : geometry };
|
|
28999
|
+
Object.keys(extra || {}).forEach(function (k) { body[k] = extra[k]; });
|
|
29000
|
+
return body;
|
|
29001
|
+
};
|
|
29002
|
+
|
|
29003
|
+
// One edit: drawn at once when its outcome is known here (`local`), sent with the plan it changes, and replaced by
|
|
29004
|
+
// the answer. `search` (insert, refine) is pushed to the history only when answered.
|
|
29005
|
+
PlanEditor.prototype._run = function (kind, extra, local, search) {
|
|
29006
|
+
if (this._destroyed) { return Promise.reject(PlanError('sMap plan editor: destroyed')); }
|
|
29007
|
+
var base = this._history[this._at];
|
|
29008
|
+
if (!base) { return Promise.reject(PlanError('sMap plan editor: no plan; call setPlan first')); }
|
|
29009
|
+
this._supersede();
|
|
29010
|
+
this.clearPreview();
|
|
29011
|
+
var entry = null;
|
|
29012
|
+
if (local) {
|
|
29013
|
+
var routes;
|
|
29014
|
+
try { routes = local(base.routes); } catch (err) { return Promise.reject(err); }
|
|
29015
|
+
entry = { kind: kind, routes: routes, jobs: base.jobs, result: null, answer: null };
|
|
29016
|
+
this._history.splice(this._at + 1);
|
|
29017
|
+
this._history.push(entry);
|
|
29018
|
+
this._at = this._history.length - 1;
|
|
29019
|
+
this._choices = null;
|
|
29020
|
+
this._last = null;
|
|
29021
|
+
this._error = null;
|
|
29022
|
+
this._changed(kind);
|
|
29023
|
+
}
|
|
29024
|
+
var body = this._body(search && search.jobs ? { routes: base.routes, jobs: search.jobs } : base, extra);
|
|
29025
|
+
return this._request(kind, PATHS[kind], body, entry, search ? { base: base, jobs: search.after || base.jobs } : null);
|
|
29026
|
+
};
|
|
29027
|
+
|
|
29028
|
+
PlanEditor.prototype._price = function (entry) {
|
|
29029
|
+
return this._request('recost', PATHS.recost, this._body(entry, {}), entry, null);
|
|
29030
|
+
};
|
|
29031
|
+
|
|
29032
|
+
PlanEditor.prototype._request = function (kind, path, body, entry, search) {
|
|
29033
|
+
var self = this;
|
|
29034
|
+
var controller = newController();
|
|
29035
|
+
var ticket = { controller: controller, kind: kind };
|
|
29036
|
+
this._inflight = ticket;
|
|
29037
|
+
this._setBusy(true);
|
|
29038
|
+
return this._call(path, body, controller && controller.signal).then(function (res) {
|
|
29039
|
+
if (self._inflight !== ticket) { return null; }
|
|
29040
|
+
self._inflight = null;
|
|
29041
|
+
var data = res.data || {};
|
|
29042
|
+
var answer = ANSWERS[kind] ? (data[ANSWERS[kind]] === undefined ? null : data[ANSWERS[kind]]) : null;
|
|
29043
|
+
var target = entry;
|
|
29044
|
+
if (search) {
|
|
29045
|
+
if (self._history[self._at] !== search.base) { self._setBusy(false); return null; }
|
|
29046
|
+
if (kind === 'refine' && answer && answer.changed === false) {
|
|
29047
|
+
// The plan as sent stays; its prices are the ones answered.
|
|
29048
|
+
target = search.base;
|
|
29049
|
+
} else {
|
|
29050
|
+
target = { kind: kind, routes: search.base.routes, jobs: clone(search.jobs), result: null, answer: null };
|
|
29051
|
+
self._history.splice(self._at + 1);
|
|
29052
|
+
self._history.push(target);
|
|
29053
|
+
self._at = self._history.length - 1;
|
|
29054
|
+
}
|
|
29055
|
+
}
|
|
29056
|
+
if (data.plan && Array.isArray(data.plan.routes)) { target.routes = withAllVehicles(routesOf(data.plan.routes), self._vehicles); }
|
|
29057
|
+
target.result = { routes: data.routes || [], summary: data.summary || null };
|
|
29058
|
+
if (kind !== 'recost') {
|
|
29059
|
+
target.answer = answer;
|
|
29060
|
+
self._last = { kind: kind, answer: answer };
|
|
29061
|
+
}
|
|
29062
|
+
if (kind === 'insert') {
|
|
29063
|
+
self._choices = (answer || []).map(function (item) {
|
|
29064
|
+
var c = clone(item);
|
|
29065
|
+
c.chosen = c.placed ? 0 : null;
|
|
29066
|
+
return c;
|
|
29067
|
+
});
|
|
29068
|
+
}
|
|
29069
|
+
self._error = null;
|
|
29070
|
+
self._setBusy(false);
|
|
29071
|
+
if (self._history[self._at] === target || kind !== 'recost') { self._changed(kind); }
|
|
29072
|
+
return { kind: kind, plan: self.getPlan(), result: self.getResult(), answer: clone(answer) };
|
|
29073
|
+
}, function (err) {
|
|
29074
|
+
var current = self._inflight === ticket;
|
|
29075
|
+
if (current) { self._inflight = null; self._setBusy(false); }
|
|
29076
|
+
if (isAbort(err) || !current || self._destroyed) { return null; }
|
|
29077
|
+
// A failed edit drawn ahead of its answer is taken back.
|
|
29078
|
+
if (entry && entry !== self._history[0] && kind !== 'recost') {
|
|
29079
|
+
var i = self._history.indexOf(entry);
|
|
29080
|
+
if (i > 0) {
|
|
29081
|
+
self._history.splice(i, 1);
|
|
29082
|
+
if (self._at >= i) { self._at -= 1; }
|
|
29083
|
+
}
|
|
29084
|
+
}
|
|
29085
|
+
self._error = { kind: kind, status: err.status || 0, code: err.code || null, message: err.message, reason: err.reason || null };
|
|
29086
|
+
self._changed('error');
|
|
29087
|
+
self._emit('error', { error: err, kind: kind });
|
|
29088
|
+
throw err;
|
|
29089
|
+
});
|
|
29090
|
+
};
|
|
29091
|
+
|
|
29092
|
+
// A call with the snapshot: opened first when needed, named as `matrix`, and opened again after it expired. A
|
|
29093
|
+
// snapshot never makes a call fail (E2): a 410 is repeated with a new snapshot, then without one.
|
|
29094
|
+
PlanEditor.prototype._call = function (path, body, signal, attempt) {
|
|
29095
|
+
var self = this;
|
|
29096
|
+
attempt = attempt || 0;
|
|
29097
|
+
var opening = attempt >= 2 ? Promise.resolve(null) : this._ensureMatrix();
|
|
29098
|
+
return opening.then(function (matrix) {
|
|
29099
|
+
if (signal && signal.aborted) { throw cancelled(); }
|
|
29100
|
+
if (matrix) { body.matrix = matrix; } else { delete body.matrix; }
|
|
29101
|
+
return self._transport.send('POST', path, body, signal);
|
|
29102
|
+
}).then(function (res) {
|
|
29103
|
+
if (body.matrix) { self._snapshotSeen(res.matrix, body.matrix); }
|
|
29104
|
+
return res;
|
|
29105
|
+
}, function (err) {
|
|
29106
|
+
if (err && err.status === 410 && body.matrix && attempt < 2) {
|
|
29107
|
+
self._dropMatrix(body.matrix, 'expired');
|
|
29108
|
+
return self._call(path, body, signal, attempt + 1);
|
|
29109
|
+
}
|
|
29110
|
+
throw err;
|
|
29111
|
+
});
|
|
29112
|
+
};
|
|
29113
|
+
|
|
29114
|
+
PlanEditor.prototype._snapshotSeen = function (header, sent) {
|
|
29115
|
+
var status = header || 'used';
|
|
29116
|
+
this._emit('snapshot', { status: status, matrix: sent });
|
|
29117
|
+
if (status === 'expired' || status === 'mismatch') {
|
|
29118
|
+
this._dropMatrix(sent, null);
|
|
29119
|
+
// Opened now, for the next call; this call was already answered without it.
|
|
29120
|
+
this._ensureMatrix();
|
|
29121
|
+
}
|
|
29122
|
+
};
|
|
29123
|
+
|
|
29124
|
+
PlanEditor.prototype._dropMatrix = function (id, status) {
|
|
29125
|
+
if (this._matrix === id) { this._matrix = null; this._matrixKey = null; }
|
|
29126
|
+
if (status) { this._emit('snapshot', { status: status, matrix: id }); }
|
|
29127
|
+
};
|
|
29128
|
+
|
|
29129
|
+
PlanEditor.prototype._ensureMatrix = function () {
|
|
29130
|
+
if (!this._snapshotOn || this._destroyed) { return Promise.resolve(null); }
|
|
29131
|
+
var key = (this._context.region || '') + '|' + (this._context.profile || '');
|
|
29132
|
+
if (this._matrix && this._matrixKey === key) { return Promise.resolve(this._matrix); }
|
|
29133
|
+
if (this._opening && this._openingKey === key) { return this._opening; }
|
|
29134
|
+
if (this._matrixRetryAt && Date.now() < this._matrixRetryAt) { return Promise.resolve(null); }
|
|
29135
|
+
var self = this;
|
|
29136
|
+
var old = this._matrix;
|
|
29137
|
+
if (old) {
|
|
29138
|
+
this._matrix = null;
|
|
29139
|
+
this._transport.send('DELETE', PATHS.matrix + '/' + encodeURIComponent(old)).catch(function () {});
|
|
29140
|
+
}
|
|
29141
|
+
var body = {};
|
|
29142
|
+
if (this._context.region) { body.region = this._context.region; }
|
|
29143
|
+
if (this._context.profile) { body.profile = this._context.profile; }
|
|
29144
|
+
this._openingKey = key;
|
|
29145
|
+
var opening = this._transport.send('POST', PATHS.matrix, body).then(function (res) {
|
|
29146
|
+
var id = res.data && res.data.matrix;
|
|
29147
|
+
if (!id) { throw PlanError('sMap plan editor: the snapshot answer has no id'); }
|
|
29148
|
+
if (self._destroyed) {
|
|
29149
|
+
self._transport.send('DELETE', PATHS.matrix + '/' + encodeURIComponent(id)).catch(function () {});
|
|
29150
|
+
return null;
|
|
29151
|
+
}
|
|
29152
|
+
self._matrixRetryAt = 0;
|
|
29153
|
+
if (self._openingKey === key) { self._matrix = id; self._matrixKey = key; }
|
|
29154
|
+
self._emit('snapshot', { status: 'opened', matrix: id, expires_at: res.data.expires_at || null, node: res.data.node || null });
|
|
29155
|
+
return id;
|
|
29156
|
+
}, function (err) {
|
|
29157
|
+
self._matrixRetryAt = Date.now() + SNAPSHOT_RETRY_MS;
|
|
29158
|
+
if (!self._destroyed) { self._emit('snapshot', { status: 'failed', matrix: null, error: err }); }
|
|
29159
|
+
return null;
|
|
29160
|
+
}).then(function (id) {
|
|
29161
|
+
if (self._opening === opening) { self._opening = null; self._openingKey = null; }
|
|
29162
|
+
return id;
|
|
29163
|
+
});
|
|
29164
|
+
this._opening = opening;
|
|
29165
|
+
return opening;
|
|
29166
|
+
};
|
|
29167
|
+
|
|
29168
|
+
// ------------------------------------------------------------------ texts (14 languages)
|
|
29169
|
+
|
|
29170
|
+
var TEXT_KEYS = ['editor', 'busy', 'undo', 'redo', 'refine', 'total', 'distance', 'drivingTime', 'stops', 'violations',
|
|
29171
|
+
'unreachable', 'unassigned', 'noStops', 'place', 'remove', 'lock', 'unlock', 'choicesFor', 'choice', 'added', 'arrival',
|
|
29172
|
+
'choose', 'chosen', 'close', 'notPlaced', 'preview', 'refined', 'notRefined', 'error', 'pending', 'km', 'hours',
|
|
29173
|
+
'minutes', 'rule.capacity', 'rule.max_tasks', 'rule.max_distance', 'rule.max_travel_time', 'rule.vehicle_time_window',
|
|
29174
|
+
'rule.skills', 'rule.time_window', 'rule.unreachable'];
|
|
29175
|
+
|
|
29176
|
+
function texts(list) {
|
|
29177
|
+
var out = {};
|
|
29178
|
+
TEXT_KEYS.forEach(function (k, i) { out[k] = list[i]; });
|
|
29179
|
+
return out;
|
|
29180
|
+
}
|
|
29181
|
+
|
|
29182
|
+
var TEXTS = {
|
|
29183
|
+
en: texts(['Plan editor', 'Updating the plan', 'Undo', 'Redo', 'Refine', 'Total', 'Distance', 'Driving time', 'Stops',
|
|
29184
|
+
'Violations', 'Unreachable legs', 'Unassigned', 'No stops', 'Place', 'Remove', 'Lock', 'Unlock', 'Positions for {job}',
|
|
29185
|
+
'{vehicle}, stop {n}', '+{distance}, +{time}', 'Arrival {time}', 'Choose', 'Chosen', 'Close', 'No position found',
|
|
29186
|
+
'Preview', 'Stops moved: {n}', 'No better order found', 'The plan could not be updated.', 'Not yet priced', '{d} km',
|
|
29187
|
+
'{h} h {m} min', '{m} min', 'Capacity exceeded', 'Too many stops', 'Distance limit exceeded',
|
|
29188
|
+
'Driving time limit exceeded', 'Working hours exceeded', 'Missing skills', 'Time window missed', 'No road to this stop']),
|
|
29189
|
+
'zh-Hans': texts(['计划编辑器', '正在更新计划', '撤销', '重做', '优化', '合计', '距离', '行驶时间', '站点', '违规',
|
|
29190
|
+
'不可达路段', '未分配', '无站点', '安排', '移除', '锁定', '解锁', '{job} 的可选位置', '{vehicle},第 {n} 站',
|
|
29191
|
+
'+{distance},+{time}', '到达 {time}', '选择', '已选', '关闭', '未找到可用位置', '预览', '已移动站点:{n}',
|
|
29192
|
+
'未找到更优的顺序', '计划未能更新。', '尚未计算', '{d} 公里', '{h} 小时 {m} 分钟', '{m} 分钟', '超出载量', '站点过多',
|
|
29193
|
+
'超出距离上限', '超出行驶时间上限', '超出工作时间', '缺少技能', '错过时间窗', '无法到达此站点']),
|
|
29194
|
+
'zh-Hant': texts(['計劃編輯器', '正在更新計劃', '復原', '重做', '優化', '合計', '距離', '行駛時間', '站點', '違規',
|
|
29195
|
+
'不可達路段', '未分配', '無站點', '安排', '移除', '鎖定', '解鎖', '{job} 的可選位置', '{vehicle},第 {n} 站',
|
|
29196
|
+
'+{distance},+{time}', '到達 {time}', '選擇', '已選', '關閉', '未找到可用位置', '預覽', '已移動站點:{n}',
|
|
29197
|
+
'未找到更優的順序', '計劃未能更新。', '尚未計算', '{d} 公里', '{h} 小時 {m} 分鐘', '{m} 分鐘', '超出載量', '站點過多',
|
|
29198
|
+
'超出距離上限', '超出行駛時間上限', '超出工作時間', '缺少技能', '錯過時間窗', '無法到達此站點']),
|
|
29199
|
+
de: texts(['Planeditor', 'Plan wird aktualisiert', 'Rückgängig', 'Wiederholen', 'Optimieren', 'Gesamt', 'Strecke',
|
|
29200
|
+
'Fahrzeit', 'Stopps', 'Verstöße', 'Nicht erreichbare Abschnitte', 'Nicht zugewiesen', 'Keine Stopps', 'Einplanen',
|
|
29201
|
+
'Entfernen', 'Sperren', 'Entsperren', 'Positionen für {job}', '{vehicle}, Stopp {n}', '+{distance}, +{time}',
|
|
29202
|
+
'Ankunft {time}', 'Auswählen', 'Ausgewählt', 'Schließen', 'Keine Position gefunden', 'Vorschau',
|
|
29203
|
+
'Verschobene Stopps: {n}', 'Keine bessere Reihenfolge gefunden', 'Der Plan konnte nicht aktualisiert werden.',
|
|
29204
|
+
'Noch nicht berechnet', '{d} km', '{h} Std. {m} Min.', '{m} Min.', 'Kapazität überschritten', 'Zu viele Stopps',
|
|
29205
|
+
'Streckenlimit überschritten', 'Fahrzeitlimit überschritten', 'Arbeitszeit überschritten', 'Fehlende Fähigkeiten',
|
|
29206
|
+
'Zeitfenster verpasst', 'Kein Weg zu diesem Stopp']),
|
|
29207
|
+
es: texts(['Editor de planes', 'Actualizando el plan', 'Deshacer', 'Rehacer', 'Optimizar', 'Total', 'Distancia',
|
|
29208
|
+
'Tiempo de conducción', 'Paradas', 'Infracciones', 'Tramos inalcanzables', 'Sin asignar', 'Sin paradas', 'Asignar',
|
|
29209
|
+
'Quitar', 'Bloquear', 'Desbloquear', 'Posiciones para {job}', '{vehicle}, parada {n}', '+{distance}, +{time}',
|
|
29210
|
+
'Llegada {time}', 'Elegir', 'Elegida', 'Cerrar', 'No se encontró ninguna posición', 'Vista previa',
|
|
29211
|
+
'Paradas movidas: {n}', 'No se encontró un orden mejor', 'No se pudo actualizar el plan.', 'Aún sin calcular',
|
|
29212
|
+
'{d} km', '{h} h {m} min', '{m} min', 'Capacidad superada', 'Demasiadas paradas', 'Límite de distancia superado',
|
|
29213
|
+
'Límite de tiempo de conducción superado', 'Horario de trabajo superado', 'Faltan habilidades',
|
|
29214
|
+
'Ventana horaria incumplida', 'No hay ruta hasta esta parada']),
|
|
29215
|
+
fr: texts(['Éditeur de plan', 'Mise à jour du plan', 'Annuler', 'Rétablir', 'Optimiser', 'Total', 'Distance',
|
|
29216
|
+
'Temps de conduite', 'Arrêts', 'Infractions', 'Tronçons inaccessibles', 'Non affectés', 'Aucun arrêt', 'Placer',
|
|
29217
|
+
'Retirer', 'Verrouiller', 'Déverrouiller', 'Positions pour {job}', '{vehicle}, arrêt {n}', '+{distance}, +{time}',
|
|
29218
|
+
'Arrivée {time}', 'Choisir', 'Choisie', 'Fermer', 'Aucune position trouvée', 'Aperçu', 'Arrêts déplacés : {n}',
|
|
29219
|
+
'Aucun meilleur ordre trouvé', 'Le plan n’a pas pu être mis à jour.', 'Pas encore calculé', '{d} km',
|
|
29220
|
+
'{h} h {m} min', '{m} min', 'Capacité dépassée', 'Trop d’arrêts', 'Limite de distance dépassée',
|
|
29221
|
+
'Limite de temps de conduite dépassée', 'Horaires de travail dépassés', 'Compétences manquantes',
|
|
29222
|
+
'Créneau horaire manqué', 'Aucune route vers cet arrêt']),
|
|
29223
|
+
it: texts(['Editor del piano', 'Aggiornamento del piano', 'Annulla', 'Ripeti', 'Ottimizza', 'Totale', 'Distanza',
|
|
29224
|
+
'Tempo di guida', 'Fermate', 'Violazioni', 'Tratti non raggiungibili', 'Non assegnate', 'Nessuna fermata', 'Assegna',
|
|
29225
|
+
'Rimuovi', 'Blocca', 'Sblocca', 'Posizioni per {job}', '{vehicle}, fermata {n}', '+{distance}, +{time}',
|
|
29226
|
+
'Arrivo {time}', 'Scegli', 'Scelta', 'Chiudi', 'Nessuna posizione trovata', 'Anteprima', 'Fermate spostate: {n}',
|
|
29227
|
+
'Nessun ordine migliore trovato', 'Impossibile aggiornare il piano.', 'Non ancora calcolato', '{d} km',
|
|
29228
|
+
'{h} h {m} min', '{m} min', 'Capacità superata', 'Troppe fermate', 'Limite di distanza superato',
|
|
29229
|
+
'Limite di tempo di guida superato', 'Orario di lavoro superato', 'Competenze mancanti', 'Finestra oraria mancata',
|
|
29230
|
+
'Nessuna strada per questa fermata']),
|
|
29231
|
+
nl: texts(['Planeditor', 'Plan wordt bijgewerkt', 'Ongedaan maken', 'Opnieuw', 'Optimaliseren', 'Totaal', 'Afstand',
|
|
29232
|
+
'Rijtijd', 'Stops', 'Overtredingen', 'Onbereikbare trajecten', 'Niet toegewezen', 'Geen stops', 'Inplannen',
|
|
29233
|
+
'Verwijderen', 'Vergrendelen', 'Ontgrendelen', 'Posities voor {job}', '{vehicle}, stop {n}', '+{distance}, +{time}',
|
|
29234
|
+
'Aankomst {time}', 'Kiezen', 'Gekozen', 'Sluiten', 'Geen positie gevonden', 'Voorbeeld', 'Verplaatste stops: {n}',
|
|
29235
|
+
'Geen betere volgorde gevonden', 'Het plan kon niet worden bijgewerkt.', 'Nog niet berekend', '{d} km',
|
|
29236
|
+
'{h} u {m} min', '{m} min', 'Capaciteit overschreden', 'Te veel stops', 'Afstandslimiet overschreden',
|
|
29237
|
+
'Rijtijdlimiet overschreden', 'Werktijd overschreden', 'Ontbrekende vaardigheden', 'Tijdvenster gemist',
|
|
29238
|
+
'Geen route naar deze stop']),
|
|
29239
|
+
// European Portuguese.
|
|
29240
|
+
pt: texts(['Editor de planos', 'A atualizar o plano', 'Anular', 'Refazer', 'Otimizar', 'Total', 'Distância',
|
|
29241
|
+
'Tempo de condução', 'Paragens', 'Infrações', 'Troços inacessíveis', 'Não atribuídas', 'Sem paragens', 'Atribuir',
|
|
29242
|
+
'Remover', 'Bloquear', 'Desbloquear', 'Posições para {job}', '{vehicle}, paragem {n}', '+{distance}, +{time}',
|
|
29243
|
+
'Chegada {time}', 'Escolher', 'Escolhida', 'Fechar', 'Nenhuma posição encontrada', 'Pré-visualização',
|
|
29244
|
+
'Paragens movidas: {n}', 'Nenhuma ordem melhor encontrada', 'Não foi possível atualizar o plano.',
|
|
29245
|
+
'Ainda não calculado', '{d} km', '{h} h {m} min', '{m} min', 'Capacidade excedida', 'Demasiadas paragens',
|
|
29246
|
+
'Limite de distância excedido', 'Limite de tempo de condução excedido', 'Horário de trabalho excedido',
|
|
29247
|
+
'Competências em falta', 'Janela horária falhada', 'Sem estrada até esta paragem']),
|
|
29248
|
+
// Serbian in the Latin script.
|
|
29249
|
+
sr: texts(['Uređivač plana', 'Plan se ažurira', 'Opozovi', 'Ponovi', 'Optimizuj', 'Ukupno', 'Rastojanje',
|
|
29250
|
+
'Vreme vožnje', 'Stanice', 'Prekršaji', 'Nedostupne deonice', 'Nedodeljeno', 'Nema stanica', 'Rasporedi', 'Ukloni',
|
|
29251
|
+
'Zaključaj', 'Otključaj', 'Pozicije za {job}', '{vehicle}, stanica {n}', '+{distance}, +{time}', 'Dolazak {time}',
|
|
29252
|
+
'Izaberi', 'Izabrano', 'Zatvori', 'Nije pronađena pozicija', 'Pregled', 'Premeštene stanice: {n}',
|
|
29253
|
+
'Nije pronađen bolji redosled', 'Plan nije mogao da se ažurira.', 'Još nije izračunato', '{d} km',
|
|
29254
|
+
'{h} h {m} min', '{m} min', 'Prekoračen kapacitet', 'Previše stanica', 'Prekoračeno ograničenje rastojanja',
|
|
29255
|
+
'Prekoračeno ograničenje vremena vožnje', 'Prekoračeno radno vreme', 'Nedostaju veštine',
|
|
29256
|
+
'Propušten vremenski prozor', 'Nema puta do ove stanice']),
|
|
29257
|
+
hu: texts(['Tervszerkesztő', 'A terv frissítése folyamatban', 'Visszavonás', 'Újra', 'Optimalizálás', 'Összesen',
|
|
29258
|
+
'Távolság', 'Vezetési idő', 'Megállók', 'Szabálysértések', 'Elérhetetlen szakaszok', 'Nincs hozzárendelve',
|
|
29259
|
+
'Nincsenek megállók', 'Beosztás', 'Eltávolítás', 'Zárolás', 'Feloldás', 'Pozíciók ehhez: {job}',
|
|
29260
|
+
'{vehicle}, {n}. megálló', '+{distance}, +{time}', 'Érkezés: {time}', 'Kiválasztás', 'Kiválasztva', 'Bezárás',
|
|
29261
|
+
'Nem található pozíció', 'Előnézet', 'Áthelyezett megállók: {n}', 'Nem található jobb sorrend',
|
|
29262
|
+
'A tervet nem sikerült frissíteni.', 'Még nincs kiszámítva', '{d} km', '{h} óra {m} perc', '{m} perc',
|
|
29263
|
+
'Kapacitás túllépve', 'Túl sok megálló', 'Távolságkorlát túllépve', 'Vezetésiidő-korlát túllépve',
|
|
29264
|
+
'Munkaidő túllépve', 'Hiányzó képességek', 'Időablak elmulasztva', 'Nincs út ehhez a megállóhoz']),
|
|
29265
|
+
pl: texts(['Edytor planu', 'Aktualizowanie planu', 'Cofnij', 'Ponów', 'Optymalizuj', 'Razem', 'Odległość',
|
|
29266
|
+
'Czas jazdy', 'Przystanki', 'Naruszenia', 'Nieosiągalne odcinki', 'Nieprzypisane', 'Brak przystanków', 'Przydziel',
|
|
29267
|
+
'Usuń', 'Zablokuj', 'Odblokuj', 'Pozycje dla {job}', '{vehicle}, przystanek {n}', '+{distance}, +{time}',
|
|
29268
|
+
'Przyjazd {time}', 'Wybierz', 'Wybrano', 'Zamknij', 'Nie znaleziono pozycji', 'Podgląd',
|
|
29269
|
+
'Przeniesione przystanki: {n}', 'Nie znaleziono lepszej kolejności', 'Nie udało się zaktualizować planu.',
|
|
29270
|
+
'Jeszcze nie obliczono', '{d} km', '{h} godz. {m} min', '{m} min', 'Przekroczona ładowność',
|
|
29271
|
+
'Zbyt wiele przystanków', 'Przekroczony limit odległości', 'Przekroczony limit czasu jazdy',
|
|
29272
|
+
'Przekroczony czas pracy', 'Brak umiejętności', 'Pominięte okno czasowe', 'Brak drogi do tego przystanku']),
|
|
29273
|
+
sk: texts(['Editor plánu', 'Plán sa aktualizuje', 'Späť', 'Znova', 'Optimalizovať', 'Spolu', 'Vzdialenosť',
|
|
29274
|
+
'Čas jazdy', 'Zastávky', 'Porušenia', 'Nedosiahnuteľné úseky', 'Nepriradené', 'Žiadne zastávky', 'Zaradiť',
|
|
29275
|
+
'Odstrániť', 'Uzamknúť', 'Odomknúť', 'Pozície pre {job}', '{vehicle}, zastávka {n}', '+{distance}, +{time}',
|
|
29276
|
+
'Príchod {time}', 'Vybrať', 'Vybrané', 'Zavrieť', 'Nenašla sa žiadna pozícia', 'Náhľad', 'Presunuté zastávky: {n}',
|
|
29277
|
+
'Lepšie poradie sa nenašlo', 'Plán sa nepodarilo aktualizovať.', 'Ešte nevypočítané', '{d} km', '{h} h {m} min',
|
|
29278
|
+
'{m} min', 'Prekročená kapacita', 'Príliš veľa zastávok', 'Prekročený limit vzdialenosti',
|
|
29279
|
+
'Prekročený limit času jazdy', 'Prekročený pracovný čas', 'Chýbajúce zručnosti', 'Zmeškané časové okno',
|
|
29280
|
+
'Žiadna cesta k tejto zastávke']),
|
|
29281
|
+
cs: texts(['Editor plánu', 'Plán se aktualizuje', 'Zpět', 'Znovu', 'Optimalizovat', 'Celkem', 'Vzdálenost',
|
|
29282
|
+
'Doba jízdy', 'Zastávky', 'Porušení', 'Nedosažitelné úseky', 'Nepřiřazené', 'Žádné zastávky', 'Zařadit', 'Odebrat',
|
|
29283
|
+
'Zamknout', 'Odemknout', 'Pozice pro {job}', '{vehicle}, zastávka {n}', '+{distance}, +{time}', 'Příjezd {time}',
|
|
29284
|
+
'Vybrat', 'Vybráno', 'Zavřít', 'Nebyla nalezena žádná pozice', 'Náhled', 'Přesunuté zastávky: {n}',
|
|
29285
|
+
'Lepší pořadí nebylo nalezeno', 'Plán se nepodařilo aktualizovat.', 'Dosud nevypočteno', '{d} km', '{h} h {m} min',
|
|
29286
|
+
'{m} min', 'Překročena kapacita', 'Příliš mnoho zastávek', 'Překročen limit vzdálenosti',
|
|
29287
|
+
'Překročen limit doby jízdy', 'Překročena pracovní doba', 'Chybějící dovednosti', 'Zmeškané časové okno',
|
|
29288
|
+
'K této zastávce nevede cesta']),
|
|
29289
|
+
};
|
|
29290
|
+
var LANGUAGES = Object.keys(TEXTS);
|
|
29291
|
+
|
|
29292
|
+
/** The panel's language for a BCP-47 tag: one of the 14, English when none fits. */
|
|
29293
|
+
function panelLanguage(tag) {
|
|
29294
|
+
var t = String(tag || 'en').toLowerCase();
|
|
29295
|
+
if (/^zh-(hant|tw|hk|mo)/.test(t)) { return 'zh-Hant'; }
|
|
29296
|
+
if (/^zh/.test(t)) { return 'zh-Hans'; }
|
|
29297
|
+
var base = t.split(/[-_]/)[0];
|
|
29298
|
+
return TEXTS[base] ? base : 'en';
|
|
29299
|
+
}
|
|
29300
|
+
|
|
29301
|
+
/** The panel's texts in a language, with the caller's own texts (`labels`) over them. */
|
|
29302
|
+
function textsFor(language, labels) {
|
|
29303
|
+
var out = {};
|
|
29304
|
+
var own = TEXTS[panelLanguage(language)];
|
|
29305
|
+
TEXT_KEYS.forEach(function (k) { out[k] = (labels && labels[k]) || own[k]; });
|
|
29306
|
+
return out;
|
|
29307
|
+
}
|
|
29308
|
+
|
|
29309
|
+
function fill(template, values) {
|
|
29310
|
+
return String(template).replace(/\{(\w+)\}/g, function (m, k) { return values[k] === undefined ? m : String(values[k]); });
|
|
29311
|
+
}
|
|
29312
|
+
|
|
29313
|
+
// ------------------------------------------------------------------ the panel
|
|
29314
|
+
|
|
29315
|
+
// The locale numbers are written in: the panel's Portuguese is European Portuguese, so any `pt` tag writes numbers
|
|
29316
|
+
// as `pt-PT` does (`pt` alone is Brazilian grouping); every other tag is used as given.
|
|
29317
|
+
function numberLocale(language) {
|
|
29318
|
+
return panelLanguage(language) === 'pt' ? 'pt-PT' : language;
|
|
29319
|
+
}
|
|
29320
|
+
|
|
29321
|
+
function numberFormat(language, digits) {
|
|
29322
|
+
try {
|
|
29323
|
+
var nf = new Intl.NumberFormat(numberLocale(language), { minimumFractionDigits: digits, maximumFractionDigits: digits });
|
|
29324
|
+
return function (v) { return nf.format(v); };
|
|
29325
|
+
} catch (e) { return function (v) { return Number(v).toFixed(digits); }; }
|
|
29326
|
+
}
|
|
29327
|
+
|
|
29328
|
+
function formatters(language, t) {
|
|
29329
|
+
var one = numberFormat(language, 1);
|
|
29330
|
+
return {
|
|
29331
|
+
distance: function (m) { return fill(t.km, { d: one((Number(m) || 0) / 1000) }); },
|
|
29332
|
+
time: function (s) {
|
|
29333
|
+
var min = Math.round((Number(s) || 0) / 60);
|
|
29334
|
+
var h = Math.floor(min / 60);
|
|
29335
|
+
var m = min % 60;
|
|
29336
|
+
return h > 0 ? fill(t.hours, { h: h, m: (m < 10 ? '0' : '') + m }) : fill(t.minutes, { m: m });
|
|
29337
|
+
},
|
|
29338
|
+
// The clock time of an ISO 8601 time with offset, as the answer gives it (the plan's own time zone).
|
|
29339
|
+
clock: function (iso) { var m = /T(\d\d:\d\d)/.exec(String(iso || '')); return m ? m[1] : ''; },
|
|
29340
|
+
};
|
|
29341
|
+
}
|
|
29342
|
+
|
|
29343
|
+
var COLORS = ['#2563eb', '#dc2626', '#16a34a', '#9333ea', '#ea580c', '#0891b2', '#db2777', '#65a30d', '#4f46e5', '#b45309'];
|
|
29344
|
+
|
|
29345
|
+
function colorOf(editor, vehicleId, colors) {
|
|
29346
|
+
var list = colors || COLORS;
|
|
29347
|
+
var i = 0;
|
|
29348
|
+
editor._vehicles.some(function (v, k) { if (String(v.id) === vehicleId) { i = k; return true; } return false; });
|
|
29349
|
+
return list[i % list.length];
|
|
29350
|
+
}
|
|
29351
|
+
|
|
29352
|
+
/**
|
|
29353
|
+
* The ready-made panel: routes with their totals and stops, violations, undo / redo / refine, the positions an
|
|
29354
|
+
* insert answered, and errors. Stops are dragged between lists, or onto the unassigned list to take them off.
|
|
29355
|
+
* @param {PlanEditor} editor
|
|
29356
|
+
* @param {Object} [o] language (BCP-47), labels (own texts by key), document, colors, className
|
|
29357
|
+
* @returns {{ element: HTMLElement, setLanguage(language: string): void, render(): void, destroy(): void }}
|
|
29358
|
+
*/
|
|
29359
|
+
function createPanel(editor, o) {
|
|
29360
|
+
o = o || {};
|
|
29361
|
+
var doc = o.document || (typeof document !== 'undefined' ? document : null);
|
|
29362
|
+
if (!doc) { throw new Error('sMap plan editor: the panel needs a document'); }
|
|
29363
|
+
var language = o.language || 'en';
|
|
29364
|
+
var t = textsFor(language, o.labels);
|
|
29365
|
+
var fmt = formatters(language, t);
|
|
29366
|
+
var root = doc.createElement('div');
|
|
29367
|
+
root.className = 'smap-plan-panel' + (o.className ? ' ' + o.className : '');
|
|
29368
|
+
var dragging = null;
|
|
29369
|
+
|
|
29370
|
+
function el(tag, className, text) {
|
|
29371
|
+
var n = doc.createElement(tag);
|
|
29372
|
+
if (className) { n.className = className; }
|
|
29373
|
+
if (text !== undefined && text !== null) { n.textContent = String(text); }
|
|
29374
|
+
return n;
|
|
29375
|
+
}
|
|
29376
|
+
function button(className, text, onClick, disabled) {
|
|
29377
|
+
var b = el('button', 'smap-plan-button ' + className, text);
|
|
29378
|
+
b.type = 'button';
|
|
29379
|
+
if (disabled) { b.disabled = true; }
|
|
29380
|
+
b.addEventListener('click', function () { var p = onClick(); if (p && p.catch) { p.catch(function () {}); } });
|
|
29381
|
+
return b;
|
|
29382
|
+
}
|
|
29383
|
+
function totals(parent, summary, stops) {
|
|
29384
|
+
var dl = el('dl', 'smap-plan-totals');
|
|
29385
|
+
function row(label, value, className) {
|
|
29386
|
+
var w = el('div', className);
|
|
29387
|
+
w.appendChild(el('dt', null, label));
|
|
29388
|
+
w.appendChild(el('dd', null, value));
|
|
29389
|
+
dl.appendChild(w);
|
|
29390
|
+
}
|
|
29391
|
+
row(t.distance, fmt.distance(summary.distance_meters), 'smap-plan-distance');
|
|
29392
|
+
row(t.drivingTime, fmt.time(summary.duration_seconds), 'smap-plan-time');
|
|
29393
|
+
row(t.stops, String(stops), 'smap-plan-stops');
|
|
29394
|
+
if (summary.violations || summary.violation_count) { row(t.violations, String(summary.violations || summary.violation_count), 'smap-plan-violations'); }
|
|
29395
|
+
if (summary.unreachable_legs) { row(t.unreachable, String(summary.unreachable_legs), 'smap-plan-unreachable'); }
|
|
29396
|
+
parent.appendChild(dl);
|
|
29397
|
+
}
|
|
29398
|
+
function ruleText(v) { return t['rule.' + v.rule] || v.message || v.rule; }
|
|
29399
|
+
function dropZone(node, onDrop) {
|
|
29400
|
+
node.addEventListener('dragover', function (e) { if (dragging) { e.preventDefault(); node.classList.add('smap-plan-over'); } });
|
|
29401
|
+
node.addEventListener('dragleave', function () { node.classList.remove('smap-plan-over'); });
|
|
29402
|
+
node.addEventListener('drop', function (e) {
|
|
29403
|
+
node.classList.remove('smap-plan-over');
|
|
29404
|
+
if (!dragging) { return; }
|
|
29405
|
+
e.preventDefault();
|
|
29406
|
+
e.stopPropagation();
|
|
29407
|
+
var id = dragging;
|
|
29408
|
+
dragging = null;
|
|
29409
|
+
var p = onDrop(id);
|
|
29410
|
+
if (p && p.catch) { p.catch(function () {}); }
|
|
29411
|
+
});
|
|
29412
|
+
}
|
|
29413
|
+
function draggable(node, id) {
|
|
29414
|
+
node.draggable = true;
|
|
29415
|
+
node.setAttribute('data-stop', id);
|
|
29416
|
+
node.addEventListener('dragstart', function (e) {
|
|
29417
|
+
dragging = id;
|
|
29418
|
+
if (e.dataTransfer) { try { e.dataTransfer.setData('text/plain', id); e.dataTransfer.effectAllowed = 'move'; } catch (x) { /* older engines */ } }
|
|
29419
|
+
});
|
|
29420
|
+
node.addEventListener('dragend', function () { dragging = null; });
|
|
29421
|
+
}
|
|
29422
|
+
|
|
29423
|
+
function render() {
|
|
29424
|
+
var s = editor.state();
|
|
29425
|
+
while (root.firstChild) { root.removeChild(root.firstChild); }
|
|
29426
|
+
root.setAttribute('role', 'region');
|
|
29427
|
+
root.setAttribute('aria-label', t.editor);
|
|
29428
|
+
root.setAttribute('aria-busy', s.busy ? 'true' : 'false');
|
|
29429
|
+
root.classList.toggle('smap-plan-busy', s.busy);
|
|
29430
|
+
|
|
29431
|
+
var bar = el('div', 'smap-plan-bar');
|
|
29432
|
+
bar.appendChild(button('smap-plan-undo', t.undo, function () { return editor.undo(); }, !s.canUndo));
|
|
29433
|
+
bar.appendChild(button('smap-plan-redo', t.redo, function () { return editor.redo(); }, !s.canRedo));
|
|
29434
|
+
bar.appendChild(button('smap-plan-refine', t.refine, function () { return editor.refine(); }, !s.plan));
|
|
29435
|
+
var status = el('span', 'smap-plan-status', s.busy ? t.busy : '');
|
|
29436
|
+
status.setAttribute('role', 'status');
|
|
29437
|
+
bar.appendChild(status);
|
|
29438
|
+
root.appendChild(bar);
|
|
29439
|
+
|
|
29440
|
+
if (s.error) {
|
|
29441
|
+
var alert = el('div', 'smap-plan-error');
|
|
29442
|
+
alert.setAttribute('role', 'alert');
|
|
29443
|
+
alert.appendChild(el('span', null, t.error + (s.error.code ? ' (' + s.error.code + (s.error.reason ? ', ' + s.error.reason : '') + ')' : '')));
|
|
29444
|
+
alert.appendChild(button('smap-plan-error-close', t.close, function () { editor._error = null; render(); }));
|
|
29445
|
+
root.appendChild(alert);
|
|
29446
|
+
}
|
|
29447
|
+
if (s.last && s.last.kind === 'refine' && s.last.answer) {
|
|
29448
|
+
root.appendChild(el('div', 'smap-plan-note', s.last.answer.changed ? fill(t.refined, { n: s.last.answer.moved || 0 }) : t.notRefined));
|
|
29449
|
+
}
|
|
29450
|
+
if (!s.plan) { return; }
|
|
29451
|
+
|
|
29452
|
+
var priced = {};
|
|
29453
|
+
((s.result && s.result.routes) || []).forEach(function (r) { priced[r.vehicle_id] = r; });
|
|
29454
|
+
var summary = s.result && s.result.summary;
|
|
29455
|
+
var total = el('section', 'smap-plan-total');
|
|
29456
|
+
total.appendChild(el('h3', null, t.total));
|
|
29457
|
+
if (summary) { totals(total, summary, summary.tasks !== undefined ? summary.tasks : 0); } else { total.appendChild(el('p', 'smap-plan-pending', t.pending)); }
|
|
29458
|
+
if (s.preview && s.preview.result && s.preview.result.summary) {
|
|
29459
|
+
var pv = el('div', 'smap-plan-preview');
|
|
29460
|
+
pv.appendChild(el('h4', null, t.preview));
|
|
29461
|
+
totals(pv, s.preview.result.summary, s.preview.result.summary.tasks || 0);
|
|
29462
|
+
total.appendChild(pv);
|
|
29463
|
+
}
|
|
29464
|
+
root.appendChild(total);
|
|
29465
|
+
|
|
29466
|
+
var routes = el('div', 'smap-plan-routes');
|
|
29467
|
+
s.plan.routes.forEach(function (r) {
|
|
29468
|
+
var p = priced[r.vehicle_id];
|
|
29469
|
+
var section = el('section', 'smap-plan-route');
|
|
29470
|
+
section.setAttribute('data-vehicle', r.vehicle_id);
|
|
29471
|
+
var head = el('h3', 'smap-plan-route-head');
|
|
29472
|
+
var swatch = el('span', 'smap-plan-swatch');
|
|
29473
|
+
swatch.style.background = colorOf(editor, r.vehicle_id, o.colors);
|
|
29474
|
+
head.appendChild(swatch);
|
|
29475
|
+
head.appendChild(el('span', null, r.vehicle_id));
|
|
29476
|
+
section.appendChild(head);
|
|
29477
|
+
if (p) {
|
|
29478
|
+
totals(section, { distance_meters: p.distance_meters, duration_seconds: p.duration_seconds, violation_count: p.violation_count, unreachable_legs: p.unreachable_legs }, r.stops.length);
|
|
29479
|
+
if (p.violations && p.violations.length) {
|
|
29480
|
+
var ul = el('ul', 'smap-plan-route-violations');
|
|
29481
|
+
p.violations.forEach(function (v) { ul.appendChild(el('li', null, ruleText(v))); });
|
|
29482
|
+
section.appendChild(ul);
|
|
29483
|
+
}
|
|
29484
|
+
}
|
|
29485
|
+
var byId = {};
|
|
29486
|
+
((p && p.stops) || []).forEach(function (st) { if (st.type === 'job') { byId[st.id] = st; } });
|
|
29487
|
+
var ol = el('ol', 'smap-plan-stops-list');
|
|
29488
|
+
if (!r.stops.length) { ol.appendChild(el('li', 'smap-plan-empty', t.noStops)); }
|
|
29489
|
+
r.stops.forEach(function (id, i) {
|
|
29490
|
+
var st = byId[id];
|
|
29491
|
+
var li = el('li', 'smap-plan-stop' + (editor.isLocked(id) ? ' smap-plan-locked' : ''));
|
|
29492
|
+
draggable(li, id);
|
|
29493
|
+
li.appendChild(el('span', 'smap-plan-seq', String(i + 1)));
|
|
29494
|
+
li.appendChild(el('span', 'smap-plan-id', id));
|
|
29495
|
+
if (st && st.arrival) {
|
|
29496
|
+
// The clock time only, the full text for the pointer and screen readers: a stop row stays on one line.
|
|
29497
|
+
var arrival = el('span', 'smap-plan-arrival', fmt.clock(st.arrival));
|
|
29498
|
+
arrival.title = fill(t.arrival, { time: fmt.clock(st.arrival) });
|
|
29499
|
+
arrival.setAttribute('aria-label', arrival.title);
|
|
29500
|
+
li.appendChild(arrival);
|
|
29501
|
+
}
|
|
29502
|
+
var marks = [];
|
|
29503
|
+
if (st && st.reachable === false) { marks.push(t['rule.unreachable']); }
|
|
29504
|
+
((st && st.violations) || []).forEach(function (v) { marks.push(ruleText(v)); });
|
|
29505
|
+
if (marks.length) { li.appendChild(el('span', 'smap-plan-stop-violations', marks.join(', '))); }
|
|
29506
|
+
var locked = editor.isLocked(id);
|
|
29507
|
+
li.appendChild(button('smap-plan-lock', locked ? t.unlock : t.lock, function () { return locked ? editor.unlock(id) : editor.lock(id); }));
|
|
29508
|
+
li.appendChild(button('smap-plan-remove', t.remove, function () { return editor.remove([id]); }));
|
|
29509
|
+
dropZone(li, function (dragged) { return editor.dropStop(dragged, r.vehicle_id, i + 1); });
|
|
29510
|
+
ol.appendChild(li);
|
|
29511
|
+
});
|
|
29512
|
+
dropZone(ol, function (dragged) { return editor.dropStop(dragged, r.vehicle_id, r.stops.length + 1); });
|
|
29513
|
+
section.appendChild(ol);
|
|
29514
|
+
routes.appendChild(section);
|
|
29515
|
+
});
|
|
29516
|
+
root.appendChild(routes);
|
|
29517
|
+
|
|
29518
|
+
var un = el('section', 'smap-plan-unassigned');
|
|
29519
|
+
un.appendChild(el('h3', null, t.unassigned + ' (' + s.plan.unassigned.length + ')'));
|
|
29520
|
+
var ulu = el('ul', 'smap-plan-unassigned-list');
|
|
29521
|
+
s.plan.unassigned.forEach(function (id) {
|
|
29522
|
+
var li = el('li', 'smap-plan-job');
|
|
29523
|
+
draggable(li, id);
|
|
29524
|
+
li.appendChild(el('span', 'smap-plan-id', id));
|
|
29525
|
+
li.appendChild(button('smap-plan-place', t.place, function () { return editor.insert(id); }));
|
|
29526
|
+
ulu.appendChild(li);
|
|
29527
|
+
});
|
|
29528
|
+
dropZone(un, function (dragged) { return s.plan.unassigned.indexOf(dragged) >= 0 ? null : editor.remove([dragged]); });
|
|
29529
|
+
un.appendChild(ulu);
|
|
29530
|
+
root.appendChild(un);
|
|
29531
|
+
|
|
29532
|
+
if (s.choices && s.choices.length) {
|
|
29533
|
+
var ch = el('section', 'smap-plan-choices');
|
|
29534
|
+
s.choices.forEach(function (item) {
|
|
29535
|
+
ch.appendChild(el('h3', null, fill(t.choicesFor, { job: item.job })));
|
|
29536
|
+
if (!item.placed && !item.choices.length) { ch.appendChild(el('p', 'smap-plan-not-placed', t.notPlaced)); }
|
|
29537
|
+
var list = el('ol', 'smap-plan-choice-list');
|
|
29538
|
+
item.choices.forEach(function (c, i) {
|
|
29539
|
+
var li = el('li', 'smap-plan-choice' + (c.feasible ? '' : ' smap-plan-infeasible'));
|
|
29540
|
+
li.appendChild(el('span', 'smap-plan-choice-where', fill(t.choice, { vehicle: c.vehicle_id, n: c.position })));
|
|
29541
|
+
li.appendChild(el('span', 'smap-plan-choice-added', fill(t.added, { distance: fmt.distance(c.added_distance_meters), time: fmt.time(c.added_duration_seconds) })));
|
|
29542
|
+
if (c.arrival) { li.appendChild(el('span', 'smap-plan-arrival', fill(t.arrival, { time: fmt.clock(c.arrival) }))); }
|
|
29543
|
+
if (!c.feasible && c.violations && c.violations.length) {
|
|
29544
|
+
li.appendChild(el('span', 'smap-plan-stop-violations', c.violations.map(ruleText).join(', ')));
|
|
29545
|
+
}
|
|
29546
|
+
var chosen = item.chosen === i;
|
|
29547
|
+
li.appendChild(button('smap-plan-choose', chosen ? t.chosen : t.choose, function () { return editor.choose(item.job, i); }, chosen));
|
|
29548
|
+
list.appendChild(li);
|
|
29549
|
+
});
|
|
29550
|
+
ch.appendChild(list);
|
|
29551
|
+
});
|
|
29552
|
+
ch.appendChild(button('smap-plan-choices-close', t.close, function () { editor.clearChoices(); }));
|
|
29553
|
+
root.appendChild(ch);
|
|
29554
|
+
}
|
|
29555
|
+
}
|
|
29556
|
+
|
|
29557
|
+
var onAny = function () { render(); };
|
|
29558
|
+
['change', 'busy', 'preview'].forEach(function (type) { editor.on(type, onAny); });
|
|
29559
|
+
var gone = function () { api.destroy(); };
|
|
29560
|
+
editor.on('destroy', gone);
|
|
29561
|
+
render();
|
|
29562
|
+
var api = {
|
|
29563
|
+
element: root,
|
|
29564
|
+
render: render,
|
|
29565
|
+
setLanguage: function (lang) { language = lang; t = textsFor(lang, o.labels); fmt = formatters(lang, t); render(); },
|
|
29566
|
+
destroy: function () {
|
|
29567
|
+
['change', 'busy', 'preview'].forEach(function (type) { editor.off(type, onAny); });
|
|
29568
|
+
editor.off('destroy', gone);
|
|
29569
|
+
if (root.parentNode) { root.parentNode.removeChild(root); }
|
|
29570
|
+
},
|
|
29571
|
+
};
|
|
29572
|
+
return api;
|
|
29573
|
+
}
|
|
29574
|
+
|
|
29575
|
+
// ------------------------------------------------------------------ the map layer (sMap)
|
|
29576
|
+
|
|
29577
|
+
/** The features drawn for the editor's plan: legs, stops, unassigned jobs and vehicle starts. */
|
|
29578
|
+
function planFeatures(editor, id, colors) {
|
|
29579
|
+
var e = editor._history[editor._at];
|
|
29580
|
+
var out = { legs: [], stops: [], unassigned: [], starts: [] };
|
|
29581
|
+
if (!e) { return out; }
|
|
29582
|
+
var jobs = {};
|
|
29583
|
+
e.jobs.forEach(function (j) { jobs[String(j.id)] = j; });
|
|
29584
|
+
var vehicles = {};
|
|
29585
|
+
editor._vehicles.forEach(function (v) { vehicles[String(v.id)] = v; });
|
|
29586
|
+
var priced = {};
|
|
29587
|
+
((e.result && e.result.routes) || []).forEach(function (r) { priced[r.vehicle_id] = r; });
|
|
29588
|
+
function feature(geometry, props) { props.smap_plan = id; return { type: 'Feature', properties: props, geometry: geometry }; }
|
|
29589
|
+
e.routes.forEach(function (r) {
|
|
29590
|
+
var v = vehicles[r.vehicle_id] || {};
|
|
29591
|
+
var color = colorOf(editor, r.vehicle_id, colors);
|
|
29592
|
+
var start = lngLat(v.start);
|
|
29593
|
+
var end = lngLat(v.end) || (v.return_to_start ? start : null);
|
|
29594
|
+
if (start) { out.starts.push(feature({ type: 'Point', coordinates: start }, { kind: 'start', vehicle_id: r.vehicle_id, position: 1, color: color })); }
|
|
29595
|
+
var p = priced[r.vehicle_id];
|
|
29596
|
+
// The answer's legs (with their lines) while the drawn order is the answered one; straight lines before.
|
|
29597
|
+
var answered = p && p.stops && p.stops.filter(function (s) { return s.type === 'job'; }).map(function (s) { return s.id; }).join('\u0000') === r.stops.join('\u0000');
|
|
29598
|
+
var prev = start;
|
|
29599
|
+
var points = r.stops.map(function (s) { return lngLat(jobs[s] && jobs[s].location); });
|
|
29600
|
+
if (answered) {
|
|
29601
|
+
var k = 0;
|
|
29602
|
+
p.stops.forEach(function (st) {
|
|
29603
|
+
if (st.type === 'start') { return; }
|
|
29604
|
+
var position = st.type === 'job' ? (k += 1) : r.stops.length + 1;
|
|
29605
|
+
var to = st.type === 'job' ? points[position - 1] : end;
|
|
29606
|
+
var line = st.leg_geometry ? decodePolyline(st.leg_geometry) : (prev && to ? [prev, to] : null);
|
|
29607
|
+
if (line && line.length > 1) { out.legs.push(feature({ type: 'LineString', coordinates: line }, { kind: 'leg', vehicle_id: r.vehicle_id, position: position, color: color })); }
|
|
29608
|
+
if (to) { prev = to; }
|
|
29609
|
+
});
|
|
29610
|
+
} else {
|
|
29611
|
+
points.concat(end ? [end] : []).forEach(function (to, i) {
|
|
29612
|
+
if (prev && to) { out.legs.push(feature({ type: 'LineString', coordinates: [prev, to] }, { kind: 'leg', vehicle_id: r.vehicle_id, position: i + 1, color: color })); }
|
|
29613
|
+
if (to) { prev = to; }
|
|
29614
|
+
});
|
|
29615
|
+
}
|
|
29616
|
+
var stopInfo = {};
|
|
29617
|
+
((p && p.stops) || []).forEach(function (st) { if (st.type === 'job') { stopInfo[st.id] = st; } });
|
|
29618
|
+
r.stops.forEach(function (s, i) {
|
|
29619
|
+
if (!points[i]) { return; }
|
|
29620
|
+
var st = answered ? stopInfo[s] : null;
|
|
29621
|
+
var violated = !!(st && ((st.violations && st.violations.length) || st.reachable === false));
|
|
29622
|
+
var locked = editor.isLocked(s);
|
|
29623
|
+
out.stops.push(feature({ type: 'Point', coordinates: points[i] }, {
|
|
29624
|
+
kind: 'stop', id: s, vehicle_id: r.vehicle_id, position: i + 1, label: String(i + 1), color: color,
|
|
29625
|
+
border: violated ? '#b91c1c' : (locked ? '#111827' : color), locked: locked, violated: violated,
|
|
29626
|
+
}));
|
|
29627
|
+
});
|
|
29628
|
+
});
|
|
29629
|
+
unassignedOf(e.jobs, e.routes).forEach(function (s) {
|
|
29630
|
+
var at = lngLat(jobs[s] && jobs[s].location);
|
|
29631
|
+
if (at) { out.unassigned.push(feature({ type: 'Point', coordinates: at }, { kind: 'unassigned', id: s, color: '#6b7280' })); }
|
|
29632
|
+
});
|
|
29633
|
+
return out;
|
|
29634
|
+
}
|
|
29635
|
+
|
|
29636
|
+
// Where a drop at these features goes: before a stop, into a leg (before the stop it leads to), or first after a start.
|
|
29637
|
+
function dropTarget(hits, dragged) {
|
|
29638
|
+
for (var i = 0; i < hits.length; i++) {
|
|
29639
|
+
var p = hits[i].properties || {};
|
|
29640
|
+
if (p.kind === 'stop' && p.id !== dragged) { return { vehicle_id: p.vehicle_id, position: Number(p.position) }; }
|
|
29641
|
+
}
|
|
29642
|
+
for (var k = 0; k < hits.length; k++) {
|
|
29643
|
+
var q = hits[k].properties || {};
|
|
29644
|
+
if (q.kind === 'leg' || q.kind === 'start') { return { vehicle_id: q.vehicle_id, position: Number(q.position) }; }
|
|
29645
|
+
}
|
|
29646
|
+
return null;
|
|
29647
|
+
}
|
|
29648
|
+
|
|
29649
|
+
var DRAG_PX = 4;
|
|
29650
|
+
var PREVIEW_MS = 250;
|
|
29651
|
+
|
|
29652
|
+
// ------------------------------------------------------------------ parts for other map libraries
|
|
29653
|
+
//
|
|
29654
|
+
// What a binding on another map library (the tool adapters, a page of your own) needs besides the editor: the
|
|
29655
|
+
// features to draw, where a drop lands, a drag with its preview, the panel and its stylesheet.
|
|
29656
|
+
|
|
29657
|
+
/** The routes after dropping stopId at `target` ({ vehicle_id, position } as dropTarget gives it); null: no change. */
|
|
29658
|
+
function dropRoutes(editor, stopId, target) {
|
|
29659
|
+
var e = editor._history[editor._at];
|
|
29660
|
+
if (!e || !target) { return null; }
|
|
29661
|
+
var id = String(stopId);
|
|
29662
|
+
var edit = dropEdit(e.routes, id, String(target.vehicle_id), Number(target.position));
|
|
29663
|
+
if (!edit) { return null; }
|
|
29664
|
+
return edit.kind === 'resequence' ? applyResequence(e.routes, edit.vehicle_id, edit.stops) : applyMove(e.routes, [id], edit.vehicle_id, edit.position);
|
|
29665
|
+
}
|
|
29666
|
+
|
|
29667
|
+
function segmentDistance(p, a, b) {
|
|
29668
|
+
var dx = b.x - a.x;
|
|
29669
|
+
var dy = b.y - a.y;
|
|
29670
|
+
var l = dx * dx + dy * dy;
|
|
29671
|
+
var t = l ? Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l)) : 0;
|
|
29672
|
+
var x = a.x + t * dx - p.x;
|
|
29673
|
+
var y = a.y + t * dy - p.y;
|
|
29674
|
+
return Math.sqrt(x * x + y * y);
|
|
29675
|
+
}
|
|
29676
|
+
|
|
29677
|
+
/**
|
|
29678
|
+
* The features within `tolerance` pixels of a screen point, nearest first, for libraries that cannot tell which
|
|
29679
|
+
* drawn feature is under the pointer. `features`: planFeatures' answer or a list; `project([lng, lat])` gives
|
|
29680
|
+
* { x, y } in the same pixels as `point`.
|
|
29681
|
+
* @param {Object} [o] tolerance (default 12 px for points, 8 px for lines)
|
|
29682
|
+
*/
|
|
29683
|
+
function featuresAt(features, project, point, o) {
|
|
29684
|
+
o = o || {};
|
|
29685
|
+
var list = Array.isArray(features) ? features : [].concat(features.stops || [], features.unassigned || [], features.starts || [], features.legs || []);
|
|
29686
|
+
var hits = [];
|
|
29687
|
+
list.forEach(function (f, order) {
|
|
29688
|
+
var g = f && f.geometry;
|
|
29689
|
+
if (!g) { return; }
|
|
29690
|
+
var d = Infinity;
|
|
29691
|
+
if (g.type === 'Point') {
|
|
29692
|
+
var q = project(g.coordinates);
|
|
29693
|
+
d = Math.sqrt((q.x - point.x) * (q.x - point.x) + (q.y - point.y) * (q.y - point.y));
|
|
29694
|
+
if (d > (o.tolerance === undefined ? 12 : o.tolerance)) { return; }
|
|
29695
|
+
} else if (g.type === 'LineString') {
|
|
29696
|
+
var pts = g.coordinates.map(project);
|
|
29697
|
+
for (var i = 1; i < pts.length; i++) { d = Math.min(d, segmentDistance(point, pts[i - 1], pts[i])); }
|
|
29698
|
+
if (d > (o.tolerance === undefined ? 8 : o.tolerance)) { return; }
|
|
29699
|
+
} else { return; }
|
|
29700
|
+
hits.push({ f: f, d: d, order: order });
|
|
29701
|
+
});
|
|
29702
|
+
hits.sort(function (a, b) { return a.d - b.d || a.order - b.order; });
|
|
29703
|
+
return hits.map(function (h) { return h.f; });
|
|
29704
|
+
}
|
|
29705
|
+
|
|
29706
|
+
/**
|
|
29707
|
+
* A stop dragged on a map: start(stopId, point?) when the pointer goes down on a stop or an unassigned job,
|
|
29708
|
+
* move(hits, point?) with the features under the pointer (it becomes a drag past `threshold` pixels, and the plan
|
|
29709
|
+
* with the stop at the target is priced as a preview after `previewMs`), end(hits?) drops it (editor.dropStop; the
|
|
29710
|
+
* last target when no hits are given), cancel() gives it up.
|
|
29711
|
+
* @param {Object} [o] preview (default true), previewMs (250), threshold (4 px)
|
|
29712
|
+
*/
|
|
29713
|
+
function planDrag(editor, o) {
|
|
29714
|
+
o = o || {};
|
|
29715
|
+
var preview = o.preview !== false;
|
|
29716
|
+
var threshold = o.threshold === undefined ? DRAG_PX : o.threshold;
|
|
29717
|
+
var previewMs = o.previewMs === undefined ? PREVIEW_MS : o.previewMs;
|
|
29718
|
+
var drag = null;
|
|
29719
|
+
var timer = null;
|
|
29720
|
+
function stopTimer() { if (timer) { clearTimeout(timer); timer = null; } }
|
|
29721
|
+
return {
|
|
29722
|
+
start: function (stopId, point) {
|
|
29723
|
+
stopTimer();
|
|
29724
|
+
drag = { id: String(stopId), start: point || null, moved: false, target: null, key: null };
|
|
29725
|
+
},
|
|
29726
|
+
move: function (hits, point) {
|
|
29727
|
+
if (!drag) { return null; }
|
|
29728
|
+
if (!drag.moved && point && drag.start && Math.abs(point.x - drag.start.x) + Math.abs(point.y - drag.start.y) < threshold) { return null; }
|
|
29729
|
+
drag.moved = true;
|
|
29730
|
+
var target = dropTarget(hits || [], drag.id);
|
|
29731
|
+
var key = target ? target.vehicle_id + '#' + target.position : null;
|
|
29732
|
+
if (key === drag.key) { return target; }
|
|
29733
|
+
drag.key = key;
|
|
29734
|
+
drag.target = target;
|
|
29735
|
+
stopTimer();
|
|
29736
|
+
if (!preview) { return target; }
|
|
29737
|
+
var routes = dropRoutes(editor, drag.id, target);
|
|
29738
|
+
if (!routes) { editor.clearPreview(); return target; }
|
|
29739
|
+
timer = setTimeout(function () { timer = null; editor.preview(routes); }, previewMs);
|
|
29740
|
+
return target;
|
|
29741
|
+
},
|
|
29742
|
+
end: function (hits) {
|
|
29743
|
+
if (!drag) { return Promise.resolve(null); }
|
|
29744
|
+
var d = drag;
|
|
29745
|
+
drag = null;
|
|
29746
|
+
stopTimer();
|
|
29747
|
+
if (!d.moved) { return Promise.resolve(null); }
|
|
29748
|
+
var target = hits ? dropTarget(hits, d.id) : d.target;
|
|
29749
|
+
editor.clearPreview();
|
|
29750
|
+
if (!target) { return Promise.resolve(null); }
|
|
29751
|
+
return editor.dropStop(d.id, target.vehicle_id, target.position).catch(function () { return null; });
|
|
29752
|
+
},
|
|
29753
|
+
cancel: function () {
|
|
29754
|
+
var d = drag;
|
|
29755
|
+
drag = null;
|
|
29756
|
+
stopTimer();
|
|
29757
|
+
if (d && d.moved) { editor.clearPreview(); }
|
|
29758
|
+
},
|
|
29759
|
+
dragging: function () { return drag ? drag.id : null; },
|
|
29760
|
+
moved: function () { return !!(drag && drag.moved); },
|
|
29761
|
+
target: function () { return drag ? drag.target : null; },
|
|
29762
|
+
};
|
|
29763
|
+
}
|
|
29764
|
+
|
|
29765
|
+
// The panel's stylesheet (the .smap-plan-* rules of smap.css), filled in by js/build.mjs.
|
|
29766
|
+
var PANEL_CSS = "/* Plan editor panel (OPEN-ROUTE-EDIT E10). Restyle through these classes; every colour is set here. */\n.smap-plan-panel {\n width: 320px; max-width: calc(100vw - 20px); max-height: 70vmin; overflow-y: auto; padding: 10px; box-sizing: border-box;\n border-radius: 8px; background: #ffffff; color: #1e293b; box-shadow: 0 2px 10px rgba(15, 23, 42, 0.18);\n font: 12px/1.35 -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;\n}\n.smap-plan-panel h3 { margin: 10px 0 4px; font-size: 13px; font-weight: 600; }\n.smap-plan-panel h4 { margin: 6px 0 2px; font-size: 12px; font-weight: 600; }\n.smap-plan-bar { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }\n.smap-plan-button {\n min-height: 26px; padding: 3px 8px; border: 1px solid rgba(15, 23, 42, 0.18); border-radius: 6px; background: #ffffff;\n color: inherit; font: inherit; cursor: pointer;\n}\n.smap-plan-button:disabled { opacity: 0.45; cursor: default; }\n.smap-plan-button:focus-visible { outline: 2px solid #2563eb; outline-offset: 1px; }\n.smap-plan-status { margin-left: auto; color: #2563eb; }\n.smap-plan-error { display: flex; align-items: center; gap: 6px; margin-top: 8px; padding: 6px 8px; border-radius: 6px; background: #fef2f2; color: #991b1b; }\n.smap-plan-error span { flex: 1 1 auto; }\n.smap-plan-note { margin-top: 8px; color: #475569; }\n.smap-plan-totals { display: flex; flex-wrap: wrap; gap: 2px 12px; margin: 2px 0 4px; }\n.smap-plan-totals div { display: flex; gap: 4px; }\n.smap-plan-totals dt { color: #64748b; }\n.smap-plan-totals dd { margin: 0; font-weight: 600; }\n.smap-plan-violations dd, .smap-plan-unreachable dd, .smap-plan-route-violations, .smap-plan-stop-violations { color: #b91c1c; }\n.smap-plan-preview { margin-top: 4px; padding: 4px 6px; border-radius: 6px; background: #eff6ff; }\n.smap-plan-pending { margin: 2px 0; color: #64748b; }\n.smap-plan-route-head { display: flex; align-items: center; gap: 6px; }\n.smap-plan-swatch { width: 10px; height: 10px; border-radius: 50%; flex: 0 0 auto; }\n.smap-plan-route-violations { margin: 2px 0; padding-left: 16px; }\n.smap-plan-stops-list, .smap-plan-unassigned-list, .smap-plan-choice-list { margin: 0; padding: 0; list-style: none; min-height: 8px; }\n.smap-plan-stop, .smap-plan-job, .smap-plan-choice {\n display: flex; flex-wrap: wrap; align-items: center; gap: 4px 6px; padding: 3px 4px; border-radius: 4px;\n}\n.smap-plan-stop, .smap-plan-job { flex-wrap: nowrap; }\n.smap-plan-stop .smap-plan-id, .smap-plan-job .smap-plan-id { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.smap-plan-stop .smap-plan-arrival { white-space: nowrap; }\n.smap-plan-stop .smap-plan-stop-violations { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; }\n.smap-plan-stop, .smap-plan-job { cursor: grab; }\n.smap-plan-stop:hover, .smap-plan-job:hover { background: #f1f5f9; }\n.smap-plan-over { outline: 2px dashed #2563eb; outline-offset: -2px; }\n.smap-plan-seq { min-width: 18px; color: #64748b; text-align: right; }\n.smap-plan-id { font-weight: 600; }\n.smap-plan-arrival { color: #475569; }\n.smap-plan-stop .smap-plan-button, .smap-plan-job .smap-plan-button, .smap-plan-choice .smap-plan-button { min-height: 22px; padding: 1px 6px; }\n.smap-plan-stop .smap-plan-lock { margin-left: auto; }\n.smap-plan-job .smap-plan-place, .smap-plan-choice .smap-plan-choose { margin-left: auto; }\n.smap-plan-locked .smap-plan-id::after { content: \" \\1F512\"; font-weight: 400; }\n.smap-plan-empty { color: #94a3b8; cursor: default; }\n.smap-plan-infeasible .smap-plan-choice-where { color: #b91c1c; }\n.smap-plan-choices { margin-top: 8px; padding-top: 4px; border-top: 1px solid rgba(15, 23, 42, 0.12); }\n.smap-plan-choices-close { margin-top: 6px; }\n.smap-style-dark .smap-plan-panel, .smap-style-black .smap-plan-panel { background: #1f2430; color: #e5e7eb; }\n.smap-style-dark .smap-plan-button, .smap-style-black .smap-plan-button { background: #1f2430; border-color: rgba(229, 231, 235, 0.2); }\n.smap-style-dark .smap-plan-stop:hover, .smap-style-black .smap-plan-stop:hover,\n.smap-style-dark .smap-plan-job:hover, .smap-style-black .smap-plan-job:hover { background: #2b3242; }\n";
|
|
29767
|
+
|
|
29768
|
+
/** Adds the panel's stylesheet to a document once (pages that load smap.css have it already). */
|
|
29769
|
+
function injectCss(doc) {
|
|
29770
|
+
if (!doc || !doc.head || PANEL_CSS.indexOf('__SMAP') === 0 || doc.getElementById('smap-plan-css')) { return; }
|
|
29771
|
+
var style = doc.createElement('style');
|
|
29772
|
+
style.id = 'smap-plan-css';
|
|
29773
|
+
style.textContent = PANEL_CSS;
|
|
29774
|
+
doc.head.appendChild(style);
|
|
29775
|
+
}
|
|
29776
|
+
|
|
29777
|
+
/**
|
|
29778
|
+
* Draws the editor's plan on an sMap map as layers `<id>:legs`, `<id>:starts`, `<id>:stops`, `<id>:unassigned`, and
|
|
29779
|
+
* lets a stop (or an unassigned job) be dragged before another stop or onto a route's line.
|
|
29780
|
+
* @returns {{ remove(): void, features(): Object }}
|
|
29781
|
+
*/
|
|
29782
|
+
function attachToMap(map, editor, o) {
|
|
29783
|
+
o = o || {};
|
|
29784
|
+
var id = o.id || 'plan';
|
|
29785
|
+
var ids = { legs: id + ':legs', starts: id + ':starts', stops: id + ':stops', unassigned: id + ':unassigned', drag: id + ':drag' };
|
|
29786
|
+
var added = false;
|
|
29787
|
+
var removed = false;
|
|
29788
|
+
var drag = planDrag(editor, { preview: o.preview !== false });
|
|
29789
|
+
|
|
29790
|
+
function draw() {
|
|
29791
|
+
if (removed) { return; }
|
|
29792
|
+
var f = planFeatures(editor, id, o.colors);
|
|
29793
|
+
var fc = function (list) { return { type: 'FeatureCollection', features: list }; };
|
|
29794
|
+
if (!added) {
|
|
29795
|
+
map.addLines(ids.legs, fc(f.legs), { color: { property: 'color' }, width: 4, casing: true, arrows: true, zIndex: o.zIndex });
|
|
29796
|
+
map.addPoints(ids.starts, fc(f.starts), { marker: { shape: 'circle', fill: { property: 'color' }, border: '#ffffff', size: 18, text: '', overlap: false } });
|
|
29797
|
+
map.addPoints(ids.unassigned, fc(f.unassigned), { marker: { shape: 'circle', fill: '#9ca3af', border: '#ffffff', size: 18, text: '', overlap: false } });
|
|
29798
|
+
map.addPoints(ids.stops, fc(f.stops), { marker: { shape: 'pin', fill: { property: 'color' }, border: { property: 'border' }, text: { property: 'label' }, overlap: false } });
|
|
29799
|
+
map.addPoints(ids.drag, fc([]), { marker: { shape: 'circle', fill: '#111827', border: '#ffffff', size: 16, text: '', overlap: false } });
|
|
29800
|
+
added = true;
|
|
29801
|
+
} else {
|
|
29802
|
+
map.setData(ids.legs, fc(f.legs));
|
|
29803
|
+
map.setData(ids.starts, fc(f.starts));
|
|
29804
|
+
map.setData(ids.unassigned, fc(f.unassigned));
|
|
29805
|
+
map.setData(ids.stops, fc(f.stops));
|
|
29806
|
+
}
|
|
29807
|
+
}
|
|
29808
|
+
|
|
29809
|
+
function engine() { return map.engine; }
|
|
29810
|
+
function hitsAt(point) {
|
|
29811
|
+
var eng = engine();
|
|
29812
|
+
if (!eng || typeof eng.queryRenderedFeatures !== 'function') { return []; }
|
|
29813
|
+
var box = [[point.x - 6, point.y - 6], [point.x + 6, point.y + 6]];
|
|
29814
|
+
return (eng.queryRenderedFeatures(box) || []).filter(function (f) { return f && f.properties && f.properties.smap_plan === id; });
|
|
29815
|
+
}
|
|
29816
|
+
function setPan(on) {
|
|
29817
|
+
var eng = engine();
|
|
29818
|
+
if (eng && eng.dragPan) { if (on) { eng.dragPan.enable(); } else { eng.dragPan.disable(); } }
|
|
29819
|
+
}
|
|
29820
|
+
|
|
29821
|
+
function down(e) {
|
|
29822
|
+
if (removed || (e.originalEvent && e.originalEvent.button) || !e.point) { return; }
|
|
29823
|
+
var hit = hitsAt(e.point).filter(function (f) { return f.properties.kind === 'stop' || f.properties.kind === 'unassigned'; })[0];
|
|
29824
|
+
if (!hit) { return; }
|
|
29825
|
+
drag.start(hit.properties.id, e.point);
|
|
29826
|
+
setPan(false);
|
|
29827
|
+
if (e.preventDefault) { e.preventDefault(); }
|
|
29828
|
+
}
|
|
29829
|
+
function move(e) {
|
|
29830
|
+
if (!drag.dragging() || !e.point) { return; }
|
|
29831
|
+
drag.move(hitsAt(e.point), e.point);
|
|
29832
|
+
if (drag.moved() && e.lngLat) { map.setData(ids.drag, [{ lng: e.lngLat.lng, lat: e.lngLat.lat }]); }
|
|
29833
|
+
}
|
|
29834
|
+
function up(e) {
|
|
29835
|
+
if (!drag.dragging()) { return; }
|
|
29836
|
+
setPan(true);
|
|
29837
|
+
map.setData(ids.drag, []);
|
|
29838
|
+
drag.end(e && e.point ? hitsAt(e.point) : null);
|
|
29839
|
+
}
|
|
29840
|
+
|
|
29841
|
+
var listening = false;
|
|
29842
|
+
function listen() {
|
|
29843
|
+
var eng = engine();
|
|
29844
|
+
if (!eng || listening || removed) { return; }
|
|
29845
|
+
listening = true;
|
|
29846
|
+
eng.on('mousedown', down);
|
|
29847
|
+
eng.on('mousemove', move);
|
|
29848
|
+
eng.on('mouseup', up);
|
|
29849
|
+
eng.on('touchstart', down);
|
|
29850
|
+
eng.on('touchmove', move);
|
|
29851
|
+
eng.on('touchend', up);
|
|
29852
|
+
}
|
|
29853
|
+
function onChange() { if (ready) { draw(); } }
|
|
29854
|
+
editor.on('change', onChange);
|
|
29855
|
+
var gone = function () { api.remove(); };
|
|
29856
|
+
editor.on('destroy', gone);
|
|
29857
|
+
var ready = false;
|
|
29858
|
+
var started = map.ready && typeof map.ready.then === 'function' ? map.ready : Promise.resolve(map);
|
|
29859
|
+
started.then(function () { ready = true; if (!removed) { draw(); listen(); } });
|
|
29860
|
+
|
|
29861
|
+
var api = {
|
|
29862
|
+
features: function () { return planFeatures(editor, id, o.colors); },
|
|
29863
|
+
remove: function () {
|
|
29864
|
+
if (removed) { return; }
|
|
29865
|
+
removed = true;
|
|
29866
|
+
drag.cancel();
|
|
29867
|
+
editor.off('change', onChange);
|
|
29868
|
+
editor.off('destroy', gone);
|
|
29869
|
+
var eng = engine();
|
|
29870
|
+
if (eng && listening) {
|
|
29871
|
+
eng.off('mousedown', down); eng.off('mousemove', move); eng.off('mouseup', up);
|
|
29872
|
+
eng.off('touchstart', down); eng.off('touchmove', move); eng.off('touchend', up);
|
|
29873
|
+
setPan(true);
|
|
29874
|
+
}
|
|
29875
|
+
if (added) { Object.keys(ids).forEach(function (k) { try { map.removeLayer(ids[k]); } catch (x) { /* already gone */ } }); }
|
|
29876
|
+
},
|
|
29877
|
+
// For tests and adapters: a drag as the map reports it.
|
|
29878
|
+
_down: down, _move: move, _up: up,
|
|
29879
|
+
};
|
|
29880
|
+
return api;
|
|
29881
|
+
}
|
|
29882
|
+
|
|
29883
|
+
/**
|
|
29884
|
+
* An editor on an sMap map: its layers, and the panel as the map tool `plan-editor` (unless `panel: false`).
|
|
29885
|
+
* options as PlanEditor, plus id (layer prefix), colors, preview (default true), panel (true | false |
|
|
29886
|
+
* { position, label, labels, className }), language (default the map's).
|
|
29887
|
+
*/
|
|
29888
|
+
function attach(map, options) {
|
|
29889
|
+
options = options || {};
|
|
29890
|
+
var editor = new PlanEditor(Object.assign({}, options, { plan: null }));
|
|
29891
|
+
var layer = attachToMap(map, editor, options);
|
|
29892
|
+
var toolId = null;
|
|
29893
|
+
var destroyed = false;
|
|
29894
|
+
editor.panel = null;
|
|
29895
|
+
editor.layer = layer;
|
|
29896
|
+
// The panel is made from the map's own page (the engine's container), so it waits for the map's engine.
|
|
29897
|
+
function mountPanel() {
|
|
29898
|
+
if (destroyed || options.panel === false) { return; }
|
|
29899
|
+
var po = typeof options.panel === 'object' && options.panel ? options.panel : {};
|
|
29900
|
+
var container = map.engine && map.engine.getContainer ? map.engine.getContainer() : null;
|
|
29901
|
+
var doc = options.document || (container && container.ownerDocument) || (typeof document !== 'undefined' ? document : null);
|
|
29902
|
+
if (!doc) { return; }
|
|
29903
|
+
var language = options.language || map._language || 'en';
|
|
29904
|
+
var labels = po.labels || options.labels;
|
|
29905
|
+
editor.panel = createPanel(editor, { language: language, labels: labels, document: doc, colors: options.colors, className: po.className });
|
|
29906
|
+
toolId = po.id || ((options.id || 'plan') + '-editor');
|
|
29907
|
+
map.addTool(toolId, editor.panel.element, { label: po.label || textsFor(language, labels).editor, position: po.position || 'top-left' });
|
|
29908
|
+
}
|
|
29909
|
+
if (map.engine || options.document) { mountPanel(); }
|
|
29910
|
+
else if (map.ready && typeof map.ready.then === 'function') { map.ready.then(mountPanel, function () {}); }
|
|
29911
|
+
var destroy = editor.destroy;
|
|
29912
|
+
editor.destroy = function () {
|
|
29913
|
+
destroyed = true;
|
|
29914
|
+
if (toolId) { try { map.removeTool(toolId); } catch (x) { /* map removed */ } }
|
|
29915
|
+
destroy.call(editor);
|
|
29916
|
+
};
|
|
29917
|
+
if (options.plan) { editor.setPlan(options.plan).catch(function () {}); }
|
|
29918
|
+
return editor;
|
|
29919
|
+
}
|
|
29920
|
+
|
|
29921
|
+
return {
|
|
29922
|
+
PlanEditor: PlanEditor,
|
|
29923
|
+
attach: attach,
|
|
29924
|
+
attachToMap: attachToMap,
|
|
29925
|
+
createPanel: createPanel,
|
|
29926
|
+
createTransport: createTransport,
|
|
29927
|
+
planFeatures: planFeatures,
|
|
29928
|
+
dropEdit: dropEdit,
|
|
29929
|
+
applyResequence: applyResequence,
|
|
29930
|
+
applyMove: applyMove,
|
|
29931
|
+
applyRemove: applyRemove,
|
|
29932
|
+
decodePolyline: decodePolyline,
|
|
29933
|
+
texts: TEXTS,
|
|
29934
|
+
textKeys: TEXT_KEYS,
|
|
29935
|
+
languages: LANGUAGES,
|
|
29936
|
+
panelLanguage: panelLanguage,
|
|
29937
|
+
numberLocale: numberLocale,
|
|
29938
|
+
formatters: formatters,
|
|
29939
|
+
// The parts a binding on another map library builds on (exported as planEditorParts).
|
|
29940
|
+
parts: {
|
|
29941
|
+
planFeatures: planFeatures, dropTarget: dropTarget, dropEdit: dropEdit, dropRoutes: dropRoutes,
|
|
29942
|
+
featuresAt: featuresAt, planDrag: planDrag, createPanel: createPanel, injectCss: injectCss, textsFor: textsFor,
|
|
29943
|
+
panelLanguage: panelLanguage, decodePolyline: decodePolyline, colors: COLORS.slice(),
|
|
29944
|
+
},
|
|
29945
|
+
};
|
|
29946
|
+
});
|
|
29947
|
+
|
|
29948
|
+
return module.exports;
|
|
29949
|
+
}
|
|
29950
|
+
function smapCreateSdk(engine, interop, plan) {
|
|
28329
29951
|
var module = { exports: {} };
|
|
28330
29952
|
var exports = module.exports;
|
|
28331
29953
|
var define;
|
|
28332
29954
|
var require = function (name) { throw new Error('sMap: unexpected require of ' + name); };
|
|
28333
|
-
var self = { maplibregl: engine, smapInterop: interop };
|
|
29955
|
+
var self = { maplibregl: engine, smapInterop: interop, smapPlan: plan };
|
|
28334
29956
|
/*!
|
|
28335
29957
|
* sMap Web SDK — maps from Superroute's sMap service.
|
|
28336
29958
|
*
|
|
@@ -28343,14 +29965,15 @@ function smapCreateSdk(engine, interop) {
|
|
|
28343
29965
|
(function (root, factory) {
|
|
28344
29966
|
if (typeof module === 'object' && module.exports) {
|
|
28345
29967
|
module.exports = factory(root.maplibregl !== undefined ? root.maplibregl : require('maplibre-gl'),
|
|
28346
|
-
root.smapInterop !== undefined ? root.smapInterop : require('./smap-interop.js')
|
|
29968
|
+
root.smapInterop !== undefined ? root.smapInterop : require('./smap-interop.js'),
|
|
29969
|
+
root.smapPlan !== undefined ? root.smapPlan : (typeof require === 'function' ? require('./smap-plan.js') : null));
|
|
28347
29970
|
} else {
|
|
28348
|
-
root.sMap = factory(root.maplibregl, root.smapInterop);
|
|
29971
|
+
root.sMap = factory(root.maplibregl, root.smapInterop, root.smapPlan);
|
|
28349
29972
|
}
|
|
28350
|
-
})(typeof self !== 'undefined' ? self : this, function (engine, interop) {
|
|
29973
|
+
})(typeof self !== 'undefined' ? self : this, function (engine, interop, plan) {
|
|
28351
29974
|
'use strict';
|
|
28352
29975
|
|
|
28353
|
-
var VERSION = '1.1.
|
|
29976
|
+
var VERSION = '1.1.6';
|
|
28354
29977
|
var FLAVORS = ['light', 'white', 'grayscale', 'dark', 'black'];
|
|
28355
29978
|
var BASEMAP_SOURCE = 'basemap';
|
|
28356
29979
|
var BUILDINGS_LAYER = 'smap-buildings-3d';
|
|
@@ -28808,7 +30431,9 @@ function smapCreateSdk(engine, interop) {
|
|
|
28808
30431
|
this._tools = [];
|
|
28809
30432
|
this._toolsHidden = {};
|
|
28810
30433
|
(toolOptions.hidden || []).forEach(function (id) { this._toolsHidden[id] = true; }, this);
|
|
28811
|
-
|
|
30434
|
+
// 1.1.6: by default the tools control is the last button of the map's toolbar (the corner holding the
|
|
30435
|
+
// navigation control, top left without one); a corner given by the caller is kept as in 1.1.5.
|
|
30436
|
+
this._toolsControlAt = toolOptions.control === undefined || toolOptions.control === true ? 'toolbar' : toolOptions.control;
|
|
28812
30437
|
this._toolsLabels = toolOptions.labels || {};
|
|
28813
30438
|
this._toolsControl = null;
|
|
28814
30439
|
this._toolHandlers = [];
|
|
@@ -28850,7 +30475,7 @@ function smapCreateSdk(engine, interop) {
|
|
|
28850
30475
|
badge._place();
|
|
28851
30476
|
}
|
|
28852
30477
|
self._mountTools();
|
|
28853
|
-
self.engine.on('style.load', function () { self._styleReady = true; self._restore(); });
|
|
30478
|
+
self.engine.on('style.load', function () { self._styleReady = true; self._restore(); self._hideLayerTools(); });
|
|
28854
30479
|
self._keyboard3D();
|
|
28855
30480
|
// One click handler for every layer's popup: the engine's hit test over those layers, the top feature opens.
|
|
28856
30481
|
self.engine.on('click', function (e) { self._popupClick(e); });
|
|
@@ -29288,6 +30913,7 @@ function smapCreateSdk(engine, interop) {
|
|
|
29288
30913
|
if (!def) { return this; }
|
|
29289
30914
|
def.hidden = !visible;
|
|
29290
30915
|
var m = this.engine;
|
|
30916
|
+
if (!m) { return this; }
|
|
29291
30917
|
def.engineLayers.forEach(function (l) { if (m.getLayer(l)) { m.setLayoutProperty(l, 'visibility', visible ? 'visible' : 'none'); } });
|
|
29292
30918
|
return this;
|
|
29293
30919
|
};
|
|
@@ -29390,9 +31016,13 @@ function smapCreateSdk(engine, interop) {
|
|
|
29390
31016
|
* map.addTool('legend', document.getElementById('legend'), { label: 'Legend', position: 'bottom-left' })
|
|
29391
31017
|
* map.addTool('zoom', 'navigation', { options: { showCompass: false } })
|
|
29392
31018
|
* @param {string} id 1-64 letters, digits, '-', '_', '.'; adding an id again replaces the first
|
|
29393
|
-
*
|
|
31019
|
+
* map.addTool('stops', { layer: ['stops', 'stop-labels'] }, { label: 'Stops' })
|
|
31020
|
+
* @param {Element|Object|string} target a page element, an engine control (onAdd / onRemove), a kind the SDK
|
|
29394
31021
|
* makes: 'navigation', 'geolocate', 'fullscreen', 'scale', or the mobile SDKs' 'zoom' (navigation without the
|
|
29395
|
-
* compass), 'compass' (without the zoom buttons) and 'locate' (geolocate)
|
|
31022
|
+
* compass), 'compass' (without the zoom buttons) and 'locate' (geolocate); or data layers, `{ layer: id }` or
|
|
31023
|
+
* `{ layer: [ids] }`: layers of addPoints / addLines / addPolygons / addData / addStyleLayer and the external
|
|
31024
|
+
* layers, or of the basemap. Hiding the tool hides the layers (layout visibility), showing it shows them; a
|
|
31025
|
+
* layer added later under one of the ids follows a hidden tool, and an id without a layer is left alone.
|
|
29396
31026
|
* @param {Object} [o] label (shown on its button), position ('top-left', 'top-right', 'bottom-left', 'bottom-right',
|
|
29397
31027
|
* or 'none': an element stays where the page put it), options (of a kind's engine control)
|
|
29398
31028
|
*/
|
|
@@ -29400,6 +31030,17 @@ function smapCreateSdk(engine, interop) {
|
|
|
29400
31030
|
o = o || {};
|
|
29401
31031
|
if (typeof id !== 'string' || !TOOL_ID.test(id)) { throw new Error('sMap: a tool id is 1-64 letters, digits, "-", "_" or "."'); }
|
|
29402
31032
|
var kind = typeof target === 'string' ? TOOL_KINDS[target] : null;
|
|
31033
|
+
var layers = layerTarget(target);
|
|
31034
|
+
if (layers) {
|
|
31035
|
+
if (o.position !== undefined && o.position !== 'none') { throw new Error('sMap: a data-layer tool is not placed in a corner'); }
|
|
31036
|
+
if (this._toolIndex(id) >= 0) { this.removeTool(id); }
|
|
31037
|
+
var layerTool = { id: id, label: String(o.label || id), position: 'none', el: null, control: null, layers: layers };
|
|
31038
|
+
this._tools.push(layerTool);
|
|
31039
|
+
if (!this._toolVisible(layerTool)) { this._applyLayerTool(layerTool, false); }
|
|
31040
|
+
if (this.engine) { this._mountTool(layerTool); }
|
|
31041
|
+
this._renderToolsControl();
|
|
31042
|
+
return this;
|
|
31043
|
+
}
|
|
29403
31044
|
if (typeof target === 'string') {
|
|
29404
31045
|
if (!kind) { throw new Error('sMap: unknown tool kind "' + target + '"'); }
|
|
29405
31046
|
if (!engine[kind.control]) { throw new Error('sMap: the rendering engine has no ' + kind.control); }
|
|
@@ -29428,6 +31069,8 @@ function smapCreateSdk(engine, interop) {
|
|
|
29428
31069
|
var tool = this._tools[i];
|
|
29429
31070
|
this._tools.splice(i, 1);
|
|
29430
31071
|
if (tool.el) { tool.el.classList.remove('smap-tool-hidden'); }
|
|
31072
|
+
// A data-layer tool leaves its layers shown, as a removed element is shown again.
|
|
31073
|
+
if (tool.layers && !this._toolVisible(tool)) { this._applyLayerTool(tool, true); }
|
|
29431
31074
|
if (tool.control && this.engine && tool.mounted) { this.engine.removeControl(tool.control); }
|
|
29432
31075
|
this._renderToolsControl();
|
|
29433
31076
|
return this;
|
|
@@ -29473,6 +31116,35 @@ function smapCreateSdk(engine, interop) {
|
|
|
29473
31116
|
SMap.prototype._setHidden = function (tool, hidden) {
|
|
29474
31117
|
if (hidden) { this._toolsHidden[tool.id] = true; } else { delete this._toolsHidden[tool.id]; }
|
|
29475
31118
|
if (tool.el) { tool.el.classList.toggle('smap-tool-hidden', hidden); }
|
|
31119
|
+
if (tool.layers) { this._applyLayerTool(tool, !hidden); }
|
|
31120
|
+
};
|
|
31121
|
+
|
|
31122
|
+
// { layer: 'id' } or { layer: ['id', ...] }: the layer ids of a data-layer tool, or null for any other target.
|
|
31123
|
+
function layerTarget(target) {
|
|
31124
|
+
if (!target || typeof target !== 'object' || isElement(target) || typeof target.onAdd === 'function' || !('layer' in target)) { return null; }
|
|
31125
|
+
var ids = Array.isArray(target.layer) ? target.layer : [target.layer];
|
|
31126
|
+
if (!ids.length || ids.some(function (x) { return typeof x !== 'string' || !x; })) { throw new Error('sMap: a data-layer tool names one or more layer ids'); }
|
|
31127
|
+
return ids.filter(function (x, i) { return ids.indexOf(x) === i; });
|
|
31128
|
+
}
|
|
31129
|
+
|
|
31130
|
+
// Shows or hides a data-layer tool's layers: the SDK's own through setVisible, any other (the basemap's) through its
|
|
31131
|
+
// layout visibility. A layer that is not there (removed, or not added yet) is left alone.
|
|
31132
|
+
SMap.prototype._applyLayerTool = function (tool, visible) {
|
|
31133
|
+
tool.layers.forEach(function (layerId) {
|
|
31134
|
+
if (this._layers[layerId]) { this.setVisible(layerId, visible); return; }
|
|
31135
|
+
var m = this.engine;
|
|
31136
|
+
if (m && m.getLayer && m.getLayer(layerId)) { this.setLayout(layerId, 'visibility', visible ? 'visible' : 'none'); }
|
|
31137
|
+
}, this);
|
|
31138
|
+
};
|
|
31139
|
+
|
|
31140
|
+
// After a style loads: the basemap layers of hidden data-layer tools are hidden (the SDK's own layers already are).
|
|
31141
|
+
SMap.prototype._hideLayerTools = function () {
|
|
31142
|
+
this._tools.forEach(function (t) { if (t.layers && !this._toolVisible(t)) { this._applyLayerTool(t, false); } }, this);
|
|
31143
|
+
};
|
|
31144
|
+
|
|
31145
|
+
// Is a layer id covered by a hidden data-layer tool? A layer added later under that id starts hidden.
|
|
31146
|
+
SMap.prototype._layerToolHides = function (layerId) {
|
|
31147
|
+
return this._tools.some(function (t) { return t.layers && t.layers.indexOf(layerId) >= 0 && !this._toolVisible(t); }, this);
|
|
29476
31148
|
};
|
|
29477
31149
|
SMap.prototype._toolsChanged = function (id) {
|
|
29478
31150
|
var hidden = this._tools.filter(function (t) { return !this._toolVisible(t); }, this).map(function (t) { return t.id; });
|
|
@@ -29483,10 +31155,12 @@ function smapCreateSdk(engine, interop) {
|
|
|
29483
31155
|
// The tools control joins the map with its first tool, so a map without tools is exactly as before.
|
|
29484
31156
|
if (this._toolsControlAt && !this._toolsControl && this.engine.addControl) {
|
|
29485
31157
|
this._toolsControl = toolsControl(this);
|
|
29486
|
-
this.engine.addControl(this._toolsControl, this._toolsControlAt);
|
|
31158
|
+
this.engine.addControl(this._toolsControl, this._toolsControlAt === 'toolbar' ? 'top-left' : this._toolsControlAt);
|
|
31159
|
+
if (this._toolsControlAt === 'toolbar') { this._toolsControl._follow(); }
|
|
29487
31160
|
}
|
|
29488
31161
|
if (tool.control && this.engine.addControl) { this.engine.addControl(tool.control, tool.position); tool.mounted = true; }
|
|
29489
31162
|
if (tool.el) { tool.el.classList.toggle('smap-tool-hidden', !this._toolVisible(tool)); }
|
|
31163
|
+
if (this._toolsControl) { this._toolsControl._place(); }
|
|
29490
31164
|
};
|
|
29491
31165
|
|
|
29492
31166
|
// Called once the engine exists: every tool registered before it.
|
|
@@ -29505,9 +31179,39 @@ function smapCreateSdk(engine, interop) {
|
|
|
29505
31179
|
var drawn = null;
|
|
29506
31180
|
var text = {};
|
|
29507
31181
|
Object.keys(TOOLS_TEXT).forEach(function (k) { text[k] = map._toolsLabels[k] || TOOLS_TEXT[k]; });
|
|
31182
|
+
var observer = null;
|
|
31183
|
+
var openCorner = null;
|
|
29508
31184
|
function open(on) {
|
|
29509
31185
|
panel.hidden = !on;
|
|
29510
31186
|
button.setAttribute('aria-expanded', on ? 'true' : 'false');
|
|
31187
|
+
// While the panel is open its corner is drawn above the map's other corners.
|
|
31188
|
+
if (openCorner) { openCorner.classList.remove('smap-tools-open'); openCorner = null; }
|
|
31189
|
+
if (on && el.parentNode) { openCorner = el.parentNode; openCorner.classList.add('smap-tools-open'); }
|
|
31190
|
+
}
|
|
31191
|
+
function cornerOf(node, root) {
|
|
31192
|
+
for (; node && node !== root; node = node.parentNode) {
|
|
31193
|
+
if (node.nodeType === 1 && /\bmaplibregl-ctrl-(top|bottom)-(left|right)\b/.test(node.className)) { return node; }
|
|
31194
|
+
}
|
|
31195
|
+
return null;
|
|
31196
|
+
}
|
|
31197
|
+
// The map's toolbar: the corner holding a navigation control (zoom buttons or compass), top left without one.
|
|
31198
|
+
function toolbarCorner(root) {
|
|
31199
|
+
var navs = root.querySelectorAll('.maplibregl-ctrl-zoom-in, .maplibregl-ctrl-zoom-out, .maplibregl-ctrl-compass');
|
|
31200
|
+
for (var i = 0; i < navs.length; i++) {
|
|
31201
|
+
if (el.contains(navs[i])) { continue; }
|
|
31202
|
+
var c = cornerOf(navs[i], root);
|
|
31203
|
+
if (c) { return c; }
|
|
31204
|
+
}
|
|
31205
|
+
return root.querySelector('.maplibregl-ctrl-top-left');
|
|
31206
|
+
}
|
|
31207
|
+
// Where the control goes in a corner: last, but in a bottom corner before the attribution and the sMap badge,
|
|
31208
|
+
// which keep the map's edge.
|
|
31209
|
+
function edgeOf(corner) {
|
|
31210
|
+
if (!/\bmaplibregl-ctrl-bottom-/.test(corner.className)) { return null; }
|
|
31211
|
+
for (var c = corner.firstElementChild; c; c = c.nextElementSibling) {
|
|
31212
|
+
if (c !== el && (c.classList.contains('maplibregl-ctrl-attrib') || c.classList.contains('smap-badge'))) { return c; }
|
|
31213
|
+
}
|
|
31214
|
+
return null;
|
|
29511
31215
|
}
|
|
29512
31216
|
function close() { if (panel && !panel.hidden) { open(false); } }
|
|
29513
31217
|
function key(e) { if (e.key === 'Escape' && !panel.hidden) { open(false); button.focus(); } }
|
|
@@ -29540,10 +31244,35 @@ function smapCreateSdk(engine, interop) {
|
|
|
29540
31244
|
},
|
|
29541
31245
|
onRemove: function (m) {
|
|
29542
31246
|
m.off('click', close);
|
|
31247
|
+
if (observer) { observer.disconnect(); observer = null; }
|
|
31248
|
+
if (openCorner) { openCorner.classList.remove('smap-tools-open'); openCorner = null; }
|
|
29543
31249
|
if (el && el.parentNode) { el.parentNode.removeChild(el); }
|
|
29544
31250
|
el = null;
|
|
29545
31251
|
drawn = null;
|
|
29546
31252
|
},
|
|
31253
|
+
// The default place (1.1.6): the last button of the map's toolbar, kept last when controls join it later.
|
|
31254
|
+
_place: function () {
|
|
31255
|
+
if (!el || map._toolsControlAt !== 'toolbar' || !map.engine || !map.engine.getContainer) { return; }
|
|
31256
|
+
var root = map.engine.getContainer();
|
|
31257
|
+
var corner = toolbarCorner(root);
|
|
31258
|
+
if (!corner) { return; }
|
|
31259
|
+
var edge = edgeOf(corner);
|
|
31260
|
+
var inPlace = el.parentNode === corner && (edge ? el.nextElementSibling === edge : !el.nextElementSibling);
|
|
31261
|
+
if (inPlace) { return; }
|
|
31262
|
+
corner.insertBefore(el, edge);
|
|
31263
|
+
if (openCorner && openCorner !== corner) { openCorner.classList.remove('smap-tools-open'); openCorner = corner; corner.classList.add('smap-tools-open'); }
|
|
31264
|
+
},
|
|
31265
|
+
// Watches the map's corners, so a control the app adds later (to the engine itself too) leaves this one last.
|
|
31266
|
+
_follow: function () {
|
|
31267
|
+
if (observer || !el || !map.engine.getContainer) { return; }
|
|
31268
|
+
var root = map.engine.getContainer();
|
|
31269
|
+
var view = root.ownerDocument && root.ownerDocument.defaultView;
|
|
31270
|
+
var Observer = view && view.MutationObserver;
|
|
31271
|
+
if (!Observer) { return; }
|
|
31272
|
+
var watched = root.querySelector('.maplibregl-control-container') || root;
|
|
31273
|
+
observer = new Observer(function () { control._place(); });
|
|
31274
|
+
observer.observe(watched, { childList: true, subtree: true });
|
|
31275
|
+
},
|
|
29547
31276
|
_render: function () {
|
|
29548
31277
|
if (!el) { return; }
|
|
29549
31278
|
var doc = el.ownerDocument;
|
|
@@ -29576,6 +31305,19 @@ function smapCreateSdk(engine, interop) {
|
|
|
29576
31305
|
return control;
|
|
29577
31306
|
}
|
|
29578
31307
|
|
|
31308
|
+
// ------------------------------------------------------------------ plan editor (OPEN-ROUTE-EDIT E10)
|
|
31309
|
+
|
|
31310
|
+
/**
|
|
31311
|
+
* A plan editor on this map: the plan drawn as layers, stops dragged within and between routes, and the ready-made
|
|
31312
|
+
* panel as the map tool `<id>-editor` (unless `panel: false`). Every edit is a plan.* call of the Open Platform.
|
|
31313
|
+
* const editor = map.planEditor({ credentials: { token: () => fetch('/plan-token').then((r) => r.json()) }, plan });
|
|
31314
|
+
* See PlanEditorOptions in the types for every option.
|
|
31315
|
+
*/
|
|
31316
|
+
SMap.prototype.planEditor = function (options) {
|
|
31317
|
+
if (!plan) { throw new Error('sMap: the plan editor is not loaded'); }
|
|
31318
|
+
return plan.attach(this, options);
|
|
31319
|
+
};
|
|
31320
|
+
|
|
29579
31321
|
// ------------------------------------------------------------------ Style Specification sources and layers (M24)
|
|
29580
31322
|
|
|
29581
31323
|
function clone(v) { return v === undefined ? undefined : JSON.parse(JSON.stringify(v)); }
|
|
@@ -30143,6 +31885,7 @@ function smapCreateSdk(engine, interop) {
|
|
|
30143
31885
|
def.popupFn = typeof o.popup === 'string' ? popupTemplate(o.popup) : null;
|
|
30144
31886
|
def.zIndex = def.o.zIndex || 0;
|
|
30145
31887
|
def.engineLayers = [];
|
|
31888
|
+
if (this._layerToolHides(id)) { def.hidden = true; }
|
|
30146
31889
|
this._layers[id] = def;
|
|
30147
31890
|
this._order = this._order.filter(function (x) { return x !== id; });
|
|
30148
31891
|
this._order.push(id);
|
|
@@ -30523,10 +32266,13 @@ function smapCreateSdk(engine, interop) {
|
|
|
30523
32266
|
parseWmtsCapabilities: interop.parseWmtsCapabilities,
|
|
30524
32267
|
PMTilesArchive: interop.PMTilesArchive,
|
|
30525
32268
|
useDeck: interop.useDeck,
|
|
32269
|
+
PlanEditor: plan ? plan.PlanEditor : undefined,
|
|
32270
|
+
planTexts: plan ? plan.texts : undefined,
|
|
32271
|
+
planEditorParts: plan ? plan.parts : undefined,
|
|
30526
32272
|
};
|
|
30527
32273
|
});
|
|
30528
32274
|
|
|
30529
32275
|
return module.exports;
|
|
30530
32276
|
}
|
|
30531
|
-
(typeof globalThis !== 'undefined' ? globalThis : window).sMap = smapCreateSdk(smapCreateEngine(), smapCreateInterop());
|
|
32277
|
+
(typeof globalThis !== 'undefined' ? globalThis : window).sMap = smapCreateSdk(smapCreateEngine(), smapCreateInterop(), smapCreatePlan());
|
|
30532
32278
|
})();
|