@superrouteca/smap 1.1.5 → 1.1.7

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