@aintela/chat 0.4.18 → 0.4.20
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/dist/components.js +4698 -4645
- package/dist/components.js.map +1 -1
- package/dist/hooks.js +1 -1
- package/dist/index.js +81 -80
- package/dist/{predictionRows-CkZdmdsi.js → predictionRows-BDZtjaRZ.js} +5 -4
- package/dist/{predictionRows-CkZdmdsi.js.map → predictionRows-BDZtjaRZ.js.map} +1 -1
- package/dist/src/components/v2/MentionPickerPanel.d.ts +3 -1
- package/dist/src/components/v2/PromptGhostHint.d.ts +1 -1
- package/dist/src/components/v2/TriggerDropdown.d.ts +5 -1
- package/dist/src/components/v2/styles.d.ts +25 -0
- package/dist/src/hooks/usePromptAssist.d.ts +5 -2
- package/dist/src/utils/promptTriggers.d.ts +4 -0
- package/dist/useContainerWidth-DKSIf5HQ.js +343 -0
- package/dist/useContainerWidth-DKSIf5HQ.js.map +1 -0
- package/dist/utils.js +1 -1
- package/package.json +1 -1
- package/dist/useContainerWidth-BDGelJd0.js +0 -335
- package/dist/useContainerWidth-BDGelJd0.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useContainerWidth-BDGelJd0.js","sources":["../src/hooks/usePromptAssist.ts","../src/hooks/useIntervalHook.ts","../src/hooks/useContainerWidth.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState, type KeyboardEvent } from 'react';\nimport type { PromptAnalysis, PromptResolution, SuggestItem } from '../services/httpPromptAssistService';\n\n/** Lower-case + strip diacritics, so a half-typed \"ama\" is recognised as the start of \"amanhã\". */\nconst foldForCompare = (s: string) => s.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '').toLowerCase();\n\n/** A dropdown item. `namedLocation` inserts `@Name` directly; `location`/`calendar` insert `@`/`#` and open the picker. */\nexport type PredictionItem = {\n key: string;\n label: string;\n kind: 'location' | 'namedLocation' | 'date' | 'calendar';\n insert?: string;\n /** Secondary line (e.g. \"GRU · SP · Brasil\") — parity with the `@` picker's hint. Optional. */\n hint?: string;\n /** Section caption shown above this item when it differs from the previous item's — the `'both'` vertical\n * (\"Hotéis e locais\" / \"Aeroportos\") and, at a MIXED slot, the category (\"Data\" / \"Localização\"). Optional. */\n section?: string;\n /** Which glyph the shared dropdown draws for this row. The list mixes dates and places now, so the row kind\n * alone is not enough: a named location is an AIRPORT when it carries an IATA code and a place otherwise. */\n icon?: 'airport' | 'place' | 'hotel' | 'person' | 'date' | 'calendar';\n /** Non-pickable (already in the prompt, same place/city) — rendered greyed and skipped by nav/apply. */\n disabled?: boolean;\n};\n\n/**\n * Which phantom cue is painted at the caret. `'date'` joined the other two on 2026-09-10 — a predicted date used to\n * drop a dropdown on the user unasked; it teaches the `#` trigger now, exactly as a location teaches `@`.\n */\nexport type GhostKind = 'location' | 'person' | 'date';\n\n/** A Data row for the `@` picker (see `slotDateOptions`). Shaped as a trigger row so a host can splice it in. */\nexport type SlotDateOption = {\n id: string;\n label: string;\n /** What replaces the `@…` token. A date phrase, or \"#\" — which re-opens the calendar instead. */\n value: string;\n kind: 'date' | 'calendar';\n section: string;\n};\n\nexport type ResolvedDateItem = { text: string; display: string };\n\n/**\n * Send-time summary of what the assist UI did during ONE composition (issue #159 Phase 1) — attached to the\n * commit so the server can store {prompt, outcome} as a behavioral label and emit gate-precision metrics:\n * gate fired + assist used ≈ true positive; fired + ignored ≈ false-positive candidate; gate quiet + the user\n * typed `@` themselves ≈ false-negative candidate. Numbers/booleans only, no extra text.\n */\nexport type AssistOutcome = {\n /** Highest location-intent confidence any analyze reported while composing. */\n maxLocationConfidence: number;\n /** Highest person-intent confidence any analyze reported while composing. */\n maxPersonConfidence: number;\n /** Highest hotel-vertical confidence any analyze reported while composing (issue #876). Optional so an\n * outcome built by an older client shape still satisfies the type. */\n maxHotelConfidence?: number;\n /** Location assist became VISIBLE at least once (dropdown, location ghost, or auto-`@`). */\n locationGateFired: boolean;\n /** The user accepted an item from the predictions dropdown. */\n suggestionAccepted: boolean;\n ghostShown: boolean;\n ghostAccepted: boolean;\n /** The `@` picker was opened at least once (host reports via noteAtOpened). */\n atOpened: boolean;\n /** Section of the last accepted `@` mention (host reports via noteAtAccepted); 'hotel' = a hotel NAME row (Issue 1139). */\n atAccepted: 'person' | 'location' | 'hotel' | null;\n /** The user typed `@` themselves while nothing assist-y was showing — a recall miss signal. */\n manualAt: boolean;\n};\n\n/** The slot's place sources: the server's `vertical` when it sends one, else the pre-2026-09-10 reading of hotelExpected. */\nconst verticalOf = (a: PromptAnalysis): SearchVertical => a.vertical ?? (lodgingOf(a) ? 'hotel' : 'air');\n/** The lodging-places verdict under either name (Issue 1139 renamed `hotel*` → `places*`; both are sent for a release). */\nconst lodgingOf = (a: PromptAnalysis): boolean => a.placesExpected ?? a.hotelExpected ?? false;\nconst lodgingScoreOf = (a: PromptAnalysis): number => a.placesConfidence ?? a.hotelConfidence ?? 0;\nconst sectionLabel = (source: SuggestItem['source']): string | undefined =>\n source === 'hotel' ? 'Hotéis e locais' : source === 'air' ? 'Aeroportos' : undefined;\n\n/** The two CATEGORY captions of a mixed slot — one caret where a date and a place are both true (2026-09-10). */\nconst DATE_SECTION = 'Data';\nconst PLACE_SECTION = 'Localização';\n\nconst emptyOutcome = (): AssistOutcome => ({\n maxLocationConfidence: 0, maxPersonConfidence: 0, maxHotelConfidence: 0,\n locationGateFired: false, suggestionAccepted: false,\n ghostShown: false, ghostAccepted: false,\n atOpened: false, atAccepted: null, manualAt: false,\n});\n\n/** The DOM operations the hook needs from its host composer — so the same logic drives PromptV2 and PromptComposer. */\nexport interface PromptAssistAdapter {\n getTextarea: () => HTMLTextAreaElement | null;\n /** Replace the draft value (host owns the React state). */\n setDraft: (next: string) => void;\n /** After a programmatic edit, focus the textarea and place the caret (host defers a frame if needed). */\n focusCaret: (pos: number) => void;\n /** Re-detect the `@`/`#` trigger at the caret and open the matching picker (host's existing flow). */\n syncTrigger: (ta: HTMLTextAreaElement) => void;\n /** Is a location/date picker already open? (suppresses the predictions dropdown / auto-`@`) */\n isPickerOpen: () => boolean;\n /** The trigger char of any open picker, or null — used to avoid re-inserting `@`. */\n currentTriggerChar: () => string | null;\n /** Whether the `@` location fetcher is wired (else no auto-`@` / generic \"Local…\"). */\n hasAtQuery: boolean;\n}\n\n/** Which vertical a location slot is searching (issue #876). Steers the source: airports vs hotel places. */\n/** Place sources for a location suggest: airports, lodging places, or both — sectioned (2026-09-10). */\nexport type SearchVertical = 'air' | 'hotel' | 'both';\n\nexport interface PromptAssistFetchers {\n analyze?: (text: string, caret: number) => Promise<PromptAnalysis>;\n resolveDates?: (text: string, sessionId?: string, signal?: AbortSignal) => Promise<PromptResolution>;\n commitIntent?: (text: string, sessionId?: string, assist?: AssistOutcome) => void;\n /** `vertical` (issue #876) says whether the location being searched is LODGING ('hotel') or a flight place\n * ('air', the default) — sourced from the server's hotel-intent head, never re-decided client-side. Hosts that\n * ignore the extra parameter keep today's airports-only behavior. */\n suggest?: (q: string, kind: 'location' | 'date' | 'both', signal?: AbortSignal, exclude?: string[],\n vertical?: SearchVertical) => Promise<SuggestItem[]>;\n}\n\nexport interface PromptAssistOptions {\n enableHashDatePicker?: boolean;\n datePresets?: string[];\n /** When true, a location OR person prediction shows a PHANTOM ghost at the caret (\"@ Localidade\" / \"@ Nome\n * pessoa\") teaching the `@` trigger, INSTEAD of auto-opening the location predictions dropdown. Date still uses\n * its dropdown. The host reads `hint` to render the ghost and wires Tab/→ to `acceptHint`. Default false. */\n promptHint?: boolean;\n /** DEVELOPMENT ONLY. A single character that, when typed in the composer, is swallowed and paints the phantom\n * ghost at the caret instead — 'location' first, 'person' on the next press — so the ghost's look can be\n * checked without a prompt-assist server predicting anything. Mid-sentence is detected from the caret, exactly\n * as a real prediction would set it. The demo pages pass `|`; production hosts leave it unset. */\n debugGhostKey?: string;\n}\n\nconst newSessionId = () =>\n typeof crypto !== 'undefined' && crypto.randomUUID ? crypto.randomUUID() : `s-${Date.now()}-${Math.random()}`;\n\n/** Next selectable (non-disabled) index from `from` moving `dir` (±1), wrapping. Stays put if all are disabled. */\nconst nextEnabledIndex = (items: PredictionItem[], from: number, dir: 1 | -1): number => {\n const n = items.length;\n let idx = from;\n for (let step = 0; step < n; step++) {\n idx = (idx + dir + n) % n;\n if (!items[idx]?.disabled) return idx;\n }\n return from;\n};\n\n/**\n * Headless prompt-assist logic shared by the chat composer (PromptV2) and the home composer (obtapp PromptComposer):\n * the analyze quick pass (auto-`@` + combined predictions dropdown), the resolve slow pass (date resolution +\n * mapped-location chips), commit-on-send learning, and keyboard nav — all with NO rendering/anchoring assumptions.\n * The host provides its DOM ops via {@link PromptAssistAdapter} and renders the returned `predictions` however it wants.\n */\nexport function usePromptAssist(\n adapter: PromptAssistAdapter,\n fetchers: PromptAssistFetchers,\n options: PromptAssistOptions = {},\n) {\n const { debugGhostKey } = options;\n const [predictions, setPredictions] = useState<PredictionItem[] | null>(null);\n // #1 phantom teaching cue: which \"@ …\" ghost to paint at the caret (promptHint option) instead of the dropdown —\n // 'location' → \"@ Localidade\", 'person' → \"@ Nome pessoa\", null → none. The dominant intent wins. Cleared each\n // analyze unless re-armed below.\n const [hint, setHint] = useState<GhostKind | null>(null);\n // The ghost is up at a MID-SENTENCE slot (the user is editing an existing prompt and typed a space where a place\n // should go — \"Busque hotéis em | chego amanhã\"). Hosts paint the compact \"@ …\" form there, because the full\n // \"@ Localidade\" phantom is an overlay at the caret and would cover the words that follow; and → is not an\n // accept key there (it is a cursor move). Only meaningful while `hint` is non-null.\n const [hintMidSentence, setHintMidSentence] = useState(false);\n // Latest analyze's location-intent confidence — hosts pass it to fetchAtMentions so the `@` picker leads with\n // Locais when location outweighs person (an `@` in a location context searches places, not people).\n const [locationConfidence, setLocationConfidence] = useState(0);\n // Issue #112 — the latest analyze's person-intent signal (P the user is referring to a PERSON/passenger). Hosts\n // use this to order/section the `@` picker's sources (people vs places). Updated on every analyze; 0 when the\n // feature is off server-side or the text is empty.\n const [personConfidence, setPersonConfidence] = useState(0);\n // Issue #876 — the latest analyze's search VERTICAL: is the place being sought lodging? `hotelExpected` is the\n // server's thresholded verdict (the client does not re-decide); hosts use it to point the `@` picker's location\n // source at hotel places instead of airports. False/0 when the server predates the hotel head or text is empty.\n const [hotelExpected, setHotelExpected] = useState(false);\n // The SLOT's place sources (2026-09-10) — hosts pass it to their `@` picker source the way they passed\n // hotelExpected. 'air' | 'hotel' | 'both'; derived from hotelExpected when the server predates the field.\n const [vertical, setVertical] = useState<SearchVertical>('air');\n const [hotelConfidence, setHotelConfidence] = useState(0);\n // Issue 1139 — the latest analyze's HOTEL-NAME head: is the traveller naming a specific hotel? Hosts hand the score\n // to their `@` location source, which then leads with catalog hotel names. False/0 when the server predates it.\n const [hotelNameExpected, setHotelNameExpected] = useState(false);\n const [hotelNameConfidence, setHotelNameConfidence] = useState(0);\n // True when the current predictions are the \"recents\" set (analyze pre-fill or an empty-query suggest) rather\n // than results for a typed query — lets the host label it \"recentes\" + hint that typing surfaces more.\n const [predictionsRecents, setPredictionsRecents] = useState(false);\n // What the open list is filtering on, as the user typed it — the dropdown's header echoes it back. Empty when\n // the list is the untyped recents, or when no list is open.\n const [predictionQuery, setPredictionQuery] = useState('');\n // The Data rows an `@` PICKER should carry at this caret (2026-09-11). At a mixed caret the predictions list\n // shows Data over Localização — and then the user types `@`, the picker takes over, and the date half used to\n // vanish with it. These are ordinary trigger rows: the host prepends them and its existing insert handles them\n // (a row whose value is \"#\" re-opens the calendar, which is what `applyTriggerInsertion` already does for a\n // value ending in a trigger char). Empty at a caret with no date reading.\n const [slotDateOptions, setSlotDateOptions] = useState<SlotDateOption[]>([]);\n const [predictionHighlight, setPredictionHighlight] = useState(0);\n const [resolvedLocations, setResolvedLocations] = useState<string[]>([]);\n const [resolvedDates, setResolvedDates] = useState<ResolvedDateItem[]>([]);\n // The date text whose marker tooltip should auto-open (set on a NEW resolution, cleared after 2s) — identical\n // to PromptV2's behavior so both composers surface a freshly-resolved date the same way.\n const [forceTooltipText, setForceTooltipText] = useState('');\n const lastResolvedKeyRef = useRef('');\n const tooltipTimerRef = useRef<number | null>(null);\n\n // Latest adapter/fetchers/options via refs — the debounced callbacks must not capture stale closures.\n const adapterRef = useRef(adapter); adapterRef.current = adapter;\n const fetchersRef = useRef(fetchers); fetchersRef.current = fetchers;\n const optionsRef = useRef(options); optionsRef.current = options;\n\n const analyzeTimerRef = useRef<number | null>(null);\n const resolveTimerRef = useRef<number | null>(null);\n const analyzeSeqRef = useRef(0);\n const suggestSeqRef = useRef(0);\n const suggestAbortRef = useRef<AbortController | null>(null);\n const draftRef = useRef('');\n const lastResolveTextRef = useRef<string | null>(null);\n const resolveAbortRef = useRef<AbortController | null>(null);\n const sessionIdRef = useRef<string>(newSessionId());\n // Current predictions (mirror of state) so the debounced analyze can tell if the dropdown is already open —\n // lets us pre-fill only on FIRST open instead of re-flashing the tenant list on every keystroke.\n const predictionsRef = useRef<PredictionItem[] | null>(null);\n predictionsRef.current = predictions;\n // Mirror of hint so the debounced analyze can (a) keep running on deletion while a ghost is up and (b) let\n // onKeyDown accept it without stale closures.\n const hintRef = useRef<GhostKind | null>(null);\n hintRef.current = hint;\n // #1 anti-nag (rewritten for #422). Counts KEYSTROKES typed while a ghost was on screen — not analyses, which\n // is what made the old version sticky: the streak was re-derived per analyze and reset the moment a cue-less\n // one arrived or the kind flipped, so a prompt whose every keystroke still predicted a location kept re-arming\n // the phantom forever. Now the count only ever goes up, and crossing MAX_HINT_STREAK LATCHES the ghost off for\n // the REST OF THE COMPOSITION (hintSuppressedRef): the user has seen the cue and typed past it, so that is\n // their answer for this prompt. Cleared only by accepting the ghost (the lesson landed) or by resetSession\n // (draft emptied / sent — a new prompt gets to be taught again).\n const hintStreakRef = useRef(0);\n const hintKindRef = useRef<GhostKind | null>(null);\n const hintSuppressedRef = useRef(false);\n const MAX_HINT_STREAK = 8;\n const PERSON_HINT_THRESHOLD = 0.5;\n // The kind the open dropdown is currently showing (null when closed) — lets a trailing space keep an open\n // location dropdown alive (as recents) instead of collapsing it.\n const lastKindRef = useRef<'location' | 'date' | null>(null);\n // The server-parsed location partial the open dropdown filtered on (\"belo\", \"São Paulo\", or \"\" for recents).\n // applyPrediction strips exactly this — including across a trailing space — so a pick REPLACES the partial\n // instead of appending after it, and never eats a completed \"@\" mention (empty partial → append).\n const locationPartialRef = useRef('');\n // Stable pointer to runResolve so applyPrediction (defined earlier) can force a resolve after a date pick.\n const runResolveRef = useRef<() => void>(() => {});\n\n // Issue #159 Phase 1 — the per-composition outcome accumulator (sent with the commit, reset per session).\n const outcomeRef = useRef<AssistOutcome>(emptyOutcome());\n // Set when WE insert the \"@\" (ghost accept / dropdown generic pick / auto-\"@\"), consumed by the host's next\n // noteAtOpened — distinguishes a programmatic picker-open from the user typing \"@\" themselves (manualAt).\n const programmaticAtRef = useRef(false);\n\n const clearPredictions = useCallback(() => { setPredictions(null); setPredictionQuery(''); }, []);\n\n /** Call when the draft empties (send / reseed): clear mapped data and start a fresh learning session. */\n const resetSession = useCallback(() => {\n setResolvedLocations([]);\n setResolvedDates([]);\n setForceTooltipText('');\n lastResolvedKeyRef.current = '';\n lastResolveTextRef.current = null;\n sessionIdRef.current = newSessionId();\n outcomeRef.current = emptyOutcome();\n programmaticAtRef.current = false;\n // New composition → the ghost gets to teach again (see hintSuppressedRef).\n hintStreakRef.current = 0;\n hintKindRef.current = null;\n hintSuppressedRef.current = false;\n setHint(null);\n }, []);\n\n const applyPrediction = useCallback((p: PredictionItem) => {\n if (p.disabled) return; // already in the prompt (same city) — not selectable; keep the dropdown open\n outcomeRef.current.suggestionAccepted = true;\n if (p.kind === 'location') programmaticAtRef.current = true; // generic pick inserts \"@\" → picker opens programmatically\n setPredictions(null);\n const ad = adapterRef.current;\n const ta = ad.getTextarea();\n if (!ta) return;\n const caret = ta.selectionStart ?? ta.value.length;\n const rawBefore = ta.value.slice(0, caret);\n const after = ta.value.slice(caret);\n // A pick must REPLACE what the dropdown filtered on, not append after it (\"sao @São Paulo\" bug).\n // LOCATIONS: strip exactly the server-parsed partial (locationPartialRef) — this spans a trailing space\n // (\"de belo \" → \"belo\") and is \"\" for a recents/mention pick, so we append instead of eating a finished\n // \"@\" mention.\n const isLocationPick = p.kind === 'namedLocation' || p.kind === 'location';\n let before: string;\n if (isLocationPick) {\n const partial = locationPartialRef.current;\n const trimmedEnd = rawBefore.replace(/\\s+$/, '');\n before = partial && trimmedEnd.endsWith(partial) ? trimmedEnd.slice(0, trimmedEnd.length - partial.length) : rawBefore;\n } else {\n // DATES: replace only an INCOMPLETE fragment — never a finished word. The date dropdown filters on the\n // trailing word, so it used to strip whatever was there, and picking the calendar after \"…Faria Lima no\n // dia\" ate \"dia\" and left \"no #\". \"dia\" is the CUE the date belongs after, not a half-typed date; only a\n // trailing space made it behave. Two tests, no vocabulary list:\n // · a date PRESET replaces the trailing word when that word is a prefix of what is being inserted\n // (\"ama\" → \"amanhã\", \"10/\" → \"10/09/2026\") — compared accent- and case-insensitively;\n // · the CALENDAR inserts \"#\" and has no value to compare, so it replaces only a half-typed NUMBER\n // (\"no dia 1\" → \"no dia #\"), which is the one thing the picker is about to supply.\n // Everything else appends. Leaving a word in is visible and the user can delete it; eating one is silent.\n const wordStart = rawBefore.search(/\\S+$/);\n const trailing = wordStart === -1 ? '' : rawBefore.slice(wordStart);\n const replaces = trailing.length > 0 && (\n p.kind === 'date' && p.insert\n ? foldForCompare(p.insert).startsWith(foldForCompare(trailing))\n : /^[\\d./-]+$/.test(trailing));\n before = replaces ? rawBefore.slice(0, wordStart) : rawBefore;\n }\n const needsSpace = before.length > 0 && !/\\s$/.test(before);\n\n if (p.kind === 'date') {\n const ins = `${needsSpace ? ' ' : ''}${p.insert} `;\n const next = `${before}${ins}${after}`;\n ad.setDraft(next);\n ad.focusCaret(before.length + ins.length);\n // A programmatic setDraft doesn't fire onChange, so force a resolve now → the picked date resolves\n // into its chip/marker immediately instead of waiting for the next keystroke.\n draftRef.current = next;\n lastResolveTextRef.current = null;\n runResolveRef.current();\n return;\n }\n if (p.kind === 'namedLocation' && p.insert) {\n // A specific place → finished \"@\" mention (NBSP-joined so a multi-word name stays one chip / one mention).\n const mention = `@${p.insert.replace(/ /g, String.fromCharCode(0xA0))}`;\n const ins = `${needsSpace ? ' ' : ''}${mention} `;\n ad.setDraft(`${before}${ins}${after}`);\n ad.focusCaret(before.length + ins.length);\n return;\n }\n // Generic location / calendar → insert the trigger char and open the host's picker.\n const chr = p.kind === 'location' ? '@' : '#';\n const ins = `${needsSpace ? ' ' : ''}${chr}`;\n ad.setDraft(`${before}${ins}${after}`);\n ad.focusCaret(before.length + ins.length);\n requestAnimationFrame(() => { const t = ad.getTextarea(); if (t) ad.syncTrigger(t); });\n }, []);\n\n const runResolve = useCallback(async () => {\n const resolve = fetchersRef.current.resolveDates;\n if (!resolve) return;\n const text = draftRef.current;\n if (text.trim() === '') { lastResolveTextRef.current = null; return; }\n if (text === lastResolveTextRef.current) return; // unchanged since last call\n\n const parts = text.split(' ');\n if(parts.length <= 2) return;\n\n lastResolveTextRef.current = text;\n resolveAbortRef.current?.abort();\n const ac = new AbortController();\n resolveAbortRef.current = ac;\n try {\n const { dates, locations } = await resolve(text, sessionIdRef.current, ac.signal);\n if (draftRef.current !== text) return; // moved on while in flight\n const resolved = dates.filter((d) => d.display).map((d) => ({ text: d.text, display: d.display }));\n setResolvedDates(resolved);\n setResolvedLocations(locations.map((l) => l.text).filter((t) => t.trim().length > 0));\n // Auto-open the newest date's tooltip for 2s (only when the resolution set actually changed).\n const key = resolved.map((r) => `${r.text}=${r.display}`).join('|');\n if (resolved.length > 0 && key !== lastResolvedKeyRef.current) {\n lastResolvedKeyRef.current = key;\n setForceTooltipText(resolved[resolved.length - 1].text);\n if (tooltipTimerRef.current != null) window.clearTimeout(tooltipTimerRef.current);\n tooltipTimerRef.current = window.setTimeout(() => setForceTooltipText(''), 2000);\n }\n if (resolved.length === 0) lastResolvedKeyRef.current = '';\n } catch { /* ignore — includes AbortError from a superseded call */ }\n }, []);\n runResolveRef.current = runResolve;\n\n /** Call from the textarea's onChange. Runs the debounced analyze (200ms) + resolve (300ms) passes. */\n const scheduleAssist = useCallback((value: string, caret: number, isDeletion: boolean) => {\n draftRef.current = value;\n\n // #422 — the ghost's life is measured in KEYSTROKES, counted here rather than in the debounced analyze:\n // that is what the user experiences (\"I typed four more characters and it's still there\"), and it is\n // independent of how many analyses the debounce happened to coalesce. Hitting the cap drops the phantom\n // immediately and pins it off for the rest of this prompt.\n if (hintRef.current !== null) {\n hintStreakRef.current += 1;\n if (hintStreakRef.current >= MAX_HINT_STREAK) {\n hintSuppressedRef.current = true;\n setHint(null);\n }\n }\n\n const parts = value.split(' ');\n if(parts.length <= 2) return;\n\n\n const analyze = fetchersRef.current.analyze;\n // Run analyze on typing, AND on deletion WHILE the dropdown is open — so backspacing re-filters the list\n // (shorter query) and closes it once the context ends. When nothing's open, deletion still skips analyze\n // (no auto-'@' / churn while correcting text elsewhere).\n if (analyze && (!isDeletion || predictionsRef.current !== null || hintRef.current !== null)) {\n if (analyzeTimerRef.current != null) window.clearTimeout(analyzeTimerRef.current);\n analyzeTimerRef.current = window.setTimeout(async () => {\n const seq = ++analyzeSeqRef.current;\n try {\n const a = await analyze(value, caret);\n if (seq !== analyzeSeqRef.current) return;\n const ad = adapterRef.current;\n const live = ad.getTextarea();\n if (!live || live.value !== value) return;\n\n // Person-intent (issue #112) — surfaced regardless of the loc/date dropdown decision below, so the\n // host's `@` picker can consult it whether or not a predictions dropdown is currently open.\n setPersonConfidence(a.personConfidence ?? 0);\n setLocationConfidence(a.locationConfidence ?? 0);\n setHotelExpected(lodgingOf(a));\n setVertical(verticalOf(a));\n setHotelConfidence(lodgingScoreOf(a));\n setHotelNameExpected(a.hotelNameExpected ?? false);\n setHotelNameConfidence(a.hotelNameConfidence ?? 0);\n // #159 Phase 1 — outcome accumulator: the composition's peak confidences.\n const outcome = outcomeRef.current;\n outcome.maxPersonConfidence = Math.max(outcome.maxPersonConfidence, a.personConfidence ?? 0);\n outcome.maxLocationConfidence = Math.max(outcome.maxLocationConfidence, a.locationConfidence ?? 0);\n outcome.maxHotelConfidence = Math.max(outcome.maxHotelConfidence ?? 0, lodgingScoreOf(a));\n // Default the ghost off; the block below re-arms it in promptHint mode. Makes every early-return\n // path (safeguards, gating) clear a stale ghost.\n setHint(null);\n\n const caretPos = live.selectionStart ?? caret;\n const caretEnd = caretPos === value.length;\n // Mid-sentence slot (2026-09-02): the server already analyzes text[..caret] — only this gate kept\n // its verdict from surfacing when the caret was not at the end. A mid-text caret counts as a slot\n // when it sits at a word START (whitespace right before it — the user just typed a space) and\n // the text after it is not already an \"@\" mention. Everything downstream splices at the caret\n // (applyPrediction, acceptHint, the auto-\"@\"), so a pick there yields \"em @São Paulo chego\".\n const beforeCaret = value.slice(0, caretPos);\n const afterCaret = value.slice(caretPos);\n const midSlot = !caretEnd && /\\s$/.test(beforeCaret) && !/^\\s*@/.test(afterCaret);\n const atSlot = caretEnd || midSlot;\n const canLoc = ad.hasAtQuery;\n const pickerOpen = ad.isPickerOpen();\n const named = a.suggestions ?? [];\n const { enableHashDatePicker = false, datePresets = ['amanhã de manhã', 'quarta-feira à noite'] } = optionsRef.current;\n\n // Single-winner dropdown kind: prefer a.category, else fall back to the (at-most-one) expected flags.\n let decided: 'location' | 'date' | null =\n a.category === 'location' ? 'location'\n : a.category === 'date' ? 'date'\n : a.locationExpected ? 'location'\n : a.dateExpected ? 'date'\n : null;\n // Grace: a bare trailing space shouldn't collapse — OR flip to dates — an already-open location\n // dropdown. After the space the server may report \"done\" (null) OR predict a date (a learned\n // \"de [loc] \" → date template), but the user just hit space and is likely still on the location —\n // keep it open as the LOCATION recents list (empty query → suggest returns recents). Overrides\n // null AND date. Only when it was a location dropdown, suggest is wired, the caret's at the end,\n // and the text ends in a space. Typing an actual date WORD (no trailing space) still switches.\n // Not when 2 locations are already present — then the natural next slot is a DATE, so let it through.\n if (decided !== 'location' && a.locationCount < 2 && Boolean(fetchersRef.current.suggest)\n && predictionsRef.current !== null && lastKindRef.current === 'location' && atSlot && /\\s$/.test(beforeCaret)) {\n decided = 'location';\n }\n // The MIXED slot (2026-09-10): the server's runner-up says the caret reads as a place AND a date\n // (\"… para @Porto Alegre para |\" — Portuguese allows both). Rather than a ghost or a date list that\n // guesses one side, show ONE dropdown: the `#` calendar line on top of the locations. Needs the\n // calendar entry enabled and the `@` fetcher wired (the locations come from it). With two places\n // already in the prompt a third is the unlikely reading, so the plain date dropdown stands instead.\n const secondary = a.secondary ?? '';\n let mixed = enableHashDatePicker && canLoc\n && ((decided === 'location' && secondary === 'date') || (decided === 'date' && secondary === 'location'));\n if (mixed && a.locationCount >= 2 && a.locationPartialEmpty) { mixed = false; decided = 'date'; }\n // Hand the `@` picker the Data half of a mixed caret, so the category survives the trigger\n // (2026-09-11). Only while the picker is CLOSED: once it opens, the text carries a trailing \"@\"\n // and the next analyze reads a different caret — the reading that opened it is the one that\n // still applies, so it is held, and the host clears the picker itself when the trigger ends.\n if (!pickerOpen) {\n const quick = (a.suggestions ?? []).filter((x) => x.kind === 'date').map((x) => x.value);\n setSlotDateOptions(!mixed ? [] : [\n ...(enableHashDatePicker\n ? [{ id: 'cal', label: '# Escolher no calendário', value: '#', kind: 'calendar' as const, section: DATE_SECTION }]\n : []),\n ...(quick.length > 0 ? quick : datePresets).map((d) => (\n { id: `date:${d}`, label: d, value: d, kind: 'date' as const, section: DATE_SECTION })),\n ]);\n }\n // #1 phantom cue: pick the DOMINANT intent and paint an \"@ …\" ghost teaching the trigger, instead\n // of a dropdown. Person can win even when the loc/date ladder is null (\"adiciona o joão\"), so we\n // decide here — BEFORE the dropdown gating. Requires promptHint mode, the caret at a slot (end of\n // text, or a mid-sentence word start), no picker open.\n if (optionsRef.current.promptHint && atSlot && !pickerOpen) {\n const per = a.personConfidence ?? 0;\n const loc = a.locationConfidence ?? 0;\n // Location ghost only when the ladder actually expects a location and it isn't the suppressed\n // 3rd-location case. Person wins ties-and-above only when it clears its threshold.\n const locationGhost = decided === 'location' && !mixed && !(a.locationCount >= 2 && a.locationPartialEmpty);\n // A lone DATE teaches \"#\" the same way (2026-09-10). Only when the host actually HAS a `#`\n // picker to open — without `enableHashDatePicker` the ghost would promise a key that does\n // nothing, so those hosts keep the date dropdown below. The mixed slot is never a ghost:\n // one trigger char cannot say \"a date OR a place starts here\", and its dropdown can.\n const dateGhost = decided === 'date' && !mixed && enableHashDatePicker;\n const kind: GhostKind | null =\n (per >= PERSON_HINT_THRESHOLD && per >= loc && !dateGhost) ? 'person'\n : dateGhost ? 'date'\n : locationGhost ? 'location'\n : null;\n if (kind) {\n // Latched off for this composition (the user typed past it — see hintSuppressedRef):\n // show NOTHING. Falling through to the dropdown instead would be a louder nag than the\n // phantom they just ignored.\n if (!hintSuppressedRef.current) {\n hintKindRef.current = kind;\n setHintMidSentence(midSlot);\n setHint(kind);\n outcome.ghostShown = true;\n if (kind === 'location') outcome.locationGateFired = true;\n }\n setPredictions(null);\n lastKindRef.current = null;\n return;\n }\n // Nothing to teach this cycle. The streak is NOT reset here — it is per composition, so a\n // cue that comes and goes and comes back can't restart the count and nag again.\n hintKindRef.current = null;\n }\n\n // 2-location safeguard: with origin + destination already present, a merely PREDICTED (not-being-\n // typed) 3rd location — typically just the model guessing — shouldn't open a dropdown. Actively\n // typing a 3rd location (partial non-empty) still shows.\n if (decided === 'location' && a.locationCount >= 2 && a.locationPartialEmpty) {\n setPredictions(null); lastKindRef.current = null; return;\n }\n\n // A location dropdown needs the `@` fetcher wired to be useful.\n const kindActive = decided === 'location' ? canLoc : decided === 'date';\n\n // Gating: caret at a slot (end of text, or a mid-sentence word start), no picker open.\n if (decided === null || !(atSlot && !pickerOpen && kindActive)) { setPredictions(null); lastKindRef.current = null; return; }\n // In promptHint mode a LOCATION is already handled by the ghost block above (returns), so reaching\n // here means the dropdown mode (promptHint off), a DATE, or the MIXED slot — all use the dropdown\n // below. A mixed list is a LOCATION list (the `@` fetcher fills it) with the calendar line on top.\n const kind: 'location' | 'date' = mixed ? 'location' : decided;\n lastKindRef.current = kind;\n // Location assist is about to surface (dropdown or the auto-\"@\" fallback below) — with the\n // blank-query pre-search in place the dropdown virtually always has content past this gate.\n if (kind === 'location') outcome.locationGateFired = true;\n\n const namedLocs = named.filter((s) => s.kind === 'location');\n const namedDates = named.filter((s) => s.kind === 'date').map((s) => s.value);\n\n // The DATE block: the \"#\" picker entry first (Ciro, 2026-09-02 — it is the one item that always\n // applies; everything under it is a guess), then the quick dates. At a mixed slot it is a whole\n // CATEGORY rather than a single line (Ciro, 2026-09-10: \"date should be first otherwise it will\n // disappear in the list, and show not only the # picker but also additional suggestions\") — one\n // calendar row buried above a dozen airports was, in practice, invisible.\n const dateRows = ({ quickDates }: { quickDates: boolean }): PredictionItem[] => {\n if (kind !== 'date' && !mixed) return [];\n const section = mixed ? DATE_SECTION : undefined;\n const rows: PredictionItem[] = [];\n if (enableHashDatePicker)\n rows.push({ key: 'cal', label: '# Escolher no calendário', kind: 'calendar', icon: 'calendar', section });\n // Off where the suggest fetcher is about to supply its OWN dates for the same section.\n if (quickDates)\n for (const d of (namedDates.length > 0 ? namedDates : datePresets))\n rows.push({ key: `date:${d}`, label: d, kind: 'date', icon: 'date', insert: d, section });\n return rows;\n };\n /** A location row's caption: the source split when the slot searches BOTH, else the category at a\n * mixed slot, else none (a plain location list needs no header). */\n const locSection = (source: SuggestItem['source'], both: boolean): string | undefined =>\n (both ? sectionLabel(source) : undefined) ?? (mixed ? PLACE_SECTION : undefined);\n\n // Pre-fill immediately (no await) from analyze's suggestions so the user sees something instantly.\n // The emoji the labels used to carry (\"📍 \", \"📅 \") are gone: the shared dropdown draws a real\n // glyph per row kind, and two icons on one row is one too many.\n const prefill: PredictionItem[] = [];\n if (kind === 'location') {\n prefill.push(...dateRows({ quickDates: true })); // empty unless the slot is mixed\n for (const s of namedLocs)\n prefill.push({ key: `loc:${s.value}`, label: s.label, kind: 'namedLocation', insert: s.value,\n icon: 'place', section: mixed ? PLACE_SECTION : undefined });\n } else {\n prefill.push(...dateRows({ quickDates: true }));\n }\n\n const suggest = fetchersRef.current.suggest;\n const hasNamed = kind === 'location' ? namedLocs.length > 0 : true;\n\n // If the dropdown would be empty AND there's no suggest fetcher to fill it, fall back to auto-'@'.\n // A mixed list is never empty — the calendar line is its floor.\n if (kind === 'location' && !hasNamed && !suggest && !mixed) {\n if (!isDeletion && a.locationExpected && a.locationPartialEmpty && a.locationCount < 2\n && canLoc && ad.currentTriggerChar() !== '@') {\n const c = live.selectionStart ?? value.length;\n const before = value.slice(0, c);\n const needsSpace = before.length > 0 && !/\\s$/.test(before);\n if (!before.endsWith('@')) {\n const insert = needsSpace ? ' @' : '@';\n programmaticAtRef.current = true; // auto-\"@\" → the picker opens programmatically\n setPredictions(null);\n ad.setDraft(`${before}${insert}${value.slice(c)}`);\n ad.focusCaret(c + insert.length);\n requestAnimationFrame(() => { const t = ad.getTextarea(); if (t) ad.syncTrigger(t); });\n }\n return;\n }\n setPredictions(null);\n return;\n }\n\n // Show the pre-filled list. With a suggest fetcher wired, only pre-fill on FIRST open (when the\n // dropdown was closed) — re-setting it every keystroke re-flashes the tenant list under the\n // incoming search results. Once open, keep the current list and let suggest refine it below.\n // Without a suggest fetcher, the pre-fill IS the content, so keep updating it each keystroke.\n if (!suggest) {\n setPredictionQuery('');\n if (prefill.length > 0) { setPredictionHighlight(0); setPredictionsRecents(true); setPredictions(prefill); }\n else setPredictions(null);\n } else if (predictionsRef.current === null && prefill.length > 0) {\n setPredictionHighlight(0);\n setPredictionsRecents(true); // pre-fill = the user's history = recents\n setPredictions(prefill);\n }\n\n // Then refine via the host-provided unified suggest source (search-as-you-type).\n if (suggest) {\n // Query = what the user is typing for the current slot. For LOCATIONS the server owns the\n // parse (a.locationPartial: \"@\"-mentions stripped, so \"@São Paulo \" → \"\" → recents and\n // \"de belo \" → \"belo\" → filter) — no client-side whitespace guessing, which can't tell a\n // partial from a cue or a finished mention. Falls back to the trailing word for dates, or if\n // an older server didn't send the field.\n const beforeCaret = value.slice(0, live.selectionStart ?? value.length);\n const wsIdx = beforeCaret.search(/[ \\t\\r\\n](?=[^ \\t\\r\\n]*$)/);\n const trailingWord = wsIdx === -1 ? beforeCaret : beforeCaret.slice(wsIdx + 1);\n const q = kind === 'location' && a.locationPartial !== undefined ? a.locationPartial : trailingWord;\n // Remember what a location pick should replace (server partial, or the trailing word fallback).\n if (kind === 'location') locationPartialRef.current = q;\n setPredictionQuery(q);\n\n // Locations already picked in the prompt (the \"@(IATA) …\" mentions) — the suggest source\n // drops them AND anything in the same city, so it never offers an impossible SAO→SAO / GRU→CGH.\n const exclude = kind === 'location'\n ? [...value.matchAll(/@\\(([A-Za-z]{3})\\)/g)].map((m) => m[1].toUpperCase())\n : undefined;\n\n const sseq = ++suggestSeqRef.current;\n suggestAbortRef.current?.abort();\n const ac = new AbortController();\n suggestAbortRef.current = ac;\n try {\n // Issue #876 — a location suggest carries its vertical, so the host's source can serve\n // hotel places (\"hotéis próximos a …\") instead of airports. Dates stay vertical-less.\n const vertical: SearchVertical = kind === 'location' ? verticalOf(a) : 'air';\n const items = await suggest(q, kind, ac.signal, exclude, vertical);\n if (sseq !== suggestSeqRef.current) return; // overtaken\n const live2 = ad.getTextarea();\n if (!live2 || live2.value !== value) return; // text changed while in flight\n // Keep the useful pre-filled list on an empty result — the \"user is ignoring the dropdown\"\n // case is handled by the server's word cap (partial > 3 plain words → not a location).\n if (kind === 'location' && items.length === 0) return;\n\n const refined: PredictionItem[] = [];\n if (kind === 'location') {\n // A mixed refine re-fetches LOCATIONS only, so the quick dates come from here.\n refined.push(...dateRows({ quickDates: true }));\n for (const it of items)\n refined.push({\n key: `loc:${it.insert}`, label: it.label, kind: 'namedLocation', insert: it.insert,\n hint: [it.iata, it.region, it.country].filter(Boolean).join(' · ') || undefined, // parity with the `@` picker\n disabled: it.disabled, // already in the prompt (same city) — greyed, not pickable\n // An IATA code is what makes a row an AIRPORT; everything else is a place.\n icon: it.iata ? 'airport' : 'place',\n section: locSection(it.source, vertical === 'both'),\n });\n } else {\n refined.push(...dateRows({ quickDates: false })); // `items` below ARE the dates\n for (const it of items)\n refined.push({ key: `date:${it.insert}`, label: it.label, kind: 'date', icon: 'date', insert: it.insert });\n }\n if (refined.length === 0) { setPredictions(null); return; } // nothing to show\n const firstEnabled = refined.findIndex((p) => !p.disabled); // don't land the highlight on a disabled item\n setPredictionHighlight(firstEnabled < 0 ? 0 : firstEnabled);\n setPredictionsRecents(q.trim() === ''); // empty query → recents; typed query → search results\n setPredictions(refined);\n } catch { /* ignore — includes AbortError from a superseded call */ }\n }\n } catch { /* transient — ignore */ }\n }, 200);\n }\n\n if (resolveTimerRef.current != null) window.clearTimeout(resolveTimerRef.current);\n resolveTimerRef.current = window.setTimeout(() => { void runResolve(); }, 300);\n }, [runResolve]);\n\n /** Call on send with the FINAL text (NBSP-preserving) so the server learns the committed intent. Attaches the\n * composition's assist outcome (#159 Phase 1) as the behavioral label, then resets the accumulator. */\n const commit = useCallback((finalText: string) => {\n const t = finalText.trim();\n if (t) fetchersRef.current.commitIntent?.(t, sessionIdRef.current, outcomeRef.current);\n outcomeRef.current = emptyOutcome();\n programmaticAtRef.current = false;\n }, []);\n\n /** Host reports: the `@` picker opened. Distinguishes a programmatic open (ghost accept / dropdown pick /\n * auto-`@` — we set the flag ourselves) from the user typing `@` with no assist showing (manualAt: the gate\n * stayed quiet but the user wanted a mention — a recall-miss label). */\n const noteAtOpened = useCallback(() => {\n const outcome = outcomeRef.current;\n outcome.atOpened = true;\n if (programmaticAtRef.current) programmaticAtRef.current = false; // consume — not manual\n else if (hintRef.current === null && predictionsRef.current === null) outcome.manualAt = true;\n }, []);\n\n /** Host reports: an `@` mention was accepted, from the given section (undefined ⇒ single-source picker). */\n const noteAtAccepted = useCallback((group?: 'person' | 'location' | 'hotel') => {\n outcomeRef.current.atAccepted = group ?? 'location';\n }, []);\n\n /** #1: accept the phantom ghost (location OR person) — insert \"@\" at the caret (a leading space if the char\n * before isn't whitespace, so it never concatenates) and open the host's `@` picker, which sections itself into\n * Pessoas/Locais. The teach-the-trigger payoff, identical for both ghost kinds. */\n const acceptHint = useCallback(() => {\n outcomeRef.current.ghostAccepted = true;\n // The char follows the ghost that was on screen: \"#\" for a date cue, \"@\" for a place or a person.\n const chr = hintRef.current === 'date' ? '#' : '@';\n programmaticAtRef.current = true; // the trigger we insert below opens the picker programmatically\n // Accepted ≠ ignored: the anti-nag count starts over, so a LATER slot in the same prompt (the destination\n // after the origin) still gets its cue.\n hintStreakRef.current = 0;\n hintKindRef.current = null;\n setHint(null);\n const ad = adapterRef.current;\n const ta = ad.getTextarea();\n if (!ta) return;\n const caret = ta.selectionStart ?? ta.value.length;\n const before = ta.value.slice(0, caret);\n const after = ta.value.slice(caret);\n const needsSpace = before.length > 0 && !/\\s$/.test(before);\n const ins = `${needsSpace ? ' ' : ''}${chr}`;\n ad.setDraft(`${before}${ins}${after}`);\n ad.focusCaret(caret + ins.length);\n requestAnimationFrame(() => { const t = ad.getTextarea(); if (t) ad.syncTrigger(t); });\n }, []);\n\n /** Wire to the textarea's onKeyDown; returns true if it handled the key (host should then stop). */\n const onKeyDown = useCallback((e: KeyboardEvent<HTMLTextAreaElement>): boolean => {\n // Development affordance: the configured key paints the ghost at the caret instead of being typed.\n if (debugGhostKey && e.key === debugGhostKey && !e.ctrlKey && !e.metaKey && !e.altKey) {\n e.preventDefault();\n const ta = adapterRef.current.getTextarea();\n const caret = ta?.selectionStart ?? ta?.value.length ?? 0;\n const rest = ta ? ta.value.slice(caret) : '';\n hintSuppressedRef.current = false; // the tester asked for it; the anti-nag latch does not apply\n hintStreakRef.current = 0;\n setHintMidSentence(rest.trim().length > 0);\n setHint(hint === 'location' ? 'person' : 'location');\n return true;\n }\n // #1 ghost: with a phantom up and no dropdown, Tab accepts it (inserts \"@\"), Esc dismisses. → also accepts,\n // but only at end-of-text: mid-sentence it is a cursor move into the words that follow, so there it stays one.\n if (hint !== null && (!predictions || predictions.length === 0)) {\n if (e.key === 'Tab' || (e.key === 'ArrowRight' && !hintMidSentence)) { e.preventDefault(); acceptHint(); return true; }\n // Escape is the loudest possible \"no\" — pin the phantom off for the rest of this prompt, same as\n // typing past it four times (#422).\n if (e.key === 'Escape') { e.preventDefault(); hintSuppressedRef.current = true; setHint(null); return true; }\n }\n if (!predictions || predictions.length === 0) return false;\n if (e.key === 'ArrowDown') { e.preventDefault(); setPredictionHighlight((i) => nextEnabledIndex(predictions, i, 1)); return true; }\n if (e.key === 'ArrowUp') { e.preventDefault(); setPredictionHighlight((i) => nextEnabledIndex(predictions, i, -1)); return true; }\n if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); const it = predictions[predictionHighlight]; if (it && !it.disabled) applyPrediction(it); return true; }\n if (e.key === 'Escape') { e.preventDefault(); setPredictions(null); return true; }\n return false;\n }, [predictions, predictionHighlight, applyPrediction, hint, hintMidSentence, acceptHint, debugGhostKey]);\n\n useEffect(() => () => {\n if (analyzeTimerRef.current != null) window.clearTimeout(analyzeTimerRef.current);\n if (resolveTimerRef.current != null) window.clearTimeout(resolveTimerRef.current);\n if (tooltipTimerRef.current != null) window.clearTimeout(tooltipTimerRef.current);\n resolveAbortRef.current?.abort();\n suggestAbortRef.current?.abort();\n }, []);\n\n return {\n predictions, predictionsRecents, predictionQuery, slotDateOptions, predictionHighlight, setPredictionHighlight,\n applyPrediction, clearPredictions,\n hint, hintMidSentence, acceptHint,\n resolvedLocations, resolvedDates, forceTooltipText,\n personConfidence, locationConfidence, hotelExpected, hotelConfidence, vertical,\n hotelNameExpected, hotelNameConfidence,\n scheduleAssist, commit, onKeyDown, resetSession,\n noteAtOpened, noteAtAccepted,\n };\n}\n","import { useEffect, useRef, useState } from \"react\";\n\n// Custom useInterval hook\nfunction useInterval(callback: () => void, delay: number) {\n const savedCallback = useRef(callback);\n const [intervalId, setIntervalId] = useState<NodeJS.Timeout | null>(null)\n\n // Remember the latest callback.\n useEffect(() => {\n savedCallback.current = callback;\n }, [callback]);\n\n // Set up the interval.\n useEffect(() => {\n function tick() {\n savedCallback.current();\n }\n if (delay !== null) {\n const id = setInterval(tick, delay);\n setIntervalId(id)\n return () => {\n\n clearInterval(id); // Cleanup function\n }\n }\n }, [delay]);\n\n return intervalId;\n}\n\nexport default useInterval","import { useState, useEffect } from \"react\";\n\nexport function useContainerRectangle(ref: React.RefObject<HTMLElement | null>, renderId: string, initialWidth = 0, initialHeight = 0) {\n const [width, setWidth] = useState(initialWidth);\n const [height, setHeight] = useState(initialHeight);\n\n useEffect(() => {\n const el = ref.current;\n if (!el) return;\n\n const observer = new ResizeObserver((entries) => {\n const entry = entries[0];\n if (entry) {\n setHeight(entry.contentRect.height);\n setWidth(entry.contentRect.width);\n }\n });\n\n observer.observe(el);\n setWidth(el.getBoundingClientRect().width);\n\n return () => observer.disconnect();\n }, [ref, renderId]);\n\n return [width, height];\n}"],"names":["foldForCompare","__name","s","verticalOf","a","lodgingOf","lodgingScoreOf","sectionLabel","source","DATE_SECTION","PLACE_SECTION","emptyOutcome","newSessionId","nextEnabledIndex","items","from","dir","n","idx","step","_a","usePromptAssist","adapter","fetchers","options","debugGhostKey","predictions","setPredictions","useState","hint","setHint","hintMidSentence","setHintMidSentence","locationConfidence","setLocationConfidence","personConfidence","setPersonConfidence","hotelExpected","setHotelExpected","vertical","setVertical","hotelConfidence","setHotelConfidence","hotelNameExpected","setHotelNameExpected","hotelNameConfidence","setHotelNameConfidence","predictionsRecents","setPredictionsRecents","predictionQuery","setPredictionQuery","slotDateOptions","setSlotDateOptions","predictionHighlight","setPredictionHighlight","resolvedLocations","setResolvedLocations","resolvedDates","setResolvedDates","forceTooltipText","setForceTooltipText","lastResolvedKeyRef","useRef","tooltipTimerRef","adapterRef","fetchersRef","optionsRef","analyzeTimerRef","resolveTimerRef","analyzeSeqRef","suggestSeqRef","suggestAbortRef","draftRef","lastResolveTextRef","resolveAbortRef","sessionIdRef","predictionsRef","hintRef","hintStreakRef","hintKindRef","hintSuppressedRef","MAX_HINT_STREAK","PERSON_HINT_THRESHOLD","lastKindRef","locationPartialRef","runResolveRef","outcomeRef","programmaticAtRef","clearPredictions","useCallback","resetSession","applyPrediction","p","ad","ta","caret","rawBefore","after","isLocationPick","before","partial","trimmedEnd","wordStart","trailing","needsSpace","ins","next","mention","chr","t","runResolve","resolve","text","ac","dates","locations","resolved","d","l","key","r","scheduleAssist","value","isDeletion","analyze","seq","live","outcome","caretPos","caretEnd","beforeCaret","afterCaret","midSlot","atSlot","canLoc","pickerOpen","named","enableHashDatePicker","datePresets","decided","secondary","mixed","quick","x","per","loc","locationGhost","dateGhost","kind","namedLocs","namedDates","dateRows","quickDates","section","rows","locSection","both","prefill","suggest","hasNamed","c","insert","wsIdx","trailingWord","q","exclude","m","sseq","live2","refined","it","firstEnabled","commit","finalText","noteAtOpened","noteAtAccepted","group","acceptHint","onKeyDown","e","rest","i","useEffect","_b","useInterval","callback","delay","savedCallback","intervalId","setIntervalId","tick","id","useContainerRectangle","ref","renderId","initialWidth","initialHeight","width","setWidth","height","setHeight","el","observer","entries","entry"],"mappings":";;;AAIA,MAAMA,KAAiB,gBAAAC,EAAA,CAACC,MAAcA,EAAE,UAAU,KAAK,EAAE,QAAQ,oBAAoB,EAAE,EAAE,YAAA,GAAlE,mBAmEjBC,KAAa,gBAAAF,EAAA,CAACG,MAAsCA,EAAE,aAAaC,GAAUD,CAAC,IAAI,UAAU,QAA/E,eAEbC,KAAY,gBAAAJ,EAAA,CAACG,MAA+BA,EAAE,kBAAkBA,EAAE,iBAAiB,IAAvE,cACZE,KAAiB,gBAAAL,EAAA,CAACG,MAA8BA,EAAE,oBAAoBA,EAAE,mBAAmB,GAA1E,mBACjBG,KAAe,gBAAAN,EAAA,CAACO,MAClBA,MAAW,UAAU,oBAAoBA,MAAW,QAAQ,eAAe,QAD1D,iBAIfC,KAAe,QACfC,KAAgB,eAEhBC,KAAe,gBAAAV,EAAA,OAAsB;AAAA,EACvC,uBAAuB;AAAA,EAAG,qBAAqB;AAAA,EAAG,oBAAoB;AAAA,EACtE,mBAAmB;AAAA,EAAO,o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