@uvalib/web-components 1.3.0 → 1.4.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.
@@ -11,6 +11,7 @@ import { installLightDomStyles } from '../../base/light-dom-styles.js';
11
11
  import { normalize, safeHref, SourceChildren } from '../../base/source-children.js';
12
12
  import { UvalibElement } from '../../base/UvalibElement.js';
13
13
  import { accessible } from '../../styles/accessible.js';
14
+ const countOf = (p) => p && Number.isFinite(p.count) && p.count > 0 ? p.count : 0;
14
15
  /** The analytics category. */
15
16
  const TAG = 'uvalib-map';
16
17
  /** OpenStreetMap's standard tiles: fine for low traffic only (see the README). */
@@ -22,6 +23,17 @@ const GROUNDS = [38.0336, -78.5048];
22
23
  const MIN_DOT = 24;
23
24
  const MAX_DOT = 56;
24
25
  const HIT = 44;
26
+ /**
27
+ * Space kept between two visible markers' hit areas: closer ones are grouped. Every target is
28
+ * at least 44px, so WCAG 2.5.8 only needs them not to overlap; a few pixels keep them visibly
29
+ * apart without grouping places that are merely close.
30
+ */
31
+ const GROUP_GAP = 4;
32
+ /** Space between the places of an open ring (and the group), generous since they are close by design. */
33
+ const GAP = 24;
34
+ /** A group's dot: big enough for the number of places in it, and never larger than this. */
35
+ const MIN_GROUP_DOT = 32;
36
+ const MAX_GROUP_DOT = 64;
25
37
  const MAP_HEIGHT = 'var(--uvalib-map-height, min(24rem, 75vw))';
26
38
  /** Shown above the map, and kept in step with base.css's pre-upgrade placeholder. */
27
39
  export const MAP_INSTRUCTIONS = 'Tab or arrow keys move between places; Enter opens one. With the map focused, arrow keys pan and + and − zoom.';
@@ -128,6 +140,7 @@ const structuralRules = (host) => `
128
140
  cursor: pointer; font: inherit; color: inherit;
129
141
  }
130
142
  ${host} .uvalib-map-marker .dot { box-sizing: border-box; display: block; flex: none; inline-size: var(--d); block-size: var(--d); border-radius: 50%; }
143
+ ${host} .uvalib-map-marker.is-group .dot { display: flex; align-items: center; justify-content: center; font-weight: 700; line-height: 1; }
131
144
  ${host} .leaflet-bar a {
132
145
  box-sizing: border-box; display: flex !important; align-items: center; justify-content: center;
133
146
  inline-size: 44px !important; block-size: 44px !important; line-height: 1 !important;
@@ -137,8 +150,9 @@ const structuralRules = (host) => `
137
150
  }
138
151
  @media (forced-colors: active) {
139
152
  ${host} .uvalib-map-marker .dot {
140
- forced-color-adjust: none; background: Canvas !important; border: 3px solid CanvasText !important; box-shadow: none !important;
153
+ forced-color-adjust: none; background: Canvas !important; color: CanvasText !important; border: 3px solid CanvasText !important; box-shadow: none !important;
141
154
  }
155
+ ${host} .uvalib-map-marker.is-group .dot { border-style: double !important; border-width: 6px !important; }
142
156
  ${host} .uvalib-map-marker.is-active .dot { outline: 3px solid Highlight; outline-offset: 3px; }
143
157
  ${host} .uvalib-map-marker .marker:focus-visible .dot { outline: 3px solid Highlight; outline-offset: 6px; }
144
158
  ${host} .map, ${host} .map .leaflet-bar, ${host} .map .leaflet-bar a, ${host} .map .leaflet-tooltip,
@@ -172,6 +186,16 @@ const shadowStructure = unsafeCSS(structuralRules(':host'));
172
186
  * list entry; hovering or focusing a list entry highlights its marker (a ring and a larger
173
187
  * dot, not colour alone) and brings it into view.
174
188
  *
189
+ * Markers whose 44px targets would overlap at the current zoom are drawn as one group
190
+ * marker (regrouped after every zoom and resize): a button
191
+ * showing how many places it holds, sized by their summed count and named like "The Rotunda
192
+ * and 2 more places, 3,610 photos" (the largest place's name; `place-label` is the noun).
193
+ * Choosing it zooms in until its places part; when they cannot (one point, or the
194
+ * maximum zoom) it spreads them in a ring around it instead, with focus on the first;
195
+ * Escape or a zoom closes the ring and focus returns to the group. The arrow keys move
196
+ * between the markers shown (a group is one); a place in the list that is in a group
197
+ * highlights the group, whose tooltip names the place.
198
+ *
175
199
  * The map is a region named by `label`, after a "Skip map, go to the list" link and a line
176
200
  * of key instructions. It opens on the bounds of the places, or on `center` and `zoom`. The
177
201
  * zoom buttons are 44px with a visible focus ring; the attribution stays. Tiles come from
@@ -182,8 +206,8 @@ const shadowStructure = unsafeCSS(structuralRules(':host'));
182
206
  *
183
207
  * @tagname uvalib-map
184
208
  * @slot - A `<ul>` or `<ol>` of places: each `<li>` holds an `<a href>` (or the `<li>` itself) with `data-lat`, `data-lng` and optionally `data-count`, `data-id` and `data-description`. Used when `items` is empty; without JavaScript it is the list.
185
- * @fires select - A marker was chosen (click, Enter or Space). `detail` is `{ item }`. Cancelable: for a place with `href`, `preventDefault()` keeps the page from following the link. Bubbles and is composed.
186
- * @fires uvalib-analytics-event - For `<site-analytics>`: `['uvalib-map', 'select', '<label>', <position from 1>]` when a marker is chosen, and `['uvalib-map', 'zoom', '<label>', <zoom level>]` 1 s after the last zoom-button press. Never a place's name, coordinates or URL. Bubbles and is composed.
209
+ * @fires select - A place's marker was chosen (click, Enter or Space); never a group's. `detail` is `{ item }`. Cancelable: for a place with `href`, `preventDefault()` keeps the page from following the link. Bubbles and is composed.
210
+ * @fires uvalib-analytics-event - For `<site-analytics>`: `['uvalib-map', 'select', '<label>', <position from 1>]` when a place's marker is chosen, `['uvalib-map', 'expand', '<label>', <places in it>]` when a group is chosen (it zooms in or opens its ring), and `['uvalib-map', 'zoom', '<label>', <zoom level>]` 1 s after the last zoom-button press. Never a place's name, coordinates or URL. Bubbles and is composed.
187
211
  * @csspart map - The map region (the Leaflet container).
188
212
  * @csspart instructions - The line of key instructions above the map.
189
213
  * @csspart list - The list of places.
@@ -239,6 +263,16 @@ export class UvalibMap extends UvalibElement {
239
263
  box-shadow: 0 0 0 1px var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b));
