@ruckc/truss-ol 1.13.0 → 1.15.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.
@@ -1,13 +1,15 @@
1
1
  <script lang="ts">
2
2
  import type OLMap from 'ol/Map.js';
3
3
  import type { getPointResolution } from 'ol/proj.js';
4
- import { watchView, scaleSegment, type ControlPosition, type ScaleSegment, type ScaleUnit } from './util.js';
4
+ import { watchView, scaleSegment, scaleTicks, scaleRatio, formatRatio, describeRatio, describeSegment, type ControlPosition, type ScaleSegment, type ScaleUnit } from './util.js';
5
5
 
6
6
  let {
7
7
  map,
8
8
  units = ['metric', 'imperial'],
9
9
  maxWidth = 120,
10
- position = 'bottom-left'
10
+ position = 'bottom-left',
11
+ variant = 'bar',
12
+ showRatio = false
11
13
  }: {
12
14
  /** The OpenLayers map this control reads (owned by your app). */
13
15
  map?: OLMap | null;
@@ -16,10 +18,15 @@
16
18
  /** Longest a bar may be, in px. Lengths are 1, 2 or 5 times a power of ten, or ¼ / ½. */
17
19
  maxWidth?: number;
18
20
  position?: ControlPosition;
21
+ /** `bar` is one bracketed bar per unit; `segmented` is a USGS-style bar of alternating dark and light segments with labels at 0, the inner boundaries and the end (2 or 4 segments, whichever keeps the labels apart). */
22
+ variant?: 'bar' | 'segmented';
23
+ /** Add a representative fraction line (`1 : 24,000`) above the bars. Computed from the view resolution at the map centre, assuming the OGC standard 0.28 mm CSS pixel, to 2 significant figures. */
24
+ showRatio?: boolean;
19
25
  } = $props();
20
26
 
21
27
  let segments = $state<ScaleSegment[]>([]);
22
- const text = $derived(segments.map((s) => s.label).join(', '));
28
+ let ratio = $state<number>();
29
+ const text = $derived(segments.map(describeSegment).join(', ') + (showRatio && ratio ? `; ${describeRatio(ratio)}` : ''));
23
30
 
