@magicx-eng/ai-autocomplete-vanilla 0.57.1 → 0.58.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/README.md CHANGED
@@ -1,40 +1,59 @@
1
1
  # @magicx-eng/ai-autocomplete-vanilla
2
2
 
3
- A framework-agnostic vanilla JS/TypeScript library that provides a guided AI-powered autocomplete experience with pill-based input and dropdown suggestions. Works with any tech stack — React, Vue, Svelte, Angular, or plain HTML.
3
+ AI Autocomplete for any web page: an input and dropdown for search boxes and
4
+ other text inputs. As the user types, it suggests the next detail to add and
5
+ the options for it. It is plain TypeScript with no dependencies, so it works
6
+ with any stack: plain HTML, Vue, Svelte, React or Angular. React and Angular
7
+ also have wrappers, `@magicx-eng/ai-autocomplete-react` and
8
+ `@magicx-eng/ai-autocomplete-angular`.
4
9
 
5
- ## Features
6
-
7
- - **Three tiers of integration** — full drop-in component, dropdown-only, or fully headless
8
- - **Zero dependencies** — no React, no framework, no virtual DOM
9
- - **Rich inline input** — a single `contentEditable` surface: typed text, bold completed params, and inline pills all share one editing context
10
- - **Pill-based input** — non-editable inline pills for unfilled parameters, bold inline text for completed ones
11
- - **Instant exact-match bolding** — typing the full text of an option immediately promotes it to a completed param (no debounced fetch wait). Works in the normal typing flow *and* while re-editing an existing completed param.
12
- - **Re-edit completed params** — tap a bold completed param to replace it; the dropdown re-opens with the cached options the server originally returned for that param
13
- - **Light/dark mode** — built-in themes with `prefers-color-scheme` support, fully overridable via CSS variables
14
- - **Access token auth** — short-lived tokens with automatic refresh, single-flight deduplication, and 401 retry
15
- - **Keyboard navigation** — arrow keys, enter to submit, tab to autocomplete, backspace to un-bold the last completed param
16
- - **Client-side filtering** — instant substring filtering on every keystroke
17
- - **Datepicker** — date parameters are answered with a calendar instead of an option list. Click a day or navigate with the arrow keys; the date is committed the way it would be written — `Tuesday` for a date inside the next week, `March 23` for one later this year, `March 23 2027` for another year. Tapping a committed date re-opens the calendar on the month that text names now — for a weekday name, that is the next such day, not the one originally picked. A date-range parameter gets the same calendar answered in two clicks, committed as one range.
18
- - **Time picker** — time parameters are answered with a time wheel instead of an option list: three wheels (hour, minutes in fives, AM/PM) and a Done button. Scroll or tap the wheels, or press ↑ / ↓ in the input to move the time five minutes; Enter or Done commits it, written as `7:30 PM`. Tapping a committed time re-opens the wheel on it.
19
- - **Option overrides** — supply the options for a parameter yourself: a fixed list, a computed one, or one fetched from your own search endpoint as the user types
20
- - **Product strip** — the dropdown renders a horizontal row of product cards below the options, filled by default with the items the `/suggest` response reports as matching the query; plug in your own product search instead with `products`, or turn the strip off with `showProducts: false`
21
- - **Catalog report** — every response says which of the query's constraints the catalog applied, which it had to drop, and how many items are left, on `customFields` / `custom_fields`
22
- - **Controlled & uncontrolled** — works out of the box or integrates with external state
23
- - **Accessible** — ARIA combobox 1.2 pattern with `role="listbox"`, `aria-activedescendant`
24
- - **IME-safe** — composition events are buffered so input text is committed once, after composition ends
25
- - **Animations** — option press (the picked option compresses while the rest step back), text shimmer on newly added params
26
- - **Loading skeleton** — while a fetch is in flight, the dropdown and inline pills keep the previous layout (same count and widths) with their text masked and a shimmer pulse. The skeleton is held back until the option-press animation finishes, so taps don't visually "stutter" into loading.
27
- - **Lightweight** — ~10 KB gzipped, styles auto-injected at runtime
28
- - **TypeScript first** — full type definitions shipped with the package
29
- - **Shadow-DOM ready** — mount the container inside a shadow root and the styles and caret follow it there, with nothing to configure; page CSS can't reach the widget
30
- - **SSR-safe** — no top-level `document`/`window` access
31
-
32
- ## Installation
10
+ ## Quick start
33
11
 
34
12
  ```bash
35
- pnpm add @magicx-eng/ai-autocomplete-vanilla
13
+ npm install @magicx-eng/ai-autocomplete-vanilla
14
+ ```
15
+
16
+ ```html
17
+ <div id="autocomplete-root"></div>
36
18
  ```
37
19
 
