ol-elevation-profile 1.0.0 → 2.0.0

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.
@@ -17,7 +17,8 @@
17
17
  import Control from 'ol/control/Control.js';
18
18
  import Overlay from 'ol/Overlay.js';
19
19
  import { unByKey } from 'ol/Observable.js';
20
- import { toLonLat } from 'ol/proj.js';
20
+ import { toLonLat, fromLonLat, transform, get as getProj } from 'ol/proj.js';
21
+ import TileState from 'ol/TileState.js';
21
22
  import { getDistance } from 'ol/sphere.js';
22
23
  import { boundingExtent } from 'ol/extent.js';
23
24
  import * as d3 from 'd3';
@@ -33,6 +34,53 @@ import * as d3 from 'd3';
33
34
 
34
35
  const POSITIONS = ['top', 'bottom', 'left', 'right', 'top-left', 'top-right', 'bottom-left', 'bottom-right'];
35
36
 
37
+ /**
38
+ * Jeux de libellés livrés avec la librairie. `en` est le défaut et la retombée : une
39
+ * langue inconnue rend l'anglais plutôt que des clés vides ou un mélange.
40
+ *
41
+ * Un jeu est complet, jamais partiel. Une traduction à trous laisserait deux langues
42
+ * cohabiter dans le même panneau, ce qui se voit ; `labels` reste là pour corriger une
43
+ * clé isolée sans avoir à redéclarer les autres.
44
+ *
45
+ * `ascent` et `descent` valent `D+` / `D-` partout : la notation est celle des cartes et
46
+ * des topos, pas un mot à traduire.
47
+ */
48
+ const LOCALES = {
49
+ en: {
50
+ distance: 'Distance', elevation: 'Elevation', slope: 'Slope',
51
+ ascent: 'D+', descent: 'D-', empty: 'Click a track',
52
+ time: 'Time', duration: 'Duration',
53
+ durationUnits: { s: 'sec', m: 'min', h: 'h', d: 'd' },
54
+ zoomStart: 'Set start (A)', zoomEnd: 'Set end (B)', zoomAll: 'Show all',
55
+ zoomBack: 'Back one level',
56
+ exportPng: 'Export as PNG',
57
+ collapse: 'Collapse the profile', expand: 'Expand the profile',
58
+ loading: 'Loading the elevation profile'
59
+ },
60
+ fr: {
61
+ distance: 'Distance', elevation: 'Altitude', slope: 'Pente',
62
+ ascent: 'D+', descent: 'D-', empty: 'Cliquez un tracé',
63
+ time: 'Temps', duration: 'Durée',
64
+ durationUnits: { s: 'sec', m: 'min', h: 'h', d: 'j' },
65
+ zoomStart: 'Définir le début (A)', zoomEnd: 'Définir la fin (B)', zoomAll: 'Tout voir',
66
+ zoomBack: 'Revenir au niveau précédent',
67
+ exportPng: 'Exporter en PNG',
68
+ collapse: 'Réduire le profil', expand: 'Agrandir le profil',
69
+ loading: 'Chargement du profil altimétrique'
70
+ },
71
+ es: {
72
+ distance: 'Distancia', elevation: 'Altitud', slope: 'Pendiente',
73
+ ascent: 'D+', descent: 'D-', empty: 'Haga clic en una traza',
74
+ time: 'Tiempo', duration: 'Duración',
75
+ durationUnits: { s: 'seg', m: 'min', h: 'h', d: 'd' },
76
+ zoomStart: 'Definir el inicio (A)', zoomEnd: 'Definir el final (B)', zoomAll: 'Ver todo',
77
+ zoomBack: 'Volver al nivel anterior',
78
+ exportPng: 'Exportar como PNG',
79
+ collapse: 'Contraer el perfil', expand: 'Desplegar el perfil',
80
+ loading: 'Cargando el perfil de elevación'
81
+ }
82
+ };
83
+
36
84
  const DEFAULTS = {
37
85
  immersion: 'docked',
38
86
  position: 'bottom',
@@ -58,6 +106,8 @@ import * as d3 from 'd3';
58
106
  maxClasses: 8, // maximum number of slope classes (colours + legend)
59
107
  xTicks: null,
60
108
  yTicks: null,
109
+ verticalScale: 'auto', // 'auto' : le profil remplit la hauteur ;
110
+ // un nombre : mètres par centimètre physique
61
111
  show: 'click',
62
112
  collapsable: true,
63
113
  collapsed: false,
@@ -67,22 +117,23 @@ import * as d3 from 'd3';
67
117
  responsive: true, // adapts width/placement, mobile included
68
118
  mobileBreakpoint: 640, // <= screen width -> mobile mode (100% width, top/bottom)
69
119
  zoom: false, // start/end buttons cropping map + profile to A..B
120
+ zoomLevels: 3, // niveaux de recadrage imbriqués (1 = l'ancien niveau unique)
121
+ exportPng: false, // toolbar button exporting the panel as a PNG
70
122
  ignoreStops: true, // duration = moving time (stops excluded)
71
123
  stopSpeed: 0.5, // stop threshold in m/s (~1.8 km/h)
72
124
  tooltipItems: ['distance', 'elevation'],
73
125
  headerItems: ['distance', 'ascent', 'descent', 'minmax'],
74
126
  titleProperty: 'name',
75
127
  titleLink: null,
76
- labels: {
77
- distance: 'Distance', elevation: 'Altitude', slope: 'Pente',
78
- ascent: 'D+', descent: 'D-', empty: 'Cliquez un tracé',
79
- time: 'Temps', duration: 'Durée',
80
- durationUnits: { s: 'sec', m: 'min', h: 'h', d: 'j' },
81
- zoomStart: 'Définir le début (A)', zoomEnd: 'Définir la fin (B)', zoomAll: 'Tout voir',
82
- loading: 'Chargement du profil altimétrique'
83
- }
128
+ lang: 'en', // 'en' | 'fr' | 'es' : jeu de libellés livré
129
+ labels: {} // surcharges clé à clé, appliquées par-dessus la langue
84
130
  };
85
131
 
132
+ /** Libellés de la langue [lang], corrigés par les surcharges [over]. */
133
+ function resolveLabels(lang, over) {
134
+ return deepMerge(LOCALES[lang] || LOCALES.en, over || null);
135
+ }
136
+
86
137
  // ----- helpers ---------------------------------------------------------
87
138
  function deepMerge(base, over) {
88
139
  const out = {};
@@ -184,15 +235,21 @@ import * as d3 from 'd3';
184
235
  const ICON_EXPAND = '<svg viewBox="0 0 24 24"><path d="M3 19l5-7 4 4 4-6 5 9z" fill="currentColor" opacity=".85"/></svg>';
185
236
  const ICON_A = '<svg viewBox="0 0 24 24"><path d="M7 5v14M11 12h8m0 0-3-3m3 3-3 3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
186
237
  const ICON_B = '<svg viewBox="0 0 24 24"><path d="M17 5v14M13 12H5m0 0 3-3m-3 3 3 3" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
238
+ const ICON_PNG = '<svg viewBox="0 0 24 24"><path d="M12 4v10m0 0 4-4m-4 4-4-4M5 18h14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
239
+ const ICON_BACK = '<svg viewBox="0 0 24 24"><path d="M10 6 4 12l6 6M4 12h10a6 6 0 0 1 6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
187
240
  const ICON_ALL = '<svg viewBox="0 0 24 24"><path d="M4 12h16M4 12l4-4M4 12l4 4M20 12l-4-4M20 12l-4 4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
188
241
 
242
+ // Recherche du segment contenant une abscisse. Construit une fois : le survol la sollicite
243
+ // à chaque mouvement de souris.
244
+ const bisectX = d3.bisector((d) => d.x).left;
245
+
189
246
  // ----- digital elevation model (DEM) -----------------------------------
190
247
  /**
191
248
  * Known terrain-tile sources.
192
249
  *
193
250
  * A PNG tile carries elevation in its R/G/B channels; it is read on a canvas rather
194
251
  * than queried point by point from an API. That is what makes a 10 000-point track a
195
- * handful of requests, with no key, no quota and no rate limit where the free
252
+ * handful of requests, with no key, no quota and no rate limit, where the free
196
253
  * elevation APIs cap out at 100 or 200 points per call.
197
254
  *
198
255
  * Attribution is not automatic: the library does not own the map. It is up to the
@@ -206,17 +263,335 @@ import * as d3 from 'd3';
206
263
  encoding: 'terrarium',
207
264
  maxZoom: 14,
208
265
  attributions: 'Elevation: <a href="https://registry.opendata.aws/terrain-tiles/">Terrain Tiles</a> (AWS Open Data)'
266
+ },
267
+ /**
268
+ * IGN Géoplateforme, serving the RGE ALTI over France and its overseas territories.
269
+ *
270
+ * A point API rather than tiles, hence its own sampler: it answers 200 points per
271
+ * request and announces one request per second, so a 10 000 point track takes about
272
+ * fifty calls spread over as many seconds. In exchange it is metre-accurate where the
273
+ * world models are at ninety.
274
+ *
275
+ * **No key is required** on the public endpoint - verified against the live service.
276
+ * `apiKey` exists for a deployment that does demand one; it is appended as a query
277
+ * parameter, named by `apiKeyParam`.
278
+ *
279
+ * Outside its coverage the service does not error: it answers OUT_OF_COVERAGE for the
280
+ * point. No border is coded here - one asks, and it says itself where it does not know.
281
+ */
282
+ ign: {
283
+ api: 'ign',
284
+ url: 'https://data.geopf.fr/altimetrie/1.0/calcul/alti/rest/elevation.json',
285
+ resource: 'ign_rge_alti_wld',
286
+ batch: 200, // more fits, but the URL grows ~20 bytes a point and hits 414
287
+ minInterval: 1100, // ms between calls; the service announces 1 req/s
288
+ attributions: 'Elevation: <a href="https://geoservices.ign.fr/rgealti">RGE ALTI</a> (IGN)'
209
289
  }
210
290
  };
211
291
 