24
31
  $effect(() => {
25
32
  if (!map) { segments = []; return; }
@@ -31,7 +38,9 @@
31
38
  const v = m.getView();
32
39
  const res = v.getResolution();
33
40
  const c = v.getCenter();
34
- segments = !resolve || res === undefined || !c ? [] : systems.map((u) => scaleSegment(resolve!(v.getProjection(), res, c, 'm'), max, u));
41
+ const mpp = !resolve || res === undefined || !c ? undefined : resolve(v.getProjection(), res, c, 'm');
42
+ segments = mpp === undefined ? [] : systems.map((u) => scaleSegment(mpp, max, u));
43
+ ratio = mpp === undefined ? undefined : scaleRatio(mpp);
35
44
  };
36
45
  // OpenLayers is loaded on demand (never during server render); the bars appear once it has
37
46
  import('ol/proj.js').then((p) => { resolve = p.getPointResolution; refresh(); });
@@ -40,9 +49,18 @@
40
49
  </script>
41
50
 
42
51
  {#if segments.length}
43
- <div class="sb" data-pos={position} role="img" aria-label={`Scale: ${text}`}>
52
+ <div class="sb" class:segmented={variant === 'segmented'} data-pos={position} role="img" aria-label={`Scale: ${text}`}>
53
+ {#if showRatio && ratio}<div class="ratio">{formatRatio(ratio)}</div>{/if}
44
54
  {#each segments as s (s.unit)}
45
- <div class="bar" style:width={`${s.width}px`}>{s.label}</div>
55
+ {#if variant === 'segmented'}
56
+ {@const t = scaleTicks(s)}
57
+ <div class="seg" style:width={`${s.width}px`}>
58
+ <div class="track">{#each { length: t.count } as _, i}<span class:dark={i % 2 === 0}></span>{/each}</div>
59
+ <div class="ticks">{#each t.ticks as k (k.pos)}<span style:left={`${k.pos * 100}%`}>{k.label}</span>{/each}</div>
60
+ </div>
61
+ {:else}
62
+ <div class="bar" style:width={`${s.width}px`}>{s.label}</div>
63
+ {/if}
46
64
  {/each}
47
65
  </div>
48
66
  {/if}
@@ -53,5 +71,13 @@
53
71
  .sb[data-pos='top-right'] { position: absolute; top: 8px; right: 8px; }
54
72
  .sb[data-pos='bottom-left'] { position: absolute; bottom: 8px; left: 8px; }
55
73
  .sb[data-pos='bottom-right'] { position: absolute; bottom: 8px; right: 8px; }
74
+ .sb.segmented { gap: 4px; padding-inline-end: 18px; }
75
+ .ratio { font-weight: 600; }
76
+ .seg { position: relative; padding-bottom: 1.4em; }
77
+ .track { display: flex; height: 6px; border: 1px solid var(--tr-on-surface); box-sizing: border-box; }
78
+ .track span { flex: 1; background: var(--tr-surface); }
79
+ .track span.dark { background: var(--tr-on-surface); }
80
+ .ticks { position: absolute; inset: 9px 0 0; line-height: 1.3; white-space: nowrap; }
81
+ .ticks span { position: absolute; transform: translateX(-50%); }
56
82
  .bar { box-sizing: border-box; min-width: 8px; padding: 0 4px; border: 1.5px solid var(--tr-on-surface-variant); border-top: 0; line-height: 1.3; white-space: nowrap; }
57
83
  </style>
@@ -8,6 +8,10 @@ type $$ComponentProps = {
8
8
  /** Longest a bar may be, in px. Lengths are 1, 2 or 5 times a power of ten, or ¼ / ½. */
9
9
  maxWidth?: number;
10
10
  position?: ControlPosition;
11
+ /** `bar` is one bracketed bar per unit; `segmented` is a USGS-style bar of alternating dark and light segments with labels at 0, the inner boundaries and the end (2 or 4 segments, whichever keeps the labels apart). */
12
+ variant?: 'bar' | 'segmented';
13
+ /** Add a representative fraction line (`1 : 24,000`) above the bars. Computed from the view resolution at the map centre, assuming the OGC standard 0.28 mm CSS pixel, to 2 significant figures. */
14
+ showRatio?: boolean;
11
15
  };
12
16
  declare const ScaleBar: import("svelte").Component<$$ComponentProps, {}, "">;
13
17
  type ScaleBar = ReturnType<typeof ScaleBar>;
@@ -1,14 +1,14 @@
1
1
  <script lang="ts">
2
2
  import { Button } from '@ruckc/truss-ui';
3
3
  import type OLMap from 'ol/Map.js';
4
- import { watchView, watchCoarse, type ControlPosition } from './util.js';
4
+ import { watchView, watchCoarse, cornerZone, rectDistance, type ControlPosition } from './util.js';
5
5
 
6
6
  let {
7
7
  map,
8
8
  reveal = 'always',
9
9
  showFit = false,
10
10
  extent,
11
- distance = 72,
11
+ distance = 160,
12
12
  delta = 1,
13
13
  duration = 200,
14
14
  position = 'top-left',
@@ -16,12 +16,13 @@
16
16
  }: {
17
17
  /** The OpenLayers map this control drives (owned by your app). */
18
18
  map?: OLMap | null;
19
- /** `proximity` shows the buttons only while the pointer is within `distance` px (or a button has focus); hidden on touch screens. */
19
+ /** `proximity` shows the buttons only while the pointer is within `distance` px of the map corner region the control sits in (or a button has focus); hidden on touch screens. The region runs from the map corner (set by `position`) to the control's far edges, so the buttons appear when the pointer approaches that corner from anywhere in the map, not only near the buttons. With `position="none"` it is the control's own box. */
20
20
  reveal?: 'always' | 'proximity';
21
21
  /** Add a button that fits the view to `extent`. */
22
22
  showFit?: boolean;
23
23
  /** Extent for the fit button, in the view projection. Defaults to the projection's extent. */
24
24
  extent?: [number, number, number, number];
25
+ /** Reach of the reveal zone, in px from the corner region's nearest edge (default 160). */
25
26
  distance?: number;
26
27
  delta?: number;
27
28
  duration?: number;
@@ -56,10 +57,8 @@
56
57
  $effect(() => {
57
58
  if (!proximity || coarse) return;
58
59
  const move = (e: PointerEvent) => {
59
- const r = root!.getBoundingClientRect();
60
- const dx = Math.max(r.left - e.clientX, 0, e.clientX - r.right);
61
- const dy = Math.max(r.top - e.clientY, 0, e.clientY - r.bottom);
62
- near = e.pointerType !== 'touch' && Math.hypot(dx, dy) <= distance;
60
+ const zone = cornerZone(root!.parentElement!.getBoundingClientRect(), root!.getBoundingClientRect(), position);
61
+ near = e.pointerType !== 'touch' && rectDistance(zone, e.clientX, e.clientY) <= distance;
63
62
  };
64
63
  const leave = () => (near = false);
65
64
  document.addEventListener('pointermove', move);
@@ -3,12 +3,13 @@ import { type ControlPosition } from './util.js';
3
3
  type $$ComponentProps = {
4
4
  /** The OpenLayers map this control drives (owned by your app). */
5
5
  map?: OLMap | null;
6
- /** `proximity` shows the buttons only while the pointer is within `distance` px (or a button has focus); hidden on touch screens. */
6
+ /** `proximity` shows the buttons only while the pointer is within `distance` px of the map corner region the control sits in (or a button has focus); hidden on touch screens. The region runs from the map corner (set by `position`) to the control's far edges, so the buttons appear when the pointer approaches that corner from anywhere in the map, not only near the buttons. With `position="none"` it is the control's own box. */
7
7
  reveal?: 'always' | 'proximity';
8
8
  /** Add a button that fits the view to `extent`. */
9
9
  showFit?: boolean;
10
10
  /** Extent for the fit button, in the view projection. Defaults to the projection's extent. */
11
11
  extent?: [number, number, number, number];
12
+ /** Reach of the reveal zone, in px from the corner region's nearest edge (default 160). */
12
13
  distance?: number;
13
14
  delta?: number;
14
15
  duration?: number;
package/dist/util.d.ts CHANGED
@@ -16,6 +16,39 @@ export declare function niceLength(max: number): number;
16
16
  export declare function formatNice(n: number): string;
17
17
  /** One scale bar for a unit system: picks the unit (km/m/cm or mi/ft/in) and a nice length that fits `maxPx`. */
18
18
  export declare function scaleSegment(metersPerPx: number, maxPx: number, system: ScaleUnit): ScaleSegment;
19
+ /** A scale bar's length in words for assistive technology, e.g. `1 mile`, `2 kilometres`. */
20
+ export declare function describeSegment(s: ScaleSegment): string;
21
+ /** OGC standard rendering pixel: 0.28 mm. OpenLayers resolutions are per CSS pixel, so devicePixelRatio does not change the ratio. */
22
+ export declare const PIXEL_MM = 0.28;
23
+ /** `n` rounded to `sig` significant figures. */
24
+ export declare function roundSig(n: number, sig: number): number;
25
+ /** The representative fraction's denominator (`24000` for 1 : 24,000) for a view resolution in metres per CSS pixel, to 2 significant figures. */
26
+ export declare function scaleRatio(metersPerPx: number): number;
27
+ export declare function formatRatio(denominator: number): string;
28
+ export declare function describeRatio(denominator: number): string;
29
+ export type ScaleTick = {
30
+ label: string;
31
+ pos: number;
32
+ };
33
+ /** A tick value as text: quarters and halves as fractions, otherwise a plain number. */
34
+ export declare function tickLabel(v: number): string;
35
+ /** Whether labels centred on ticks `segPx` apart stay clear of each other. */
36
+ export declare function ticksFit(labels: string[], segPx: number): boolean;
37
+ /** Ticks for a segmented bar: 4 segments if their labels fit at the bar's width, else 2. `pos` runs 0 to 1; only the last label carries the unit. */
38
+ export declare function scaleTicks(seg: ScaleSegment): {
39
+ count: number;
40
+ ticks: ScaleTick[];
41
+ };
42
+ export type Rect = {
43
+ left: number;
44
+ top: number;
45
+ right: number;
46
+ bottom: number;
47
+ };
48
+ /** The corner region a control is anchored to: from the map corner it sits in to the control's far edges. `none` (custom placement) is just the control's box. */
49
+ export declare function cornerZone(area: Rect, box: Rect, position: ControlPosition): Rect;
50
+ /** Distance from a point to a rect (0 inside it). */
51
+ export declare function rectDistance(r: Rect, x: number, y: number): number;
19
52
  /** Call `cb` now and whenever the map's view moves, zooms or rotates (also across `map.setView`). Returns the unsubscribe. */
20
53
  export declare function watchView(map: OLMap, cb: () => void): () => void;
21
54
  /** Report whether the primary pointer is coarse (touch), now and when it changes. Returns the unsubscribe. */
package/dist/util.js CHANGED
@@ -22,6 +22,62 @@ export function scaleSegment(metersPerPx, maxPx, system) {
22
22
  const value = niceLength(maxM / f);
23
23
  return { unit, value, label: `${formatNice(value)} ${unit}`, width: (value * f) / metersPerPx };
24
24
  }
25
+ const UNIT_NAMES = {
26
+ km: ['kilometre', 'kilometres'], m: ['metre', 'metres'], cm: ['centimetre', 'centimetres'],
27
+ mi: ['mile', 'miles'], ft: ['foot', 'feet'], in: ['inch', 'inches']
28
+ };
29
+ /** A scale bar's length in words for assistive technology, e.g. `1 mile`, `2 kilometres`. */
30
+ export function describeSegment(s) {
31
+ return `${s.value} ${UNIT_NAMES[s.unit][s.value === 1 ? 0 : 1]}`;
32
+ }
33
+ /** OGC standard rendering pixel: 0.28 mm. OpenLayers resolutions are per CSS pixel, so devicePixelRatio does not change the ratio. */
34
+ export const PIXEL_MM = 0.28;
35
+ /** `n` rounded to `sig` significant figures. */
36
+ export function roundSig(n, sig) {
37
+ const p = 10 ** (Math.floor(Math.log10(n)) - sig + 1);
38
+ return Math.round(n / p) * p;
39
+ }
40
+ /** The representative fraction's denominator (`24000` for 1 : 24,000) for a view resolution in metres per CSS pixel, to 2 significant figures. */
41
+ export function scaleRatio(metersPerPx) {
42
+ return Math.max(1, Math.round(roundSig(metersPerPx / (PIXEL_MM / 1000), 2)));
43
+ }
44
+ export function formatRatio(denominator) {
45
+ return `1 : ${denominator.toLocaleString('en-US')}`;
46
+ }
47
+ export function describeRatio(denominator) {
48
+ return `1 to ${denominator.toLocaleString('en-US')}`;
49
+ }
50
+ /** A tick value as text: quarters and halves as fractions, otherwise a plain number. */
51
+ export function tickLabel(v) {
52
+ return v === 0.75 ? '¾' : formatNice(Math.round(v * 1000) / 1000);
53
+ }
54
+ const LABEL_PX = 6.5; // average glyph width at --tr-text-xs
55
+ const LABEL_GAP = 6;
56
+ /** Whether labels centred on ticks `segPx` apart stay clear of each other. */
57
+ export function ticksFit(labels, segPx) {
58
+ return labels.every((l, i) => i === 0 || ((l.length + labels[i - 1].length) / 2) * LABEL_PX + LABEL_GAP <= segPx);
59
+ }
60
+ /** Ticks for a segmented bar: 4 segments if their labels fit at the bar's width, else 2. `pos` runs 0 to 1; only the last label carries the unit. */
61
+ export function scaleTicks(seg) {
62
+ const build = (count) => Array.from({ length: count + 1 }, (_, i) => {
63
+ const t = tickLabel((seg.value * i) / count);
64
+ return { label: i === count ? `${t} ${seg.unit}` : t, pos: i / count };
65
+ });
66
+ const four = build(4);
67
+ return ticksFit(four.map((t) => t.label), seg.width / 4) ? { count: 4, ticks: four } : { count: 2, ticks: build(2) };
68
+ }
69
+ /** The corner region a control is anchored to: from the map corner it sits in to the control's far edges. `none` (custom placement) is just the control's box. */
70
+ export function cornerZone(area, box, position) {
71
+ if (position === 'none')
72
+ return box;
73
+ const right = position.endsWith('right');
74
+ const bottom = position.startsWith('bottom');
75
+ return { left: right ? box.left : area.left, right: right ? area.right : box.right, top: bottom ? box.top : area.top, bottom: bottom ? area.bottom : box.bottom };
76
+ }
77
+ /** Distance from a point to a rect (0 inside it). */
78
+ export function rectDistance(r, x, y) {
79
+ return Math.hypot(Math.max(r.left - x, 0, x - r.right), Math.max(r.top - y, 0, y - r.bottom));
80
+ }
25
81
  const VIEW_EVENTS = ['change:center', 'change:resolution', 'change:rotation'];
26
82
  /** Call `cb` now and whenever the map's view moves, zooms or rotates (also across `map.setView`). Returns the unsubscribe. */
27
83
  export function watchView(map, cb) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-ol",
3
- "version": "1.13.0",
3
+ "version": "1.15.0",
4
4
  "description": "OpenLayers map styled with Truss UI",
5
5
  "type": "module",
6
6
  "license": "MIT",