20
+ ```ts
21
+ import { AIAutocomplete } from "@magicx-eng/ai-autocomplete-vanilla";
22
+
23
+ new AIAutocomplete(document.getElementById("autocomplete-root")!, {
24
+ apiConfig: { apiKey: "pk_v1_your_public_key" },
25
+ onSubmit: (result) => console.log(result.query),
26
+ });
27
+ ```
28
+
29
+ Pass an empty container element, such as a `div`. The widget builds its own input inside it. Styles are injected at runtime, so there is no CSS file to import.
30
+
31
+ To get a key, create your product at https://ai-autocomplete.com/edit/logic (it sets what the box suggests), then create a public key at https://ai-autocomplete.com/account/keys. Public keys start with `pk_v1_` and are safe to ship in the browser.
32
+
33
+ - Docs: https://ai-autocomplete.com/docs/vanilla/getting-started
34
+ - Install with an AI coding agent: https://ai-autocomplete.com/install/vanilla.md
35
+ - Product strip and datepicker guides: [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), also shipped in the package
36
+ - On Shopify? The Shopify app sets this up in a few minutes, no code: https://apps.shopify.com/ai-autocomplete
37
+
38
+ ## Features
39
+
40
+ - **Three tiers:** the full component, the dropdown on an input you own, or headless state for your own UI.
41
+ - **No dependencies:** no framework and no virtual DOM. The ESM entry, styles included, is about 90 KB gzipped.
42
+ - **Pills and options:** the details still to fill show as pills in the input, with their options in the dropdown. Typing an option's full text completes it at once, and tapping a completed detail lets the user change it.
43
+ - **Datepicker:** date and date-range parameters get a calendar instead of a list.
44
+ - **Time picker:** time parameters get a time wheel instead of a list.
45
+ - **Multiple selections:** a multi-select question gets checkbox options and a Done button.
46
+ - **Location search:** a location parameter sent without options gets a search field for any city or address.
47
+ - **Product strip:** a row of product cards under the options, from your catalog or from your own search.
48
+ - **Option overrides:** supply a parameter's options yourself, as a fixed list, a computed one, or results from your own endpoint.
49
+ - **Catalog report:** each response says which of the query's constraints the catalog applied, which it dropped, and how many items are left.
50
+ - **Motion:** the picked option presses in, new details shimmer, and a loading skeleton keeps the layout while a request is in flight.
51
+ - **Input handling:** keyboard navigation, the ARIA combobox 1.2 pattern, and IME-safe typing.
52
+ - **Auth:** a public key, or short-lived access tokens with automatic refresh and one retry on a 401.
53
+ - **Styling:** light and dark themes, CSS variables, stable `data-aia-*` selector hooks, and shadow DOM support.
54
+ - **Controlled or uncontrolled:** works on its own or with your own state.
55
+ - **TypeScript:** full type definitions, and safe to import during server-side rendering.
56
+
38
57
  ## Three Tiers
39
58
 
40
59
  | Tier | What you get | What you own | Use when |
@@ -53,10 +72,7 @@ Drop-in. The library creates and owns the input, dropdown, pills, and all DOM.
53
72
  import { AIAutocomplete } from "@magicx-eng/ai-autocomplete-vanilla";
54
73
 