292
+ /** Value the IGN service returns where it holds no measurement. */
293
+ const IGN_NO_DATA = -99999;
294
+
295
+ /**
296
+ * Request URL for one batch, in the order given: the response returns the elevations in
297
+ * the same one.
298
+ *
299
+ * `zonly=true` cuts the response down to the elevations alone, without echoing the
300
+ * coordinates - a third of the weight for the same information. Coordinates rounded to
301
+ * the millionth of a degree, about ten centimetres: beyond that one only adds digits to
302
+ * the URL.
303
+ */
304
+ function ignUrl(cfg, pts) {
305
+ const f = (v) => v.toFixed(6);
306
+ const sep = cfg.url.indexOf('?') >= 0 ? '&' : '?';
307
+ let u = cfg.url + sep + 'resource=' + encodeURIComponent(cfg.resource) +
308
+ '&delimiter=|&zonly=true' +
309
+ '&lon=' + pts.map((p) => f(p[0])).join('|') +
310
+ '&lat=' + pts.map((p) => f(p[1])).join('|');
311
+ if (cfg.apiKey) u += '&' + (cfg.apiKeyParam || 'apikey') + '=' + encodeURIComponent(cfg.apiKey);
312
+ return u;
313
+ }
314
+
315
+ /**
316
+ * Sampler for the IGN service: batches, paces, and maps out-of-coverage to null.
317
+ *
318
+ * A batch whose response does not carry exactly as many elevations as points were asked
319
+ * for fails the whole fill. Elevations one can no longer map to their points are worse
320
+ * than absent ones: they would land on the wrong places, silently.
321
+ */
322
+ function ignSampler(cfg) {
323
+ const size = Math.max(1, cfg.batch || 200);
324
+ const gap = cfg.minInterval || 0;
325
+ return (lonlats) => {
326
+ const out = [];
327
+ let last = 0;
328
+ const step = (i) => {
329
+ if (i >= lonlats.length) return Promise.resolve(out);
330
+ const chunk = lonlats.slice(i, i + size);
331
+ const wait = Math.max(0, gap - (Date.now() - last));
332
+ return new Promise((r) => setTimeout(r, wait))
333
+ .then(() => { last = Date.now(); return fetch(ignUrl(cfg, chunk)); })
334
+ .then((r) => (r && r.ok) ? r.json() : null)
335
+ .then((body) => {
336
+ const z = body && body.elevations;
337
+ if (!Array.isArray(z) || z.length !== chunk.length) return null;
338
+ for (const v of z) out.push((v == null || v <= IGN_NO_DATA) ? null : v);
339
+ return step(i + size);
340
+ });
341
+ };
342
+ return step(0);
343
+ };
344
+ }
345
+
212
346
  const DEM_DEFAULTS = { source: 'terrarium', zoom: 'auto', maxZoom: 14, maxTiles: 32, concurrency: 6, tileSize: 256 };
213
347
 
214
- /** RGB → metres decoders, one per encoding convention. */
348
+ /**
349
+ * RGB to metres decoders, one per encoding convention.
350
+ *
351
+ * `encoding` also takes a function `(r, g, b, a) => metres`, for a tile set that packs
352
+ * elevation its own way. Return null where the pixel carries no measurement: the fill is
353
+ * abandoned rather than guessed.
354
+ *
355
+ * A GeoServer greyscale DEM is NOT decoded here. What a WMS returns is a rendered image,
356
+ * stretched and quantised by its style, not the coverage values; reading it back would
357
+ * be reading the rendering. Those go through `featureInfo`, which asks the server for the
358
+ * band value itself (see demConfig).
359
+ */
215
360
  const DEM_DECODERS = {
216
361
  terrarium: (r, g, b) => (r * 256 + g + b / 256) - 32768,
217
362
  mapbox: (r, g, b) => -10000 + (r * 65536 + g * 256 + b) * 0.1
218
363
  };
219
364
 
365
+ /** Half the Web Mercator world, in metres: the bound of EPSG:3857. */
366
+ const MERC_HALF = 20037508.342789244;
367
+
368
+ /** Extent of an XYZ tile in EPSG:3857, for the WMS requests built below. */
369
+ function tileExtent(z, x, y) {
370
+ const span = 2 * MERC_HALF / Math.pow(2, z);
371
+ const minX = -MERC_HALF + x * span, maxY = MERC_HALF - y * span;
372
+ return [minX, maxY - span, minX + span, maxY];
373
+ }
374
+
375
+ function query(base, params) {
376
+ const sep = base.indexOf('?') >= 0 ? '&' : '?';
377
+ return base.replace(/[?&]$/, '') + sep +
378
+ Object.keys(params).map((k) => k + '=' + encodeURIComponent(params[k])).join('&');
379
+ }
380
+
381
+ /**
382
+ * WMS GetMap URL covering one XYZ tile, so a WMS behaves like any other tile source.
383
+ *
384
+ * The axis-order trap: WMS 1.3.0 names the reference system `CRS`, 1.1.1 names it `SRS`,
385
+ * and sending the wrong one gets the request rejected or silently mis-georeferenced.
386
+ * The version actually in force decides, after the caller's params are merged in.
387
+ */
388
+ function wmsTileUrl(w, z, x, y, tileSize) {
389
+ const p = Object.assign({
390
+ SERVICE: 'WMS', REQUEST: 'GetMap', VERSION: '1.3.0', FORMAT: 'image/png',
391
+ TRANSPARENT: 'false', STYLES: ''
392
+ }, w.params || {});
393
+ const key = String(p.VERSION).indexOf('1.1') === 0 ? 'SRS' : 'CRS';
394
+ delete p.SRS; delete p.CRS;
395
+ p[key] = w.projection || 'EPSG:3857';
396
+ p.LAYERS = w.layers;
397
+ p.WIDTH = tileSize; p.HEIGHT = tileSize;
398
+ p.BBOX = tileExtent(z, x, y).join(',');
399
+ return query(w.url, p);
400
+ }
401
+
402
+ /**
403
+ * Where a tile comes from: an OpenLayers source, a WMS, or an XYZ template.
404
+ *
405
+ * Handing an `ol/source/TileImage` (XYZ, TileWMS, or any subclass) delegates URL building
406
+ * to OpenLayers itself, which already knows that source's quirks - subdomains, custom
407
+ * params, tile grid. Cheaper and safer than reimplementing each one here.
408
+ */
409
+ function tileUrlFn(cfg) {
410
+ const src = cfg.olSource;
411
+ if (src && typeof src.getTileUrlFunction === 'function') {
412
+ const fn = src.getTileUrlFunction();
413
+ const proj = getProj('EPSG:3857');
414
+ return (z, x, y) => fn([z, x, y], 1, proj);
415
+ }
416
+ if (cfg.wms) return (z, x, y) => wmsTileUrl(cfg.wms, z, x, y, cfg.tileSize);
417
+ return (z, x, y) => cfg.url.replace('{z}', z).replace('{x}', x).replace('{y}', y);
418
+ }
419
+
420
+ /**
421
+ * Values of one DataTile, or null if it never arrived.
422
+ *
423
+ * A DataTile carries no URL: it is loaded by the source itself and its values are read
424
+ * back with getData(). The state has to be watched rather than awaited - OpenLayers
425
+ * announces it through a `change` event, not a promise.
426
+ */
427
+ function loadDataTile(tile) {
428
+ return new Promise((resolve) => {
429
+ const settle = () => {
430
+ const st = tile.getState();
431
+ if (st === TileState.LOADED) { resolve(tile.getData ? tile.getData() : null); return true; }
432
+ if (st === TileState.ERROR || st === TileState.EMPTY) { resolve(null); return true; }
433
+ return false;
434
+ };
435
+ if (settle()) return;
436
+ const onChange = () => { if (settle()) tile.removeEventListener('change', onChange); };
437
+ tile.addEventListener('change', onChange);
438
+ if (tile.load) tile.load();
439
+ });
440
+ }
441
+
442
+ /**
443
+ * Sampler for an `ol/source/DataTile` - `ol/source/GeoTIFF` above all.
444
+ *
445
+ * Its own path because such a source shares nothing with the XYZ one: no URL, no Web
446
+ * Mercator, no 256 pixel tiles. A GeoTIFF keeps **its own projection and its own tile
447
+ * grid**, both only known once `getView()` has resolved, and its values are real numbers
448
+ * rather than colours - so nothing here goes through a decoder.
449
+ *
450
+ * Positions are held in grid pixels, as with the XYZ tiles and for the same reason: the
451
+ * four neighbours of a point straddle two tiles as soon as it runs along an edge.
452
+ *
453
+ * `normalize: false` matters on the source, otherwise OpenLayers rescales the values to
454
+ * 0..1 and the profile comes out in fractions of nothing.
455
+ */
456
+ function dataTileSampler(cfg) {
457
+ const src = cfg.olSource;
458
+ const band = cfg.band || 0;
459
+ return (lonlats) => {
460
+ // getView() is only awaited when the grid is not known yet - which is the GeoTIFF
461
+ // case, where it settles once the metadata has been read. On a plain DataTile that
462
+ // promise never settles at all, and awaiting it unconditionally hangs the fill.
463
+ const known = src.getTileGrid && src.getTileGrid();
464
+ const ready = known ? Promise.resolve(null) : Promise.resolve(src.getView ? src.getView() : null);
465
+ return ready.then((view) => {
466
+ const grid = known || (src.getTileGrid && src.getTileGrid()) || (view && view.tileGrid);
467
+ if (!grid) return null;
468
+ const proj = getProj((view && view.projection) || (src.getProjection && src.getProjection()) || 'EPSG:3857');
469
+ const zs = grid.getResolutions ? grid.getResolutions().length - 1 : 0;
470
+ const bands = src.bandCount || 1;
471
+ const coords = lonlats.map((ll) => transform([ll[0], ll[1]], 'EPSG:4326', proj));
472
+
473
+ // Finest level whose tile count stays within maxTiles, as for the XYZ tiles: it is
474
+ // the tiling that widens with the track, not the model that degrades.
475
+ // Pixel bounds of the coverage, when it declares an extent. A point inside the raster
476
+ // but within half a pixel of its edge lands on a neighbour that does not exist: its
477
+ // tile would come back empty and the all-or-nothing rule would drop the whole track.
478
+ // Half a pixel of tolerance at the borders, as on any regular grid.
479
+ const ext = (grid.getExtent && grid.getExtent()) || (view && view.extent) || null;
480
+ const plan = (z) => {
481
+ const res = grid.getResolution(z), origin = grid.getOrigin(z);
482
+ let ts = grid.getTileSize(z); ts = Array.isArray(ts) ? ts : [ts, ts];
483
+ const cols = ext ? Math.round((ext[2] - ext[0]) / res) : Infinity;
484
+ const rows = ext ? Math.round((ext[3] - ext[1]) / res) : Infinity;
485
+ const clampI = (i) => Math.min(cols - 1, Math.max(0, i));
486
+ const clampJ = (j) => Math.min(rows - 1, Math.max(0, j));
487
+ const need = new Map();
488
+ const at = coords.map((c) => {
489
+ const px = (c[0] - origin[0]) / res - 0.5, py = (origin[1] - c[1]) / res - 0.5;
490
+ const i0 = clampI(Math.floor(px)), j0 = clampJ(Math.floor(py));
491
+ for (let di = 0; di < 2; di++) for (let dj = 0; dj < 2; dj++) {
492
+ const tx = Math.floor(clampI(i0 + di) / ts[0]), ty = Math.floor(clampJ(j0 + dj) / ts[1]);
493
+ need.set(tx + '/' + ty, [tx, ty]);
494
+ }
495
+ // Interpolation fractions clamped too: a point beyond the last pixel centre keeps
496
+ // that pixel's value rather than extrapolating past the edge of the data.
497
+ return { i0, j0, tx: Math.min(1, Math.max(0, px - i0)), ty: Math.min(1, Math.max(0, py - j0)), clampI, clampJ };
498
+ });
499
+ return { res, origin, ts, need, at, clampI, clampJ };
500
+ };
501
+ let z = zs, p = plan(z);
502
+ while (z > 0 && p.need.size > cfg.maxTiles) { z--; p = plan(z); }
503
+ if (p.need.size > cfg.maxTiles) return null;
504
+
505
+ const keys = Array.from(p.need.keys());
506
+ return Promise.all(keys.map((k) => {
507
+ const t = p.need.get(k);
508
+ return loadDataTile(src.getTile(z, t[0], t[1], 1, proj)).then((d) => [k, d]);
509
+ })).then((pairs) => {
510
+ const tiles = new Map(pairs);
511
+ const value = (i, j) => {
512
+ const tx = Math.floor(p.clampI(i) / p.ts[0]), ty = Math.floor(p.clampJ(j) / p.ts[1]);
513
+ i = p.clampI(i); j = p.clampJ(j);
514
+ const d = tiles.get(tx + '/' + ty);
515
+ if (!d) return null;
516
+ const col = i - tx * p.ts[0], row = j - ty * p.ts[1];
517
+ const v = d[(row * p.ts[0] + col) * bands + band];
518
+ return (v == null || !isFinite(v)) ? null : v;
519
+ };
520
+ return p.at.map((n) => {
521
+ const a = value(n.i0, n.j0), b = value(n.i0 + 1, n.j0);
522
+ const c = value(n.i0, n.j0 + 1), e = value(n.i0 + 1, n.j0 + 1);
523
+ if (a == null || b == null || c == null || e == null) return null;
524
+ const north = a + (b - a) * n.tx, south = c + (e - c) * n.tx;
525
+ return north + (south - north) * n.ty;
526
+ });
527
+ });
528
+ });
529
+ };
530
+ }
531
+
532
+ /**
533
+ * WMS GetFeatureInfo sampler: one request per point, for a coverage served as a rendered
534
+ * greyscale that cannot be decoded from its pixels.
535
+ *
536
+ * **It is slow**, unavoidably: a thousand-point track is a thousand round trips, where a
537
+ * tile source needs a handful. Worth it only when nothing else can reach the data - and
538
+ * `concurrency` is what keeps it bearable.
539
+ */
540
+ function featureInfoSampler(cfg) {
541
+ const fi = cfg.featureInfo;
542
+ const lanes = Math.max(1, cfg.concurrency || 6);
543
+ return (lonlats) => {
544
+ const out = new Array(lonlats.length);
545
+ let next = 0, broken = false;
546
+ const one = () => {
547
+ if (broken || next >= lonlats.length) return Promise.resolve();
548
+ const i = next++;
549
+ return fetch(featureInfoUrl(fi, lonlats[i]))
550
+ .then((r) => (r && r.ok) ? r.json() : null)
551
+ .then((body) => { out[i] = bandValue(body, fi.property); return one(); })
552
+ .catch(() => { broken = true; });
553
+ };
554
+ const running = [];
555
+ for (let i = 0; i < Math.min(lanes, lonlats.length); i++) running.push(one());
556
+ return Promise.all(running).then(() => broken ? null : out);
557
+ };
558
+ }
559
+
560
+ /** GetFeatureInfo URL for one point: a one-pixel image centred on it. */
561
+ function featureInfoUrl(fi, ll) {
562
+ const c = fromLonLat([ll[0], ll[1]]);
563
+ const d = fi.resolution || 1; // half-size of the box, in metres
564
+ const p = Object.assign({
565
+ SERVICE: 'WMS', REQUEST: 'GetFeatureInfo', VERSION: '1.3.0',
566
+ INFO_FORMAT: 'application/json', STYLES: '', FEATURE_COUNT: 1
567
+ }, fi.params || {});
568
+ const key = String(p.VERSION).indexOf('1.1') === 0 ? 'SRS' : 'CRS';
569
+ delete p.SRS; delete p.CRS;
570
+ p[key] = fi.projection || 'EPSG:3857';
571
+ p.LAYERS = fi.layers;
572
+ p.QUERY_LAYERS = fi.queryLayers || fi.layers;
573
+ p.WIDTH = 1; p.HEIGHT = 1; p.I = 0; p.J = 0; p.X = 0; p.Y = 0; // I/J is 1.3.0, X/Y is 1.1.1
574
+ p.BBOX = [c[0] - d, c[1] - d, c[0] + d, c[1] + d].join(',');
575
+ return query(fi.url, p);
576
+ }
577
+
578
+ /**
579
+ * Band value in a GetFeatureInfo response.
580
+ *
581
+ * The band's property name is not standard - GeoServer calls it GRAY_INDEX for a
582
+ * single-band coverage, but a styled or renamed layer answers otherwise. Without an
583
+ * explicit `property` the first finite number wins, which is right whenever the coverage
584
+ * carries one band, and is why `property` exists for when it does not.
585
+ */
586
+ function bandValue(body, property) {
587
+ const f = body && body.features && body.features[0];
588
+ const props = f && f.properties;
589
+ if (!props) return null;
590
+ if (property) { const v = Number(props[property]); return isFinite(v) ? v : null; }
591
+ for (const k of Object.keys(props)) { const v = Number(props[k]); if (props[k] !== null && props[k] !== '' && isFinite(v)) return v; }
592
+ return null;
593
+ }
594
+
220
595
  /** Web Mercator pixel coordinates at zoom `z`, origin at the top-left corner of the world. */