240
264
  transition: transform 0.15s ease, box-shadow 0.15s ease;
241
265
  }
266
+ /* A group: its number of places, and a second ring (not colour alone). */
267
+ .uvalib-map-marker.is-group .dot {
268
+ color: var(--uva-color-on-accent, #fff);
269
+ font-family: var(--uva-font-family, system-ui, sans-serif);
270
+ font-size: 0.875rem;
271
+ box-shadow:
272
+ 0 0 0 1px var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b)),
273
+ 0 0 0 3px var(--uva-color-on-accent, #fff),
274
+ 0 0 0 5px var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b));
275
+ }
242
276
  .uvalib-map-marker.is-active .dot {
243
277
  transform: scale(1.25);
244
278
  box-shadow:
@@ -297,6 +331,7 @@ export class UvalibMap extends UvalibElement {
297
331
  }
298
332
  .leaflet-tooltip::before { display: none !important; }
299
333
  .tip-name { display: block; font-weight: 600; }
334
+ .tip-note { display: block; }
300
335
  .places {
301
336
  display: grid;
302
337
  grid-template-columns: repeat(auto-fill, minmax(min(100%, 15rem), 1fr));
@@ -359,6 +394,11 @@ export class UvalibMap extends UvalibElement {
359
394
  this.label = '';
360
395
  /** The noun after each count, plural ("photos"); a count of one drops a trailing s. */
361
396
  this.countLabel = 'items';
397
+ /**
398
+ * The noun for places in a group's name, plural: "The Rotunda and 2 more places" (one
399
+ * drops a trailing s: "and 1 more place"). For example "rooms".
400
+ */
401
+ this.placeLabel = 'places';
362
402
  /** The tile URL template (`{z}/{x}/{y}`, optionally `{s}` and `{r}`). */
363
403
  this.tileUrl = OSM_TILE_URL;
364
404
  /** Tiles for the page's dark mode. Without it, dark mode filters the light tiles instead. */
@@ -369,18 +409,29 @@ export class UvalibMap extends UvalibElement {
369
409
  this.center = '';
370
410
  this.sourceItems = [];
371
411
  this.hasLeaflet = false;
372
- this.active = -1;
412
+ /** The highlighted target: "3" a place, "g:1,3" a group, "" none. */
413
+ this.active = '';
373
414
  this.dark = false;
374
415
  this.uid = `uvalib-map-${++instanceCounter}`;
375
416
  this.sourceKey = '[]';
376
417
  this.markers = [];
418
+ this.dots = [];
419
+ this.maxCount = 0;
420
+ /** The groups drawn at the current zoom, by key. */
421
+ this.groups = new Map();
422
+ /** A grouped place's index → its group's key. */
423
+ this.groupOf = new Map();
424
+ /** The key of the group whose places are spread in a ring, or "". */
425
+ this.ring = '';
426
+ /** The visible markers' controls, in keyboard (and document) order. */
427
+ this.order = [];
377
428
  this.drawn = [];
378
429
  this.reduceMotion = false;
379
430
  /** The visitor moved the map: a resize no longer refits it. */
380
431
  this.userMoved = false;
381
432
  this.fitting = false;
382
- this.hoverIndex = -1;
383
- this.focusIndex = -1;
433
+ this.hoverKey = '';
434
+ this.focusKey = '';
384
435
  this.dismissed = false;
385
436
  this.warnedLabel = false;
386
437
  this.warnedLeaflet = false;
@@ -394,9 +445,8 @@ export class UvalibMap extends UvalibElement {
394
445
  this.queueZoomReport();
395
446
  return;
396
447
  }
397
- const i = this.indexOf(e);
398
- const p = this.places[i];
399
- if (i < 0 || !p)
448
+ const key = this.targetOf(e);
449
+ if (!key)
400
450
  return;
401
451
  // The end of a drag that started on a marker is not a choice (a key press always is).
402
452
  const drag = this.map?.dragging;
@@ -404,6 +454,14 @@ export class UvalibMap extends UvalibElement {
404
454
  e.preventDefault();
405
455
  return;
406
456
  }
457
+ if (key.startsWith('g:')) {
458
+ this.expand(key.slice(2));
459
+ return;
460
+ }
461
+ const i = Number(key);
462
+ const p = this.places[i];
463
+ if (!p)
464
+ return;
407
465
  trackEvent(this, [TAG, 'select', this.label, i + 1]);
408
466
  const go = this.dispatchEvent(new CustomEvent('select', {
409
467
  detail: { item: p },
@@ -422,20 +480,32 @@ export class UvalibMap extends UvalibElement {
422
480
  t.closest('a').click();
423
481
  return;
424
482
  }
425
- const i = this.indexOf(e);
426
- if (i < 0)
483
+ const ctl = t.closest?.('.marker');
484
+ if (!ctl)
427
485
  return;
428
- const order = this.markers.flatMap((m, j) => (m ? [j] : []));
429
- const at = order.indexOf(i);
430
- let next = -1;
486
+ // Escape in a ring (on its places or its group) closes it; focus goes to the group.
487
+ if (e.key === 'Escape' && this.ring) {
488
+ const key = this.keyOf(ctl);
489
+ const g = this.groups.get(this.ring);
490
+ if (g && (key === `g:${g.key}` || g.members.includes(Number(key)))) {
491
+ e.preventDefault();
492
+ e.stopPropagation();
493
+ this.unring();
494
+ this.regroup();
495
+ return;
496
+ }
497
+ }
498
+ const order = this.order;
499
+ const at = order.indexOf(ctl);
500
+ let next;
431
501
  if (e.key === 'ArrowRight' || e.key === 'ArrowDown')
432
- next = order[at + 1] ?? -1;
502
+ next = order[at + 1];
433
503
  else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp')
434
- next = order[at - 1] ?? -1;
504
+ next = at > 0 ? order[at - 1] : undefined;
435
505
  else if (e.key === 'Home')
436
- next = order[0] ?? -1;
506
+ next = order[0];
437
507
  else if (e.key === 'End')
438
- next = order[order.length - 1] ?? -1;
508
+ next = order[order.length - 1];
439
509
  else if (e.key === ' ' && t.localName === 'a') {
440
510
  // A link marker is a control here: Space chooses it, like Enter.
441
511
  e.preventDefault();
@@ -446,31 +516,31 @@ export class UvalibMap extends UvalibElement {
446
516
  return;
447
517
  e.preventDefault();
448
518
  e.stopPropagation();
449
- if (next >= 0) {
450
- this.reveal(next);
451
- this.markerEl(next)?.querySelector('.marker')?.focus();
519
+ if (next) {
520
+ this.reveal(this.keyOf(next));
521
+ next.focus();
452
522
  }
453
523
  };
454
524
  this.onMapFocusIn = (e) => {
455
- const i = this.indexOf(e);
456
- if (i < 0)
525
+ const key = this.targetOf(e);
526
+ if (!key)
457
527
  return;
458
- this.focusIndex = i;
528
+ this.focusKey = key;
459
529
  this.dismissed = false;
460
- this.reveal(i);
530
+ this.reveal(key);
461
531
  this.syncActive();
462
532
  };
463
533
  this.onMapFocusOut = (e) => {
464
- if (this.indexOf(e) < 0)
534
+ if (!this.targetOf(e))
465
535
  return;
466
536
  const to = e.relatedTarget;
467
537
  if (to?.closest?.('.marker'))
468
538
  return; // the next marker's focusin sets it
469
- this.focusIndex = -1;
539
+ this.focusKey = '';
470
540
  this.syncActive();
471
541
  };
472
542
  this.onMapLeave = () => {
473
- this.hoverIndex = -1;
543
+ this.hoverKey = '';
474
544
  this.syncActive();
475
545
  };
476
546
  /** The skip link: focus the list (a fragment link cannot reach into a shadow root). */
@@ -480,7 +550,7 @@ export class UvalibMap extends UvalibElement {
480
550
  };
481
551
  new SourceChildren(this, () => this.lightDom, (nodes) => this.readList(nodes));
482
552
  this.addEventListener('keydown', (e) => {
483
- if (e.key === 'Escape' && this.active >= 0) {
553
+ if (e.key === 'Escape' && this.active) {
484
554
  this.dismissed = true;
485
555
  this.syncActive();
486
556
  }
@@ -616,16 +686,20 @@ export class UvalibMap extends UvalibElement {
616
686
  changed.has('attribution') ||
617
687
  changed.has('dark')))
618
688
  this.drawTiles();
619
- if (created || this.places !== this.drawn || changed.has('countLabel')) {
689
+ if (created ||
690
+ this.places !== this.drawn ||
691
+ changed.has('countLabel') ||
692
+ changed.has('placeLabel')) {
620
693
  this.drawMarkers();
621
694
  if (created || !this.userMoved)
622
695
  this.fit();
696
+ this.regroup();
623
697
  }
624
698
  else if (changed.has('center') || changed.has('zoom')) {
625
699
  this.fit();
626
700
  }
627
701
  if (changed.has('active'))
628
- this.showActive(changed.get('active'));
702
+ this.showActive();
629
703
  }
630
704
  get container() {
631
705
  return this.renderRoot.querySelector(`#${this.uid}-map`);
@@ -668,6 +742,14 @@ export class UvalibMap extends UvalibElement {
668
742
  if (!this.fitting)
669
743
  this.userMoved = true;
670
744
  });
745
+ // Any zoom closes a ring; every zoom regroups.
746
+ map.on('zoomstart', () => {
747
+ if (!this.ring)
748
+ return;
749
+ this.unring();
750
+ this.regroup();
751
+ });
752
+ map.on('zoomend', () => this.regroup());
671
753
  this.drawTiles();
672
754
  this.ro = new ResizeObserver(() => {
673
755
  if (!this.map)
@@ -675,6 +757,7 @@ export class UvalibMap extends UvalibElement {
675
757
  this.map.invalidateSize({ animate: false });
676
758
  if (!this.userMoved)
677
759
  this.fit();
760
+ this.regroup();
678
761
  });
679
762
  this.ro.observe(el);
680
763
  return true;
@@ -688,6 +771,11 @@ export class UvalibMap extends UvalibElement {
688
771
  this.tiles = undefined;
689
772
  this.tooltip = undefined;
690
773
  this.markers = [];
774
+ this.groups.clear();
775
+ this.groupOf.clear();
776
+ this.ring = '';
777
+ this.order = [];
778
+ this.activeIcon = undefined;
691
779
  this.drawn = [];
692
780
  this.userMoved = false;
693
781
  }
@@ -716,55 +804,321 @@ export class UvalibMap extends UvalibElement {
716
804
  href(p) {
717
805
  return p.href && safeHref(p.href, this.ownerDocument.baseURI) ? p.href : null;
718
806
  }
807
+ /** A group's dot: by the square root of its summed count, between MIN_GROUP_DOT and MAX_GROUP_DOT. */
808
+ groupDot(sum) {
809
+ const max = this.maxCount;
810
+ if (!(max > 0) || !(sum > 0))
811
+ return MIN_GROUP_DOT;
812
+ const d = Math.round(MIN_DOT + (MAX_DOT - MIN_DOT) * Math.sqrt(sum / max));
813
+ return Math.min(MAX_GROUP_DOT, Math.max(MIN_GROUP_DOT, d));
814
+ }
815
+ /** "The Rotunda and 2 more places": the largest place's name and how many more. */
816
+ groupName(members) {
817
+ const n = members.length - 1;
818
+ return `${this.places[members[0]].name} and ${fmt(n)} more ${noun(this.placeLabel || 'places', n)}`;
819
+ }
820
+ /** A marker's hit area (px): its dot, at least 44px; a group's dot for several places. */
821
+ hitOf(members) {
822
+ if (members.length === 1)
823
+ return Math.max(HIT, this.dots[members[0]] ?? MIN_DOT);
824
+ return Math.max(HIT, this.groupDot(members.reduce((s, i) => s + countOf(this.places[i]), 0)));
825
+ }
826
+ makeMarker(ll, ctl, d, className) {
827
+ const L = this.L;
828
+ const hit = Math.max(HIT, d);
829
+ return L.marker(ll, {
830
+ icon: L.divIcon({
831
+ className,
832
+ html: ctl,
833
+ iconSize: [hit, hit],
834
+ iconAnchor: [hit / 2, hit / 2],
835
+ }),
836
+ keyboard: false,
837
+ // Smaller dots above larger ones.
838
+ zIndexOffset: (MAX_DOT - d) * 10,
839
+ });
840
+ }
841
+ /** The control inside a marker: its dot (with `text`, for a group) and its hidden name. */
842
+ makeControl(tag, d, label, text = '') {
843
+ const doc = this.ownerDocument;
844
+ const ctl = doc.createElement(tag);
845
+ if (ctl instanceof HTMLButtonElement)
846
+ ctl.type = 'button';
847
+ ctl.className = 'marker';
848
+ ctl.style.setProperty('--d', `${d}px`);
849
+ const dot = doc.createElement('span');
850
+ dot.className = 'dot';
851
+ dot.setAttribute('aria-hidden', 'true');
852
+ dot.textContent = text;
853
+ const name = doc.createElement('span');
854
+ name.className = 'visually-hidden';
855
+ name.textContent = label;
856
+ ctl.append(dot, name);
857
+ return ctl;
858
+ }
859
+ /** One marker per place, not yet on the map: `regroup()` adds the ones not in a group. */
719
860
  drawMarkers() {
720
861
  const { L, map } = this;
721
862
  if (!L || !map)
722
863
  return;
723
864
  for (const m of this.markers)
724
865
  m?.remove();
866
+ for (const g of this.groups.values())
867
+ g.marker.remove();
868
+ this.groups.clear();
869
+ this.groupOf.clear();
870
+ this.ring = '';
871
+ this.order = [];
872
+ this.activeIcon = undefined;
725
873
  const places = this.places;
726
874
  this.drawn = places;
727
- const max = Math.max(0, ...places.map((p) => (Number.isFinite(p.count) ? p.count : 0)));
728
- const doc = this.ownerDocument;
875
+ this.maxCount = Math.max(0, ...places.map(countOf));
876
+ this.dots = places.map((p) => this.dotSize(p.count, this.maxCount));
729
877
  this.markers = places.map((p, i) => {
730
878
  if (!validPlace(p))
731
879
  return undefined;
732
- const d = this.dotSize(p.count, max);
733
- const hit = Math.max(HIT, d);
880
+ const d = this.dots[i];
734
881
  const href = this.href(p);
735
- const ctl = doc.createElement(href ? 'a' : 'button');
882
+ const ctl = this.makeControl(href ? 'a' : 'button', d, this.placeName(p));
736
883
  if (ctl instanceof HTMLAnchorElement)
737
884
  ctl.href = href;
738
- else
739
- ctl.type = 'button';
740
- ctl.className = 'marker';
741
885
  ctl.dataset.index = String(i);
742
- ctl.style.setProperty('--d', `${d}px`);
743
- const dot = doc.createElement('span');
744
- dot.className = 'dot';
745
- dot.setAttribute('aria-hidden', 'true');
746
- const name = doc.createElement('span');
747
- name.className = 'visually-hidden';
748
- name.textContent = this.placeName(p);
749
- ctl.append(dot, name);
750
- const marker = L.marker([p.lat, p.lng], {
751
- icon: L.divIcon({
752
- className: 'uvalib-map-marker',
753
- html: ctl,
754
- iconSize: [hit, hit],
755
- iconAnchor: [hit / 2, hit / 2],
756
- }),
757
- keyboard: false,
758
- // Smaller dots above larger ones, so every one stays reachable by pointer.
759
- zIndexOffset: (MAX_DOT - d) * 10,
760
- });
761
- marker.on('mouseover', () => this.hover(i));
762
- return marker.addTo(map);
886
+ const marker = this.makeMarker([p.lat, p.lng], ctl, d, 'uvalib-map-marker');
887
+ marker.on('mouseover', () => this.hover(String(i)));
888
+ return marker;
889
+ });
890
+ this.hoverKey = '';
891
+ this.focusKey = '';
892
+ if (this.active)
893
+ this.active = '';
894
+ }
895
+ /**
896
+ * Greedy screen-space grouping at `zoom`: largest count first, each place takes every
897
+ * later one whose hit area (plus GROUP_GAP) would overlap its own; then groups whose larger
898
+ * markers now overlap merge, until none do. Each group's largest place comes first.
899
+ */
900
+ cluster(idx, zoom) {
901
+ const map = this.map;
902
+ const places = this.places;
903
+ const byCount = (a, b) => countOf(places[b]) - countOf(places[a]) || a - b;
904
+ const pt = new Map(idx.map((i) => [i, map.project([places[i].lat, places[i].lng], zoom)]));
905
+ const clash = (a, b) => {
906
+ const p = pt.get(a[0]);
907
+ const q = pt.get(b[0]);
908
+ const t = (this.hitOf(a) + this.hitOf(b)) / 2 + GROUP_GAP;
909
+ return Math.abs(p.x - q.x) < t && Math.abs(p.y - q.y) < t;
910
+ };
911
+ const sorted = [...idx].sort(byCount);
912
+ const out = [];
913
+ const taken = new Set();
914
+ for (const i of sorted) {
915
+ if (taken.has(i))
916
+ continue;
917
+ const c = [i];
918
+ taken.add(i);
919
+ for (const j of sorted)
920
+ if (!taken.has(j) && clash([i], [j])) {
921
+ c.push(j);
922
+ taken.add(j);
923
+ }
924
+ out.push(c);
925
+ }
926
+ for (let merged = true; merged;) {
927
+ merged = false;
928
+ for (let a = 0; a < out.length && !merged; a++)
929
+ for (let b = a + 1; b < out.length && !merged; b++)
930
+ if (clash(out[a], out[b])) {
931
+ out[a] = [...out[a], ...out[b]].sort(byCount);
932
+ out.splice(b, 1);
933
+ merged = true;
934
+ }
935
+ }
936
+ return out;
937
+ }
938
+ makeGroup(key, members) {
939
+ const p = this.places;
940
+ const lead = p[members[0]];
941
+ const sum = members.reduce((s, i) => s + countOf(p[i]), 0);
942
+ const counted = members.some((i) => Number.isFinite(p[i].count));
943
+ const d = this.groupDot(sum);
944
+ const name = this.groupName(members);
945
+ const ctl = this.makeControl('button', d, counted ? `${name}, ${this.countText(sum)}` : name, String(members.length));
946
+ ctl.dataset.group = key;
947
+ const marker = this.makeMarker([lead.lat, lead.lng], ctl, d, 'uvalib-map-marker is-group');
948
+ marker.on('mouseover', () => this.hover(`g:${key}`));
949
+ return { key, members, marker, ctl, d, sum, counted };
950
+ }
951
+ /** The marker control that has focus, if any. */
952
+ focusedControl() {
953
+ const r = this.renderRoot;
954
+ const a = r instanceof ShadowRoot ? r.activeElement : this.ownerDocument.activeElement;
955
+ const ctl = a?.closest?.('.marker');
956
+ return ctl && this.container?.contains(ctl) ? ctl : null;
957
+ }
958
+ /**
959
+ * Group the markers whose hit areas would overlap at the current zoom, show one marker
960
+ * per group (and the ring's places, when one is open), keep the markers' document order
961
+ * the keyboard order, and give focus back if its marker went.
962
+ */
963
+ regroup() {
964
+ const { map } = this;
965
+ if (!map || !map._loaded)
966
+ return;
967
+ const had = this.focusedControl();
968
+ const hadKey = had ? this.keyOf(had) : '';
969
+ const lead = hadKey.startsWith('g:')
970
+ ? (this.groups.get(hadKey.slice(2))?.members[0] ?? -1)
971
+ : hadKey
972
+ ? Number(hadKey)
973
+ : -1;
974
+ const idx = this.markers.flatMap((m, i) => (m ? [i] : []));
975
+ const groups = new Map();
976
+ this.groupOf.clear();
977
+ for (const c of this.cluster(idx, map.getZoom())) {
978
+ if (c.length < 2)
979
+ continue;
980
+ const key = [...c].sort((a, b) => a - b).join(',');
981
+ groups.set(key, this.groups.get(key) ?? this.makeGroup(key, c));
982
+ for (const i of c)
983
+ this.groupOf.set(i, key);
984
+ }
985
+ for (const [key, g] of this.groups)
986
+ if (!groups.has(key))
987
+ g.marker.remove();
988
+ if (this.ring && !groups.has(this.ring))
989
+ this.unring();
990
+ this.groups = groups;
991
+ // The visible markers, by the first place in each; a ring's places follow its group.
992
+ const spots = [];
993
+ const shown = new Set();
994
+ for (const i of idx)
995
+ if (!this.groupOf.has(i)) {
996
+ shown.add(i);
997
+ spots.push({ first: i, list: [this.spot(i)] });
998
+ }
999
+ for (const g of groups.values()) {
1000
+ const list = [{ marker: g.marker, ctl: g.ctl }];
1001
+ if (this.ring === g.key)
1002
+ for (const i of g.members) {
1003
+ shown.add(i);
1004
+ list.push(this.spot(i));
1005
+ }
1006
+ spots.push({ first: Number(g.key.split(',')[0]), list });
1007
+ }
1008
+ spots.sort((a, b) => a.first - b.first);
1009
+ const added = new Set();
1010
+ for (const i of idx) {
1011
+ const m = this.markers[i];
1012
+ if (shown.has(i) && !map.hasLayer(m)) {
1013
+ m.addTo(map);
1014
+ added.add(m.getElement());
1015
+ }
1016
+ else if (!shown.has(i) && map.hasLayer(m))
1017
+ m.remove();
1018
+ }
1019
+ for (const g of groups.values())
1020
+ if (!map.hasLayer(g.marker)) {
1021
+ g.marker.addTo(map);
1022
+ added.add(g.marker.getElement());
1023
+ }
1024
+ const flat = spots.flatMap((s) => s.list);
1025
+ // Move only the markers just added, so a focused one is never moved.
1026
+ const els = flat.map((s) => s.marker.getElement());
1027
+ for (let k = els.length - 2; k >= 0; k--)
1028
+ if (added.has(els[k]))
1029
+ els[k + 1].before(els[k]);
1030
+ this.order = flat.map((s) => s.ctl);
1031
+ for (const g of groups.values())
1032
+ if (this.ring === g.key)
1033
+ g.ctl.setAttribute('aria-expanded', 'true');
1034
+ else
1035
+ g.ctl.removeAttribute('aria-expanded');
1036
+ if (had && !had.isConnected && lead >= 0) {
1037
+ const to = shown.has(lead)
1038
+ ? this.spot(lead).ctl
1039
+ : groups.get(this.groupOf.get(lead) ?? '')?.ctl;
1040
+ to?.focus({ preventScroll: true });
1041
+ }
1042
+ // A group hovered or focused that is gone highlights nothing.
1043
+ const gone = (k) => k.startsWith('g:') && !groups.has(k.slice(2));
1044
+ if (gone(this.hoverKey))
1045
+ this.hoverKey = '';
1046
+ if (gone(this.focusKey))
1047
+ this.focusKey = '';
1048
+ this.syncActive();
1049
+ this.showActive();
1050
+ }
1051
+ spot(i) {
1052
+ const marker = this.markers[i];
1053
+ const html = marker.options.icon.options.html;
1054
+ return { marker, ctl: html };
1055
+ }
1056
+ /** The first zoom (in zoomSnap steps, up to the maximum) at which a group's places part. */
1057
+ splitZoom(members) {
1058
+ const map = this.map;
1059
+ const step = map.options.zoomSnap || 1;
1060
+ const max = map.getMaxZoom();
1061
+ for (let z = map.getZoom() + step; z <= max + 1e-9; z += step)
1062
+ if (this.cluster(members, z).length > 1)
1063
+ return z;
1064
+ return undefined;
1065
+ }
1066
+ /** A group chosen: zoom in until its places part, or (when they cannot) spread them in a ring. */
1067
+ expand(key) {
1068
+ const { L, map } = this;
1069
+ const g = this.groups.get(key);
1070
+ if (!L || !map || !g)
1071
+ return;
1072
+ if (this.ring === key) {
1073
+ this.unring();
1074
+ this.regroup();
1075
+ return;
1076
+ }
1077
+ trackEvent(this, [TAG, 'expand', this.label, g.members.length]);
1078
+ const z = this.splitZoom(g.members);
1079
+ if (z === undefined) {
1080
+ this.spread(g);
1081
+ return;
1082
+ }
1083
+ const bounds = L.latLngBounds(g.members.map((i) => [this.places[i].lat, this.places[i].lng]));
1084
+ map.setView(bounds.getCenter(), z, { animate: !this.reduceMotion });
1085
+ }
1086
+ /**
1087
+ * Spread a group's places in a ring around it, far enough apart that each 44px target
1088
+ * keeps 24px from its neighbours and from the group's own marker; focus the first.
1089
+ */
1090
+ spread(g) {
1091
+ const map = this.map;
1092
+ if (this.ring)
1093
+ this.unring();
1094
+ const z = map.getZoom();
1095
+ const c = map.project(g.marker.getLatLng(), z);
1096
+ const h = Math.max(...g.members.map((i) => Math.max(HIT, this.dots[i] ?? MIN_DOT)));
1097
+ const n = g.members.length;
1098
+ // Square hit areas: centres √2 × (size + gap) apart are clear in every direction.
1099
+ const r = Math.ceil(Math.max(((h + GAP) * Math.SQRT2) / (2 * Math.sin(Math.PI / n)), ((Math.max(HIT, g.d) + h) / 2 + GAP) * Math.SQRT2));
1100
+ g.members.forEach((i, k) => {
1101
+ const a = -Math.PI / 2 + (2 * Math.PI * k) / n;
1102
+ this.markers[i].setLatLng(map.unproject(c.add([r * Math.cos(a), r * Math.sin(a)]), z));
763
1103
  });
764
- this.hoverIndex = -1;
765
- this.focusIndex = -1;
766
- if (this.active !== -1)
767
- this.active = -1;
1104
+ this.ring = g.key;
1105
+ this.regroup();
1106
+ const size = map.getSize();
1107
+ const pad = r + h / 2 + 8;
1108
+ const at = map.latLngToContainerPoint(g.marker.getLatLng());
1109
+ if (at.x < pad || at.y < pad || at.x > size.x - pad || at.y > size.y - pad)
1110
+ map.panTo(g.marker.getLatLng(), { animate: !this.reduceMotion });
1111
+ this.spot(g.members[0]).ctl.focus();
1112
+ }
1113
+ /** Put a ring's places back on their own point (the next regroup hides them). */
1114
+ unring() {
1115
+ const g = this.groups.get(this.ring);
1116
+ for (const i of g?.members ?? []) {
1117
+ const p = this.places[i];
1118
+ if (p)
1119
+ this.markers[i]?.setLatLng([p.lat, p.lng]);
1120
+ }
1121
+ this.ring = '';
768
1122
  }
769
1123
  /** Open on `center`/`zoom`, else on the places' bounds, else on Grounds. */
770
1124
  fit() {
@@ -820,70 +1174,104 @@ export class UvalibMap extends UvalibElement {
820
1174
  y <= r.bottom + 12);
821
1175
  });
822
1176
  }
823
- markerEl(i) {
824
- return this.markers[i]?.getElement();
1177
+ /** The marker on the map for a target ("3" a place, "g:1,3" a group): a place's own, or its group's. */
1178
+ markerFor(key) {
1179
+ if (key.startsWith('g:')) {
1180
+ const g = this.groups.get(key.slice(2));
1181
+ return g && { marker: g.marker, group: g };
1182
+ }
1183
+ const i = Number(key);
1184
+ const m = this.markers[i];
1185
+ if (!m || !this.map)
1186
+ return undefined;
1187
+ if (this.map.hasLayer(m))
1188
+ return { marker: m };
1189
+ const g = this.groups.get(this.groupOf.get(i) ?? '');
1190
+ return g && { marker: g.marker, group: g };
825
1191
  }
826
- hover(i) {
827
- this.hoverIndex = i;
1192
+ hover(key) {
1193
+ this.hoverKey = key;
828
1194
  this.dismissed = false;
829
1195
  this.syncActive();
830
1196
  }
831
- /** The highlighted place: the one hovered, else the one focused (none after Escape). */
1197
+ /** The highlighted target: the one hovered, else the one focused (none after Escape). */
832
1198
  syncActive() {
833
- this.active = this.dismissed ? -1 : this.hoverIndex >= 0 ? this.hoverIndex : this.focusIndex;
1199
+ this.active = this.dismissed ? '' : this.hoverKey || this.focusKey;
834
1200
  }
835
- /** Highlight the active place's marker and show its tooltip (after a render). */
836
- showActive(prev) {
1201
+ /**
1202
+ * Highlight the active target's marker (a place inside a group highlights the group) and
1203
+ * show its tooltip: the name and count, and for a place in a group, how many share it.
1204
+ */
1205
+ showActive() {
837
1206
  const { map, tooltip } = this;
838
1207
  if (!map || !tooltip)
839
1208
  return;
840
- if (prev !== undefined && prev >= 0) {
841
- this.markerEl(prev)?.classList.remove('is-active');
842
- const d = this.markerDot(prev);
843
- this.markers[prev]?.setZIndexOffset((MAX_DOT - d) * 10);
1209
+ const prev = this.activeIcon;
1210
+ if (prev) {
1211
+ prev.marker.getElement()?.classList.remove('is-active');
1212
+ prev.marker.setZIndexOffset(prev.z);
1213
+ this.activeIcon = undefined;
844
1214
  }
845
- const i = this.active;
846
- const marker = this.markers[i];
847
- const p = this.places[i];
848
- if (i < 0 || !marker || !p) {
1215
+ const key = this.active;
1216
+ const spot = key ? this.markerFor(key) : undefined;
1217
+ const el = spot?.marker.getElement();
1218
+ if (!spot || !el) {
849
1219
  tooltip.remove();
850
1220
  return;
851
1221
  }
852
- this.markerEl(i)?.classList.add('is-active');
853
- marker.setZIndexOffset(10000);
854
- const content = this.ownerDocument.createElement('span');
855
- const name = this.ownerDocument.createElement('span');
1222
+ const g = spot.group;
1223
+ const own = spot.marker === this.markers[Number(key)];
1224
+ const d = own ? (this.dots[Number(key)] ?? MIN_DOT) : (g?.d ?? MIN_DOT);
1225
+ el.classList.add('is-active');
1226
+ this.activeIcon = { marker: spot.marker, z: (MAX_DOT - d) * 10 };
1227
+ spot.marker.setZIndexOffset(10000);
1228
+ const doc = this.ownerDocument;
1229
+ const content = doc.createElement('span');
1230
+ const name = doc.createElement('span');
856
1231
  name.className = 'tip-name';
857
- name.textContent = p.name;
858
1232
  content.append(name);
859
- if (p.count !== undefined)
860
- content.append(this.countText(p.count));
861
- const size = Math.max(HIT, this.markerDot(i));
1233
+ if (key.startsWith('g:') && g) {
1234
+ name.textContent = this.groupName(g.members);
1235
+ if (g.counted)
1236
+ content.append(this.countText(g.sum));
1237
+ }
1238
+ else {
1239
+ const p = this.places[Number(key)];
1240
+ name.textContent = p.name;
1241
+ if (p.count !== undefined)
1242
+ content.append(this.countText(p.count));
1243
+ if (g) {
1244
+ const note = doc.createElement('span');
1245
+ note.className = 'tip-note';
1246
+ note.textContent = `One of ${fmt(g.members.length)} ${this.placeLabel || 'places'} here`;
1247
+ content.append(note);
1248
+ }
1249
+ }
1250
+ const size = Math.max(HIT, d);
862
1251
  tooltip.options.offset = [0, -Math.round(size * 0.6)];
863
- tooltip.setLatLng(marker.getLatLng()).setContent(content);
1252
+ tooltip.setLatLng(spot.marker.getLatLng()).setContent(content);
864
1253
  if (!map.hasLayer(tooltip))
865
1254
  tooltip.addTo(map);
866
1255
  else
867
1256
  tooltip.update();
868
1257
  }
869
- markerDot(i) {
870
- const d = parseFloat(this.markerEl(i)?.querySelector('.marker')?.style.getPropertyValue('--d') ?? '');
871
- return Number.isFinite(d) ? d : MIN_DOT;
872
- }
873
- /** Bring a place into view (on focus), without animation under reduced motion. */
874
- reveal(i) {
1258
+ /** Bring a target's marker into view (on focus), without animation under reduced motion. */
1259
+ reveal(key) {
875
1260
  const { map } = this;
876
- const marker = this.markers[i];
877
- if (!map || !marker)
1261
+ const spot = this.markerFor(key);
1262
+ if (!map || !spot)
878
1263
  return;
879
- const ll = marker.getLatLng();
1264
+ const ll = spot.marker.getLatLng();
880
1265
  if (!map.getBounds().pad(-0.15).contains(ll))
881
1266
  map.panTo(ll, { animate: !this.reduceMotion });
882
1267
  }
883
- indexOf(e) {
884
- const t = e.target;
885
- const ctl = t?.closest?.('.marker');
886
- return ctl ? Number(ctl.dataset.index) : -1;
1268
+ /** "3" for a place's marker, "g:1,3" for a group's. */
1269
+ keyOf(ctl) {
1270
+ return ctl.dataset.group !== undefined ? `g:${ctl.dataset.group}` : (ctl.dataset.index ?? '');
1271
+ }
1272
+ targetOf(e) {
1273
+ const ctl = e.target?.closest?.('.marker');
1274
+ return ctl ? this.keyOf(ctl) : '';
887
1275
  }
888
1276
  /** Report the zoom level 1 s after the last zoom-button press. */
889
1277
  queueZoomReport() {
@@ -894,28 +1282,31 @@ export class UvalibMap extends UvalibElement {
894
1282
  }, 1000);
895
1283
  }
896
1284
  onPlaceEnter(i) {
897
- this.hover(i);
1285
+ this.hover(String(i));
898
1286
  }
899
1287
  onPlaceLeave() {
900
- this.hoverIndex = -1;
1288
+ this.hoverKey = '';
901
1289
  this.syncActive();
902
1290
  }
903
1291
  onPlaceFocusIn(i) {
904
- this.focusIndex = i;
1292
+ this.focusKey = String(i);
905
1293
  this.dismissed = false;
906
- this.reveal(i);
1294
+ this.reveal(String(i));
907
1295
  this.syncActive();
908
1296
  }
909
1297
  onPlaceFocusOut(e) {
910
1298
  const to = e.relatedTarget;
911
1299
  if (to?.closest?.('.place'))
912
1300
  return;
913
- this.focusIndex = -1;
1301
+ this.focusKey = '';
914
1302
  this.syncActive();
915
1303
  }
916
1304
  render() {
917
1305
  const places = this.places;
918
1306
  const label = this.label.trim() || 'Places';
1307
+ // A list entry is highlighted with its place, or with its group.
1308
+ const a = this.active;
1309
+ const lit = new Set(a.startsWith('g:') ? a.slice(2).split(',').map(Number) : a ? [Number(a)] : []);
919
1310
  const listId = `${this.uid}-list`;
920
1311
  const map = this.hasLeaflet
921
1312
  ? html `<a class="skip-link" href="#${listId}" @click=${this.skipToList}
@@ -942,7 +1333,7 @@ export class UvalibMap extends UvalibElement {
942
1333
  ${places.map((p, i) => {
943
1334
  const href = this.href(p);
944
1335
  return html `<li
945
- class=${i === this.active ? 'place is-active' : 'place'}
1336
+ class=${lit.has(i) ? 'place is-active' : 'place'}
946
1337
  part="place"
947
1338
  @mouseenter=${() => this.onPlaceEnter(i)}
948
1339
  @mouseleave=${() => this.onPlaceLeave()}
@@ -968,6 +1359,9 @@ __decorate([
968
1359
  __decorate([
969
1360
  property({ type: String, attribute: 'count-label' })
970
1361
  ], UvalibMap.prototype, "countLabel", void 0);
1362
+ __decorate([
1363
+ property({ type: String, attribute: 'place-label' })
1364
+ ], UvalibMap.prototype, "placeLabel", void 0);
971
1365
  __decorate([
972
1366
  property({ type: String, attribute: 'tile-url' })
973
1367
  ], UvalibMap.prototype, "tileUrl", void 0);