55
74
  const ac = new AIAutocomplete(document.getElementById("root"), {
56
- apiConfig: {
57
- endpoint: "https://api.example.com/ac/suggest",
58
- apiKey: "your_api_key",
59
- },
75
+ apiConfig: { apiKey: "your_api_key" },
60
76
  onSubmit: (result) => {
61
77
  console.log(result.query); // "Create a email"
62
78
  console.log(result.raw_query); // "Create a {{TASK_1}}"
@@ -92,6 +108,7 @@ const ac = new AIAutocomplete(container, {
92
108
  dropdownTrigger: "auto", // "auto" | "manual" | "hidden"
93
109
  closeDropdownOnBlur: true, // false = keep dropdown open even when input loses focus
94
110
  showNonTappableOptions: true, // false = hide non-tappable options from the dropdown
111
+ locationSearch: true, // false = a location field takes typed text only, no lookups
95
112
  showSkipButton: true, // false = hide the pill bar's trailing "skip" button
96
113
  showOptionIcons: true, // false = render option rows as text only (no icons)
97
114
  showChipIcons: true, // false = render completed chips as text only (no icons)
@@ -188,295 +205,23 @@ ac.getRequestId(); // The latest applied /suggest request ID, or nul
188
205
 
189
206
  ### Product strip
190
207
 
191
- The dropdown renders a horizontal row of product cards below the options grid
192
- whenever it has products to show. By default those are the items the
193
- `/suggest` response itself reports as matching the query — no configuration,
194
- no extra request: the cards land in the same state write as the suggestions,
195
- so what the strip shows and what the pills offer always describe the same
196
- narrowing.
197
-
198
- ```ts
199
- import { AIAutocomplete } from "@magicx-eng/ai-autocomplete-vanilla";
200
-
201
- new AIAutocomplete(container, {
202
- apiConfig: { apiKey: "..." },
203
- // Selection emits — the SDK never navigates.
204
- onProductSelect: (product) => {
205
- if (product.url) window.location.assign(product.url); // …or add to cart, or fill the input
206
- },
207
- });
208
- ```
209
-
210
- Each server item becomes a `Product` with `id` (the item's stable id), `title`,
211
- `price` (the item's lowest price, verbatim as the catalog spells it — the
212
- currency is yours to add), `compareAtPrice` (the price before a markdown, on a
213
- discounted item only, struck through beside the price), `vendor`, `imageUrl`, and a `url`: the item's own
214
- `item_url` when the uploaded catalog named one (absolute or root-relative;
215
- anything else is ignored), else a **relative** `/products/{handle}` — the right
216
- link for a Shopify widget running on the storefront itself — opened on the
217
- variant the query chose (`?variant=…`, e.g. the blue one for "blue shoes") when
218
- there is one, whose price and image the card then shows. `available` is carried
219
- over when the server reports it. An item with
220
- neither gets no `url`: its card is still activatable and still emits
221
- `onProductSelect`, it just has nothing for cmd-click to open. `productFromMatchedItem` / `productsFromCustomFields` are
222
- exported for a hand-rolled strip that wants the same mapping.
223
-
224
- Set `showProducts: false` to render no strip at all. The catalog report
225
- (below) stays readable either way.
226
-
227
- `productsLayout: "list"` stacks the same cards as full-width rows — thumbnail
228
- on the left, title, vendor and price on the right — for results that read as
229
- a list (courses, listings, documents) rather than products on a shelf. The
230
- column scrolls vertically inside `--aia-product-list-max-height` (320px by
231
- default); `--aia-product-list-media-size` (44px) sizes the thumbnail and
232
- `--aia-product-list-gap` (2px) the space between rows. `"row"`, the default,
233
- is the horizontal strip. `update({ productsLayout })` re-lays the strip out at
234
- once.
235
-
236
- **Product image fallback.** A product's image takes priority when its
237
- `imageUrl` loads successfully. A missing or blank URL, or an image load error,
238
- uses `productImageFallback`: `"image"` (the default) shows the existing
239
- placeholder pictogram; `"initial"` shows the first character of the trimmed,
240
- uppercased title. This is a Unicode grapheme (so a combined character or emoji
241
- stays together), with a Unicode code point fallback in older browsers. An
242
- empty or whitespace-only title shows `?`. The fallback works in both row and
243
- list layouts. Initial tiles are decorative (`aria-hidden="true"`); the card's
244
- visible title supplies its text.
245
-
246
- **Sold out.** A product with `available: false` shows a "Sold out" badge over
247
- the top-left of its image (in the list layout, a smaller banner across the
248
- bottom of the thumbnail) and its image is desaturated; the card stays
249
- selectable and keeps its link. Absent or `true` shows no
250
- badge, so leave `available` out when you don't know. The badge is part of the
251
- card's text, so screen readers announce it. Theme it with
252
- `--aia-product-badge-bg`, `--aia-product-badge-color`,
253
- `--aia-product-badge-font-size` and `--aia-product-badge-inset`, and the list
254
- banner with `--aia-product-badge-list-bg`, `--aia-product-badge-list-color` and
255
- `--aia-product-badge-list-font-size`.
256
-
257
- Set the option at construction or change it through `update()`. Both
258
- rendered tiers (`"full"` and `"dropdown"`) apply it to the visible cards:
259
-
260
- ```ts
261
- const ac = new AIAutocomplete(container, {
262
- apiConfig: { apiKey: "..." },
263
- productImageFallback: "initial",
264
- });
265
-
266
- // Switch existing fallback tiles back to the placeholder pictogram.
267
- ac.update({ productImageFallback: "image" });
268
- ```
269
-
270
- Style the initial tile itself with `[data-aia-product-initial]`. For
271
- example, wrap the widget in an element with `id="catalog-search"` and add this
272
- rule to your stylesheet. The existing `--aia-product-media-bg` variable sets
273
- the background; `color`, `font-size` and `border-radius` style the initial
274
- without additional SDK options.
275
-
276
- ```css
277
- #catalog-search [data-aia-product-initial] {
278
- --aia-product-media-bg: #eef2ff;
279
- color: #4338ca;
280
- font-size: 22px;
281
- border-radius: 12px;
282
- }
283
- ```
208
+ The dropdown shows a row of product cards under the options whenever there are products to show. By default they are the items the `/suggest` response reports as matching the query. When a card is picked, `onProductSelect` fires; the SDK never navigates. `showProducts: false` turns the strip off, `productsLayout: "list"` stacks the cards as rows, and `productImageFallback` sets what a card shows when it has no image. The full guide, with the `Product` shape, sold-out badges and accessibility, is in [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "Product strip".
284
209
 
285
210
  #### Add to cart
286
211
 
287
- Pass `onProductAddToCart` and every card that isn't sold out gets a round
288
- add-to-cart button in the bottom right corner of its image. Sold-out cards
289
- (`available: false`) get none. Pressing it calls your handler, not
290
- `onProductSelect`. The card doesn't open, and the panel stays open. The SDK
291
- never touches a cart; your handler does the adding:
292
-
293
- ```ts
294
- new AIAutocomplete(container, {
295
- apiConfig: { apiKey: "..." },
296
- onProductAddToCart: async (product) => {
297
- const res = await fetch("/cart/add", { method: "POST", body: JSON.stringify({ id: product.id }) });
298
- if (!res.ok) throw new Error(`cart ${res.status}`);
299
- },
300
- });
301
- ```
302
-
303
- Return a promise to have the button show progress. It carries
304
- `data-aia-cart-state="adding"` while the promise is pending, then `"added"`
305
- (the cart glyph turns into a check) once it resolves. The check stays until the
306
- card's product changes (a price-only change keeps it); pressing it again adds
307
- another unit, going back through `"adding"` to `"added"`. A rejection returns
308
- it to rest. Style it with
309
- `--aia-product-cart-size` (28px), `--aia-product-cart-bg` and
310
- `--aia-product-cart-color`, or `[data-aia-product-cart]`. In the list layout
311
- the button sits at the row's right end. Headless consumers rendering
312
- their own cards call `addProductToCart(product)`, which resolves or rejects
313
- with the handler.
212
+ Pass `onProductAddToCart` and every card that isn't sold out gets a cart button; pressing it calls your handler, and the SDK never touches a cart. Details: [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "Add to cart".
314
213
 
315
214
  #### The catalog report (`customFields`)
316
215
 
317
- Every response that read the catalog also says what it did with the query, and
318
- the SDK exposes that as `customFields` on state (and as `custom_fields` on
319
- `AutocompleteResult`, so `onResult` / `getResult()` carry it too):
320
-
321
- ```ts
322
- ac.subscribe((state) => {
323
- const report = state.customFields;
324
- if (!report) return; // no catalog was read for this response
325
- count.textContent = `${report.items.total} results`;
326
- if (report.dropped_filters.length > 0) {
327
- // e.g. { parameter: "Color", value: "Chartreuse", op: "eq" } — the shopper asked
328
- // for a colour no item carries, so the results ignore it. Say so.
329
- note.textContent = `No match for ${report.dropped_filters.map((f) => f.value).join(", ")}`;
330
- }
331
- });
332
- ```
333
-
334
- - `applied_filters` / `dropped_filters` — the constraints the server read out
335
- of the query as `{ parameter, value, op }` (`op` is one of `eq`, `ne`, `lt`,
336
- `lte`, `gt`, `gte`), split into the ones the catalog answered and the ones it
337
- could not (a parameter it does not have, a bound that is not a number, a
338
- value no item carries). The items answer the applied set, so the dropped
339
- list is what tells "87 black t-shirts" from "no black item, so here are
340
- t-shirts". Both are always arrays.
341
- - `items.total` — how many items the applied filters left standing. It also
342
- moves with the query's own words, so it drops as a typed word starts
343
- matching a title. `items.matched` is the list the strip renders, capped by
344
- the server; it is empty (with a non-zero `total`) when nothing narrowed the
345
- catalog, where listing arbitrary items as matches would mislead.
346
- - `null` means the response carried no report — no catalog was read for it
347
- (a product with no catalog, the starting state, a response with no
348
- option-bearing parameter to offer). That is "no news", not an empty
349
- catalog. The strip clears on such a response rather than keeping an older
350
- query's items.
216
+ Each response that read the catalog says which of the query's constraints it applied (`applied_filters`), which it dropped (`dropped_filters`) and how many items are left (`items.total`). Read it from `customFields` on state, or from `custom_fields` on `AutocompleteResult`. `null` means no catalog was read for that response. Details: [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "The catalog report".
351
217
 
352
218
  #### Change product cards before display
353
219
 
354
- - `mapProducts(products, items)` synchronously returns the cards to show.
355
- - The SDK calls it once per response with its default cards and their matched items in the same order.
356
- - The returned array becomes the product state and the displayed strip.
357
- - A thrown error or a non-array result keeps the default cards. A thrown error warns once per instance.
358
- - `refreshProducts()` maps the current items again without a request. Call it when your own data arrives.
359
- - Both APIs leave a custom `products` integration unchanged.
360
-
361
- ```ts
362
- const autocomplete = new AIAutocomplete(container, {
363
- mapProducts: (products, items) =>
364
- products.map((product, index) => ({
365
- ...product,
366
- price: shopperPrices[items[index].source_id] ?? "",
367
- })),
368
- });
369
-
370
- // After updating shopperPrices:
371
- autocomplete.refreshProducts();
372
- ```
373
-
374
- - `update({ mapProducts })` immediately maps the current items with the new mapper.
375
- - Price changes add, update, or remove price text on the same cards. Selection reports the updated product.
220
+ `mapProducts(products, items)` changes the cards before they show (to put in the shopper's own prices, say), and `refreshProducts()` maps them again when your data arrives. Details: [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "Change product cards before display".
376
221
 
377
222
  #### Your own product search (`products`)
378
223
 
379
- To source the cards from your own search instead — a platform with its own
380
- endpoint and response shape — set `products`. The SDK owns the UI; you own
381
- only the fetching and the mapping. The server's items are then not rendered
382
- (they stay readable on `customFields`).
383
-
384
- ```ts
385
- import { AIAutocomplete, type Product } from "@magicx-eng/ai-autocomplete-vanilla";
386
-
387
- new AIAutocomplete(container, {
388
- apiConfig: { apiKey: "..." },
389
-
390
- products: {
391
- // You own the request entirely — auth headers, GraphQL body, locale
392
- // prefixes, whatever the platform needs. Honour the signal: the SDK aborts
393
- // it as soon as a newer query supersedes this one.
394
- fetch: (query, signal) =>
395
- fetch("/api/2024-10/graphql.json", {
396
- method: "POST",
397
- headers: { "X-Shopify-Storefront-Access-Token": token },
398
- body: JSON.stringify({ query: SEARCH_QUERY, variables: { q: query } }),
399
- signal,
400
- }).then((r) => r.json()),
401
-
402
- // Pure mapping, kept out of `fetch` so you can unit-test it without a
403
- // network. Fold it into `fetch` and return the array if you prefer.
404
- transform: (raw) =>
405
- raw.data.products.nodes.map((node) => ({
406
- id: node.id,
407
- title: node.title,
408
- url: node.onlineStoreUrl,
409
- imageUrl: node.featuredImage?.url ?? null,
410
- price: formatMoney(node.priceRange.minVariantPrice), // you know the currency
411
- vendor: node.vendor,
412
- })),
413
-
414
- limit: 8, // applied by the SDK, after transform
415
- },
416
-
417
- onProductSelect: (product) => {
418
- if (product.url) window.location.assign(product.url);
419
- },
420
- });
421
- ```
422
-
423
- `Product` is exactly seven fields; only `id` and `title` are required:
424
-
425
- ```ts
426
- type Product = {
427
- id: string;
428
- title: string;
429
- url?: string; // absent = a card with no link (still activatable)
430
- imageUrl?: string | null; // null uses the configured productImageFallback
431
- price?: string; // pre-formatted by you
432
- compareAtPrice?: string; // the price before a markdown; struck through beside price
433
- vendor?: string;
434
- available?: boolean; // false shows a "Sold out" badge
435
- };
436
- ```
437
-
438
- **What the SDK guarantees**
439
-
440
- - **One fetch cadence.** The product search rides the same debounce, the same
441
- `AbortController` and the same version guard as `/suggest` — there is no
442
- second timer to drift out of step. A query that never triggers a suggestions
443
- request (e.g. one still narrowing the current option list) doesn't trigger a
444
- product search either.
445
- - **Empty queries never reach you.** On mount and after `reset()` the strip
446
- simply clears.
447
- - **Out-of-order responses are dropped.** A slow response for an older query is
448
- never rendered over a newer one.
449
- - **Failure is silent.** A rejected `fetch` or a throwing `transform` clears the
450
- strip, logs once, and leaves the suggestions half untouched — no `error`
451
- state, no `onError`, no effect on `isLoading`.
452
- - **The two halves are independent.** The panel opens if *either* has content,
453
- so products keep it open when option filtering empties the list, and
454
- suggestions render normally when there are no products. `dropdownTrigger`
455
- (`manual` / `hidden`) still gates the panel as before — products don't
456
- overrule an explicit opt-out of an auto-opening panel.
457
-
458
- **Selection and links.** Cards are real `<a href>` elements, so cmd/ctrl-click,
459
- middle-click and "copy link address" behave natively. A plain left click is
460
- intercepted (`preventDefault`) and emits `onProductSelect` instead — the SDK
461
- never navigates on your behalf.
462
-
463
- `product.url` is used verbatim — the SDK trusts your `transform` output and
464
- does not sanitise it, so validate the URL there if the platform response isn't
465
- fully under your control. (Angular additionally runs its own `href`
466
- sanitiser, so unrecognised schemes like `myapp://…` are rewritten to
467
- `unsafe:…` in that package only.)
468
-
469
- **Accessibility.** The strip is a `role="group"` labelled "Products"; each card
470
- is a `role="option"` in the tab order, activated with Enter or Space, with a
471
- visible focus ring. Tabbing into the strip does not close the panel. The row
472
- scrolls horizontally by trackpad, wheel, touch and keyboard; the page never
473
- scrolls sideways and the scrollbar chrome is hidden in all engines.
474
-
475
- `update({ products })` swaps the integration and clears the current cards; the
476
- strip repopulates on the *next* `/suggest` request, since the product search
477
- rides that one scheduler and changing the config doesn't itself change the
478
- query. `update({ products: undefined })` hands the strip back to the server's
479
- items at once, and `update({ showProducts })` empties or restores it at once.
224
+ Set `products` to fill the cards from your own search. You write a `fetch` that honours the abort signal and a `transform` that maps the response to `Product` objects; the SDK keeps the UI, the timing and the order of responses. Details: [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "Your own product search".
480
225
 
481
226
  #### Custom submit button
482
227
 
@@ -497,151 +242,19 @@ new AIAutocomplete(container, { ..., submitButton: null });
497
242
 
498
243
  ### Datepicker
499
244
 
500
- When the next parameter is a date, the dropdown shows a calendar instead of a
501
- list of options. Which parameters are dates is the server's call: one whose
502
- `type` is `date` gets a calendar, and one without a date type keeps its option
503
- list, however date-like its name or options look.
504
-
505
- Nothing is required to switch it on — a date parameter renders this way
506
- automatically, and every other parameter is unaffected. Tier 1 and Tier 2 render
507
- the calendar for you; in Tier 3 the same data reaches your own renderer (see
508
- [Tier 3](#tier-3-headless)).
509
-
510
- **What the user can do**
511
-
512
- | Input | Result |
513
- |---|---|
514
- | Click a day | Commits that date |
515
- | <kbd>↓</kbd> | Moves into the calendar, starting on today |
516
- | <kbd>←</kbd> / <kbd>→</kbd> | Previous / next day, crossing week boundaries |
517
- | <kbd>↑</kbd> / <kbd>↓</kbd> | Previous / next week. Past either end of the month, focus returns to the input |
518
- | <kbd>Enter</kbd> | Commits the highlighted day |
519
- | Month arrows | Page the calendar. Paging never commits anything |
520
- | <kbd>→</kbd> at the end of the input | Skips the parameter, same as any other pill |
521
-
522
- **The committed value** is written the way a person would write it, always in
523
- English regardless of the visitor's locale, so the value you receive has one
524
- vocabulary everywhere:
525
-
526
- - a date inside the next week (today included) commits as its weekday name —
527
- `Tuesday`. Like the sentence it sits in, that name is relative: read later,
528
- it means the next such day;
529
- - one further out in the current year as `MONTH DAY` — `March 23`;
530
- - one in another year as `MONTH DAY YEAR` — `March 23 2027`.
531
-
532
- It arrives as an ordinary completed parameter: bold in the input,
533
- and present in `completed_params` on submit like any other answer.
534
-
535
- **Re-editing** a committed date re-opens the calendar on the month the committed
536
- text names, with that day marked, so changing an answer takes one click. For a
537
- weekday name that reading is relative, so once the day it named has gone by,
538
- re-editing marks the next such day rather than the one originally picked — the
539
- calendar shows what the sentence says today, which is also what gets submitted.
540
-
541
- **Reading the value back.** The date arrives as text, so if you need a `Date`
542
- object, `parseDate` is exported for it:
543
-
544
- ```ts
545
- import { parseDate } from "@magicx-eng/ai-autocomplete-vanilla";
546
-
547
- // Reads all three committed shapes: a weekday name is the one date it can
548
- // mean in the next seven days, and a yearless month-day is the current year.
549
- const due = parseDate("March 23"); // Date, or null if the text isn't one of ours
550
- ```
551
-
552
- `parseLooseDate` is exported too, for the looser shapes a person types into a
553
- query — it reads `september 5th`, `5th September`, `Sept 5` and `2026-09-05`,
554
- and answers `null` for anything ambiguous rather than guessing.
555
-
556
- **Dates the user writes themselves.** When someone types a date into their query
557
- — "fly to vegas on september 5th" — the parameter it answers is recognised in
558
- place and the date becomes tappable. Tapping it opens the calendar on that
559
- month with the day already marked, so confirming or changing it takes one tap,
560
- and the picked date replaces their words with the canonical form.
561
-
562
- The written date is read where it can be: `september 5th`, `5th September`,
563
- `Sept 5`, `September 5, 2026` and `2026-09-05` all resolve, in any of those
564
- orders and with or without the year (a date with no year means its next
565
- occurrence). Two cases deliberately don't pre-select — a numeric date like
566
- `09/05`, which is September 5th in the US and May 9th elsewhere with nothing to
567
- say which, and phrases like `next friday`. Those still open the calendar, just
568
- on the current month with nothing marked, so the user picks rather than being
569
- shown a guess that might be wrong.
570
-
571
- **Date ranges.** A parameter whose `type` is `date_range` is answered by the
572
- same calendar in two clicks: the first sets the start, the second the end, and the pair
573
- commits as one answer. The days between them band as the user moves across the
574
- calendar, so the span being chosen is visible before it is committed. Paging the
575
- month between the two clicks is expected — that is how a span crosses months —
576
- and <kbd>Esc</kbd> drops the start and lets them begin again. Clicking the end
577
- before the start is fine; the two are ordered on the way in.
578
-
579
- It commits as one parameter, written as a span —
580
- `September 11 - October 13`, with the year on whichever end needs it — and both
581
- ends are also recorded on the completed parameter's `metadata` as `YYYY-MM-DD`,
582
- under the `DATE_RANGE_META_START` / `DATE_RANGE_META_END` keys this package
583
- exports (`aiaDateRangeStart` / `aiaDateRangeEnd`), so you never have to parse
584
- the prose. Re-editing one re-opens the calendar with both ends marked.
585
-
586
- **Typing** while the calendar is open does not filter it. The text is treated as
587
- a new query, so suggestions refresh as the user types — useful when someone
588
- would rather describe what they want than pick a day.
245
+ When the next parameter is a date, the dropdown shows a calendar instead of a list of options, and a date-range parameter gets the same calendar answered in two clicks. Nothing is needed to switch it on. The date is committed the way a person writes it (`Tuesday`, `March 23`, `March 23 2027`), and `parseDate` reads it back as a `Date`. Keyboard use, dates the user types and date ranges are covered in [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "Datepicker".
589
246
 
590
247
  ### Time picker
591
248
 
592
- When the next parameter is a time, the dropdown shows a time wheel instead of a
593
- list of options. As with dates, which parameters are times is the server's call:
594
- one whose `type` is `time` gets the wheel, and one without it keeps its option
595
- list, however time-like its options look.
596
-
597
- Nothing is required to switch it on. The options the server still sends for a
598
- time parameter are never shown, but they choose where the wheel opens: on the
599
- middle of the times suggested (`6 PM`, `7 PM`, `8 PM` opens on 7:00 PM), or on
600
- the next whole hour when there are none.
601
-
602
- **What the user can do**
603
-
604
- | Input | Result |
605
- |---|---|
606
- | Scroll or tap a wheel | Turns that wheel; the time on the top rows is the time. Commits nothing |
607
- | <kbd>↓</kbd> / <kbd>↑</kbd> in the input | Moves the time 5 minutes later / earlier |
608
- | <kbd>Enter</kbd> | Commits the time — once the wheel has been moved. Until then it is only a suggestion, and Enter submits as usual |
609
- | Done | Commits the time |
610
- | <kbd>Esc</kbd> | Puts a moved wheel back on its suggested time |
611
- | <kbd>→</kbd> at the end of the input | Skips the parameter, same as any other pill |
612
-
613
- **The committed value** is written the way a person would write it, always in
614
- English: `7:30 PM`, `12:05 AM`. It arrives as an ordinary completed parameter
615
- (bold in the input, in `completed_params` on submit) with the server's lead-in
616
- before it when there is one (`at 7:30 PM`). The exact time is also recorded on
617
- the parameter's `metadata` as 24-hour `HH:MM` under the `TIME_META_KEY` key
618
- (`aiaTime`), so you never have to parse the prose:
619
-
620
- ```ts
621
- import { parseTime, TIME_META_KEY } from "@magicx-eng/ai-autocomplete-vanilla";
622
-
623
- const time = param.metadata?.[TIME_META_KEY]; // "19:30"
624
- const minutes = parseTime(param.text); // 1170 — minutes since midnight, or null
625
- ```
626
-
627
- **Re-editing** a committed time re-opens the wheel on it.
628
-
629
- **Typing** while the wheel is open does not filter anything. As with the
630
- calendar, the text is treated as a new query.
249
+ When the next parameter is a time, the dropdown shows a time wheel instead of a list of options. Nothing is needed to switch it on. The time is committed as `7:30 PM`, and the 24-hour value is on the parameter's `metadata` under `TIME_META_KEY`. Keyboard use and re-editing are covered in [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "Time picker".
631
250
 
632
251
  ### Multiple selections
633
252
 
634
- - A suggestion with `type: { kind: "multi_select" }` shows checkbox options and a Done button.
635
- - Select rows to toggle values. Typing filters the options and keeps the current picks.
636
- - Done joins the picks in selection order with the UI language's word for "and".
637
- - Each value has its own `completed_params` entry. The input shows one chip for the group.
638
- - Remove the group chip to change the answer. Group chips do not open for editing.
639
- - Done without picks skips the question. Typing a phrase with no matching options closes the question and keeps that phrase.
640
- - Space toggles the highlighted row when nothing is typed for the question. Enter commits the picks, or selects the highlighted row when no values are picked.
641
- - Headless integrations can call `toggleMultiSelectOption(option)` and `commitMultiSelect()`.
642
- - `multiSelectView.picked` contains the selected option texts. The view is null outside a multi_select question.
253
+ A suggestion with `type: { kind: "multi_select" }` shows checkbox options and a Done button. Each picked value gets its own `completed_params` entry, and the input shows one chip for the group. Details: [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "Multiple selections".
643
254
 
644
- ---
255
+ ### Location search
256
+
257
+ A location parameter the server sends without options gets a search field that looks up any city or address through the MagicX server. If `apiConfig.endpoint` points at a proxy with its own path, set `apiConfig.locationEndpoint` too. `locationSearch: false` takes typed text only, and an `optionOverrides` entry for the parameter replaces the search. Details: [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "Location search".
645
258
 
646
259
  ## Tier 2: Dropdown Only
647
260
 
@@ -968,79 +581,7 @@ This is the way to embed the widget in a page whose CSS you don't control. In th
968
581
 
969
582
  Override these on the container element. The variables are declared with `:where()` (zero specificity), so a value you set on the container always wins without `!important`.
970
583
 
971
- The full input also accepts `--aia-input-radius` and `--aia-written-text-font-weight` on its container or an ancestor. Omit them to retain the default `10px` radius and `300` weight; changing `mode` does not reset these overrides. In dropdown-only integrations, style your own input directly.
972
-
973
- ```css
974
- .my-search {
975
- --aia-input-radius: 0;
976
- --aia-written-text-font-weight: 500;
977
- }
978
- ```
979
-
980
- | Variable | Default (light) | Default (dark) | Description |
981
- |---|---|---|---|
982
- | `--aia-font-family` | `inherit` | `inherit` | Font used by the library. Defaults to `inherit` so the library picks up your page's font automatically. Set this to pin a specific font on the library without changing the surrounding page. |
983
- | `--aia-pill-bg` | `#bdbdbd` | `#bdbdbd` | Pill background |
984
- | `--aia-pill-color` | `#000000` | `#ffffff` | Pill text |
985
- | `--aia-pill-font-size` | `19px` | `19px` | Pill font size |
986
- | `--aia-option-bg` | `transparent` | `transparent` | Option background (highlighted) |
987
- | `--aia-option-color` | `#000000` | `#ffffff` | Option text |
988
- | `--aia-option-color-selected` | `#000000` | `#ffffff` | Highlighted option text |
989
- | `--aia-option-font-size` | `19px` | `19px` | Option font size |
990
- | `--aia-written-text-color` | `#000000` | `#ffffff` | Input text |
991
- | `--aia-written-text-font-size` | `19px` | `19px` | Input text font size |
992
- | `--aia-written-text-font-weight` | `300` | `300` | Written text weight in the full input. Completed chips keep their own typography. |
993
- | `--aia-caret-color` | `--aia-written-text-color` | `--aia-written-text-color` | Editor caret color. Override independently of input text color. |
994
- | `--aia-submit-bg` | `#000000` | `#ffffff` | Submit button background. Solid + full-opacity at rest, even when the input is empty/disabled. |
995
- | `--aia-submit-color` | `#ffffff` | `#000000` | Submit button arrow color |
996
- | `--aia-submit-bg-disabled` | `--aia-submit-bg` | `--aia-submit-bg` | Submit background when disabled (empty input). Defaults to the enabled background so themed colors aren't washed out. Set this for a faded rest state. |
997
- | `--aia-submit-color-disabled` | `--aia-submit-color` | `--aia-submit-color` | Submit arrow color when disabled. Defaults to the enabled color. |
998
- | `--aia-border` | `rgba(17, 24, 39, 0.14)` | `#505050` | Input container border color |
999
- | `--aia-input-radius` | `10px` | `10px` | Full input corner radius. Set `0` for square corners. |
1000
- | `--aia-shadow` | `none` | `none` | Input container elevation (box-shadow). Flat by default; set it to add one |
1001
- | `--aia-dropdown-offset` | `13px` | `13px` | Gap between the input box and the dropdown (the dropdown's margin toward the input). |
1002
- | `--aia-content-inset-left` | `16px` | `16px` | Left inset of the SDK's content: the input wrapper's left padding, and the line the dropdown's content (parameter label, option text, product strip) starts on. Set it when you pad the field to clear a leading icon of your own, so the dropdown's content stays aligned under the typed text. Practical minimum is `10px` (the option text's own inset); both surfaces floor it there. |
1003
- | `--aia-footer-gap` | `12px` | `12px` | Breathing room above the dropdown footer (badge / keyboard hints), additive to the dropdown's 8px section gap. |
1004
- | `--aia-footer-chip-bg` | `--aia-surface` at 65% | `--aia-surface` at 65% | Fill behind the footer's keyboard hint and AI-Autocomplete badge. The option list scrolls under the footer, so this keeps both legible over the row passing behind them. `transparent` on the glass surface. |
1005
- | `--aia-dropdown-bg` | — | — | Optional bg color the dropdown's "glass" rim shadow tints toward. Set this to the page background behind the dropdown so the bottom-corner glow blends seamlessly. |
1006
- | `--aia-scrollbar-thumb` | `rgba(0, 0, 0, 0.3)` | `rgba(0, 0, 0, 0.3)` | No longer used: the option list hides its scrollbar in every browser. Kept so existing overrides don't break. |
1007
- | `--aia-streak-rgb` | `99, 102, 241` | `255, 255, 255` | Comma-separated RGB triplet tinting the datepicker's pressed cell, and its selected cell when `--aia-date-selected-bg` is unset. The today ring uses `--aia-date-today-ring`, not this. |
1008
- | `--aia-product-card-width` | `116px` | `116px` | Width of a product card in the strip. The media tile is square, so this also sets its height. |
1009
- | `--aia-product-gap` | `8px` | `8px` | Gap between product cards. |
1010
- | `--aia-product-bg` | `transparent` | `transparent` | Product card background. |
1011
- | `--aia-product-bg-active` | `--aia-option-bg` | `--aia-option-bg` | Product card background on hover. |
1012
- | `--aia-product-media-bg` | `--aia-skeleton-bg` | `--aia-skeleton-bg` | Placeholder fill of the product tile: shown until the photo loads, and behind both fallback tiles (placeholder pictogram or title initial) used when an image URL is missing, blank or fails to load. Once a photo loads the tile is transparent. |
1013
- | `--aia-scroll-arrow-color` | `--aia-option-color` | `--aia-option-color` | Chevron color of the arrow (`--aia-scroll-arrow-color-hover` on hover). |
1014
- | `--aia-placeholder-fade` | `120ms` | `120ms` | Fade-out of the outgoing placeholder phrase when the starting-state placeholder changes (the incoming one types itself in). |
1015
- | `--aia-product-image-radius` | `8px` | `8px` | Corner radius of a product photo narrower than its square tile (a tall one), which is scaled to fit rather than cropped. A photo that fills the tile takes the tile's own 8px corners. |
1016
- | `--aia-product-placeholder-image` | storefront pictogram | storefront pictogram | The pictogram used by `productImageFallback: "image"` (the default) when an image URL is missing, blank or fails to load. Defaults to a two-tone storefront inlined as a data URI. Set any `url(...)` to swap it; it is centered and contained over `--aia-product-media-bg`. Does not affect `"initial"` tiles. |
1017
- | `--aia-product-title-color` | `--aia-option-color-selected` | `--aia-option-color-selected` | Product title text. Follows the option colors by default, so theming the panel moves suggestions and products together. |
1018
- | `--aia-product-price-color` | `--aia-option-color-selected` | `--aia-option-color-selected` | Product price text. |
1019
- | `--aia-product-compare-at-color` | `currentColor` | `currentColor` | The struck price before a markdown. Defaults to the price's colour. |
1020
- | `--aia-product-compare-at-opacity` | `0.6` | `0.6` | How far the struck price is dimmed. |
1021
- | `--aia-product-vendor-color` | `--aia-option-color` | `--aia-option-color` | Product vendor line. |
1022
- | `--aia-product-focus-ring` | `--aia-option-color-selected` | `--aia-option-color-selected` | Focus ring drawn on a keyboard-focused card. |
1023
- | `--aia-products-label-color` | `--aia-option-color` | `--aia-option-color` | "Products" section label. |
1024
- | `--aia-product-title-font-size` | `12px` | `12px` | Product title font size. |
1025
- | `--aia-product-price-font-size` | `11px` | `11px` | Product price font size. |
1026
- | `--aia-product-vendor-font-size` | `10px` | `10px` | Product vendor font size. |
1027
- | `--aia-products-label-font-size` | `11px` | `11px` | Section label font size. |
1028
- | `--aia-date-panel-width` | `312px` | `312px` | Max width of the whole dropdown panel while the calendar is up — the panel narrows to calendar size. |
1029
- | `--aia-date-cell-size` | `26px` | `26px` | Size of a day's square — the box that carries the highlight, the today ring and the selected fill. |
1030
- | `--aia-date-row-height` | `28px` | `28px` | Height of one week row. Lower it to fit a 6-week month in a shorter dropdown. |
1031
- | `--aia-date-cell-font-size` | `13px` | `13px` | Day-number font size. |
1032
- | `--aia-date-month-font-size` | `14px` | `14px` | Font size of the "March 2026" header. |
1033
- | `--aia-date-weekday-font-size` | `11px` | `11px` | Font size of the S/M/T/W/T/F/S column letters. |
1034
- | `--aia-date-today-ring` | `--aia-option-color` | `--aia-option-color` | Outline drawn around today's date. |
1035
- | `--aia-date-selected-bg` | white at 12% | white at 12% | Fill behind the date a re-edited parameter already holds. |
1036
- | `--aia-date-range-bg` | white at 6% | white at 6% | Band across the days between the two ends of a picked date range. The ends themselves use `--aia-date-selected-bg`. |
1037
- | `--aia-time-panel-width` | `240px` | `240px` | Max width of the whole dropdown panel while the time wheel is up. |
1038
- | `--aia-time-font-size` | `15px` | `15px` | The time wheel's numbers and its `:` separator. |
1039
- | `--aia-time-band-bg` | white at 8% | white at 8% | The band behind the wheels' top rows — the chosen time. |
1040
- | `--aia-time-done-bg` | white at 10% | white at 10% | The time wheel's Done button. |
1041
- | `--aia-time-done-bg-hover` | white at 16% | white at 16% | The Done button on hover. |
1042
- | `--aia-time-done-color` | `--aia-option-color-selected` | `--aia-option-color-selected` | The Done button's text. |
1043
- | `--aia-skeleton-bg` | `rgba(189, 189, 189, 0.083)` | `#1a1b1d` | Fill color for the loading skeleton bars and the masked text in cached pills/options, and of the option and chip image tiles while their picture loads (unless `--aia-option-image-bg` / `--aia-chip-image-bg` are set). |
584
+ Every variable, with its default, is listed in [REFERENCE.md](https://unpkg.com/@magicx-eng/ai-autocomplete-vanilla/REFERENCE.md), under "CSS variables".
1044
585
 
1045
586
  ### Per-mode Overrides
1046
587
 
@@ -1090,6 +631,7 @@ For styling beyond the CSS variables, target these stable `data-aia-*` attribute
1090
631
  | `[data-aia-dropdown]` | The dropdown root (listbox). Carries `data-aia-has-products` while the product strip has cards, and `data-aia-fit` while it is fitted to a short screen (see [Short screens](#short-screens)). |
1091
632
  | `[data-aia-datepicker]` | The calendar, rendered in place of the option list for a date parameter |
1092
633
  | `[data-aia-time-wheel]` | The time wheel, rendered in place of the option list for a time parameter |
634
+ | `[data-aia-location]` | The location search, rendered in place of the option list for a location parameter without options (`[data-aia-location-input]` is its field, `[data-aia-location-row]` each place) |
1093
635
  | `[data-aia-date-month]` | The "March 2026" header label |
1094
636
  | `[data-aia-date-prev]` / `[data-aia-date-next]` | The month arrows |
1095
637
  | `[data-aia-date-grid]` | The 7-column grid of day cells |
@@ -1192,4 +734,4 @@ Tier 3 exposes the pieces: `state.optionQuery` is the phrase, and `state.isSearc
1192
734
 
1193
735
  ## License
1194
736
 
1195
- Private package. All rights reserved.
737
+ MIT.