221
596
  function worldPixel(lon, lat, z, tileSize) {
222
597
  const n = tileSize * Math.pow(2, z);
@@ -236,7 +611,9 @@ import * as d3 from 'd3';
236
611
  /** @param {Object} cfg `url`, `encoding`, `tileSize`, `concurrency`. */
237
612
  constructor(cfg) {
238
613
  this.cfg = cfg;
239
- this.decode = DEM_DECODERS[cfg.encoding] || DEM_DECODERS.terrarium;
614
+ this.decode = (typeof cfg.encoding === 'function') ? cfg.encoding
615
+ : (DEM_DECODERS[cfg.encoding] || DEM_DECODERS.terrarium);
616
+ this.tileUrl = tileUrlFn(cfg);
240
617
  this.tiles = new Map(); // "z/x/y" -> RGBA pixels, or null if the tile was lost
241
618
  }
242
619
 
@@ -268,7 +645,8 @@ import * as d3 from 'd3';
268
645
  const data = this.tiles.get(r.key);
269
646
  if (!data) return null;
270
647
  const o = ((r.jj % ts) * ts + (r.ii % ts)) * 4;
271
- return this.decode(data[o], data[o + 1], data[o + 2]);
648
+ const v = this.decode(data[o], data[o + 1], data[o + 2], data[o + 3]);
649
+ return (v == null || !isFinite(v)) ? null : v;
272
650
  }
273
651
 
274
652
  /**
@@ -277,7 +655,7 @@ import * as d3 from 'd3';
277
655
  *
278
656
  * Bilinear rather than "the pixel containing the point": on a 30 or 90 m model, taking
279
657
  * the pixel value makes the profile advance in stairs, and every stair counts as a
280
- * climb then a descent in the ascent total. The interpolation invents no relief it
658
+ * climb then a descent in the ascent total. The interpolation invents no relief: it
281
659
  * renders the same surface, without the steps of the sampling grid.
282
660
  */
