@superrouteca/smap 1.1.2 → 1.1.6

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