@superrouteca/sindoor-react-native 0.0.0-stage → 0.1.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.
package/src/geo.ts ADDED
@@ -0,0 +1,29 @@
1
+ // Level millimetres <-> longitude / latitude through a level's anchor: the formulas of sIndoor's
2
+ // sindoor_model::outdoor (level_to_geo / geo_to_level), so the SDK, sMap's indoor layer and the engine agree.
3
+ import type { Anchor } from './types';
4
+
5
+ export function mmPerDegree(lat: number): [number, number] {
6
+ const r = (lat * Math.PI) / 180;
7
+ const latM = 111132.92 - 559.82 * Math.cos(2 * r) + 1.175 * Math.cos(4 * r);
8
+ const lonM = 111412.84 * Math.cos(r) - 93.5 * Math.cos(3 * r);
9
+ return [latM * 1000, lonM * 1000];
10
+ }
11
+
12
+ /** A level point (mm, x east, y south) → [lng, lat]. */
13
+ export function levelToLngLat(anchor: Anchor, x: number, y: number): [number, number] {
14
+ const [kLat, kLon] = mmPerDegree(anchor.lat);
15
+ const rot = ((anchor.rotation_deg || 0) * Math.PI) / 180;
16
+ const s = Math.sin(rot), c = Math.cos(rot), k = anchor.scale ?? 1;
17
+ const xs = x * k, ys = y * k;
18
+ const e = xs * c - ys * s, south = xs * s + ys * c;
19
+ return [anchor.lon + e / kLon, anchor.lat - south / kLat];
20
+ }
21
+
22
+ /** [lng, lat] → a level point (mm). */
23
+ export function lngLatToLevel(anchor: Anchor, lng: number, lat: number): [number, number] {
24
+ const [kLat, kLon] = mmPerDegree(anchor.lat);
25
+ const e = (lng - anchor.lon) * kLon, south = -(lat - anchor.lat) * kLat;
26
+ const rot = ((anchor.rotation_deg || 0) * Math.PI) / 180;
27
+ const s = Math.sin(rot), c = Math.cos(rot), k = anchor.scale ?? 1;
28
+ return [(e * c + south * s) / k, (-e * s + south * c) / k];
29
+ }
package/src/hooks.ts ADDED
@@ -0,0 +1,126 @@
1
+ // sIndoor for React Native as hooks (as @superrouteca/sindoor-react): a site loaded once (then offline), a locator
2
+ // fed by the phone's sensors and beacons, and the navigation screen on an sMap map (with
3
+ // @superrouteca/smap-react-native, pass the <SMap> ref's map or useSMap()).
4
+ import { useEffect, useRef, useState } from 'react';
5
+ import type { SindoorClient } from './client';
6
+ import { SindoorNavigator, type NavigatorOptions, type SindoorMap } from './navigator';
7
+ import { SindoorSite, type SindoorLocator } from './site';
8
+ import type { SindoorError } from './errors';
9
+ import type { BeaconStatus, Download, Estimate, Observation } from './types';
10
+
11
+ export interface SiteHookOptions {
12
+ site?: string;
13
+ key?: string;
14
+ token?: string;
15
+ form?: 'customer' | 'full';
16
+ baseUrl?: string;
17
+ client?: SindoorClient;
18
+ /** Start from a download kept earlier instead (offline). */
19
+ download?: Download | string;
20
+ }
21
+
22
+ /** Load a site: `{site, key | token | client, form?, baseUrl?}` downloads it, `{download}` starts from a kept one.
23
+ * → `{site, error, loading}`; the site is disposed on unmount or when the inputs change. */
24
+ export function useSindoorSite(o: SiteHookOptions = {}): { site: SindoorSite | null; error: (Error & { code?: string }) | null; loading: boolean } {
25
+ const { site: id, key, token, form = 'customer', baseUrl, client, download } = o;
26
+ const [state, setState] = useState<{ site: SindoorSite | null; error: (Error & { code?: string }) | null; loading: boolean }>({ site: null, error: null, loading: true });
27
+ useEffect(() => {
28
+ let live = true;
29
+ let made: SindoorSite | null = null;
30
+ setState({ site: null, error: null, loading: true });
31
+ (async () => {
32
+ const s = download ? await SindoorSite.fromDownload(download) : await SindoorSite.load({ site: id as string, key, token, form, baseUrl, client });
33
+ if (live) {
34
+ made = s;
35
+ setState({ site: s, error: null, loading: false });
36
+ } else {
37
+ s.dispose();
38
+ }
39
+ })().catch((error: Error) => {
40
+ if (live) setState({ site: null, error, loading: false });
41
+ });
42
+ return () => {
43
+ live = false;
44
+ made?.dispose();
45
+ };
46
+ }, [id, key, token, form, baseUrl, client, download]);
47
+ return state;
48
+ }
49
+
50
+ export interface LocatorHookOptions {
51
+ /** Feed the phone's motion sensors (ask for the motion permission first on iOS). */
52
+ sensors?: boolean;
53
+ /** Feed BLE beacons: true for the site's / every beacon, or the iBeacon UUIDs (ask for the permissions first). */
54
+ beacons?: boolean | string[];
55
+ }
56
+
57
+ /** A locator on the site; `estimate` follows `observe`, the sensors and the beacons. Re-made when the site changes
58
+ * (config is read once per site); sensors and beacons follow their options. */
59
+ export function useSindoorLocator(site: SindoorSite | null, config?: object, options: LocatorHookOptions = {}): {
60
+ estimate: Estimate | null;
61
+ observe(obs: Observation | Observation[]): Estimate | null;
62
+ locator: SindoorLocator | null;
63
+ error: SindoorError | null;
64
+ beacons: BeaconStatus | null;
65
+ } {
66
+ const [locator, setLocator] = useState<SindoorLocator | null>(null);
67
+ const [estimate, setEstimate] = useState<Estimate | null>(null);
68
+ const [error, setError] = useState<SindoorError | null>(null);
69
+ const [beacons, setBeacons] = useState<BeaconStatus | null>(null);
70
+ const ref = useRef<SindoorLocator | null>(null);
71
+ useEffect(() => {
72
+ if (!site) return undefined;
73
+ const l = site.locator(config || {});
74
+ ref.current = l;
75
+ const offE = l.onEstimate(setEstimate);
76
+ const offErr = l.onError(setError);
77
+ setLocator(l);
78
+ return () => {
79
+ offE();
80
+ offErr();
81
+ l.dispose();
82
+ ref.current = null;
83
+ setLocator(null);
84
+ setEstimate(null);
85
+ };
86
+ }, [site]); // config is read once per site
87
+ const wantSensors = !!options.sensors;
88
+ const beaconKey = options.beacons === undefined || options.beacons === false ? '' : JSON.stringify(options.beacons === true ? [] : options.beacons);
89
+ useEffect(() => {
90
+ if (!locator || !wantSensors) return undefined;
91
+ locator.startSensors();
92
+ return () => locator.stopSensors();
93
+ }, [locator, wantSensors]);
94
+ useEffect(() => {
95
+ if (!locator || !beaconKey) return undefined;
96
+ setBeacons(locator.startBeacons(JSON.parse(beaconKey)));
97
+ return () => locator.stopBeacons();
98
+ }, [locator, beaconKey]);
99
+ const observe = (obs: Observation | Observation[]) => ref.current?.observe(obs) ?? null;
100
+ return { estimate, observe, locator, error, beacons };
101
+ }
102
+
103
+ /** The navigation screen on a map you hold (`map` the <SMap> ref's map). Re-made when map or site change; with
104
+ * `position` the blue dot follows it. */
105
+ export function useSindoorNavigator(map: SindoorMap | null | undefined, site: SindoorSite | null, options?: NavigatorOptions & { position?: Estimate | null }): SindoorNavigator | null {
106
+ const [nav, setNav] = useState<SindoorNavigator | null>(null);
107
+ const latest = useRef(options);
108
+ latest.current = options;
109
+ useEffect(() => {
110
+ if (!map || !site) return undefined;
111
+ let live = true;
112
+ const { position: _p, ...o } = latest.current || {};
113
+ const n = new SindoorNavigator(map, site, { ...o, onSteps: (lines) => latest.current?.onSteps?.(lines) });
114
+ n.ready.then(() => live && setNav(n), () => {});
115
+ return () => {
116
+ live = false;
117
+ n.destroy();
118
+ setNav(null);
119
+ };
120
+ }, [map, site]);
121
+ const position = options?.position;
122
+ useEffect(() => {
123
+ if (nav && position !== undefined) nav.showPosition(position);
124
+ }, [nav, position]);
125
+ return nav;
126
+ }
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ // sIndoor for React Native (sIndoor DESIGN.md Part 2h, IK4 / IK5): the indoor engine on the phone over the sIndoor
2
+ // Android and iOS SDKs (routes, tours, approach, positioning; offline once a site is downloaded), the phone's sensors
3
+ // and BLE beacons fed to the locator, the Open Platform's indoor routes, and a navigation screen on sMap maps.
4
+ export { SindoorError } from './errors';
5
+ export { SindoorClient, DEFAULT_BASE_URL } from './client';
6
+ export type { ClientOptions } from './client';
7
+ export { SindoorSite, SindoorLocator, engineVersion } from './site';
8
+ export type { LoadOptions, RouteOptions } from './site';
9
+ export { SindoorNavigator, DEFAULT_TEXT, defaultLevel } from './navigator';
10
+ export type { NavigatorOptions, SindoorMap, StepLine } from './navigator';
11
+ export { useSindoorSite, useSindoorLocator, useSindoorNavigator } from './hooks';
12
+ export type { SiteHookOptions, LocatorHookOptions } from './hooks';
13
+ export { levelToLngLat, lngLatToLevel, mmPerDegree } from './geo';
14
+ export type { Anchor, BeaconStatus, Download, Estimate, IndoorLayer, LayerLevel, Observation, Place, PublicSite, Route, Step } from './types';
15
+ export const VERSION = '0.1.0';
@@ -0,0 +1,232 @@
1
+ // The ready navigation screen (sIndoor DESIGN.md Part 2h, IK5) on an sMap React Native map: the site drawn as sMap's
2
+ // indoor layer (the native SDKs draw it), its level switcher, the blue dot and its accuracy, the route lines and the
3
+ // steps. The logic of @superrouteca/sindoor's SindoorNavigator, with the same names; the map is the ref of
4
+ // @superrouteca/smap-react-native's <SMap> (or useSMap()), whose indoor calls answer promises — so the level shown is
5
+ // kept here from `indoorlevelchange` and the step list is handed to `onSteps` instead of a DOM panel.
6
+ import { SindoorError } from './errors';
7
+ import type { SindoorSite } from './site';
8
+ import type { Estimate, Place, Route } from './types';
9
+
10
+ export const DEFAULT_TEXT: Record<string, string> = {
11
+ start: 'Start',
12
+ arrive: 'Arrive',
13
+ straight: 'Go straight',
14
+ slight_left: 'Bear left',
15
+ slight_right: 'Bear right',
16
+ left: 'Turn left',
17
+ right: 'Turn right',
18
+ sharp_left: 'Turn sharp left',
19
+ sharp_right: 'Turn sharp right',
20
+ u_turn: 'Turn around',
21
+ connector: 'Change level',
22
+ level: 'Level',
23
+ metres: '{n} m',
24
+ no_route: 'No walking route to this place.',
25
+ };
26
+
27
+ const fmt = (t: string, vars: Record<string, unknown>) => t.replace(/\{(\w+)\}/g, (_, k: string) => String(vars[k] ?? ''));
28
+
29
+ /** What the navigator needs of an sMap React Native map (`SMapHandle` of @superrouteca/smap-react-native 1.6.2+). */
30
+ export interface SindoorMap {
31
+ addIndoor(id: string, source: { geojson: object }, options?: Record<string, unknown>): Promise<void> | void;
32
+ setIndoorLevel(id: string, level: string): Promise<void> | void;
33
+ getIndoorLevel(id: string): Promise<string | null> | string | null;
34
+ removeIndoor(id: string): Promise<void> | void;
35
+ addPoints(id: string, data: any, options?: Record<string, unknown>): void;
36
+ addLines(id: string, data: any, options?: Record<string, unknown>): void;
37
+ addCircles?(id: string, data: any, options?: Record<string, unknown>): void;
38
+ removeLayer(id: string): void;
39
+ on?(type: 'indoorlevelchange', listener: (e: { id: string; level: string }) => void): void;
40
+ off?(type: 'indoorlevelchange', listener: (e: { id: string; level: string }) => void): void;
41
+ }
42
+
43
+ export interface StepLine {
44
+ kind: string;
45
+ level: string;
46
+ distance_mm: number;
47
+ text: string;
48
+ }
49
+
50
+ export interface NavigatorOptions {
51
+ /** The indoor layer's id on the map (default `sindoor`). */
52
+ id?: string;
53
+ /** The level switcher (default true). */
54
+ control?: boolean | { position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' };
55
+ /** The level shown first. */
56
+ level?: string;
57
+ /** Any DEFAULT_TEXT key, for translations. */
58
+ text?: Partial<Record<string, string>>;
59
+ /** Movement profile (default the site's pedestrian). */
60
+ profile?: string;
61
+ /** `customer` (default), `staff`, `delivery`, `all`. */
62
+ role?: 'customer' | 'staff' | 'delivery' | 'all';
63
+ /** Keep the shown level on the walker's (default true). */
64
+ follow?: boolean;
65
+ colors?: { dot?: string; accuracy?: string; route?: string };
66
+ /** The step list changed (a route drawn, cleared, or none found) — what a step list shows. */
67
+ onSteps?: (lines: { text: string; level?: string; kind?: string; distance_mm?: number }[]) => void;
68
+ }
69
+
70
+ const swallow = (v: unknown) => {
71
+ if (v && typeof (v as Promise<unknown>).then === 'function') (v as Promise<unknown>).then(undefined, () => {});
72
+ };
73
+
74
+ export class SindoorNavigator {
75
+ readonly map: SindoorMap;
76
+ readonly site: SindoorSite;
77
+ readonly o: NavigatorOptions & { id: string; control: NavigatorOptions['control']; role: string; follow: boolean };
78
+ readonly text: Record<string, string>;
79
+ readonly colors: { dot: string; accuracy: string; route: string };
80
+ position: Estimate | null = null;
81
+ routeResult: Route | null = null;
82
+ /** Resolves once the map has the site (sMap's addIndoor waits for its data); `create()` waits for it. */
83
+ readonly ready: Promise<SindoorNavigator>;
84
+ private _routeLayers: string[] = [];
85
+ private _dotLayers = new Set<string>();
86
+ private _level: string | null;
87
+ private _destroyed = false;
88
+ private readonly _onLevel: (e: { id: string; level: string }) => void;
89
+
90
+ constructor(map: SindoorMap, site: SindoorSite, o: NavigatorOptions = {}) {
91
+ if (!map || typeof map.addIndoor !== 'function') throw new SindoorError('no_indoor_layer', 'this sMap map has no indoor layer (needs @superrouteca/smap-react-native with addIndoor)');
92
+ this.map = map;
93
+ this.site = site;
94
+ this.o = { id: 'sindoor', control: true, role: 'customer', follow: true, ...o } as SindoorNavigator['o'];
95
+ this.text = { ...DEFAULT_TEXT, ...((o.text || {}) as Record<string, string>) };
96
+ this.colors = { dot: '#1a73e8', accuracy: 'rgba(26,115,232,0.15)', route: '#1a73e8', ...(o.colors || {}) };
97
+ const layer = site.layer();
98
+ this._level = o.level ?? defaultLevel(layer.levels || []);
99
+ this._onLevel = (e) => {
100
+ if (e?.id !== this.o.id) return;
101
+ this._level = e.level;
102
+ this._redrawDot();
103
+ };
104
+ map.on?.('indoorlevelchange', this._onLevel);
105
+ const opts: Record<string, unknown> = { control: this.o.control };
106
+ if (this.o.level !== undefined) opts.level = this.o.level;
107
+ this.ready = Promise.resolve(map.addIndoor(this.o.id, { geojson: layer }, opts))
108
+ .then(() => Promise.resolve(map.getIndoorLevel(this.o.id)))
109
+ .then((shown) => {
110
+ if (shown) this._level = String(shown);
111
+ // A position shown before the layer was in follows it now.
112
+ if (this.position && this.o.follow && this.position.level !== this._level) this.setLevel(this.position.level);
113
+ return this;
114
+ });
115
+ }
116
+
117
+ /** A navigator once the map has drawn the site. */
118
+ static async create(map: SindoorMap, site: SindoorSite, o: NavigatorOptions = {}): Promise<SindoorNavigator> {
119
+ return new SindoorNavigator(map, site, o).ready;
120
+ }
121
+
122
+ /** The level shown (kept from the map's `indoorlevelchange`). */
123
+ get level(): string | null {
124
+ return this._level;
125
+ }
126
+
127
+ setLevel(level: string): void {
128
+ this._level = level;
129
+ swallow(this.map.setIndoorLevel(this.o.id, level));
130
+ }
131
+
132
+ /** Show where the walker is: an estimate of a SindoorLocator (`{level, x, y, acc_mm}`, lng / lat added). */
133
+ showPosition(e: Estimate | null): void {
134
+ this.position = e || null;
135
+ if (e && this.o.follow && e.level !== this.level) this.setLevel(e.level);
136
+ this._redrawDot();
137
+ }
138
+
139
+ private _remove(id: string): void {
140
+ try {
141
+ this.map.removeLayer(id);
142
+ } catch {
143
+ /* gone */
144
+ }
145
+ }
146
+
147
+ private _redrawDot(): void {
148
+ for (const id of this._dotLayers) this._remove(id);
149
+ this._dotLayers.clear();
150
+ const e = this.position;
151
+ if (!e || this._destroyed) return;
152
+ const id = `${this.o.id}-me`;
153
+ const [lng, lat] = this.site.toLngLat(e.level, e.x, e.y);
154
+ const indoor = { id: this.o.id, level: e.level };
155
+ if (this.map.addCircles && e.acc_mm) {
156
+ this.map.addCircles(`${id}-acc`, [{ lng, lat, radius: e.acc_mm / 1000 }], { color: this.colors.accuracy, fill: this.colors.accuracy, indoor });
157
+ this._dotLayers.add(`${id}-acc`);
158
+ }
159
+ this.map.addPoints(id, [{ lng, lat }], { color: this.colors.dot, radius: 7, strokeColor: '#ffffff', strokeWidth: 2, indoor });
160
+ this._dotLayers.add(id);
161
+ }
162
+
163
+ /** Walk to a target (a ref such as `fixture:12`, `{level, x, y}` or `{lng, lat, level}`) from the shown position (or
164
+ * `from`); draws the route and hands the steps to `onSteps`. Answers the engine's route. */
165
+ navigateTo(target: Place, { from }: { from?: Place } = {}): Route {
166
+ const start: Place | null = from ?? (this.position ? { level: this.position.level, x: this.position.x, y: this.position.y } : null);
167
+ if (!start) throw new SindoorError('no_position', 'no position yet: pass from or call showPosition first');
168
+ let r: Route;
169
+ try {
170
+ r = this.site.route(start, target, { role: this.o.role, profile: this.o.profile });
171
+ } catch (e) {
172
+ this.clearRoute();
173
+ this._panel([{ text: this.text.no_route }]);
174
+ throw e;
175
+ }
176
+ this.showRoute(r);
177
+ return r;
178
+ }
179
+
180
+ /** Draw an engine route (`{legs: [{level, polyline}], steps}`) and its steps. */
181
+ showRoute(r: Route): void {
182
+ this.clearRoute();
183
+ this.routeResult = r;
184
+ (r.legs || []).forEach((leg, i) => {
185
+ const id = `${this.o.id}-route-${i}`;
186
+ const coords = leg.polyline.map(([x, y]) => this.site.toLngLat(leg.level, x, y));
187
+ this.map.addLines(id, { type: 'Feature', geometry: { type: 'LineString', coordinates: coords }, properties: {} }, { color: this.colors.route, width: 5, indoor: { id: this.o.id, level: leg.level } });
188
+ this._routeLayers.push(id);
189
+ });
190
+ this._panel(this.steps(r));
191
+ }
192
+
193
+ /** The route's steps as text lines `[{kind, level, text, distance_mm}]` (also what `onSteps` is given). */
194
+ steps(r: Route | null = this.routeResult): StepLine[] {
195
+ return (r?.steps || []).map((s) => {
196
+ const what = this.text[s.kind] ?? s.kind;
197
+ const dist = s.distance_mm > 0 ? ' · ' + fmt(this.text.metres, { n: Math.round(s.distance_mm / 1000) }) : '';
198
+ return { kind: s.kind, level: s.level, distance_mm: s.distance_mm, text: `${what}${dist}` };
199
+ });
200
+ }
201
+
202
+ clearRoute(): void {
203
+ for (const id of this._routeLayers) this._remove(id);
204
+ this._routeLayers = [];
205
+ this.routeResult = null;
206
+ this._panel([]);
207
+ }
208
+
209
+ private _panel(lines: { text: string; level?: string; kind?: string; distance_mm?: number }[]): void {
210
+ this.o.onSteps?.(lines);
211
+ }
212
+
213
+ destroy(): void {
214
+ if (this._destroyed) return;
215
+ this.clearRoute();
216
+ this.position = null;
217
+ this._redrawDot();
218
+ this._destroyed = true;
219
+ this.map.off?.('indoorlevelchange', this._onLevel);
220
+ swallow(this.map.removeIndoor(this.o.id));
221
+ }
222
+ }
223
+
224
+ /** The level sMap shows first: the first of ordinal 0, else the lowest. */
225
+ export function defaultLevel(levels: { id: string; ordinal: number }[]): string | null {
226
+ let best: { id: string; ordinal: number } | null = null;
227
+ for (const l of levels) {
228
+ if (l.ordinal === 0) return String(l.id);
229
+ if (!best || l.ordinal < best.ordinal) best = l;
230
+ }
231
+ return best ? String(best.id) : null;
232
+ }