283
661
  sample(lon, lat, z) {
@@ -302,7 +680,7 @@ import * as d3 from 'd3';
302
680
  /** Pixels of one tile, or null if it could not be read. */
303
681
  _fetch(key) {
304
682
  const parts = key.split('/');
305
- const url = this.cfg.url.replace('{z}', parts[0]).replace('{x}', parts[1]).replace('{y}', parts[2]);
683
+ const url = this.tileUrl(+parts[0], +parts[1], +parts[2]);
306
684
  return new Promise((resolve) => {
307
685
  const img = new Image();
308
686
  // Without this attribute the canvas is tainted and getImageData throws: the tile
@@ -344,13 +722,44 @@ import * as d3 from 'd3';
344
722
  }
345
723
  }
346
724
 
347
- /** The `dem` option (true | source name | object) → a full configuration, or null. */
725
+ /**
726
+ * The `dem` option (true | source name | sampling function | object) into
727
+ * a full configuration, or null.
728
+ *
729
+ * A `sample` function short-circuits the tile machinery entirely: the application
730
+ * answers with the elevations itself, from wherever it can reach them - a GeoServer
731
+ * WCS coverage, a GeoTIFF decoded with geotiff.js, a national elevation API. Only the
732
+ * transport is delegated; the control keeps the sequencing, the all-or-nothing rule,
733
+ * the spinner and the `demload` event, which is where the subtle parts live.
734
+ *
735
+ * That extension point rather than a WMS/WCS/GeoTIFF mode per protocol: reading a
736
+ * GeoTIFF means a full decoder, and this library has no runtime dependency to spend
737
+ * on one that most users would never load.
738
+ */
348
739
  function demConfig(opt) {
349
740
  if (!opt) return null;
741
+ if (typeof opt === 'function') return Object.assign({}, DEM_DEFAULTS, { sample: opt });
350
742
  const raw = (opt === true || typeof opt === 'string') ? { source: opt === true ? 'terrarium' : opt } : Object.assign({}, opt);
351
- const preset = DEM_PRESETS[raw.source] || (raw.url ? {} : DEM_PRESETS.terrarium);
743
+ if (typeof raw.sample === 'function') return Object.assign({}, DEM_DEFAULTS, raw);
744
+ // A point-query source: no tile grid, no pixel decoding.
745
+ if (raw.featureInfo) {
746
+ const fiCfg = Object.assign({}, DEM_DEFAULTS, raw);
747
+ fiCfg.sample = featureInfoSampler(fiCfg);
748
+ return fiCfg;
749
+ }
750
+ // An ol/source/DataTile (GeoTIFF above all) carries values, not URLs: its own path.
751
+ if (raw.olSource && typeof raw.olSource.getTileUrlFunction !== 'function' &&
752
+ typeof raw.olSource.getTile === 'function') {
753
+ const dtCfg = Object.assign({}, DEM_DEFAULTS, raw);
754
+ dtCfg.sample = dataTileSampler(dtCfg);
755
+ return dtCfg;
756
+ }
757
+ // Tiles: an OpenLayers source or a WMS both stand in for the url template.
758
+ const hasTiles = raw.url || raw.wms || raw.olSource;
759
+ const preset = DEM_PRESETS[raw.source] || (hasTiles ? {} : DEM_PRESETS.terrarium);
352
760
  const cfg = Object.assign({}, DEM_DEFAULTS, preset, raw);
353
- return cfg.url ? cfg : null;
761
+ if (cfg.api === 'ign') { cfg.sample = ignSampler(cfg); return cfg; } // a point API
762
+ return (cfg.url || cfg.wms || cfg.olSource) ? cfg : null;
354
763
  }
355
764
 
356
765
  /**
@@ -384,12 +793,19 @@ import * as d3 from 'd3';
384
793
  * @property {boolean} [slope=false] Split the profile into slope-class colored portions.
385
794
  * @property {number} [slopeClassSize=2.5] Slope class width, in percent.
386
795
  * @property {number} [maxClasses=8] Maximum number of slope classes (colors + legend).
387
- * @property {?string[]} [slopeColors=null] `null` = bluered ramp; otherwise an interpolated color array.
796
+ * @property {?string[]} [slopeColors=null] `null` = blue-to-red ramp; otherwise an interpolated color array.
388
797
  * @property {boolean} [slopeSeparators=true] Vertical separator at each slope-class change.
389
798
  * @property {boolean} [slopeLegend=true] Color legend under the title.
390
799
  * @property {number} [smoothing=0] Elevation smoothing window, in METERS (0 = none).
391
800
  * @property {?number} [xTicks=null] X axis ticks (null = auto from width).
392
801
  * @property {?number} [yTicks=null] Y axis ticks (null = auto from height).
802
+ * @property {('auto'|number)} [verticalScale='auto'] `'auto'`: the profile fills the
803
+ * height, which is legible but changes scale from one track to the next, so a 2 % ramp
804
+ * looks like a wall and two profiles cannot be compared. A number fixes the metres
805
+ * covered per physical centimetre. It is a **floor**, not a cage: a track whose range
806
+ * exceeds what the height can show would spill out of the frame, which is worse than
807
+ * losing comparability: the scale then widens silently, nothing being drawn on the
808
+ * chart to say so.
393
809
  * @property {'click'|'mouseover'} [show='click'] How a track is selected on the map.
394
810
  * @property {boolean} [hideOnMapClick=true] Click on empty map hides the profile.
395
811
  * @property {boolean} [collapsable=true] Show the collapse/expand button.
@@ -399,15 +815,32 @@ import * as d3 from 'd3';
399
815
  * @property {boolean} [responsive=true] Adapt width/placement; mobile included.
400
816
  * @property {number} [mobileBreakpoint=640] Below this width: mobile mode (100% width, top/bottom only).
401
817
  * @property {boolean} [zoom=false] A/B buttons to crop map + profile to a sub-range.
818
+ * @property {number} [zoomLevels=3] Nested crops allowed: a crop can itself be cropped,
819
+ * down to this depth. `1` restores the former single level. A "back" button appears
820
+ * from the second level; "show all" empties the stack whatever the depth.
821
+ * @property {boolean} [exportPng=false] Toolbar button exporting the whole panel as a PNG.
402
822
  * @property {boolean} [ignoreStops=true] When computing time, ignore stopped segments (moving time).
403
823
  * @property {number} [stopSpeed=0.5] Speed threshold (m/s) below which a segment counts as a stop.
404
824
  * @property {Array<'distance'|'elevation'|'slope'|'time'>} [tooltipItems=['distance','elevation']] Tooltip content (`'time'` = elapsed time at the cursor, if the track has time data).
405
825
  * @property {Array<string|{property:string,label?:string,asLink?:boolean,linkText?:string}>} [headerItems] Header content (string tokens: distance, ascent, descent, min, max, minmax, `'duration'` = total elapsed time).
826
+ * @property {('en'|'fr'|'es')} [lang='en'] Language of the shipped labels. An unknown
827
+ * code falls back to English rather than leaving keys empty.
828
+ * @property {Object} [labels={}] Per-key overrides applied on top of `lang`. They survive
829
+ * a later language change, so a corrected key stays corrected.
406
830
  * @property {string} [titleProperty='name'] Feature property used as the title.
407
- * @property {?string} [titleLink=null] Feature property holding a URL clickable title.
831
+ * @property {?string} [titleLink=null] Feature property holding a URL, making the title a link.
408
832
  * @property {number} [maxPoints=2000] Decimation for render/interaction (stats use full data).
409
833
  * @property {?import('ol/proj/Projection').default|string} [dataProjection=null] Projection of the feature coordinates.
410
- * @property {?(boolean|string|Object)} [dem='terrarium'] Fill missing elevations from a terrain model. `'terrarium'` (default) or `true` = AWS Terrain Tiles (keyless); `null` disables it; or `{url,encoding:'terrarium'|'mapbox',zoom,maxZoom,maxTiles,tileSize,concurrency}`.
834
+ * @property {?(boolean|string|Function|Object)} [dem='terrarium'] Fill missing elevations
835
+ * from a terrain model. Sources: `'terrarium'` (default) or `true` = AWS Terrain Tiles;
836
+ * `'ign'` = IGN Géoplateforme RGE ALTI (France, keyless, `apiKey` optional);
837
+ * `{url}` = XYZ template; `{wms:{url,layers,params}}` = WMS tiles;
838
+ * `{olSource}` = any `ol/source/TileImage` (XYZ, TileWMS, and so on);
839
+ * `{featureInfo:{url,layers,property}}` = WMS GetFeatureInfo, one request per point,
840
+ * for a greyscale coverage that cannot be decoded from its pixels (slow);
841
+ * a function or `{sample}` `(lonlats, ctx) => number[]|Promise<number[]>` to source them
842
+ * yourself; `null` disables the whole thing.
843
+ * Decoding: `encoding` is `'terrarium'`, `'mapbox'`, or a function `(r,g,b,a) => metres`.
411
844
  */
412
845
 
413
846
  /**
@@ -424,23 +857,37 @@ import * as d3 from 'd3';
424
857
  constructor(opts) {
425
858
  const o = deepMerge(DEFAULTS, opts || {});
426
859
  if (POSITIONS.indexOf(o.position) === -1) o.position = 'bottom';
860
+ // Les surcharges sont gardées à part de leur résultat : changer de langue plus tard
861
+ // doit reprendre le jeu neuf de la nouvelle langue sans perdre ce que l'appelant a
862
+ // corrigé, ce que le seul jeu résolu ne permettrait plus de démêler.
863
+ const userLabels = o.labels;
864
+ o.labels = resolveLabels(o.lang, userLabels);
427
865
  const element = buildElement(o);
428
866
  super({ element, target: opts && opts.target });
429
867
 
430
868
  this.options = o;
869
+ this._userLabels = userLabels;
431
870
  this.slopeColors = o.slopeColors || null;
432
871
  this._feature = null;
433
872
  this._fullSamples = null; this._fullStats = null;
434
873
  this._samples = null; this._stats = null;
435
874
  this._marker = null;
436
875
  this._collapsed = !!o.collapsed;
437
- this._cropMode = false; this._zoomA = null; this._zoomB = null; this._armed = null; this._fitRes = null;
876
+ this._crops = []; this._off = 0;
877
+ this._zoomA = null; this._zoomB = null; this._armed = null;
438
878
  this._demZ = null; this._demFor = null; this._demSeq = 0; this._demLoading = false;
439
879
  this._onResize = () => { if (this._feature && !this._collapsed) this._render(); };
440
880
  this._buildDom(element);
441
881
  element.style.display = 'none';
442
882
  }
443
883
 
884
+ /** Recadré dès qu'un niveau est empilé. Lu partout où le booléen l'était. */
885
+ get _cropMode() { return this._crops.length > 0; }
886
+ /** Profondeur courante ; 0 quand on voit la trace entière. */
887
+ get _cropDepth() { return this._crops.length; }
888
+ /** Niveaux imbriqués autorisés, au moins un. */
889
+ get _cropMax() { const n = this.options.zoomLevels; return n == null ? 3 : Math.max(1, n | 0); }
890
+
444
891
  // ---------- static helpers ----------------------------------------
445
892
  /**
446
893
  * Whether a feature has any Z (elevation) coordinate.
@@ -487,16 +934,19 @@ import * as d3 from 'd3';
487
934
  };
488
935
  this._btnA = mkBtn('oep-a', ICON_A, o.labels.zoomStart, () => this._arm('A'));
489
936
  this._btnB = mkBtn('oep-b', ICON_B, o.labels.zoomEnd, () => this._arm('B'));
937
+ this._btnBack = mkBtn('oep-back', ICON_BACK, o.labels.zoomBack, () => this._popCrop());
490
938
  this._btnAll = mkBtn('oep-all', ICON_ALL, o.labels.zoomAll, () => this._exitZoom());
939
+ // Last of the toolbar, so it sits to the right of the zoom buttons.
940
+ this._btnPng = mkBtn('oep-png', ICON_PNG, o.labels.exportPng, () => this.exportPNG());
491
941
  header.appendChild(this._toolbar);
492
942
 
493
943
  const btn = document.createElement('button');
494
944
  btn.className = 'oep-toggle'; btn.type = 'button';
495
- btn.setAttribute('aria-label', 'Réduire ou agrandir le profil');
496
945
  btn.innerHTML = this._collapsed ? ICON_EXPAND : ICON_COLLAPSE;
497
946
  btn.addEventListener('click', () => this.toggleCollapsed());
498
947
  header.appendChild(btn);
499
948
  this._toggleBtn = btn;
949
+ this._applyToggleLabel();
500
950
 
501
951
  this._legendEl = document.createElement('div'); this._legendEl.className = 'oep-legend'; this._legendEl.style.display = 'none';
502
952
  this._body = document.createElement('div'); this._body.className = 'oep-body';
@@ -507,6 +957,34 @@ import * as d3 from 'd3';
507
957
  if (this._collapsed) root.classList.add('oep-collapsed');
508
958
  }
509
959
 
960
+ /**
961
+ * Reporte les libellés courants sur ce que le rendu ne réécrit pas.
962
+ *
963
+ * Les boutons et le bouton de repli sont construits une fois pour toutes ; sans cela,
964
+ * changer de langue ne toucherait que le graphe et laisserait les infobulles dans
965
+ * l'ancienne. Le titre n'est repris que faute de tracé : sinon il porte le nom du tracé,
966
+ * qui n'est pas un libellé de la librairie.
967
+ */
968
+ _applyLabels() {
969
+ const l = this.options.labels;
970
+ const set = (b, t) => { if (b && t) { b.title = t; b.setAttribute('aria-label', t); } };
971
+ set(this._btnA, l.zoomStart); set(this._btnB, l.zoomEnd);
972
+ set(this._btnBack, l.zoomBack); set(this._btnAll, l.zoomAll); set(this._btnPng, l.exportPng);
973
+ this._applyToggleLabel();
974
+ if (this._titleEl && !this._feature) this._titleEl.textContent = l.empty;
975
+ }
976
+ /**
977
+ * Le bouton de repli dit ce qu'il va faire, non ce qu'il montre.
978
+ *
979
+ * Un seul libellé pour les deux états ("réduire ou agrandir") laisse deviner lequel
980
+ * des deux le clic déclenche ; l'icône, elle, a déjà basculé. Le titre suit donc l'état,
981
+ * et l'infobulle visible dit la même chose que le nom accessible.
982
+ */
983
+ _applyToggleLabel() {
984
+ const l = this.options.labels, t = this._collapsed ? l.expand : l.collapse;
985
+ if (!this._toggleBtn || !t) return;
986
+ this._toggleBtn.title = t; this._toggleBtn.setAttribute('aria-label', t);
987
+ }
510
988
  _resolveColor() { const o = this.options; if (!o.color) return null; if (o.color === 'auto') return this._featureColor(); return o.color; }
511
989
  _featureColor() {
512
990
  const f = this._feature; if (!f) return null;
@@ -547,6 +1025,7 @@ import * as d3 from 'd3';
547
1025
  this._collapsed = (typeof force === 'boolean') ? force : !this._collapsed;
548
1026
  this.element.classList.toggle('oep-collapsed', this._collapsed);
549
1027
  this._toggleBtn.innerHTML = this._collapsed ? ICON_EXPAND : ICON_COLLAPSE;
1028
+ this._applyToggleLabel();
550
1029
  if (!this._collapsed && this._feature) this._render();
551
1030
  this._adjustAttribution();
552
1031
  }
@@ -611,19 +1090,32 @@ import * as d3 from 'd3';
611
1090
  });
