panelui-native 0.106.0 → 0.107.1

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.
Files changed (35) hide show
  1. package/lib/module/components/animated-badge/index.js +9 -2
  2. package/lib/module/components/animated-badge/index.js.map +1 -1
  3. package/lib/module/components/button/index.js +18 -4
  4. package/lib/module/components/button/index.js.map +1 -1
  5. package/lib/module/components/map/index.js +22 -4
  6. package/lib/module/components/map/index.js.map +1 -1
  7. package/lib/module/components/map/native-style.js +191 -0
  8. package/lib/module/components/map/native-style.js.map +1 -0
  9. package/lib/module/components/progress/index.js +5 -3
  10. package/lib/module/components/progress/index.js.map +1 -1
  11. package/lib/module/components/skeleton/index.js +3 -3
  12. package/lib/module/components/skeleton/index.js.map +1 -1
  13. package/lib/module/components/spinner/index.js +3 -3
  14. package/lib/module/components/spinner/index.js.map +1 -1
  15. package/lib/module/primitives/text.js +25 -0
  16. package/lib/module/primitives/text.js.map +1 -1
  17. package/lib/typescript/src/components/animated-badge/index.d.ts.map +1 -1
  18. package/lib/typescript/src/components/button/index.d.ts +25 -3
  19. package/lib/typescript/src/components/button/index.d.ts.map +1 -1
  20. package/lib/typescript/src/components/map/index.d.ts +12 -2
  21. package/lib/typescript/src/components/map/index.d.ts.map +1 -1
  22. package/lib/typescript/src/components/map/native-style.d.ts +25 -0
  23. package/lib/typescript/src/components/map/native-style.d.ts.map +1 -0
  24. package/lib/typescript/src/components/progress/index.d.ts.map +1 -1
  25. package/lib/typescript/src/primitives/text.d.ts +16 -0
  26. package/lib/typescript/src/primitives/text.d.ts.map +1 -1
  27. package/package.json +1 -1
  28. package/src/components/animated-badge/index.tsx +8 -1
  29. package/src/components/button/index.tsx +39 -6
  30. package/src/components/map/index.tsx +80 -49
  31. package/src/components/map/native-style.ts +205 -0
  32. package/src/components/progress/index.tsx +3 -1
  33. package/src/components/skeleton/index.tsx +1 -1
  34. package/src/components/spinner/index.tsx +1 -1
  35. package/src/primitives/text.tsx +25 -0
@@ -80,6 +80,7 @@ import {
80
80
  type MapFeatureAccessibilityDescription,
81
81
  } from './map-accessibility';
82
82
  import { asMapLayer, partitionMapChildren } from './map-children';
83
+ import { useNativeStyle } from './native-style';
83
84
 
84
85
  export { hasMapLibre, CARTO_SOURCE };
