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