612
1091
 
613
1092
  this._mapKeys = [];
614
- this._mapKeys.push(map.on(o.show === 'mouseover' ? 'pointermove' : 'click', (evt) => {
615
- const feature = lineAt(evt.pixel); if (feature && feature !== this._feature) this.setFeature(feature);
1093
+ // `show`, `hideOnMapClick` et `followMap` sont relus à l'événement, non à
1094
+ // l'abonnement. Les abonnements sont posés une fois pour toutes, ici ; les figer
1095
+ // rendait ces trois options muettes dès que `setOptions` les changeait ensuite,
1096
+ // basculer en survol ne faisait rien, sans que rien ne le dise. Les deux types
1097
+ // d'événement sont donc écoutés en permanence, et c'est l'option qui tranche.
1098
+ this._mapKeys.push(map.on('click', (evt) => {
1099
+ const feature = lineAt(evt.pixel);
1100
+ if (this.options.show !== 'mouseover' && feature && feature !== this._feature) this.setFeature(feature);
1101
+ if (this.options.hideOnMapClick && !feature && this._feature) this.clear();
616
1102
  }));
617
- if (o.hideOnMapClick) this._mapKeys.push(map.on('click', (evt) => { if (!lineAt(evt.pixel) && this._feature) this.clear(); }));
618
- if (o.followMap) this._mapKeys.push(map.on('pointermove', (evt) => {
619
- if (!this._feature || this._collapsed) return;
1103
+ this._mapKeys.push(map.on('pointermove', (evt) => {
1104
+ if (this.options.show === 'mouseover') {
1105
+ const feature = lineAt(evt.pixel);
1106
+ if (feature && feature !== this._feature) this.setFeature(feature);
1107
+ }
1108
+ // Le survol coûte un `lineAt` par déplacement : rien n'est cherché tant qu'aucune
1109
+ // des deux options ne le demande.
1110
+ if (!this.options.followMap || !this._feature || this._collapsed) return;
620
1111
  const cp = this._closestOnProfile(evt.coordinate); if (!cp) return;
621
1112
  const px = map.getPixelFromCoordinate(cp); if (!px) return;
622
1113
  if (Math.hypot(px[0] - evt.pixel[0], px[1] - evt.pixel[1]) < 14) this._focusByCoord(cp); else this._clearFocus();
623
1114
  }));
624
1115
  // leave the A/B crop when the map is zoomed out
625
1116
  this._mapKeys.push(map.on('moveend', () => {
626
- if (this._cropMode && this._fitRes && map.getView().getResolution() > this._fitRes * 1.25) this._exitZoom();
1117
+ const cur = this._crops[this._crops.length - 1];
1118
+ if (cur && cur.fitRes && map.getView().getResolution() > cur.fitRes * 1.25) this._popCrop();
627
1119
  }));
628
1120
  this._mapKeys.push(map.on('change:size', this._onResize));
629
1121
  }
@@ -638,7 +1130,7 @@ import * as d3 from 'd3';
638
1130
  */
639
1131
  setFeature(feature) {
640
1132
  this._feature = feature || null;
641
- this._cropMode = false; this._zoomA = null; this._zoomB = null; this._armed = null;
1133
+ this._crops = []; this._off = 0; this._zoomA = null; this._zoomB = null; this._armed = null;
642
1134
  if (!feature) { this._fullSamples = this._samples = null; this._demZ = this._demFor = null; this._clear(); return this; }
643
1135
  this.element.style.display = '';
644
1136
  this._compute();
@@ -672,7 +1164,14 @@ import * as d3 from 'd3';
672
1164
  if (patch && (patch.theme || 'color' in patch)) this._applyTheme();
673
1165
  if (patch && ('transparency' in patch || 'transparencyLevel' in patch)) this._applyTransparency();
674
1166
  if (patch && 'collapsable' in patch) this._applyCollapsable();
675
- if (patch && 'zoom' in patch) this._updateZoomButtons();
1167
+ if (patch && 'labels' in patch) this._userLabels = deepMerge(this._userLabels || {}, patch.labels);
1168
+ // Recalculé depuis la langue, jamais empilé sur le jeu précédent : passer de 'fr' à
1169
+ // 'es' ne doit rien laisser en français derrière lui, hors surcharges de l'appelant.
1170
+ if (patch && ('lang' in patch || 'labels' in patch)) {
1171
+ this.options.labels = resolveLabels(this.options.lang, this._userLabels);
1172
+ this._applyLabels();
1173
+ }
1174
+ if (patch && ('zoom' in patch || 'exportPng' in patch)) this._updateZoomButtons();
676
1175
  if (patch && typeof patch.width !== 'undefined' && typeof patch.width === 'number') this.options.width = patch.width;
677
1176
  if (patch && 'dem' in patch) { this._demZ = null; this._demFor = null; }
678
1177
  if (this._feature) { this._compute(); this._fillFromDem(this._feature); this._updateZoomButtons(); if (this._collapsed) this._renderTitle(); else this._render(); }
@@ -688,7 +1187,7 @@ import * as d3 from 'd3';
688
1187
  * and the ascent total becomes absurd. Better the flat profile we would have had
689
1188
  * without the DEM.
690
1189
  *
691
- * Nothing is reported to the user on failure the fill is a supplement, it has no
1190
+ * Nothing is reported to the user on failure: the fill is a supplement, it has no
692
1191
  * business breaking a display that succeeded without it. The `demload` event lets the
693
1192
  * application know if it wants to.
694
1193
  *
@@ -700,7 +1199,9 @@ import * as d3 from 'd3';
700
1199
  const cfg = demConfig(this.options.dem);
701
1200
  if (!cfg || !feature || this._demFor === feature) return;
702
1201
  if (ElevationProfile.featureHasZ(feature)) return; // the track already carries its Z
703
- if (typeof Image === 'undefined' || typeof document === 'undefined') return;
1202
+ // Canvas decoding needs a browser; a `sample` function does not, and must stay
1203
+ // usable where there is no DOM.
1204
+ if (!cfg.sample && (typeof Image === 'undefined' || typeof document === 'undefined')) return;
704
1205
 
705
1206
  const geom = feature.getGeometry && feature.getGeometry();
706
1207
  if (!geom) return;
@@ -713,28 +1214,67 @@ import * as d3 from 'd3';
713
1214
  // Sequence number: a track clicked while another is loading must win, otherwise the
714
1215
  // slowest response would overwrite the profile on screen.
715
1216
  const seq = ++this._demSeq;
1217
+ this._demLoading = true;
1218
+
1219
+ // A misconfigured source must not take the profile down with it. _fillFromDem runs
1220
+ // inside setFeature, so anything thrown here would reach the caller and leave no
1221
+ // chart at all - where the whole point is that the fill is a supplement.
1222
+ try {
1223
+ this._startFill(cfg, seq, feature, lonlats, dataProj);
1224
+ } catch (e) {
1225
+ this._demDone(seq, feature, null, lonlats.length, null, 0);
1226
+ }
1227
+ }
1228
+
1229
+ /** @private */
1230
+ _startFill(cfg, seq, feature, lonlats, dataProj) {
1231
+ if (cfg.sample) {
1232
+ // Wrapped in a promise chain so a function that throws synchronously fails the
1233
+ // same way as one that rejects - a source that misbehaves must not leave the
1234
+ // spinner turning forever.
1235
+ Promise.resolve()
1236
+ .then(() => cfg.sample(lonlats, { feature, projection: dataProj }))
1237
+ .then((zs) => this._demDone(seq, feature, zs, lonlats.length, null, 0))
1238
+ .catch(() => this._demDone(seq, feature, null, lonlats.length, null, 0));
1239
+ return;
1240
+ }
1241
+
716
1242
  const sampler = new DemSampler(cfg);
717
1243
  const z = demZoomFor(sampler, lonlats, cfg);
718
- this._demLoading = true;
719
1244
  sampler.load(sampler.tilesFor(lonlats, z)).then((ok) => {
720
- // A newer fill has taken over: it owns _demLoading and will clear it itself.
721
- if (seq !== this._demSeq || this._feature !== feature) return;
722
1245
  const zs = ok ? lonlats.map((ll) => sampler.sample(ll[0], ll[1], z)) : null;
723
- const complete = !!zs && zs.every((v) => v != null && isFinite(v));
724
- this._demLoading = false;
725
- if (complete) { this._demZ = zs; this._demFor = feature; this._compute(); }
726
- // Redrawn even on failure: the spinner has to give way to the flat profile.
727
- this._updateZoomButtons();
728
- if (!this._collapsed) this._render();
729
- /**
730
- * Fired once a terrain-model fill has completed (or failed).
731
- * @event demload
732
- * @property {boolean} ok Whether every point could be sampled.
733
- * @property {number} zoom Tile zoom level used.
734
- * @property {number} tiles Tiles fetched.
735
- */
736
- this.dispatchEvent({ type: 'demload', ok: complete, zoom: z, tiles: sampler.tiles.size });
737
- });
1246
+ this._demDone(seq, feature, zs, lonlats.length, z, sampler.tiles.size);
1247
+ }).catch(() => this._demDone(seq, feature, null, lonlats.length, z, 0));
1248
+ }
1249
+
1250
+ /**
1251
+ * Outcome of a fill, whatever produced it: adopt the elevations, drop the spinner,
1252
+ * redraw, announce.
1253
+ *
1254
+ * A result of the wrong length is refused outright rather than padded. Elevations one
1255
+ * can no longer map to their points are worse than absent ones: they would land on the
1256
+ * wrong places, and nothing downstream would notice.
1257
+ *
1258
+ * @fires demload
1259
+ * @private
1260
+ */
1261
+ _demDone(seq, feature, zs, expected, zoom, tiles) {
1262
+ // A newer fill has taken over: it owns _demLoading and will clear it itself.
1263
+ if (seq !== this._demSeq || this._feature !== feature) return;
1264
+ const usable = Array.isArray(zs) && zs.length === expected && zs.every((v) => v != null && isFinite(v));
1265
+ this._demLoading = false;
1266
+ if (usable) { this._demZ = zs; this._demFor = feature; this._compute(); }
1267
+ // Redrawn even on failure: the spinner has to give way to the flat profile.
1268
+ this._updateZoomButtons();
1269
+ if (!this._collapsed) this._render();
1270
+ /**
1271
+ * Fired once a terrain-model fill has completed (or failed).
1272
+ * @event demload
1273
+ * @property {boolean} ok Whether every point could be sampled.
1274
+ * @property {?number} zoom Tile zoom level used, `null` for a custom sampler.
1275
+ * @property {number} tiles Tiles fetched, `0` for a custom sampler.
1276
+ */
1277
+ this.dispatchEvent({ type: 'demload', ok: usable, zoom, tiles });
738
1278
  }
739
1279
 
740
1280
  // ---------- computation -------------------------------------------
@@ -777,7 +1317,60 @@ import * as d3 from 'd3';
777
1317
  this._addSlope(samples);
778
1318
  this._fullSamples = samples;
779
1319
  this._fullStats = this._statsOf(samples, true);
780
- this._samples = samples; this._stats = this._fullStats;
1320
+ // Un recalcul (option changée, altitudes arrivées du MNT) ne doit pas défaire le
1321
+ // recadrage : la pile est rejouée sur les nouveaux échantillons. Pile vide, on
1322
+ // retombe sur la trace entière, ce que faisait l'affectation directe d'avant.
1323
+ this._applyCrops();
1324
+ }
1325
+ /**
1326
+ * Pixels CSS d'un centimètre physique, mesurés plutôt que déduits.
1327
+ *
1328
+ * Le rapport nominal est de 96 px par pouce, soit 37,8 px par centimètre, mais le zoom
1329
+ * du navigateur le déplace : mesurer un élément d'un centimètre suit ce zoom là où une
1330
+ * constante mentirait. Non mémorisé - la mesure force un calcul de disposition, mais un
1331
+ * rendu est rare et un cache se périmerait au premier Ctrl+molette.
1332
+ */
1333
+ _pxPerCm() {
1334
+ try {
1335
+ const temoin = document.createElement('div');
1336
+ temoin.style.cssText = 'position:absolute;left:-9999px;top:0;width:1cm;height:1cm';
1337
+ (this.element || document.body).appendChild(temoin);
1338
+ const px = temoin.getBoundingClientRect().height;
1339
+ temoin.remove();
1340
+ if (px > 0) return px;
1341
+ } catch (e) { /* document indisponible : on retombe sur la valeur nominale */ }
1342
+ return 96 / 2.54;
1343
+ }
1344
+
1345
+ /**
1346
+ * Échelle verticale du graphe.
1347
+ *
1348
+ * En `'auto'`, le profil remplit la hauteur : c'est lisible, mais l'échelle change d'une
1349
+ * trace à l'autre, si bien qu'une pente de 2 % y prend l'allure d'un mur et que deux
1350
+ * profils ne se comparent pas. Un nombre fixe au contraire les mètres couverts par
1351
+ * centimètre physique.
1352
+ *
1353
+ * La valeur demandée est un **plancher**, non un carcan : une trace dont l'amplitude
1354
+ * dépasse ce que la hauteur peut montrer déborderait du cadre, ce qui est pire que de
1355
+ * perdre la comparabilité. Le graphe n'en dit rien : l'échelle n'est pas une donnée de
1356
+ * la trace et n'a pas à encombrer le dessin ; l'échelle réellement appliquée est
1357
+ * seulement publiée dans `_vScale`, à qui veut la connaître.
1358
+ *
1359
+ * `nice()` n'est pas appliqué en échelle absolue : il arrondit le domaine vers
1360
+ * l'extérieur, donc il fausserait le rapport qu'on vient de fixer.
1361
+ */
1362
+ _yScale(s, zpad, innerH) {
1363
+ const o = this.options, bas = s.min - zpad, haut = s.max + zpad;
1364
+ const vs = typeof o.verticalScale === 'number' ? o.verticalScale : 0;
1365
+ if (!(vs > 0)) {
1366
+ this._vScale = null;
1367
+ return d3.scaleLinear().domain([bas, haut]).range([innerH, 0]).nice();
1368
+ }
1369
+ const cm = innerH / this._pxPerCm(); // hauteur du graphe, en centimètres
1370
+ const etendue = Math.max(vs * cm, haut - bas); // jamais moins qu'il n'en faut
1371
+ const milieu = (bas + haut) / 2;
1372
+ this._vScale = etendue / cm; // m/cm effectivement appliqués
1373
+ return d3.scaleLinear().domain([milieu - etendue / 2, milieu + etendue / 2]).range([innerH, 0]);
781
1374
  }
782
1375
  _statsOf(samples, fromTotal) {
783
1376
  let ascent = 0, descent = 0, zmin = Infinity, zmax = -Infinity, maxAbs = 0;
@@ -849,7 +1442,7 @@ import * as d3 from 'd3';
849
1442
  // 7 sec | 26 min | 1 h 48 min | 2 d 3 h (days + hours normalised)
850
1443
  _fmtDuration(sec) {
851
1444
  if (sec == null || !isFinite(sec)) return '';
852
- const u = (this.options.labels && this.options.labels.durationUnits) || { s: 'sec', m: 'min', h: 'h', d: 'j' };
1445
+ const u = (this.options.labels && this.options.labels.durationUnits) || LOCALES.en.durationUnits;
853
1446
  sec = Math.max(0, Math.round(sec));
854
1447
  if (sec < 60) return sec + ' ' + u.s;
855
1448
  if (sec < 3600) return Math.round(sec / 60) + ' ' + u.m;
@@ -868,7 +1461,7 @@ import * as d3 from 'd3';
868
1461
  * Track title, and its optional link.
869
1462
  *
870
1463
  * Its own method because it is the only part of the header that stays visible once
871
- * collapsed the CSS hides the body, the stats, the legend and the toolbar. `_render`
1464
+ * collapsed: the CSS hides the body, the stats, the legend and the toolbar. `_render`
872
1465
  * is skipped while collapsed, so without a separate entry point the title would keep
873
1466
  * naming the previous track after a change of feature.
874
1467
  */
@@ -901,7 +1494,7 @@ import * as d3 from 'd3';
901
1494
  else if (it === 'descent') { html.push(`<span class="oep-down">${o.labels.descent} ${fmtElevation(s.descent, o.units)}</span>`); text.push(`${o.labels.descent} ${fmtElevation(s.descent, o.units)}`); }
902
1495
  else if (it === 'min') { html.push(fmtElevation(s.min, o.units)); text.push(fmtElevation(s.min, o.units)); }
903
1496
  else if (it === 'max') { html.push(fmtElevation(s.max, o.units)); text.push(fmtElevation(s.max, o.units)); }
904
- else if (it === 'minmax') { const v = `${fmtElevation(s.min, o.units)}–${fmtElevation(s.max, o.units)}`; html.push(v); text.push(v); }
1497
+ else if (it === 'minmax') { const v = `${fmtElevation(s.min, o.units)}-${fmtElevation(s.max, o.units)}`; html.push(v); text.push(v); }
905
1498
  else if (it === 'duration') { if (s.duration != null) { const v = this._fmtDuration(s.duration); html.push(`<span class="oep-time">${esc(o.labels.duration)} ${v}</span>`); text.push(`${o.labels.duration} ${v}`); } }
906
1499
  } else if (it && it.property) {
907
1500
  const val = f.get && f.get(it.property); if (val == null || val === '') return;
@@ -918,7 +1511,7 @@ import * as d3 from 'd3';
918
1511
  const sc = this._slopeScale();
919
1512
  for (let idx = 0; idx <= sc.maxIdx; idx++) {
920
1513
  const color = sc.colorByIndex(idx);
921
- const label = (sc.capped && idx === sc.maxIdx) ? `≥ ${idx * sc.classSize} %` : `${idx * sc.classSize}–${(idx + 1) * sc.classSize} %`;
1514
+ const label = (sc.capped && idx === sc.maxIdx) ? `≥ ${idx * sc.classSize} %` : `${idx * sc.classSize}-${(idx + 1) * sc.classSize} %`;
922
1515
  const item = document.createElement('span'); item.className = 'oep-leg-it';
923
1516
  item.innerHTML = `<i class="oep-sw" style="background:${color}"></i>${label}`;
924
1517
  this._legendEl.appendChild(item);
@@ -981,7 +1574,7 @@ import * as d3 from 'd3';
981
1574
 
982
1575
  const x = d3.scaleLinear().domain([0, s.distance]).range([0, innerW]);
983
1576
  const zpad = (s.max - s.min) * 0.1 || 10;
984
- const y = d3.scaleLinear().domain([s.min - zpad, s.max + zpad]).range([innerH, 0]).nice();
1577
+ const y = this._yScale(s, zpad, innerH);
985
1578
  this._x = x; this._y = y; this._dims = { innerW, innerH };
986
1579
 
987
1580
  if (o.grid) g.append('g').attr('class', 'oep-grid').call(d3.axisLeft(y).ticks(yTicks).tickSize(-innerW).tickFormat(''));
@@ -1014,7 +1607,7 @@ import * as d3 from 'd3';
1014
1607
  g.append('g').attr('class', 'oep-axis oep-axis-y').call(d3.axisLeft(y).ticks(yTicks).tickFormat((d) => o.units === 'imperial' ? Math.round(d * 3.28084) : d));
1015
1608
 
1016
1609
  // A / B markers while a range is being picked
1017
- if (o.zoom && !this._cropMode) {
1610
+ if (o.zoom && this._cropDepth < this._cropMax) {
1018
1611
  [['A', this._zoomA], ['B', this._zoomB]].forEach(([nm, val]) => {
1019
1612
  if (val == null) return;
1020
1613
  const px = x(val);
@@ -1029,61 +1622,264 @@ import * as d3 from 'd3';
1029
1622
  const lbl = focus.append('g').attr('class', 'oep-focus-label'); lbl.append('rect').attr('class', 'oep-focus-bg'); lbl.append('text').attr('class', 'oep-focus-txt');
1030
1623
  this._focus = focus;
1031
1624
 
1032
- const bisect = d3.bisector((d) => d.x).left;
1033
1625
  const pick = (event) => { const mx = d3.pointer(event, g.node())[0]; return Math.max(0, Math.min(s.distance, x.invert(mx))); };
1034
1626
  const overlay = svg.append('rect').attr('class', 'oep-overlay').attr('x', ml).attr('y', mt).attr('width', innerW).attr('height', innerH);
1035
1627
  overlay.on('mousemove', (event) => {
1036
- const x0 = pick(event); const idx = bisect(data, x0, 1);
1037
- const d0 = data[idx - 1], d1 = data[idx] || d0; const d = (x0 - d0.x) > (d1.x - x0) ? d1 : d0;
1628
+ const d = this._sampleAt(pick(event)); if (!d) return;
1038
1629
  this._setFocus(d); if (this._marker) this._marker.setPosition(d.coord);
1039
1630
  }).on('mouseout', () => this._clearFocus());
1040
- overlay.on('click', (event) => {
1041
- if (!this._armed || this._cropMode) return;
1042
- const x0 = pick(event);
1043
- if (this._armed === 'A') this._zoomA = x0; else this._zoomB = x0;
1044
- this._armed = null; this._updateZoomButtons();
1045
- if (this._zoomA != null && this._zoomB != null) this._applyZoom(); else this._render();
1046
- });
1631
+ overlay.on('click', (event) => this._placeBound(pick(event)));
1047
1632
  if (this._armed) overlay.style('cursor', 'col-resize');
1048
1633
  this._adjustAttribution();
1049
1634
  }
1050
1635
 
1636
+ // ---------- PNG export ---------------------------------------------
1637
+ /**
1638
+ * Properties frozen onto the exported clone.
1639
+ *
1640
+ * A serialized SVG carries no stylesheet: rules that live in the CSS file, and every
1641
+ * `var(--oep-*)` they resolve, vanish the moment the markup leaves the document. The
1642
+ * export would come out as black shapes on nothing. So the computed value of each
1643
+ * painting property is written inline, node by node.
1644
+ */
1645
+ static get _EXPORT_PROPS() {
1646
+ return ['fill', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-dasharray',
1647
+ 'stroke-linecap', 'stroke-linejoin', 'opacity', 'font-family', 'font-size',
1648
+ 'font-weight', 'text-anchor', 'shape-rendering'];
1649
+ }
1650
+
1651
+ /** Copies the computed painting styles of `src` onto `dst`, recursively. */
1652
+ _freezeStyles(src, dst) {
1653
+ const props = ElevationProfile._EXPORT_PROPS;
1654
+ const cs = getComputedStyle(src);
1655
+ let inline = '';
1656
+ for (const p of props) { const v = cs.getPropertyValue(p); if (v) inline += `${p}:${v};`; }
1657
+ dst.setAttribute('style', inline);
1658
+ const a = src.children, b = dst.children;
1659
+ for (let i = 0; i < a.length && i < b.length; i++) this._freezeStyles(a[i], b[i]);
1660
+ }
1661
+
1662
+ /**
1663
+ * The whole panel as an SVG string: background, title, stats, legend, chart.
1664
+ *
1665
+ * Rebuilt rather than screenshotted. The header is HTML and the chart is SVG, and the
1666
+ * only way to put HTML in an SVG is a `foreignObject`, which browsers refuse to
1667
+ * rasterise consistently. Redrawing the two text lines as `<text>` is a handful of
1668
+ * lines and works everywhere.
1669
+ *
1670
+ * The current-position indicator is dropped: it marks where the pointer happens to be,
1671
+ * which means nothing once the image is saved.
1672
+ */
1673
+ _exportSvg() {
1674
+ const chart = this._body.querySelector('svg');
1675
+ if (!chart) return null;
1676
+ const cs = getComputedStyle(this.element);
1677
+ const bg = cs.getPropertyValue('--oep-bg').trim() || '#fff';
1678
+ const fg = cs.getPropertyValue('--oep-text').trim() || '#222';
1679
+ const font = cs.fontFamily || 'system-ui, sans-serif';
1680
+ const W = +chart.getAttribute('width'), H = +chart.getAttribute('height');
1681
+ const pad = 8, titleH = 20, statsH = this._statsEl.textContent ? 15 : 0;
1682
+ const legend = (this._legendEl.style.display !== 'none') ? this._legendEl : null;
1683
+ const legH = legend ? 18 : 0;
1684
+ const top = pad + titleH + statsH + legH;
1685
+
1686
+ const clone = chart.cloneNode(true);
1687
+ // The pointer indicator and the hit-test overlay have no place in a saved image.
1688
+ clone.querySelectorAll('.oep-focus, .oep-overlay').forEach((n) => n.remove());
1689
+ this._freezeStyles(chart, clone);
1690
+ // width/height are kept: a nested <svg> without them fills the parent viewport, so
1691
+ // the chart would be stretched over the header's height as well.
1692
+
1693
+ const esc2 = (t) => esc(String(t));
1694
+ const parts = [];
1695
+ parts.push(`<rect width="${W + 2 * pad}" height="${H + top + pad}" fill="${esc2(bg)}"/>`);
1696
+ parts.push(`<text x="${pad}" y="${pad + 13}" style="font-family:${esc2(font)};font-size:13px;font-weight:600;fill:${esc2(fg)}">${esc2(this._titleEl.textContent)}</text>`);
1697
+ if (statsH) parts.push(`<text x="${pad}" y="${pad + titleH + 10}" style="font-family:${esc2(font)};font-size:11px;fill:${esc2(fg)};opacity:.85">${esc2(this._statsEl.textContent)}</text>`);
1698
+ if (legend) {
1699
+ let x = pad;
1700
+ const y = pad + titleH + statsH + 12;
1701
+ for (const item of legend.querySelectorAll('.oep-leg-it')) {
1702
+ const sw = item.querySelector('.oep-sw');
1703
+ const color = sw ? getComputedStyle(sw).backgroundColor : 'none';
1704
+ const label = item.textContent.trim();
1705
+ parts.push(`<rect x="${x}" y="${y - 8}" width="10" height="10" fill="${esc2(color)}"/>`);
1706
+ parts.push(`<text x="${x + 14}" y="${y}" style="font-family:${esc2(font)};font-size:10px;fill:${esc2(fg)}">${esc2(label)}</text>`);
1707
+ x += 14 + label.length * 5.6 + 10;
1708
+ }
1709
+ }
1710
+ parts.push(`<g transform="translate(${pad},${top})">${new XMLSerializer().serializeToString(clone)}</g>`);
1711
+ return {
1712
+ width: W + 2 * pad, height: H + top + pad,
1713
+ svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${W + 2 * pad}" height="${H + top + pad}" ` +
1714
+ `viewBox="0 0 ${W + 2 * pad} ${H + top + pad}">${parts.join('')}</svg>`
1715
+ };
1716
+ }
1717
+
1718
+ /**
1719
+ * Export the whole panel - title, stats, legend and chart - as a PNG.
1720
+ *
1721
+ * Resolves with the Blob. Unless `download` is false, it also saves the file, which is
1722
+ * what the toolbar button does.
1723
+ *
1724
+ * @param {{scale?:number, filename?:string, download?:boolean}} [opts]
1725
+ * `scale` defaults to the device pixel ratio, so the image is not soft on a retina
1726
+ * screen. `filename` defaults to the track title.
1727
+ * @returns {Promise<Blob>}
1728
+ */
1729
+ exportPNG(opts) {
1730
+ const o = opts || {};
1731
+ const built = this._exportSvg();
1732
+ if (!built) return Promise.reject(new Error('ol-elevation-profile: nothing to export'));
1733
+ const scale = o.scale || (typeof window !== 'undefined' && window.devicePixelRatio) || 1;
1734
+ return new Promise((resolve, reject) => {
1735
+ const img = new Image();
1736
+ img.onload = () => {
1737
+ try {
1738
+ const cv = document.createElement('canvas');
1739
+ cv.width = Math.round(built.width * scale);
1740
+ cv.height = Math.round(built.height * scale);
1741
+ const ctx = cv.getContext('2d');
1742
+ ctx.scale(scale, scale);
1743
+ ctx.drawImage(img, 0, 0);
1744
+ cv.toBlob((blob) => {
1745
+ if (!blob) { reject(new Error('ol-elevation-profile: PNG encoding failed')); return; }
1746
+ if (o.download !== false) this._save(blob, o.filename);
1747
+ resolve(blob);
1748
+ }, 'image/png');
1749
+ } catch (e) { reject(e); }
1750
+ };
1751
+ img.onerror = () => reject(new Error('ol-elevation-profile: SVG could not be rasterised'));
1752
+ // Encoded as a data URL rather than a blob: URL - a blob: source taints the canvas
1753
+ // in some browsers, and toBlob would then throw a security error.
1754
+ img.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(built.svg);
1755
+ });
1756
+ }
1757
+
1758
+ /** @private */
1759
+ _save(blob, filename) {
1760
+ const name = filename || `${(this._titleEl.textContent || 'profile').replace(/[\\/:*?"<>|]+/g, '-').trim()}.png`;
1761
+ const url = URL.createObjectURL(blob);
1762
+ const a = document.createElement('a');
1763
+ a.href = url; a.download = name;
1764
+ document.body.appendChild(a); a.click(); a.remove();
1765
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
1766
+ }
1767
+
1051
1768
  // ---------- zoom A/B ----------------------------------------------
1052
1769
  _arm(which) { this._armed = (this._armed === which) ? null : which; this._updateZoomButtons(); if (this._focus) this._render(); }
1770
+ /**
1771
+ * Pose la borne armée à l'abscisse [x0], puis arme l'autre tant qu'elle manque.
1772
+ *
1773
+ * Poser A n'a d'intérêt que pour poser B ensuite : enchaîner d'un clic sur l'autre
1774
+ * évite l'aller-retour par la barre d'outils entre les deux. Les deux bornes réunies,
1775
+ * le recadrage part et rien ne reste armé.
1776
+ */
1777
+ _placeBound(x0) {
1778
+ if (!this._armed || this._cropDepth >= this._cropMax) return;
1779
+ const autre = this._armed === 'A' ? 'B' : 'A';
1780
+ if (this._armed === 'A') this._zoomA = x0; else this._zoomB = x0;
1781
+ const complet = this._zoomA != null && this._zoomB != null;
1782
+ this._armed = complet ? null : autre;
1783
+ this._updateZoomButtons();
1784
+ if (complet) this._pushCrop(this._zoomA, this._zoomB); else this._render();
1785
+ }
1053
1786
  _updateZoomButtons() {
1054
- const show = !!this.options.zoom && !!this._feature;
1055
- this._toolbar.style.display = show ? '' : 'none';
1056
- const crop = this._cropMode;
1057
- this._btnA.style.display = show && !crop ? '' : 'none';
1058
- this._btnB.style.display = show && !crop ? '' : 'none';
1059
- this._btnAll.style.display = show && crop ? '' : 'none';
1787
+ const o = this.options, has = !!this._feature;
1788
+ const show = !!o.zoom && has;
1789
+ const png = !!o.exportPng && has;
1790
+ // The toolbar carries both: it stays visible as long as either has something to show.
1791
+ this._toolbar.style.display = (show || png) ? '' : 'none';
1792
+ this._btnPng.style.display = png ? '' : 'none';
1793
+ const deep = this._cropDepth, peutDescendre = deep < this._cropMax;
1794
+ this._btnA.style.display = show && peutDescendre ? '' : 'none';
1795
+ this._btnB.style.display = show && peutDescendre ? '' : 'none';
1796
+ // Au premier niveau, revenir et tout voir sont le même geste : seul "tout voir"
1797
+ // paraît, ce qui laisse le niveau unique (zoomLevels: 1) exactement tel qu'il était.
1798
+ this._btnBack.style.display = show && deep > 1 ? '' : 'none';
1799
+ this._btnAll.style.display = show && deep > 0 ? '' : 'none';
1060
1800
  this._btnA.classList.toggle('armed', this._armed === 'A');
1061
1801
  this._btnB.classList.toggle('armed', this._armed === 'B');
1062
1802
  }
1063
- _applyZoom() {
1064
- const a = Math.min(this._zoomA, this._zoomB), b = Math.max(this._zoomA, this._zoomB);
1803
+ /**
1804
+ * Recadre sur le sommet de la pile : échantillons, statistiques, origine des abscisses.
1805
+ *
1806
+ * Les bornes empilées sont gardées en abscisse de la trace **entière**, jamais dans le
1807
+ * repère du niveau courant : sinon chaque cran se lirait dans celui du précédent et
1808
+ * l'erreur de rebasage se composerait de niveau en niveau. Rend les coordonnées
1809
+ * cartographiques du niveau, dont le cadrage a besoin.
1810
+ */
1811
+ _applyCrops() {
1812
+ if (!this._crops.length) {
1813
+ this._off = 0; this._samples = this._fullSamples; this._stats = this._fullStats;
1814
+ return null;
1815
+ }
1816
+ const { a, b } = this._crops[this._crops.length - 1];
1065
1817
  const raw = this._fullSamples.filter((p) => p.x >= a && p.x <= b);
1066
- if (raw.length < 2) return;
1067
- const off = raw[0].x; // A devient 0
1068
- const tOff = raw[0].t != null ? raw[0].t : 0;
1069
- const cropped = raw.map((p) => ({ x: p.x - off, z: p.z, coord: p.coord, slope: p.slope, t: (p.t != null ? p.t - tOff : null) }));
1070
- const coords = raw.map((p) => p.coord);
1071
- this._samples = cropped; this._stats = this._statsOf(cropped, false); this._cropMode = true;
1072
- this._updateZoomButtons(); this._render();
1073
- const map = this.getMap();
1074
- if (map) {
1075
- const ext = boundingExtent(coords);
1076
- const view = map.getView();
1077
- try { this._fitRes = view.getResolutionForExtent(ext, map.getSize()); } catch (e) { this._fitRes = null; }
1078
- view.fit(ext, { padding: [40, 40, 40, 40], duration: 400 });
1818
+ if (raw.length < 2) { this._crops.pop(); return this._applyCrops(); }
1819
+ const off = raw[0].x, tOff = raw[0].t != null ? raw[0].t : 0;
1820
+ this._off = off;
1821
+ this._samples = raw.map((p) => ({ x: p.x - off, z: p.z, coord: p.coord, slope: p.slope, t: (p.t != null ? p.t - tOff : null) }));
1822
+ this._stats = this._statsOf(this._samples, false);
1823
+ return raw.map((p) => p.coord);
1824
+ }
1825
+
1826
+ /** Cadre la carte sur un niveau, ou sur la trace entière si [coords] est nul. */
1827
+ _fitMap(coords) {
1828
+ const map = this.getMap(); if (!map) return null;
1829
+ let ext = null;
1830
+ if (coords && coords.length) ext = boundingExtent(coords);
1831
+ else if (this._feature) ext = this._feature.getGeometry().getExtent();
1832
+ if (!ext) return null;
1833
+ const view = map.getView();
1834
+ let res = null;
1835
+ try { res = view.getResolutionForExtent(ext, map.getSize()); } catch (e) { res = null; }
1836
+ view.fit(ext, { padding: [40, 40, 40, 40], duration: 400 });
1837
+ return res;
1838
+ }
1839
+
1840
+ /** Empile un niveau. [a0] et [b0] sont lus dans le repère du niveau courant. */
1841
+ _pushCrop(a0, b0) {
1842
+ this._zoomA = null; this._zoomB = null; this._armed = null;
1843
+ if (this._cropDepth >= this._cropMax) { this._updateZoomButtons(); this._render(); return; }
1844
+ const a = this._off + Math.min(a0, b0), b = this._off + Math.max(a0, b0);
1845
+ let n = 0;
1846
+ for (let k = 0; k < this._fullSamples.length; k++) {
1847
+ const px = this._fullSamples[k].x; if (px >= a && px <= b) n++;
1079
1848
  }
1849
+ if (n < 2) { this._updateZoomButtons(); this._render(); return; }
1850
+ this._crops.push({ a, b, fitRes: null });
1851
+ const coords = this._applyCrops();
1852
+ this._updateZoomButtons(); this._render();
1853
+ const cur = this._crops[this._crops.length - 1];
1854
+ if (cur) cur.fitRes = this._fitMap(coords);
1080
1855
  }
1856
+
1857
+ /**
1858
+ * Recadre sur A..B déjà posés. Conservé : c'était le point d'entrée du niveau unique,
1859
+ * et le supprimer casserait ce qui l'appelle sans rien apporter.
1860
+ */
1861
+ _applyZoom() {
1862
+ if (this._zoomA == null || this._zoomB == null) return;
1863
+ this._pushCrop(this._zoomA, this._zoomB);
1864
+ }
1865
+
1866
+ /** Remonte d'un niveau. */
1867
+ _popCrop() {
1868
+ if (!this._crops.length) return;
1869
+ this._crops.pop();
1870
+ this._zoomA = null; this._zoomB = null; this._armed = null;
1871
+ const coords = this._applyCrops();
1872
+ this._updateZoomButtons(); if (!this._collapsed) this._render();
1873
+ this._fitMap(coords);
1874
+ }
1875
+
1876
+ /** Vide la pile d'un coup, quel que soit le nombre de niveaux. */
1081
1877
  _exitZoom() {
1082
- this._cropMode = false; this._zoomA = null; this._zoomB = null; this._armed = null; this._fitRes = null;
1083
- this._samples = this._fullSamples; this._stats = this._fullStats;
1878
+ this._crops.length = 0;
1879
+ this._zoomA = null; this._zoomB = null; this._armed = null;
1880
+ this._applyCrops();
1084
1881
  this._updateZoomButtons(); if (!this._collapsed) this._render();
1085
- const map = this.getMap();
1086
- if (map && this._feature) map.getView().fit(this._feature.getGeometry().getExtent(), { padding: [40, 40, 40, 40], duration: 400 });
1882
+ this._fitMap(null);
1087
1883
  }
1088
1884
 
1089
1885
  /**
@@ -1098,13 +1894,31 @@ import * as d3 from 'd3';
1098
1894
  const g = this._feature && this._feature.getGeometry();
1099
1895
  if (!g) return null;
1100
1896
  if (!/Polygon/.test(g.getType())) return g.getClosestPoint(coordinate);
1101
- const data = this._fullSamples;
1897
+ const hit = this._projectOn(this._fullSamples, coordinate);
1898
+ return hit ? hit.coord : null;
1899
+ }
1900
+
1901
+ /**
1902
+ * Projeté d'une coordonnée sur la ligne brisée [data] : le point, et son abscisse
1903
+ * curviligne dans le repère de [data].
1904
+ *
1905
+ * Retenir l'échantillon le plus proche ferait sauter le marqueur de sommet en sommet,
1906
+ * l'écart entre deux points de trace étant souvent bien plus grand que le pas du
1907
+ * pointeur. La projection sur les segments donne le point réellement visé.
1908
+ */
1909
+ _projectOn(data, coord) {
1102
1910
  if (!data || !data.length) return null;
1911
+ if (data.length === 1) return { x: data[0].x, coord: data[0].coord.slice(0, 2) };
1103
1912
  let best = null, bd = Infinity;
1104
- for (const p of data) {
1105
- const dx = p.coord[0] - coordinate[0], dy = p.coord[1] - coordinate[1];
1106
- const dd = dx * dx + dy * dy;
1107
- if (dd < bd) { bd = dd; best = p.coord; }
1913
+ for (let i = 1; i < data.length; i++) {
1914
+ const a = data[i - 1].coord, b = data[i].coord;
1915
+ const abx = b[0] - a[0], aby = b[1] - a[1], len2 = abx * abx + aby * aby;
1916
+ // Segment dégénéré (deux points confondus) : le projeté est le point lui-même.
1917
+ let r = len2 > 0 ? ((coord[0] - a[0]) * abx + (coord[1] - a[1]) * aby) / len2 : 0;
1918
+ r = r < 0 ? 0 : (r > 1 ? 1 : r);
1919
+ const px = a[0] + abx * r, py = a[1] + aby * r;
1920
+ const dx = px - coord[0], dy = py - coord[1], dd = dx * dx + dy * dy;
1921
+ if (dd < bd) { bd = dd; best = { x: data[i - 1].x + (data[i].x - data[i - 1].x) * r, coord: [px, py] }; }
1108
1922
  }
1109
1923
  return best;
1110
1924
  }
@@ -1134,11 +1948,42 @@ import * as d3 from 'd3';
1134
1948
  else if (x(d.x) - bb.width / 2 < 0) t.attr('text-anchor', 'start');
1135
1949
  else t.attr('text-anchor', 'middle');
1136
1950
  }
1951
+ /**
1952
+ * Point du profil à une abscisse quelconque, interpolé entre les deux échantillons qui
1953
+ * l'encadrent.
1954
+ *
1955
+ * Se caler sur l'échantillon le plus proche ferait avancer le curseur de sommet en
1956
+ * sommet : sur un tracé peu dense, ou décimé par `maxPoints`, le saut est franc et le
1957
+ * survol perd sa continuité. Les échantillons sont les points *mesurés*, non les seules
1958
+ * positions que le curseur ait le droit d'occuper.
1959
+ *
1960
+ * La pente n'est pas interpolée : `_addSlope` la pose sur le segment qui précède chaque
1961
+ * échantillon, elle est donc constante sur ce segment et vaut celle de son extrémité.
1962
+ * Le temps l'est, mais seulement si les deux bornes en portent un.
1963
+ */
1964
+ _sampleAt(x0) {
1965
+ const data = this._samples;
1966
+ if (!data || !data.length) return null;
1967
+ if (data.length === 1) return data[0];
1968
+ const xa = data[0].x, xb = data[data.length - 1].x;
1969
+ const xc = Math.max(xa, Math.min(xb, x0));
1970
+ const i = Math.min(Math.max(bisectX(data, xc, 1), 1), data.length - 1);
1971
+ const d0 = data[i - 1], d1 = data[i];
1972
+ const span = d1.x - d0.x, r = span > 0 ? (xc - d0.x) / span : 0;
1973
+ const lerp = (a, b) => a + (b - a) * r;
1974
+ return {
1975
+ x: xc,
1976
+ z: lerp(d0.z, d1.z),
1977
+ coord: [lerp(d0.coord[0], d1.coord[0]), lerp(d0.coord[1], d1.coord[1])],
1978
+ slope: d1.slope,
1979
+ t: (d0.t != null && d1.t != null) ? lerp(d0.t, d1.t) : null
1980
+ };
1981
+ }
1982
+ /** Suit une coordonnée de la carte, projetée sur le tracé courant. */
1137
1983
  _focusByCoord(coord) {
1138
- const data = this._samples; if (!data) return;
1139
- let best = null, bd = Infinity;
1140
- for (const p of data) { const dx = p.coord[0] - coord[0], dy = p.coord[1] - coord[1]; const dd = dx * dx + dy * dy; if (dd < bd) { bd = dd; best = p; } }
1141
- if (best) { this._setFocus(best); if (this._marker) this._marker.setPosition(best.coord); }
1984
+ const hit = this._projectOn(this._samples, coord); if (!hit) return;
1985
+ const d = this._sampleAt(hit.x); if (!d) return;
1986
+ this._setFocus(d); if (this._marker) this._marker.setPosition(d.coord);
1142
1987
  }
1143
1988
  _clearFocus() { if (this._focus) this._focus.style('display', 'none'); if (this._marker) this._marker.setPosition(undefined); }
1144
1989
  _clear() {
@@ -1146,7 +1991,7 @@ import * as d3 from 'd3';
1146
1991
  this._legendEl.innerHTML = ''; this._legendEl.style.display = 'none';
1147
1992
  this._titleEl.textContent = this.options.labels.empty; this._titleEl.removeAttribute('title');
1148
1993
  this._statsEl.innerHTML = ''; this._statsEl.removeAttribute('title');
1149
- this._cropMode = false; this._demLoading = false; this._updateZoomButtons();
1994
+ this._crops = []; this._off = 0; this._demLoading = false; this._updateZoomButtons();
1150
1995
  this._clearFocus();
1151
1996
  this.element.style.display = 'none';
1152
1997
  this._adjustAttribution();