85
86
  export type {
@@ -284,11 +285,21 @@ export interface MapProps extends Omit<ViewProps, 'children'> {
284
285
  /**
285
286
  * Where the vector tiles come from. Defaults to CARTO, which is free for
286
287
  * non-commercial use and licensed for everything else.
288
+ *
289
+ * Ignored when `mapStyle` is set, because that style names its own sources.
287
290
  */
288
291
  source?: BasemapSource;
289
292
  /**
290
- * Use this style wholesale instead of building one from tokens. The escape
291
- * hatch for a map that has to match something outside the app.
293
+ * Use this style wholesale instead of building one from tokens — a URL, or
294
+ * the style document itself. For a map that has to match something outside
295
+ * the app.
296
+ *
297
+ * Styles written for the browser can use properties the native renderer
298
+ * cannot parse, and it drops every layer that has one. `Map` translates
299
+ * them to the older names the renderer does read before handing the style
300
+ * over. To do that it fetches a URL itself, and draws nothing until the
301
+ * style has arrived. If the fetch fails, the URL goes to the renderer
302
+ * unchanged.
292
303
  */
293
304
  mapStyle?: string | StyleSpecification;
294
305
  /** Let the map rotate and tilt. Off by default — most maps only pan and zoom. */
@@ -387,8 +398,8 @@ const MapRoot = forwardRef<MapHandle, MapProps>(function MapRoot(
387
398
  labelHalo: useToken('--color-background', '#ffffff'),
388
399
  };
389
400
 
390
- const style = useMemo(
391
- () => mapStyle ?? buildBasemapStyle(tokens, { blank, source }),
401
+ const built = useMemo(
402
+ () => (mapStyle === undefined ? buildBasemapStyle(tokens, { blank, source }) : undefined),
392
403
  // The token object is rebuilt every render, so depend on its values.
393
404
  // eslint-disable-next-line react-hooks/exhaustive-deps
394
405
  [
@@ -405,6 +416,23 @@ const MapRoot = forwardRef<MapHandle, MapProps>(function MapRoot(
405
416
  ]
406
417
  );
407
418
 
419
+ // A caller's style is translated into what the native renderer can parse
420
+ // first. `null` means a hosted one is still being fetched — see
421
+ // `native-style.ts`.
422
+ const hosted = useNativeStyle(mapStyle);
423
+ const next = built ?? hosted;
424
+
425
+ /*
426
+ * The last style that was ready, so switching to a hosted one keeps drawing
427
+ * the old style until the new one arrives. Without it the map would unmount
428
+ * for the length of the fetch and come back at its opening position.
429
+ */
430
+ const [shown, setShown] = useState(next);
431
+ useEffect(() => {
432
+ if (next) setShown(next);
433
+ }, [next]);
434
+ const style = next ?? shown;
435
+
408
436
  // The opening view, kept from the first render. The props describe where
409
437
  // the map starts, not where it is, so a later change to them must not move
410
438
  // the target `recenter` returns to without the caller asking.
@@ -470,52 +498,55 @@ const MapRoot = forwardRef<MapHandle, MapProps>(function MapRoot(
470
498
  return (
471
499
  <MapContext.Provider value={context}>
472
500
  <View className={slots.root({ className })} {...props}>
473
- <MapLibreMap
474
- ref={mapRef}
475
- mapStyle={style}
476
- style={{ flex: 1 }}
477
- // The library's own ornaments are turned off across the board:
478
- // they are drawn by the renderer in its own style and cannot be
479
- // themed, so `Map.Controls` replaces them with views that can.
480
- logo={false}
481
- compass={false}
482
- attribution={false}
483
- scaleBar={false}
484
- dragPan={interactive}
485
- touchZoom={interactive}
486
- touchRotate={rotatable}
487
- touchPitch={rotatable}
488
- accessible={false}
489
- importantForAccessibility="no"
490
- onDidFinishLoadingMap={() => {
491
- setReady(true);
492
- onReady?.();
493
- }}
494
- onRegionDidChange={
495
- onViewStateChange
496
- ? (event) => onViewStateChange(event.nativeEvent)
497
- : undefined
498
- }
499
- onPress={
500
- onPress
501
- ? (event) => onPress(event.nativeEvent.lngLat, event.nativeEvent.point)
502
- : undefined
503
- }
504
- >
505
- <Camera
506
- ref={cameraRef}
507
- // The opening position, and only that: this is applied on the
508
- // first frame and never again, so a re-render cannot pull the map
509
- // back to its starting point mid-gesture. Everything afterwards
510
- // goes through the ref.
511
- initialViewState={
512
- bounds
513
- ? { bounds }
514
- : { center: center ?? [0, 20], zoom, bearing, pitch }
501
+ {/* Nothing to draw until a hosted style has arrived the first time. */}
502
+ {style ? (
503
+ <MapLibreMap
504
+ ref={mapRef}
505
+ mapStyle={style}
506
+ style={{ flex: 1 }}
507
+ // The library's own ornaments are turned off across the board:
508
+ // they are drawn by the renderer in its own style and cannot be
509
+ // themed, so `Map.Controls` replaces them with views that can.
510
+ logo={false}
511
+ compass={false}
512
+ attribution={false}
513
+ scaleBar={false}
514
+ dragPan={interactive}
515
+ touchZoom={interactive}
516
+ touchRotate={rotatable}
517
+ touchPitch={rotatable}
518
+ accessible={false}
519
+ importantForAccessibility="no"
520
+ onDidFinishLoadingMap={() => {
521
+ setReady(true);
522
+ onReady?.();
523
+ }}
524
+ onRegionDidChange={
525
+ onViewStateChange
526
+ ? (event) => onViewStateChange(event.nativeEvent)
527
+ : undefined
515
528
  }
516
- />
517
- {layers}
518
- </MapLibreMap>
529
+ onPress={
530
+ onPress
531
+ ? (event) => onPress(event.nativeEvent.lngLat, event.nativeEvent.point)
532
+ : undefined
533
+ }
534
+ >
535
+ <Camera
536
+ ref={cameraRef}
537
+ // The opening position, and only that: this is applied on the
538
+ // first frame and never again, so a re-render cannot pull the map
539
+ // back to its starting point mid-gesture. Everything afterwards
540
+ // goes through the ref.
541
+ initialViewState={
542
+ bounds
543
+ ? { bounds }
544
+ : { center: center ?? [0, 20], zoom, bearing, pitch }
545
+ }
546
+ />
547
+ {layers}
548
+ </MapLibreMap>
549
+ ) : null}
519
550
  {overlay.length > 0 ? (
520
551
  <View style={StyleSheet.absoluteFill} pointerEvents="box-none">
521
552
  {textChildren(overlay)}
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Fits a style written for the browser renderer to the native one.
3
+ *
4
+ * Hosted styles are written and checked in a browser, and the native renderer
5
+ * lags behind it in what it can parse. Where the two disagree, native does not
6
+ * skip the one property. It throws away the whole layer and logs a warning. A
7
+ * street style that labels its stations and bus stops with `text-overlap`
8
+ * reaches a phone with neither, and the only sign is a run of
9
+ * `layer doesn't support this property` lines in the terminal.
10
+ *
11
+ * Everything the style specification lists as unsupported on native is
12
+ * translated here:
13
+ *
14
+ * - `icon-overlap` and `text-overlap` become `icon-allow-overlap` and
15
+ * `text-allow-overlap`, the older names native has always read.
16
+ * - `resampling` becomes `raster-resampling` on a raster layer. Hillshade and
17
+ * color-relief layers have no older name for it, so there it is dropped and
18
+ * the layer keeps the default.
19
+ * - A tiled source with neither `url` nor `tiles` is removed. Hosted styles use
20
+ * one to carry attribution text. Native cannot parse it, and it draws
21
+ * nothing either way.
22
+ *
23
+ * The browser gives the newer name priority when a layer sets both, so the
24
+ * translation overwrites the older one rather than deferring to it.
25
+ */
26
+ import { useEffect, useMemo, useState } from 'react';
27
+ import type { StyleSpecification } from './maplibre';
28
+
29
+ type Json = Record<string, unknown>;
30
+
31
+ function isObject(value: unknown): value is Json {
32
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
33
+ }
34
+
35
+ const TILED_SOURCES = new Set(['vector', 'raster', 'raster-dem']);
36
+
37
+ /**
38
+ * Each overlap mode as the boolean the older property takes.
39
+ *
40
+ * Native has no `cooperative` mode, which lets a symbol overlap others that
41
+ * allow it but not the ones that refuse. It becomes `false`. A label that is
42
+ * hidden on a collision is how every map label behaves already, and a label
43
+ * printed over another cannot be read.
44
+ */
45
+ const OVERLAP = new Map<unknown, boolean>([
46
+ ['always', true],
47
+ ['never', false],
48
+ ['cooperative', false],
49
+ ]);
50
+
51
+ /** The layout with `-overlap` translated, or `null` when it has none. */
52
+ function adaptLayout(layout: Json): Json | null {
53
+ let next: Json | null = null;
54
+ for (const kind of ['icon', 'text']) {
55
+ const key = `${kind}-overlap`;
56
+ if (!(key in layout)) continue;
57
+ next ??= { ...layout };
58
+ const allowed = OVERLAP.get(layout[key]);
59
+ delete next[key];
60
+ // A zoom expression has no direct translation. Dropping it leaves
61
+ // `-allow-overlap` in charge, which is what a browser renderer older than
62
+ // the property did with the same style.
63
+ if (allowed !== undefined) next[`${kind}-allow-overlap`] = allowed;
64
+ }
65
+ return next;
66
+ }
67
+
68
+ /** The paint with `resampling` translated, or `null` when it has none. */
69
+ function adaptPaint(type: unknown, paint: Json): Json | null {
70
+ if (!('resampling' in paint)) return null;
71
+ const { resampling, ...next } = paint;
72
+ if (type === 'raster') next['raster-resampling'] = resampling;
73
+ return next;
74
+ }
75
+
76
+ /**
77
+ * The style with everything native cannot parse translated or removed.
78
+ *
79
+ * Returns the same object when there is nothing to change, and never mutates
80
+ * the one it is given — a caller passing a style constant would otherwise
81
+ * find it rewritten under them.
82
+ */
83
+ export function adaptStyleForNative(style: StyleSpecification): StyleSpecification {
84
+ let changed = false;
85
+
86
+ let sources = style.sources;
87
+ if (isObject(sources)) {
88
+ const kept = Object.entries(sources).filter(
89
+ ([, source]) =>
90
+ !isObject(source) ||
91
+ !TILED_SOURCES.has(source.type as string) ||
92
+ source.url != null ||
93
+ source.tiles != null
94
+ );
95
+ if (kept.length !== Object.keys(sources).length) {
96
+ sources = Object.fromEntries(kept);
97
+ changed = true;
98
+ }
99
+ }
100
+
101
+ let layers = style.layers;
102
+ if (Array.isArray(layers)) {
103
+ let layersChanged = false;
104
+ const next = layers.map((layer: unknown) => {
105
+ if (!isObject(layer)) return layer;
106
+ const layout = isObject(layer.layout) ? adaptLayout(layer.layout) : null;
107
+ const paint = isObject(layer.paint) ? adaptPaint(layer.type, layer.paint) : null;
108
+ if (!layout && !paint) return layer;
109
+ layersChanged = true;
110
+ return { ...layer, ...(layout ? { layout } : null), ...(paint ? { paint } : null) };
111
+ });
112
+ if (layersChanged) {
113
+ layers = next;
114
+ changed = true;
115
+ }
116
+ }
117
+
118
+ return changed ? { ...style, sources, layers } : style;
119
+ }
120
+
121
+ const REMOTE_STYLE = /^https?:\/\//i;
122
+
123
+ /**
124
+ * Adapted styles by URL. Bounded, because an app that switches between a
125
+ * handful of styles should not refetch them on every switch, and one that
126
+ * builds URLs on the fly should not keep every style it ever loaded.
127
+ */
128
+ const loaded = new Map<string, Promise<StyleSpecification | null>>();
129
+ const LOADED_LIMIT = 8;
130
+
131
+ /**
132
+ * Fetches a hosted style and adapts it. Resolves `null` when the style could
133
+ * not be fetched or read, so the caller can leave the URL to the renderer —
134
+ * which has its own cache and request headers, and reports its own errors.
135
+ */
136
+ export function loadStyleForNative(url: string): Promise<StyleSpecification | null> {
137
+ const cached = loaded.get(url);
138
+ if (cached) return cached;
139
+
140
+ const pending = fetch(url)
141
+ .then((response) => (response.ok ? response.json() : null))
142
+ .then((json: unknown) => (isObject(json) ? adaptStyleForNative(json) : null))
143
+ .catch(() => null)
144
+ .then((style) => {
145
+ // A failure is not remembered: the next map to ask should try again.
146
+ if (!style) loaded.delete(url);
147
+ return style;
148
+ });
149
+
150
+ loaded.set(url, pending);
151
+ if (loaded.size > LOADED_LIMIT) {
152
+ loaded.delete(loaded.keys().next().value as string);
153
+ }
154
+ return pending;
155
+ }
156
+
157
+ /** A style passed inline — as an object, or as JSON text — adapted in place. */
158
+ function adaptInline(style: string | StyleSpecification): string | StyleSpecification {
159
+ if (typeof style !== 'string') return adaptStyleForNative(style);
160
+ if (!style.trimStart().startsWith('{')) return style;
161
+ try {
162
+ const parsed: unknown = JSON.parse(style);
163
+ return isObject(parsed) ? adaptStyleForNative(parsed) : style;
164
+ } catch {
165
+ return style;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * `mapStyle`, ready for the native renderer.
171
+ *
172
+ * `undefined` when no style was given, and `null` while a hosted style is
173
+ * still being fetched. Anything that is not an http(s) URL or a style document
174
+ * — an `asset://` path, a provider scheme — is passed through untouched,
175
+ * because only the renderer knows how to load it.
176
+ */
177
+ export function useNativeStyle(
178
+ style: string | StyleSpecification | undefined
179
+ ): string | StyleSpecification | null | undefined {
180
+ const remote = typeof style === 'string' && REMOTE_STYLE.test(style) ? style : undefined;
181
+
182
+ const inline = useMemo(
183
+ () => (style === undefined || remote ? undefined : adaptInline(style)),
184
+ [remote, style]
185
+ );
186
+
187
+ const [fetched, setFetched] = useState<{
188
+ url: string;
189
+ style: string | StyleSpecification;
190
+ }>();
191
+
192
+ useEffect(() => {
193
+ if (!remote) return undefined;
194
+ let live = true;
195
+ loadStyleForNative(remote).then((adapted) => {
196
+ if (live) setFetched({ url: remote, style: adapted ?? remote });
197
+ });
198
+ return () => {
199
+ live = false;
200
+ };
201
+ }, [remote]);
202
+
203
+ if (!remote) return inline;
204
+ return fetched?.url === remote ? fetched.style : null;
205
+ }
@@ -305,7 +305,9 @@ export const Progress = forwardRef<View, ProgressProps>(
305
305
  accessibilityLabel={label}
306
306
  // Indeterminate has no value to announce, so `busy` is the only thing
307
307
  // separating "working, length unknown" from "empty and going nowhere".
308
- accessibilityState={indeterminate ? { busy: true } : undefined}
308
+ // Always a boolean, never `undefined`: Android ignores a state that
309
+ // goes missing, so a bar turning determinate would still read as busy.
310
+ accessibilityState={{ busy: indeterminate }}
309
311
  accessibilityValue={
310
312
  indeterminate
311
313
  ? undefined
@@ -88,7 +88,7 @@ export const Skeleton = memo(function Skeleton({
88
88
  <Animated.View
89
89
  accessibilityRole={announced ? 'progressbar' : undefined}
90
90
  accessibilityLabel={label}
91
- accessibilityState={announced ? { busy: true } : undefined}
91
+ accessibilityState={{ busy: announced }}
92
92
  accessibilityElementsHidden={!announced}
93
93
  importantForAccessibility={announced ? 'auto' : 'no-hide-descendants'}
94
94
  style={[style, animatedStyle]}
@@ -129,7 +129,7 @@ export const Spinner = memo(function Spinner({
129
129
  <Animated.View
130
130
  accessibilityRole={announced ? 'progressbar' : undefined}
131
131
  accessibilityLabel={label}
132
- accessibilityState={announced ? { busy: true } : undefined}
132
+ accessibilityState={{ busy: announced }}
133
133
  accessibilityElementsHidden={!announced}
134
134
  importantForAccessibility={announced ? 'auto' : 'no-hide-descendants'}
135
135
  // After the class, so a colour passed here wins over the theme's. The
@@ -90,3 +90,28 @@ export function textChildren(
90
90
  typeof child === 'string' || typeof child === 'number' ? render(child) : child
91
91
  );
92
92
  }
93
+
94
+ /**
95
+ * The words among `children`, for a part that needs an accessibility label of
96
+ * its own — or `undefined` when the children are not all text.
97
+ *
98
+ * Android needs the label. React Native writes a state such as `busy` into a
99
+ * view's content description, and it rebuilds that description only when
100
+ * there is something to put in it. A view with no label that stops being busy
101
+ * has nothing to rebuild from, so it keeps saying "busy" and never reads its
102
+ * text again.
103
+ *
104
+ * All or nothing, unlike `textChildren`. An element among the children might
105
+ * carry words of its own, such as a count in a badge. A label built from the
106
+ * text beside it would leave those out, and a screen reader that already reads
107
+ * them would stop.
108
+ */
109
+ export function textLabel(children: ReactNode): string | undefined {
110
+ const parts = Children.toArray(children);
111
+ if (!parts.length) return undefined;
112
+ if (!parts.every((part) => typeof part === 'string' || typeof part === 'number')) {
113
+ return undefined;
114
+ }
115
+ const label = parts.join('').trim();
116
+ return label || undefined;
117
+ }