findort 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kramer Multimedia Solutions
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # Findort for JavaScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![CI](https://github.com/Findort/findort-js/actions/workflows/ci.yml/badge.svg)](https://github.com/Findort/findort-js/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/findort.svg)](https://www.npmjs.com/package/findort)
5
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ Geocoding and address autocomplete on OpenStreetMap, with a tiny client and the
8
+ `<findort-search>` Web Component. No dependencies. Works in browsers, Node 18+, Deno and Bun.
9
+
10
+ > **Deutsch:** Offizielle JavaScript-Library für die [Findort](https://findort.com)-API:
11
+ > Adressen und Orte suchen, Koordinaten auflösen und ein fertiges Suchfeld als Web Component.
12
+ > Die Dokumentation auf Deutsch steht auf [findort.com](https://findort.com).
13
+
14
+ You need an API key from [findort.com](https://findort.com): a public key (`pk_…`) for web pages,
15
+ restricted to your domain, or a secret key (`sk_…`) for servers. Never put a secret key in a web page.
16
+
17
+ ## Web Component (no build step)
18
+
19
+ ```html
20
+ <script type="module" src="https://api.findort.com/sdk/v1/search.js"></script>
21
+
22
+ <findort-search key="pk_…" country="ch" lang="de" name="address"></findort-search>
23
+
24
+ <script>
25
+ document.querySelector('findort-search')
26
+ .addEventListener('findort-select', (e) => console.log(e.detail.place));
27
+ </script>
28
+ ```
29
+
30
+ `/sdk/v1/…` always serves the newest 1.x. For a fixed version, use `/sdk/1.0.1/search.js`:
31
+ it never changes, so you can cache it forever and pin it with Subresource Integrity.
32
+
33
+ **Attributes:** `key`, `base-url`, `lang`, `country`, `types`, `limit`, `near` (`"lat,lon"`),
34
+ `placeholder`, `value`, `name` (form field), `min-length`, `debounce`.
35
+
36
+ **Events:** `findort-select` (`detail.place`), `findort-error` (`detail.error`), `change`.
37
+ The element is form-associated: with a `name`, the chosen label is submitted with the form.
38
+
39
+ **Styling:** CSS custom properties `--findort-accent`, `--findort-bg`, `--findort-fg`,
40
+ `--findort-muted`, `--findort-border`, `--findort-radius`, `--findort-font`, or
41
+ `::part(input)`, `::part(list)`, `::part(option)`.
42
+
43
+ ## Client
44
+
45
+ ```bash
46
+ npm install findort
47
+ ```
48
+
49
+ ```js
50
+ import { Findort, autocomplete } from 'findort';
51
+
52
+ const findort = new Findort('pk_…', { lang: 'de', country: 'ch' });
53
+
54
+ const places = await findort.search('Zytglogge'); // list of places
55
+ const place = await findort.geocode('Bundesplatz 3, Bern'); // best match or null
56
+ const here = await findort.reverse(46.9465, 7.4443); // what is at this point
57
+
58
+ const suggest = autocomplete(findort, 150); // debounced, only the latest call resolves
59
+ input.addEventListener('input', async () => render(await suggest(input.value)));
60
+ ```
61
+
62
+ With a bundler, the Web Component is `import 'findort/search';`.
63
+
64
+ ### Options
65
+
66
+ | Option | Default | |
67
+ |---|---|---|
68
+ | `key` | none | `pk_…` in the browser, `sk_…` on servers |
69
+ | `baseUrl` | `https://api.findort.com` | |
70
+ | `lang` | none | language of results: `de`, `fr`, `it`, `en` |
71
+ | `country` | none | `"ch"` or `["ch", "li"]` |
72
+ | `timeout` | `8000` | ms |
73
+ | `fetch` | `globalThis.fetch` | your own fetch, e.g. for tests |
74
+
75
+ Per call: `limit`, `lang`, `country`, `near`, `bbox`, `types`, `signal` (search) and
76
+ `limit`, `lang`, `radius`, `types`, `signal` (reverse). Types are in [`src/index.d.ts`](src/index.d.ts).
77
+
78
+ ### Errors
79
+
80
+ Everything that goes wrong is a `FindortError` with `status` and `code`, for example
81
+ `invalid_key`, `origin_not_allowed`, `rate_limited` or `quota_exceeded`. `timeout` and
82
+ `network_error` (status 0) come from the client. Your own `AbortSignal` still rejects with
83
+ an `AbortError`. The client never follows redirects, so your key cannot travel to another address.
84
+
85
+ ## Development
86
+
87
+ ```bash
88
+ npm ci
89
+ npm test # node --test
90
+ npm run lint # ESLint and TypeScript
91
+ ```
92
+
93
+ Issues and pull requests are welcome here. Releases: see [CHANGELOG.md](CHANGELOG.md).
94
+
95
+ ## License
96
+
97
+ [MIT](LICENSE). Map data © [OpenStreetMap contributors](https://www.openstreetmap.org/copyright) (ODbL).
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "findort",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Geocoding and address autocomplete on OpenStreetMap. Tiny client plus <findort-search> Web Component.",
5
+ "type": "module",
6
+ "main": "./src/findort.js",
7
+ "types": "./src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "default": "./src/findort.js"
12
+ },
13
+ "./search": {
14
+ "types": "./src/search.d.ts",
15
+ "default": "./src/search.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "src"
20
+ ],
21
+ "sideEffects": [
22
+ "./src/search.js"
23
+ ],
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "scripts": {
28
+ "test": "node --test test/*.test.js",
29
+ "lint": "eslint . && tsc -p .",
30
+ "version:check": "node scripts/check-version.mjs"
31
+ },
32
+ "keywords": [
33
+ "geocoding",
34
+ "autocomplete",
35
+ "address",
36
+ "openstreetmap",
37
+ "web-component",
38
+ "swiss",
39
+ "switzerland"
40
+ ],
41
+ "homepage": "https://findort.com",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/Findort/findort-js.git"
45
+ },
46
+ "bugs": {
47
+ "url": "https://github.com/Findort/findort-js/issues"
48
+ },
49
+ "author": "Kramer Multimedia Solutions (https://findort.com)",
50
+ "license": "MIT",
51
+ "devDependencies": {
52
+ "@eslint/js": "^10.0.1",
53
+ "eslint": "^10.16.0",
54
+ "globals": "^17.15.0",
55
+ "typescript": "^7.0.2"
56
+ }
57
+ }
package/src/findort.js ADDED
@@ -0,0 +1,158 @@
1
+ // Findort JavaScript client. Works in browsers, Node 18+, Deno and Bun. No dependencies.
2
+ // @ts-check
3
+
4
+ export const DEFAULT_BASE_URL = 'https://api.findort.com';
5
+ /** SDK version, the same as in package.json and in /sdk/<version>/ URLs. */
6
+ export const VERSION = '1.0.1';
7
+
8
+ export class FindortError extends Error {
9
+ /** @param {number} status @param {string} code @param {string} message */
10
+ constructor(status, code, message) {
11
+ super(message);
12
+ this.name = 'FindortError';
13
+ this.status = status;
14
+ this.code = code;
15
+ }
16
+ }
17
+
18
+ /** @param {Record<string, unknown>} obj */
19
+ function toQuery(obj) {
20
+ const sp = new URLSearchParams();
21
+ for (const [k, v] of Object.entries(obj)) {
22
+ if (v === undefined || v === null || v === '') continue;
23
+ if (k === 'near' && typeof v === 'object') {
24
+ const n = /** @type {any} */ (v);
25
+ sp.set('near', Array.isArray(n) ? n.join(',') : `${n.lat},${n.lon}`);
26
+ } else if (Array.isArray(v)) {
27
+ sp.set(k, v.join(','));
28
+ } else {
29
+ sp.set(k, String(v));
30
+ }
31
+ }
32
+ return sp.toString();
33
+ }
34
+
35
+ export class Findort {
36
+ /**
37
+ * @param {string | import('./index').FindortOptions} [keyOrOptions]
38
+ * @param {import('./index').FindortOptions} [options]
39
+ */
40
+ constructor(keyOrOptions, options = {}) {
41
+ const opts = typeof keyOrOptions === 'string' ? { ...options, key: keyOrOptions } : { ...(keyOrOptions ?? {}) };
42
+ this.key = opts.key;
43
+ this.baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, '');
44
+ this.lang = opts.lang;
45
+ this.country = opts.country;
46
+ this.timeout = opts.timeout ?? 8000;
47
+ this._fetch = opts.fetch ?? globalThis.fetch.bind(globalThis);
48
+ }
49
+
50
+ /**
51
+ * Search places by text. Made for autocomplete.
52
+ * @param {string} q
53
+ * @param {import('./index').SearchOptions} [options]
54
+ * @returns {Promise<import('./index').Place[]>}
55
+ */
56
+ async search(q, options = {}) {
57
+ const { signal, ...rest } = options;
58
+ const res = await this._get('/v1/search', { q, lang: this.lang, country: this.country, ...rest }, signal);
59
+ return res.results;
60
+ }
61
+
62
+ /**
63
+ * Find what is at a coordinate.
64
+ * @param {number} lat
65
+ * @param {number} lon
66
+ * @param {import('./index').ReverseOptions} [options]
67
+ * @returns {Promise<import('./index').Place[]>}
68
+ */
69
+ async reverse(lat, lon, options = {}) {
70
+ const { signal, ...rest } = options;
71
+ const res = await this._get('/v1/reverse', { lat, lon, lang: this.lang, ...rest }, signal);
72
+ return res.results;
73
+ }
74
+
75
+ /**
76
+ * The single best match for a text, or null.
77
+ * @param {string} q
78
+ * @param {import('./index').SearchOptions} [options]
79
+ */
80
+ async geocode(q, options = {}) {
81
+ return (await this.search(q, { ...options, limit: 1 }))[0] ?? null;
82
+ }
83
+
84
+ /**
85
+ * @param {string} path
86
+ * @param {Record<string, unknown>} params
87
+ * @param {AbortSignal} [signal]
88
+ * @returns {Promise<{results: import('./index').Place[], attribution: string}>}
89
+ */
90
+ async _get(path, params, signal) {
91
+ // Own controller instead of AbortSignal.any/timeout: works in older browsers and Node 18 too,
92
+ // and tells a timeout (FindortError "timeout") apart from the caller aborting.
93
+ const ctrl = new AbortController();
94
+ let timedOut = false;
95
+ const timer = setTimeout(() => { timedOut = true; ctrl.abort(); }, this.timeout);
96
+ const onAbort = () => ctrl.abort();
97
+ if (signal) {
98
+ if (signal.aborted) ctrl.abort();
99
+ else signal.addEventListener('abort', onAbort, { once: true });
100
+ }
101
+ /** @type {Record<string, string>} */
102
+ const headers = { Accept: 'application/json' };
103
+ if (this.key) headers.Authorization = `Bearer ${this.key}`;
104
+ try {
105
+ // No redirects: the key must never travel to another address.
106
+ const res = await this._fetch(`${this.baseUrl}${path}?${toQuery(params)}`, { headers, signal: ctrl.signal, redirect: 'error' });
107
+ let body;
108
+ try { body = await res.json(); } catch { body = null; }
109
+ if (!res.ok) {
110
+ throw new FindortError(res.status, body?.error?.code ?? 'http_error', body?.error?.message ?? `HTTP ${res.status}`);
111
+ }
112
+ return body;
113
+ } catch (e) {
114
+ if (e instanceof FindortError) throw e;
115
+ if (timedOut) throw new FindortError(0, 'timeout', `No answer within ${this.timeout} ms`);
116
+ if (signal?.aborted) throw e; // the caller's own abort stays an AbortError
117
+ throw new FindortError(0, 'network_error', /** @type {Error} */ (e).message || 'Network error');
118
+ } finally {
119
+ clearTimeout(timer);
120
+ signal?.removeEventListener('abort', onAbort);
121
+ }
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Wraps a search so only the latest call resolves; older ones are aborted.
127
+ * Use it for "search as you type".
128
+ * @param {Findort} client
129
+ * @param {number} [wait] debounce in ms
130
+ */
131
+ export function autocomplete(client, wait = 150) {
132
+ /** @type {AbortController | null} */
133
+ let ctrl = null;
134
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
135
+ let timer;
136
+ /**
137
+ * @param {string} q
138
+ * @param {import('./index').SearchOptions} [options]
139
+ * @returns {Promise<import('./index').Place[]>}
140
+ */
141
+ return (q, options = {}) => {
142
+ ctrl?.abort();
143
+ clearTimeout(timer);
144
+ const mine = (ctrl = new AbortController());
145
+ if (!q.trim()) return Promise.resolve([]);
146
+ return new Promise((resolve, reject) => {
147
+ timer = setTimeout(() => {
148
+ client.search(q, { ...options, signal: mine.signal }).then(resolve, (e) => {
149
+ if (mine.signal.aborted) resolve([]);
150
+ else reject(e);
151
+ });
152
+ }, wait);
153
+ mine.signal.addEventListener('abort', () => resolve([]), { once: true });
154
+ });
155
+ };
156
+ }
157
+
158
+ export default Findort;
package/src/index.d.ts ADDED
@@ -0,0 +1,88 @@
1
+ export type PlaceType =
2
+ | 'address' | 'street' | 'poi' | 'locality' | 'city'
3
+ | 'district' | 'county' | 'state' | 'country';
4
+
5
+ export interface Address {
6
+ street?: string;
7
+ housenumber?: string;
8
+ postcode?: string;
9
+ locality?: string;
10
+ district?: string;
11
+ city?: string;
12
+ county?: string;
13
+ state?: string;
14
+ country?: string;
15
+ /** ISO 3166-1 alpha-2, upper case, e.g. "CH" */
16
+ countryCode?: string;
17
+ }
18
+
19
+ export interface Place {
20
+ /** OSM type letter + id, e.g. "W254958900" */
21
+ id: string;
22
+ /** Ready-to-show one-line label */
23
+ label: string;
24
+ name: string;
25
+ type: PlaceType;
26
+ /** OSM key:value, e.g. "amenity:restaurant" */
27
+ category: string;
28
+ address: Address;
29
+ location: { lat: number; lon: number };
30
+ /** [minLon, minLat, maxLon, maxLat] */
31
+ bbox?: [number, number, number, number];
32
+ }
33
+
34
+ export interface FindortOptions {
35
+ /** pk_… in the browser, sk_… on servers */
36
+ key?: string;
37
+ /** Default https://api.findort.com */
38
+ baseUrl?: string;
39
+ /** Default language for results: de, fr, it, en */
40
+ lang?: string;
41
+ /** Default country filter: "ch" or ["ch", "li"] */
42
+ country?: string | string[];
43
+ /** Request timeout in ms, default 8000 */
44
+ timeout?: number;
45
+ fetch?: typeof fetch;
46
+ }
47
+
48
+ export interface SearchOptions {
49
+ limit?: number;
50
+ lang?: string;
51
+ country?: string | string[];
52
+ near?: { lat: number; lon: number } | [number, number] | string;
53
+ /** [minLon, minLat, maxLon, maxLat] */
54
+ bbox?: [number, number, number, number] | string;
55
+ types?: PlaceType[] | string;
56
+ signal?: AbortSignal;
57
+ }
58
+
59
+ export interface ReverseOptions {
60
+ limit?: number;
61
+ lang?: string;
62
+ /** Search radius in km */
63
+ radius?: number;
64
+ types?: PlaceType[] | string;
65
+ signal?: AbortSignal;
66
+ }
67
+
68
+ export declare const VERSION: string;
69
+ export declare const DEFAULT_BASE_URL: string;
70
+
71
+ export declare class FindortError extends Error {
72
+ status: number;
73
+ /** 'timeout' and 'network_error' (status 0) come from the client itself. */
74
+ code: 'invalid_request' | 'missing_key' | 'invalid_key' | 'origin_not_allowed' | 'rate_limited' | 'quota_exceeded' | 'secret_key_in_url' | 'upstream_error' | 'timeout' | 'network_error' | string;
75
+ }
76
+
77
+ export declare class Findort {
78
+ constructor(key?: string, options?: FindortOptions);
79
+ constructor(options?: FindortOptions);
80
+ search(q: string, options?: SearchOptions): Promise<Place[]>;
81
+ reverse(lat: number, lon: number, options?: ReverseOptions): Promise<Place[]>;
82
+ geocode(q: string, options?: Omit<SearchOptions, 'limit'>): Promise<Place | null>;
83
+ }
84
+
85
+ /** Debounced search where only the latest call resolves with results. */
86
+ export declare function autocomplete(client: Findort, wait?: number): (q: string, options?: SearchOptions) => Promise<Place[]>;
87
+
88
+ export default Findort;
@@ -0,0 +1,19 @@
1
+ import type { Place } from './index';
2
+ export { Findort } from './index';
3
+
4
+ export declare class FindortSearch extends HTMLElement {
5
+ /** The place the user picked, or null after typing. */
6
+ selected: Place | null;
7
+ value: string;
8
+ clear(): void;
9
+ }
10
+
11
+ declare global {
12
+ interface HTMLElementTagNameMap {
13
+ 'findort-search': FindortSearch;
14
+ }
15
+ interface HTMLElementEventMap {
16
+ 'findort-select': CustomEvent<{ place: Place }>;
17
+ 'findort-error': CustomEvent<{ error: Error }>;
18
+ }
19
+ }
package/src/search.js ADDED
@@ -0,0 +1,211 @@
1
+ // <findort-search>: an address/place search field. Framework-free Web Component.
2
+ //
3
+ // <script type="module" src="https://api.findort.com/sdk/v1/search.js"></script>
4
+ // <findort-search key="pk_…" country="ch" lang="de" name="address"></findort-search>
5
+ //
6
+ // el.addEventListener('findort-select', (e) => console.log(e.detail.place));
7
+ //
8
+ // Attributes: key, base-url, lang, country, types, limit, near ("lat,lon"),
9
+ // placeholder, value, name (form field), min-length, debounce.
10
+ // Styling: CSS custom properties --findort-accent, --findort-bg, --findort-fg,
11
+ // --findort-muted, --findort-border, --findort-radius, --findort-font, or ::part(input|list|option).
12
+
13
+ import { Findort, autocomplete } from './findort.js';
14
+
15
+ const ICONS = {
16
+ address: 'M4 10.5 12 4l8 6.5V20h-5v-6H9v6H4z',
17
+ poi: 'M12 2a7 7 0 0 0-7 7c0 5 7 13 7 13s7-8 7-13a7 7 0 0 0-7-7zm0 9.5A2.5 2.5 0 1 1 12 6.5a2.5 2.5 0 0 1 0 5z',
18
+ street: 'M9 3 7 21M15 3l2 18M12 5v2m0 4v2m0 4v2',
19
+ city: 'M3 21V9l6-3v15M9 21V3l12 4v14M13 9h2m-2 4h2m-2 4h2',
20
+ };
21
+
22
+ const CSS = `
23
+ :host { display: block; position: relative; font: var(--findort-font, inherit); color: var(--findort-fg, #14161a); }
24
+ input {
25
+ box-sizing: border-box; width: 100%; font: inherit; color: inherit;
26
+ padding: .7em .9em .7em 2.4em; border: 1px solid var(--findort-border, #d6d6cf);
27
+ border-radius: var(--findort-radius, 10px); background: var(--findort-bg, #fff) no-repeat .85em center / 1.1em;
28
+ outline: none; transition: border-color .15s, box-shadow .15s;
29
+ }
30
+ input:focus { border-color: var(--findort-accent, #ffc531); box-shadow: 0 0 0 3px color-mix(in srgb, var(--findort-accent, #ffc531) 35%, transparent); }
31
+ .pin { position: absolute; left: .85em; top: 50%; translate: 0 -50%; width: 1.1em; height: 1.1em; pointer-events: none; color: var(--findort-muted, #8a8a84); }
32
+ ul {
33
+ position: absolute; z-index: 1000; left: 0; right: 0; top: calc(100% + 4px); margin: 0; padding: 4px;
34
+ list-style: none; background: var(--findort-bg, #fff); border: 1px solid var(--findort-border, #d6d6cf);
35
+ border-radius: var(--findort-radius, 10px); box-shadow: 0 10px 30px rgb(0 0 0 / .12); max-height: 22em; overflow: auto;
36
+ }
37
+ ul[hidden] { display: none; }
38
+ li[role=option] { display: flex; gap: .7em; align-items: center; padding: .55em .65em; border-radius: calc(var(--findort-radius, 10px) - 4px); cursor: pointer; }
39
+ li[aria-selected=true] { background: color-mix(in srgb, var(--findort-accent, #ffc531) 22%, transparent); }
40
+ li svg { flex: none; width: 1.1em; height: 1.1em; color: var(--findort-muted, #8a8a84); }
41
+ .main { display: block; font-weight: 550; }
42
+ .sub { display: block; font-size: .85em; color: var(--findort-muted, #8a8a84); }
43
+ mark { background: none; color: inherit; font-weight: 750; }
44
+ .foot { padding: .4em .65em .2em; font-size: .72em; color: var(--findort-muted, #8a8a84); text-align: right; }
45
+ .foot a { color: inherit; }
46
+ .empty { padding: .6em .65em; color: var(--findort-muted, #8a8a84); }
47
+ `;
48
+
49
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
50
+
51
+ function highlight(text, q) {
52
+ const words = q.toLowerCase().split(/\s+/).filter((w) => w.length > 1);
53
+ let out = esc(text);
54
+ for (const w of words) {
55
+ out = out.replace(new RegExp(`(^|[\\s,(-])(${esc(w).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi'), '$1<mark>$2</mark>');
56
+ }
57
+ return out;
58
+ }
59
+
60
+ function icon(type) {
61
+ const d = ICONS[type] ?? (type === 'poi' ? ICONS.poi : ICONS.city);
62
+ return `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round" aria-hidden="true"><path d="${d}"/></svg>`;
63
+ }
64
+
65
+ let uid = 0;
66
+
67
+ export class FindortSearch extends HTMLElement {
68
+ static formAssociated = true;
69
+ static observedAttributes = ['placeholder', 'value', 'disabled'];
70
+
71
+ constructor() {
72
+ super();
73
+ this._id = `findort-${++uid}`;
74
+ this._results = [];
75
+ this._active = -1;
76
+ this._query = '';
77
+ this.selected = null;
78
+ this._internals = 'attachInternals' in this ? this.attachInternals() : null;
79
+ const root = this.attachShadow({ mode: 'open', delegatesFocus: true });
80
+ root.innerHTML = `
81
+ <style>${CSS}</style>
82
+ <svg class="pin" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>
83
+ <input part="input" type="text" role="combobox" autocomplete="off" spellcheck="false"
84
+ aria-autocomplete="list" aria-expanded="false" aria-controls="${this._id}-list">
85
+ <ul part="list" id="${this._id}-list" role="listbox" hidden></ul>`;
86
+ this.input = root.querySelector('input');
87
+ this.list = root.querySelector('ul');
88
+
89
+ this.input.addEventListener('input', () => this._onInput());
90
+ this.input.addEventListener('keydown', (e) => this._onKey(e));
91
+ this.input.addEventListener('blur', () => setTimeout(() => this._close(), 120));
92
+ this.input.addEventListener('focus', () => { if (this._results.length) this._open(); });
93
+ this.list.addEventListener('mousedown', (e) => e.preventDefault());
94
+ this.list.addEventListener('click', (e) => {
95
+ const li = /** @type {HTMLElement} */ (e.target).closest('li[data-i]');
96
+ if (li) this._select(Number(li.dataset.i));
97
+ });
98
+ }
99
+
100
+ connectedCallback() {
101
+ const en = (this.getAttribute('lang') ?? document.documentElement.lang ?? '').startsWith('en');
102
+ this._empty = en ? 'Nothing found' : 'Nichts gefunden';
103
+ this.input.placeholder = this.getAttribute('placeholder') ?? (en ? 'Search address or place' : 'Adresse oder Ort suchen');
104
+ if (this.hasAttribute('value')) this.input.value = this.getAttribute('value');
105
+ this.input.disabled = this.hasAttribute('disabled');
106
+ const key = this.getAttribute('key') ?? '';
107
+ // A secret key in a web page is public: anyone can copy it from the HTML.
108
+ if (key.startsWith('sk_')) console.warn('<findort-search>: secret keys (sk_) do not belong in a web page. Use a public key (pk_) with your domain as origin.');
109
+ this._client = new Findort({
110
+ key: this.getAttribute('key') ?? undefined,
111
+ baseUrl: this.getAttribute('base-url') ?? undefined,
112
+ lang: this.getAttribute('lang') ?? (document.documentElement.lang.slice(0, 2) || undefined),
113
+ country: this.getAttribute('country') ?? undefined,
114
+ });
115
+ this._search = autocomplete(this._client, Number(this.getAttribute('debounce') ?? 150));
116
+ this._sync();
117
+ }
118
+
119
+ attributeChangedCallback(name, _old, val) {
120
+ if (!this.input) return;
121
+ if (name === 'placeholder') this.input.placeholder = val ?? '';
122
+ if (name === 'value') { this.input.value = val ?? ''; this._sync(); }
123
+ if (name === 'disabled') this.input.disabled = val !== null;
124
+ }
125
+
126
+ get value() { return this.input.value; }
127
+ set value(v) { this.input.value = v ?? ''; this.selected = null; this._sync(); }
128
+
129
+ focus(opts) { this.input.focus(opts); }
130
+ clear() { this.value = ''; this._results = []; this._close(); }
131
+
132
+ _sync() {
133
+ this._internals?.setFormValue(this.input.value);
134
+ }
135
+
136
+ async _onInput() {
137
+ const q = this.input.value;
138
+ this._query = q;
139
+ this.selected = null;
140
+ this._sync();
141
+ if (q.trim().length < Number(this.getAttribute('min-length') ?? 2)) { this._results = []; this._close(); return; }
142
+ const near = this.getAttribute('near');
143
+ try {
144
+ const results = await this._search(q, {
145
+ limit: Number(this.getAttribute('limit') ?? 6),
146
+ types: this.getAttribute('types') ?? undefined,
147
+ near: near ?? undefined,
148
+ });
149
+ if (q !== this._query) return;
150
+ this._results = results;
151
+ this._active = results.length ? 0 : -1;
152
+ this._render();
153
+ } catch (err) {
154
+ this.dispatchEvent(new CustomEvent('findort-error', { detail: { error: err }, bubbles: true, composed: true }));
155
+ }
156
+ }
157
+
158
+ _render() {
159
+ const q = this._query;
160
+ if (!this._results.length) {
161
+ this.list.innerHTML = `<li class="empty" role="presentation">${esc(this._empty ?? 'Nichts gefunden')}</li>`;
162
+ } else {
163
+ this.list.innerHTML = this._results.map((p, i) => {
164
+ const [main, ...rest] = p.label.split(', ');
165
+ return `<li part="option" role="option" id="${this._id}-${i}" data-i="${i}" aria-selected="${i === this._active}">
166
+ ${icon(p.type)}<span><span class="main">${highlight(main, q)}</span><span class="sub">${esc(rest.join(', ') || p.address?.country || '')}</span></span></li>`;
167
+ }).join('') + `<li class="foot" role="presentation">© <a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">OpenStreetMap</a>${
168
+ this._results.some((p) => /^(CH|LI)A/.test(p.id)) ? ' · <a href="https://www.swisstopo.admin.ch" target="_blank" rel="noopener">swisstopo</a>' : ''} · findort</li>`;
169
+ }
170
+ this.input.setAttribute('aria-activedescendant', this._active >= 0 ? `${this._id}-${this._active}` : '');
171
+ this._open();
172
+ }
173
+
174
+ _open() { this.list.hidden = false; this.input.setAttribute('aria-expanded', 'true'); }
175
+ _close() { this.list.hidden = true; this.input.setAttribute('aria-expanded', 'false'); }
176
+
177
+ _move(delta) {
178
+ if (!this._results.length) return;
179
+ this._active = (this._active + delta + this._results.length) % this._results.length;
180
+ for (const li of this.list.querySelectorAll('li[data-i]')) {
181
+ li.setAttribute('aria-selected', String(Number(li.dataset.i) === this._active));
182
+ }
183
+ this.input.setAttribute('aria-activedescendant', `${this._id}-${this._active}`);
184
+ this.list.querySelector(`[data-i="${this._active}"]`)?.scrollIntoView({ block: 'nearest' });
185
+ }
186
+
187
+ _onKey(e) {
188
+ const open = !this.list.hidden;
189
+ if (e.key === 'ArrowDown') { e.preventDefault(); open ? this._move(1) : this._results.length && this._open(); }
190
+ else if (e.key === 'ArrowUp') { e.preventDefault(); this._move(-1); }
191
+ else if (e.key === 'Enter' && open && this._active >= 0) { e.preventDefault(); this._select(this._active); }
192
+ else if (e.key === 'Escape') { this._close(); }
193
+ }
194
+
195
+ _select(i) {
196
+ const place = this._results[i];
197
+ if (!place) return;
198
+ this.selected = place;
199
+ this.input.value = place.label;
200
+ this._sync();
201
+ this._close();
202
+ this.dispatchEvent(new CustomEvent('findort-select', { detail: { place }, bubbles: true, composed: true }));
203
+ this.dispatchEvent(new Event('change', { bubbles: true }));
204
+ }
205
+ }
206
+
207
+ if (!customElements.get('findort-search')) customElements.define('findort-search', FindortSearch);
208
+
209
+ export { Findort };
210
+ /** Internal helpers, exported for the tests only. */
211
+ export const __test = { esc, highlight };