@aintela/chat 0.4.33 → 0.4.34
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 +3829 -3816
- package/dist/components.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{predictionRows-BIWfLLDA.js → predictionRows-Damfwthh.js} +6 -6
- package/dist/{predictionRows-BIWfLLDA.js.map → predictionRows-Damfwthh.js.map} +1 -1
- package/dist/src/components/v2/PromptV2.d.ts +6 -0
- package/dist/utils.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"predictionRows-BIWfLLDA.js","sources":["../src/utils/urlParser.ts","../src/utils/stringUtils.ts","../src/utils/interactionIdChecker.ts","../src/utils/sortable-table.js","../src/utils/promptHighlight.ts","../src/utils/placeCaret.ts","../src/utils/swallowNextClick.ts","../src/utils/atMentions.ts","../src/utils/predictionRows.ts"],"sourcesContent":["export type LinkAction = 'Export' | 'Question' | 'OpenDashboard' | 'URL' | 'Navigate'\n\n/**\n * Absolute http(s) URL. Deliberately anchored: the check used to be\n * `link.indexOf(\"http\") > -1`, which classified `exported/http-logs.csv` — and\n * `/blog/http-basics` — as an external URL and handed a relative string to\n * `window.open`.\n */\nconst ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\nexport const extractLinkAction = (link: string, sessionId: string, content: string | null): { action: LinkAction, url: string | null, question: string | null, parameter: string | null } => {\n let action: LinkAction = 'URL';\n let question: string | null = null;\n let url: string | null = null;\n let parameter: string | null = null;\n if (link[0] == '#') {\n const firstDash = link.indexOf(\"-\");\n const firstPart = link.slice(1, firstDash);\n parameter = link.slice(firstDash + 1);\n switch (firstPart.toLowerCase()) {\n case \"opendashboard\":\n action = 'OpenDashboard'\n break;\n case \"ask\":\n action = 'Question'\n question = content\n break;\n }\n }\n else if (ABSOLUTE_URL.test(link)) {\n action = 'URL'\n url = link\n }\n else if (link[0] === '/') {\n // A ROOT-RELATIVE path is a route in the HOST app, not a generated file.\n // Everything relative used to fall through to `Export` below, so the agent\n // writing `<a href=\"/institutional/policy-agent\">` (the first-trip tips do)\n // got the page prefixed with the agent-server base URL and DOWNLOADED —\n // while \"open in new tab\", which bypasses the click handler and follows the\n // real href, worked. The host routes this one instead (`onNavigate`).\n action = 'Navigate'\n url = link\n }\n else {\n // What is left is the export protocol: `exported/<file>`. Left exactly as it\n // was, `url` included: the caller re-derives the download address from the\n // raw href, so this stamping has never reached anyone and returning it now\n // would change every export's URL as a side effect of a link-routing fix.\n link = link.replaceAll(\"exported/\", `exported/${sessionId}/`)\n action = 'Export'\n }\n\n return { action, url, question, parameter }\n}\n","export const chunkArray = (char: string[], size: number): string[][] =>\n Array.from({ length: Math.ceil(char.length / size) }, (_v, i) =>\n char.slice(i * size, i * size + size)\n );\n\nexport const splitBigLinesWithSpaces = (content: string): string => {\n // If content already contains newlines or is short, return as-is\n content = content.replaceAll(\"\\\\n\", \"\\n\");\n\n const limit = 90;\n\n const whiteSpaceBreak = content.split(\" \");\n const allWords: string[] = []\n let hadOne = false;\n for (const word of whiteSpaceBreak) {\n if (word.length > limit) {\n hadOne = true;\n const charArray = [...word];\n const chunkedText = chunkArray(charArray, limit);\n const chunkedWord = chunkedText.map(chunk => chunk.join(\"\")).join(\"\\n\");\n allWords.push(chunkedWord);\n }\n else {\n allWords.push(word);\n }\n }\n\n return hadOne ? allWords.join(\" \") : content;\n}\n\nexport function parseRawNumber(text: string): number {\n let number = parseFloat(text);\n if (!isNaN(number)) {\n text = text.replaceAll(/[,\\.]/g, '');\n return parseInt(text);\n }\n\n var finalNumber = \"\"\n for (const char of text) {\n if (char.match(/[0-9]/)) {\n finalNumber += char;\n }\n }\n\n const ratio = finalNumber.length / text.length;\n number = parseInt(finalNumber);\n if (!isNaN(number) && ratio > 0.5) {\n return number;\n }\n\n return NaN;\n}\n\nexport function parseKnownNumbers(text?: string): { prefix?: string, suffix?: string, number?: number } {\n if (!text) return { prefix: undefined, suffix: undefined, number: undefined };\n\n const knownChars = /[$%(\\w?\\$)]/gi;\n const currencySymbol = /[a-z]?\\$/gi;\n\n let prefix = \"\";\n let suffix = \"\";\n\n if (text.match(knownChars)) {\n if (text.indexOf(\"%\") > -1) {\n suffix = \" %\"\n }\n const match = text.match(currencySymbol)\n if (match) {\n prefix = match[0] + \" \";\n }\n }\n\n let number = parseFloat(text);\n\n if (!isNaN(number)) {\n text = text.replaceAll(\".\", '').replaceAll(\",\", \".\");\n return { prefix, suffix, number: parseFloat(text) };\n }\n\n var finalNumber = \"\"\n for (const char of text) {\n if (char.match(/[0-9.,]/)) {\n let replacedChar = char;\n if (replacedChar == '.')\n replacedChar = \"\"\n else if (replacedChar == \",\")\n replacedChar = \".\"\n finalNumber += replacedChar;\n }\n }\n\n number = parseFloat(finalNumber);\n if (!isNaN(number)) {\n return { prefix, suffix, number: number };\n }\n\n return { prefix: undefined, suffix: undefined, number: undefined };;\n}","/**\n * Utility function to check if a string starts with an interaction ID (UUID)\n * Supports both formats:\n * - With dashes: ebd067ef-0dbd-49b3-8eff-c54b2a9ff314\n * - Without dashes: 62ec037ae42c439192c64dd112136583\n */\n\n/**\n * Regular expression for UUID with dashes (standard format)\n * Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n */\nconst UUID_WITH_DASHES_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;\n\n/**\n * Regular expression for UUID without dashes (compact format)\n * Format: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (32 hex characters)\n */\nconst UUID_WITHOUT_DASHES_REGEX = /^[0-9a-f]{32}/i;\n\n/**\n * Check if a string starts with an interaction ID (UUID)\n * @param str - The string to check\n * @returns true if the string starts with a valid UUID, false otherwise\n */\nexport function startsWithInteractionId(str: string): boolean {\n if (!str || typeof str !== 'string') {\n return false;\n }\n\n const interactionId = extractInteractionId(str);\n\n return interactionId === null ? false : str.startsWith(interactionId);\n}\n\n/**\n * Extract the interaction ID from the beginning of a string\n * @param str - The string to extract from\n * @returns The interaction ID if found, null otherwise\n */\nexport function extractInteractionId(str: string): string | null {\n if (!str || typeof str !== 'string') {\n return null;\n }\n\n // Try to match UUID with dashes first\n const withDashesMatch = str.match(UUID_WITH_DASHES_REGEX);\n if (withDashesMatch) {\n return withDashesMatch[0];\n }\n\n // Try to match UUID without dashes\n const withoutDashesMatch = str.match(UUID_WITHOUT_DASHES_REGEX);\n if (withoutDashesMatch) {\n return withoutDashesMatch[0];\n }\n\n return null;\n}\n\nexport function prettiffyFileName(fileName: string) {\n const prettyName = fileName.replaceAll(\"_\", \" \").replaceAll(\"-\", \" \");\n const userRemoved = prettyName.replaceAll(\"user:\", \"\");\n const withNoExtension = userRemoved.replace(/\\.[^/.]+$/, \"\");\n const withNoInteractionId = extractNameFromStringWithInteractionId(withNoExtension).trim();\n if (withNoInteractionId.length > 1)\n return withNoInteractionId[0].toUpperCase() + withNoInteractionId.slice(1);\n else\n return withNoInteractionId;\n}\n\nexport function prettiffyPythonFunctionName(functionName: string) {\n if (functionName.length == 0)\n return functionName;\n\n const prettyName = functionName.replaceAll(\"_\", \" \").replaceAll(\"-\", \" \");\n const withFirstCapitalLetter = prettyName[0].toUpperCase() + prettyName.slice(1);\n\n return withFirstCapitalLetter;\n}\n\nexport function extractNameFromStringWithInteractionId(str: string): string {\n // Try to match UUID with dashes first and remove it\n const withDashesMatch = str.match(UUID_WITH_DASHES_REGEX);\n if (withDashesMatch) {\n return str.replace(withDashesMatch[0], \"\");\n }\n\n // Try to match UUID without dashes\n const withoutDashesMatch = str.match(UUID_WITHOUT_DASHES_REGEX);\n if (withoutDashesMatch) {\n return str.replace(withoutDashesMatch[0], \"\");\n }\n\n return str;\n}\n\n/**\n * Check if a string is a valid interaction ID (UUID) on its own\n * @param str - The string to check\n * @returns true if the string is a valid UUID, false otherwise\n */\nexport function isValidInteractionId(str: string): boolean {\n if (!str || typeof str !== 'string') {\n return false;\n }\n\n // Check if it's exactly a UUID with dashes\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(str)) {\n return true;\n }\n\n // Check if it's exactly a UUID without dashes\n if (/^[0-9a-f]{32}$/i.test(str)) {\n return true;\n }\n\n return false;\n}\n","/**\n * SortableTable - A pure JavaScript library for making tables sortable\n * \n * Features:\n * - Automatically scans document for tables\n * - Supports tables with or without thead elements (converts first row to header if needed)\n * - Adds Material UI icons to column headers\n * - Supports text, number, and date sorting\n * - Visual feedback for sort direction\n * - Preserves existing table styling\n */\n\nconst initializedTables = new Set(); // Track which tables have been initialized\n\nimport { parseRawNumber } from './stringUtils';\n\nclass SortableTable {\n constructor(options = {}) {\n this.options = {\n // CSS class for sortable headers\n sortableClass: 'sortable-header',\n // CSS class for active sort\n activeSortClass: 'active-sort',\n // CSS class for ascending sort\n ascendingClass: 'sort-asc',\n // CSS class for descending sort\n descendingClass: 'sort-desc',\n // Icon for unsorted state\n unsortedIcon: 'unfold_more',\n // Icon for ascending sort\n ascendingIcon: 'keyboard_arrow_up',\n // Icon for descending sort\n descendingIcon: 'keyboard_arrow_down',\n // Whether to sort on first click (true) or cycle through states (false)\n sortOnFirstClick: true,\n // Custom sort functions for specific columns\n customSorters: {},\n // Columns to exclude from sorting (0-based index)\n excludeColumns: [],\n // Whether to preserve existing icons in headers\n preserveExistingIcons: false,\n // Enable column resizing\n enableResizing: true,\n // Enable column reordering\n enableReordering: true,\n // CSS class for resizable columns\n resizableClass: 'resizable-column',\n // CSS class for draggable columns\n draggableClass: 'draggable-column',\n // CSS class for drag placeholder\n dragPlaceholderClass: 'drag-placeholder',\n // CSS class for drag over state\n dragOverClass: 'drag-over',\n theme: {\n palette: {\n primary: {\n main: '#999',\n },\n background: {\n default: '#fff',\n paper: '#555',\n },\n text: {\n primary: \"#000\",\n secondary: \"#999\",\n disabled: \"#BBB\",\n },\n surface: {\n panel: \"#999\",\n raised: \"#999\",\n hover: \"#444\",\n },\n divider: \"#999\",\n border: {\n default: \"#999\",\n soft: \"#BBB\",\n },\n },\n shape: {\n borderRadius: 7,\n radiusSm: 1,\n radiusLg: 10,\n },\n },\n ...options\n };\n\n this.tables = [];\n this.sortStates = new Map(); // Track sort state for each table\n this.originalColumnOrder = new Map(); // Track original column order\n this.isDragging = false;\n this.dragSource = null;\n this.dragTarget = null;\n this.charWidth = 0;\n }\n\n /**\n * Initialize the library - scan document for tables and make them sortable\n * @param {HTMLElement} container - Optional container element to limit search scope\n */\n init(container = null) {\n if (this.charWidth == 0)\n this.charWidth = this.getCharWidth(this.options.theme.typography.fontFamily, this.options.theme.typography.fontMono)\n\n this.scanTables(container);\n this.makeTablesSortable();\n this.addStyles();\n }\n\n /**\n * Scan for tables in the document or within a specific container\n * @param {HTMLElement} container - Optional container element to limit search scope\n */\n scanTables(container = null) {\n const searchScope = container || document;\n const tables = searchScope.querySelectorAll('table');\n this.tables = Array.from(tables);\n }\n\n /**\n * Make all found tables sortable\n */\n makeTablesSortable() {\n this.tables.forEach((table, tableIndex) => {\n this.makeTableSortable(table, tableIndex);\n });\n }\n\n /**\n * Make a specific table sortable\n */\n makeTableSortable(table, tableIndex) {\n let thead = table.querySelector('thead');\n let headerRow = null;\n let headers = [];\n\n // Check if table has a proper thead\n if (thead) {\n headerRow = thead.querySelector('tr');\n if (headerRow) {\n headers = headerRow.querySelectorAll('th');\n }\n }\n\n if (headers.length === 0) {\n console.warn('Table has no sortable columns, skipping');\n return;\n }\n // First-time-only arrival animation. ChatPane's effect\n // destroys + re-inits the SortableTable on every `messages`\n // update, so a CSS animation tied to `.sortable-table`\n // alone would replay on each new chunk and feel jittery.\n // The DOM attribute persists across destroy/init cycles\n // (destroy() doesn't touch table attributes), so it cleanly\n // marks \"this table has already arrived once.\"\n const isFirstSortableMount = !table.hasAttribute('data-sortable-arrived');\n // Add sortable-table class for styling\n table.classList.add('sortable-table');\n if (isFirstSortableMount) {\n table.setAttribute('data-sortable-arrived', 'true');\n table.classList.add('sortable-table-arriving');\n // Drop the trigger class after the animation finishes so\n // it can't fire again if the table is somehow re-added to\n // a different DOM position.\n setTimeout(() => {\n table.classList.remove('sortable-table-arriving');\n }, 400);\n }\n\n // Calculate intelligent table width based on header text length\n //const calculatedWidth = this.calculateTableWidth(table);\n // table.style.width = 'auto';\n // table.style.minWidth = '80%';\n //table.style.tableLayout = 'fixed'; // Use fixed layout to respect manual widths\n\n // Cell styles are now handled by CSS only\n\n // Initialize sort state for this table\n this.sortStates.set(tableIndex, {\n currentColumn: -1,\n direction: 'none'\n });\n\n // Capture the table's pre-transform width once so calculateTableWidth\n // can use it as a floor. Persisted as a data attribute (like\n // data-sortable-arrived) so it survives ChatPane's destroy/init\n // cycle — re-reading on every mount would pick up the inline\n // width left behind by the previous calculation, not the\n // natural width the user originally saw.\n if (!table.hasAttribute('data-original-width')) {\n table.setAttribute('data-original-width', table.getBoundingClientRect().width);\n }\n\n this.applyTableStyles(table);\n\n // Store original column order\n this.originalColumnOrder.set(tableIndex, Array.from(headers).map((_, index) => index));\n\n // Make each header sortable\n headers.forEach((header, columnIndex) => {\n if (this.options.excludeColumns.includes(columnIndex)) {\n return;\n }\n\n this.makeHeaderSortable(header, table, tableIndex, columnIndex);\n });\n\n // Replace exponential values in all cells with full numbers\n this.replaceExponentialValues(table);\n\n // Mark this table as initialized\n initializedTables.add(table);\n }\n\n /**\n * Replace exponential values in table cells with full numbers\n * @param {HTMLElement} table - The table to process\n */\n replaceExponentialValues(table) {\n const tbody = table.querySelector('tbody');\n if (!tbody) return;\n\n const rows = tbody.querySelectorAll('tr');\n rows.forEach(row => {\n const cells = row.querySelectorAll('td, th');\n cells.forEach(cell => {\n const text = cell.textContent.trim();\n const exponentialMatch = text.match(/^([\\d,]+\\.?\\d*)[eE][+-]?(\\d+)$/);\n\n if (exponentialMatch) {\n const base = parseFloat(exponentialMatch[1].replace(/,/g, ''));\n const exponent = parseInt(exponentialMatch[2]);\n const fullNumber = base * Math.pow(10, exponent);\n\n // Format the number with commas for readability\n const formattedNumber = this.formatNumber(fullNumber);\n cell.textContent = formattedNumber;\n }\n });\n });\n }\n\n /**\n * Format a number with commas for readability\n * @param {number} num - The number to format\n * @returns {string} The formatted number\n */\n formatNumber(num) {\n if (num === 0) return '0';\n\n // Handle very large or very small numbers\n if (Math.abs(num) >= 1e12) {\n return (num / 1e12).toFixed(2) + 'T';\n } else if (Math.abs(num) >= 1e9) {\n return (num / 1e9).toFixed(2) + 'B';\n } else if (Math.abs(num) >= 1e6) {\n return (num / 1e6).toFixed(2) + 'M';\n } else if (Math.abs(num) >= 1e3) {\n return (num / 1e3).toFixed(2) + 'K';\n } else if (Math.abs(num) < 0.01 && num !== 0) {\n return num.toExponential(2);\n } else {\n return num.toLocaleString();\n }\n }\n\n /**\n * Convert the first row to a header row\n * @param {HTMLElement} firstRow - The first row to convert\n * @param {HTMLElement} thead - The thead element to append to\n * @param {HTMLElement} tbody - The tbody element to remove from\n * @returns {HTMLElement} The converted header row\n */\n convertRowToHeader(firstRow, thead, tbody) {\n try {\n // Clone the row\n const headerRow = firstRow.cloneNode(true);\n\n // Convert all td elements to th elements\n const cells = headerRow.querySelectorAll('td');\n cells.forEach(td => {\n const th = document.createElement('th');\n\n // Copy all attributes\n Array.from(td.attributes).forEach(attr => {\n th.setAttribute(attr.name, attr.value);\n });\n\n // Copy content\n th.innerHTML = td.innerHTML;\n\n // Copy styles\n th.style.cssText = td.style.cssText;\n\n // Replace td with th\n td.parentNode.replaceChild(th, td);\n });\n\n // Remove the original first row from tbody\n if (tbody && tbody.contains(firstRow)) {\n tbody.removeChild(firstRow);\n } else if (firstRow.parentNode) {\n firstRow.parentNode.removeChild(firstRow);\n }\n\n // Add the header row to thead\n thead.appendChild(headerRow);\n\n return headerRow;\n\n } catch (error) {\n console.error('Error converting row to header:', error);\n return null;\n }\n }\n\n /**\n * Make a specific header sortable\n */\n makeHeaderSortable(header, table, tableIndex, columnIndex) {\n // Add sortable class\n header.classList.add(this.options.sortableClass);\n\n // Add cursor pointer\n header.style.cursor = 'pointer';\n\n // Add sort icon if not preserving existing icons\n if (!this.options.preserveExistingIcons || !header.querySelector('.material-icons')) {\n this.addSortIcon(header);\n }\n\n // Add resizing functionality\n if (this.options.enableResizing) {\n this.addResizing(header, table, tableIndex, columnIndex);\n }\n\n // Add drag and drop functionality\n if (this.options.enableReordering) {\n this.addDragAndDrop(header, table, tableIndex, columnIndex);\n // Note: We rely on header drop targets only for better reliability\n }\n\n const clickListener = (e) => {\n e.preventDefault();\n this.sortTable(table, tableIndex, columnIndex);\n }\n\n const mouseEnterListener = (e) => {\n if (!header.classList.contains(this.options.activeSortClass)) {\n header.style.background = this.options.theme.palette.surface.hover;\n }\n }\n\n const mouseLeaveListener = (e) => {\n if (!header.classList.contains(this.options.activeSortClass)) {\n header.style.background = '';\n }\n }\n\n header.removeEventListener('click', clickListener);\n const resp = header.addEventListener('click', clickListener);\n header.removeEventListener('mouseenter', mouseEnterListener);\n header.addEventListener('mouseenter', mouseEnterListener);\n header.removeEventListener('mouseleave', mouseLeaveListener);\n header.addEventListener('mouseleave', mouseLeaveListener);\n }\n\n /**\n * Add sort icon to header\n */\n addSortIcon(header) {\n if (header.querySelector('.sortable-table-icon')) {\n return;\n }\n\n const icon = document.createElement('i');\n icon.id = 'sortable-table-icon';\n icon.className = 'material-icons';\n icon.textContent = this.options.unsortedIcon;\n icon.style.marginRight = '2px';\n icon.style.fontSize = '12px';\n icon.style.verticalAlign = 'middle';\n // Start invisible, then animate to the resting opacity on a\n // later frame so the existing `.sortable-header .material-icons\n // { transition: opacity 0.2s ease }` rule fades in instead of\n // popping in alongside the rest of the table transformation.\n // Double-rAF guarantees the browser paints the 0 state first;\n // a single rAF can be coalesced into the insertion frame in\n // some engines and skip the transition.\n icon.style.opacity = '0';\n\n const existingIcon = header.querySelector('.material-icons');\n if (!existingIcon) {\n header.insertBefore(icon, header.firstChild);\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n icon.style.opacity = '0.6';\n });\n });\n }\n }\n\n /**\n * Sort table by column\n */\n sortTable(table, tableIndex, columnIndex) {\n const tbody = table.querySelector('tbody');\n if (!tbody) {\n console.warn('Table has no tbody element');\n return;\n }\n\n const rows = Array.from(tbody.querySelectorAll('tr'));\n if (rows.length === 0) {\n console.warn('Table has no data rows');\n return;\n }\n\n const sortState = this.sortStates.get(tableIndex);\n const header = table.querySelector(`thead tr th:nth-child(${columnIndex + 1})`);\n\n // Determine sort direction\n let newDirection;\n if (this.options.sortOnFirstClick) {\n newDirection = sortState.currentColumn === columnIndex && sortState.direction === 'asc' ? 'desc' : 'asc';\n } else {\n if (sortState.currentColumn !== columnIndex) {\n newDirection = 'asc';\n } else {\n newDirection = sortState.direction === 'none' ? 'asc' :\n sortState.direction === 'asc' ? 'desc' : 'none';\n }\n }\n\n // Update sort state\n sortState.currentColumn = columnIndex;\n sortState.direction = newDirection;\n this.sortStates.set(tableIndex, sortState);\n\n // Update visual indicators\n this.updateSortIndicators(table, tableIndex, columnIndex, newDirection);\n\n // If direction is 'none', restore original order\n if (newDirection === 'none') {\n this.restoreOriginalOrder(table, rows);\n return;\n }\n\n // Sort the rows\n const sortedRows = this.sortRows(rows, columnIndex, newDirection);\n\n // Re-append sorted rows\n sortedRows.forEach(row => tbody.appendChild(row));\n }\n\n /**\n * Sort rows based on column data\n */\n sortRows(rows, columnIndex, direction) {\n return rows.sort((a, b) => {\n const cellA = a.cells[columnIndex];\n const cellB = b.cells[columnIndex];\n\n if (!cellA || !cellB) return 0;\n\n const valueA = this.extractValue(cellA);\n const valueB = this.extractValue(cellB);\n\n // Use custom sorter if available\n if (this.options.customSorters[columnIndex]) {\n return this.options.customSorters[columnIndex](valueA, valueB, direction);\n }\n\n // Default sorting logic\n const comparison = this.compareValues(valueA, valueB);\n return direction === 'asc' ? comparison : -comparison;\n });\n }\n\n /**\n * Extract sortable value from cell\n */\n extractValue(cell) {\n let text = cell.textContent.trim();\n\n let number = parseRawNumber(text);\n if (!isNaN(number)) {\n console.log(number);\n return number;\n }\n\n // Remove all material icons and common symbols from the text\n text = text.replace(/arrow_upward|arrow_downward|remove|keyboard_arrow_up|keyboard_arrow_down|unfold_more|expand_more|expand_less|trending_up|trending_down|↗|↘|↑|↓|→|←/g, '').trim();\n\n // Handle N/A, N/D, ND, blank and variants as -1\n const naVariants = /^(N\\/A|N\\/D|ND|N\\/A|n\\/a|n\\/d|nd|N\\/A|N\\/D|ND|\\s*)$/i;\n if (naVariants.test(text)) {\n return -1;\n }\n\n // Try to parse as percentage\n const percentageMatch = text.match(/^([\\d,]+\\.?\\d*)\\s*%$/);\n if (percentageMatch) {\n return parseFloat(percentageMatch[1].replace(/,/g, ''));\n }\n\n // Try to parse as exponential notation (scientific notation)\n const exponentialMatch = text.match(/^([\\d,]+\\.?\\d*)[eE][+-]?(\\d+)$/);\n if (exponentialMatch) {\n const base = parseFloat(exponentialMatch[1].replace(/,/g, ''));\n const exponent = parseInt(exponentialMatch[2]);\n return base * Math.pow(10, exponent);\n }\n\n // Try to parse as number\n const numberMatch = text.match(/^[\\d,]+\\.?\\d*[KMB]?$/);\n if (numberMatch) {\n return this.parseNumber(text);\n }\n\n // Try to parse as currency\n const currencyMatch = text.match(/^R\\$\\s*([\\d,]+\\.?\\d*)$/);\n if (currencyMatch) {\n return this.parseNumber(currencyMatch[1]);\n }\n\n // Try to parse as date\n const date = new Date(text);\n if (!isNaN(date.getTime())) {\n return date.getTime();\n }\n\n // Return as string (case-insensitive)\n return text.toLowerCase();\n }\n\n /**\n * Compare two values for sorting\n */\n compareValues(a, b) {\n // Handle null/undefined values\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n\n // Handle different types\n if (typeof a !== typeof b) {\n return String(a).localeCompare(String(b));\n }\n\n // Handle numbers\n if (typeof a === 'number') {\n return a - b;\n }\n\n // Handle dates\n if (a instanceof Date) {\n return a.getTime() - b.getTime();\n }\n\n // Handle strings\n return a.localeCompare(b);\n }\n\n /**\n * Update visual indicators for sort state\n */\n updateSortIndicators(table, tableIndex, columnIndex, direction) {\n const headers = table.querySelectorAll('thead tr th');\n\n // Reset all headers\n headers.forEach((header, index) => {\n header.classList.remove(this.options.activeSortClass, this.options.ascendingClass, this.options.descendingClass);\n const icon = header.querySelector('.material-icons');\n if (icon) {\n icon.textContent = this.options.unsortedIcon;\n icon.style.opacity = '0.6';\n }\n });\n\n // Update active header\n if (direction !== 'none') {\n const activeHeader = headers[columnIndex];\n activeHeader.classList.add(this.options.activeSortClass);\n\n const icon = activeHeader.querySelector('.material-icons');\n if (icon) {\n if (direction === 'asc') {\n activeHeader.classList.add(this.options.ascendingClass);\n icon.textContent = this.options.ascendingIcon;\n } else {\n activeHeader.classList.add(this.options.descendingClass);\n icon.textContent = this.options.descendingIcon;\n }\n icon.style.opacity = '1';\n }\n }\n }\n\n /**\n * Restore original order (when sort direction is 'none')\n */\n restoreOriginalOrder(table, rows) {\n // This is a simplified implementation\n // In a real scenario, you might want to store the original order\n const tbody = table.querySelector('tbody');\n rows.forEach(row => tbody.appendChild(row));\n }\n\n /**\n * Add resizing functionality to a header\n */\n addResizing(header, table, tableIndex, columnIndex) {\n header.classList.add(this.options.resizableClass);\n header.style.position = 'relative';\n\n\n if (header.querySelector('.resize-handle')) {\n return;\n }\n\n const resizeHandle = document.createElement('div');\n resizeHandle.className = 'resize-handle';\n resizeHandle.style.cssText = `\n position: absolute;\n top: 0;\n right: 0;\n width: 4px;\n height: 100%;\n background: transparent;\n cursor: col-resize;\n z-index: 10;\n `;\n\n header.appendChild(resizeHandle);\n\n let isResizing = false;\n let startX = 0;\n let startWidth = 0;\n\n resizeHandle.addEventListener('mousedown', (e) => {\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation(); // Prevent sort from triggering\n isResizing = true;\n startX = e.clientX;\n startWidth = header.offsetWidth;\n\n // Add visual feedback\n header.style.borderRight = '2px solid var(--primary-main, #2196F3)';\n header.style.background = 'var(--background-active, rgba(255, 255, 255, 0.1))';\n\n document.addEventListener('mousemove', handleResize);\n document.addEventListener('mouseup', stopResize);\n document.body.style.cursor = 'col-resize';\n document.body.style.userSelect = 'none';\n });\n\n const handleResize = (e) => {\n if (!isResizing) return;\n const newWidth = startWidth + (e.clientX - startX);\n if (newWidth > 30) { // Minimum width\n header.style.width = newWidth + 'px';\n\n // Set the same width on all cells in this column\n const columnIndex = Array.from(header.parentNode.children).indexOf(header);\n const tbody = table.querySelector('tbody');\n if (tbody) {\n const rows = tbody.querySelectorAll('tr');\n rows.forEach(row => {\n const cell = row.children[columnIndex];\n if (cell) {\n cell.style.width = newWidth + 'px';\n }\n });\n }\n\n // Update table width if column width increased\n this.updateTableWidth(table);\n }\n };\n\n const stopResize = () => {\n isResizing = false;\n\n // Remove visual feedback\n header.style.borderRight = '';\n header.style.background = '';\n\n document.removeEventListener('mousemove', handleResize);\n document.removeEventListener('mouseup', stopResize);\n document.body.style.cursor = '';\n document.body.style.userSelect = '';\n };\n }\n\n /**\n * Add drag and drop functionality to a header\n */\n addDragAndDrop(header, table, tableIndex, columnIndex) {\n if (header.querySelector('.drag-handle')) {\n return;\n }\n\n header.classList.add(this.options.draggableClass);\n header.draggable = true;\n\n const thead = table.querySelector('thead tr');\n\n header.addEventListener('dragstart', (e) => {\n this.isDragging = true;\n // Store the current DOM position, not the original column index\n const currentPosition = Array.from(thead.children).indexOf(header);\n this.dragSource = { table, tableIndex, columnIndex: currentPosition };\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/html', header.outerHTML);\n const headerContent = header.outerHTML;\n header.style.opacity = '0.5';\n\n // Create a custom drag image\n this.createCustomDragImage(e, header, headerContent);\n });\n\n header.addEventListener('dragend', (e) => {\n this.isDragging = false;\n this.dragSource = null;\n header.style.opacity = '';\n // Remove all column highlights\n this.clearAllColumnHighlights(table);\n });\n\n header.addEventListener('dragover', (e) => {\n e.preventDefault();\n e.dataTransfer.dropEffect = 'move';\n });\n\n header.addEventListener('dragenter', (e) => {\n e.preventDefault();\n if (this.dragSource && this.dragSource.tableIndex === tableIndex) {\n const currentColumnIndex = Array.from(thead.children).indexOf(header);\n if (this.dragSource.columnIndex !== currentColumnIndex) {\n // Add visual feedback to the entire column\n this.highlightColumn(table, currentColumnIndex, true);\n }\n }\n });\n\n header.addEventListener('dragleave', (e) => {\n // Only remove highlight if we're leaving the entire column\n if (!header.contains(e.relatedTarget)) {\n const currentColumnIndex = Array.from(thead.children).indexOf(header);\n this.highlightColumn(table, currentColumnIndex, false);\n }\n });\n\n header.addEventListener('drop', (e) => {\n e.preventDefault();\n\n if (this.dragSource && this.dragSource.tableIndex === tableIndex) {\n const currentColumnIndex = Array.from(thead.children).indexOf(header);\n if (this.dragSource.columnIndex !== currentColumnIndex) {\n this.reorderColumns(table, tableIndex, this.dragSource.columnIndex, currentColumnIndex);\n }\n }\n\n // Remove all column highlights\n this.clearAllColumnHighlights(table);\n });\n }\n\n /**\n * Create a custom drag image for better UX\n */\n createCustomDragImage(e, header, headerContent) {\n // Create a temporary element for the drag image\n const dragImage = document.createElement('div');\n dragImage.style.cssText = `\n position: absolute;\n top: -1000px;\n left: -1000px;\n background: var(--background-elevated, #333);\n border: 2px solid var(--primary-main, #2196F3);\n border-radius: 4px;\n padding: 8px 12px;\n font-size: 12px;\n font-weight: bold;\n color: var(--text-primary, #fff);\n white-space: nowrap;\n max-width: 150px;\n min-width: 60px;\n overflow: hidden;\n text-overflow: ellipsis;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\n z-index: 10000;\n pointer-events: none;\n min-height: 50px;\n display: flex;\n align-items: center;\n `;\n\n // Get the header text without icons and create a compact representation\n const headerText = headerContent;\n dragImage.innerHTML = `\n <div style=\"display: flex; align-items: center; gap: 5px; align-content: center;color:white;\">\n <span style=\"overflow: hidden; text-overflow: ellipsis\">${headerText}</span>\n <svg style=\"fill: grey; font-size: 10px\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" ><defs><path id=\"a\" d=\"M0 0h24v24H0V0z\"/></defs><clipPath id=\"b\"><use xlink:href=\"#a\" overflow=\"visible\"/></clipPath><path clip-path=\"url(#b)\" d=\"M9.01 14H2v2h7.01v3L13 15l-3.99-4v3zm5.98-1v-3H22V8h-7.01V5L11 9l3.99 4z\"/></svg>\n </div> \n `;\n\n // Add to document temporarily\n document.body.appendChild(dragImage);\n\n // Set as drag image with centered offset\n e.dataTransfer.setDragImage(dragImage, 50, 12);\n\n // Clean up after a short delay\n setTimeout(() => {\n if (document.body.contains(dragImage)) {\n document.body.removeChild(dragImage);\n }\n }, 100);\n }\n\n\n\n /**\n * Highlight an entire column during drag operations\n */\n highlightColumn(table, columnIndex, highlight) {\n const thead = table.querySelector('thead tr');\n const tbody = table.querySelector('tbody');\n\n if (!thead || !tbody) return;\n\n const header = thead.children[columnIndex];\n if (!header) return;\n\n if (highlight) {\n header.classList.add(this.options.dragOverClass);\n // Highlight all cells in this column\n const rows = tbody.children;\n for (let i = 0; i < rows.length; i++) {\n const cell = rows[i].children[columnIndex];\n if (cell) {\n cell.classList.add(this.options.dragOverClass);\n }\n }\n } else {\n header.classList.remove(this.options.dragOverClass);\n // Remove highlight from all cells in this column\n const rows = tbody.children;\n for (let i = 0; i < rows.length; i++) {\n const cell = rows[i].children[columnIndex];\n if (cell) {\n cell.classList.remove(this.options.dragOverClass);\n }\n }\n }\n }\n\n /**\n * Clear all column highlights\n */\n clearAllColumnHighlights(table) {\n const thead = table.querySelector('thead tr');\n const tbody = table.querySelector('tbody');\n\n if (!thead || !tbody) return;\n\n // Clear header highlights\n const headers = thead.children;\n for (let i = 0; i < headers.length; i++) {\n headers[i].classList.remove(this.options.dragOverClass);\n }\n\n // Clear cell highlights\n const rows = tbody.children;\n for (let i = 0; i < rows.length; i++) {\n const cells = rows[i].children;\n for (let j = 0; j < cells.length; j++) {\n cells[j].classList.remove(this.options.dragOverClass);\n }\n }\n }\n\n /**\n * Reorder columns in a table\n */\n reorderColumns(table, tableIndex, fromIndex, toIndex) {\n const thead = table.querySelector('thead tr');\n const tbody = table.querySelector('tbody');\n\n if (!thead || !tbody) return;\n\n const headers = Array.from(thead.children);\n const rows = Array.from(tbody.children);\n\n // Validate indices\n if (fromIndex < 0 || fromIndex >= headers.length || toIndex < 0 || toIndex >= headers.length) {\n console.warn('Invalid column indices for reordering');\n return;\n }\n\n // Don't do anything if dropping on the same position\n if (fromIndex === toIndex) {\n return;\n }\n\n // Move the header element directly in the DOM\n const headerToMove = headers[fromIndex];\n const targetHeader = headers[toIndex];\n\n if (fromIndex < toIndex) {\n // Moving right: insert after target\n thead.insertBefore(headerToMove, targetHeader.nextSibling);\n } else {\n // Moving left: insert before target\n thead.insertBefore(headerToMove, targetHeader);\n }\n\n // Move cells in each row\n rows.forEach((row, rowIndex) => {\n const cells = Array.from(row.children);\n const cellToMove = cells[fromIndex];\n const targetCell = cells[toIndex];\n\n if (fromIndex < toIndex) {\n // Moving right: insert after target\n row.insertBefore(cellToMove, targetCell.nextSibling);\n } else {\n // Moving left: insert before target\n row.insertBefore(cellToMove, targetCell);\n }\n });\n\n // Update column order tracking\n const currentOrder = this.originalColumnOrder.get(tableIndex);\n if (currentOrder) {\n const newOrder = [...currentOrder];\n const columnToMove = newOrder[fromIndex];\n newOrder.splice(fromIndex, 1);\n newOrder.splice(toIndex, 0, columnToMove);\n this.originalColumnOrder.set(tableIndex, newOrder);\n }\n\n // Reapply inline styles after reordering\n this.applyTableStyles(table);\n\n // Refresh drag and drop listeners for the reordered columns\n this.refreshDragAndDropListeners(table, tableIndex);\n }\n\n /**\n * Refresh drag and drop listeners after column reordering\n */\n refreshDragAndDropListeners(table, tableIndex) {\n const thead = table.querySelector('thead tr');\n if (!thead) return;\n\n const headers = Array.from(thead.children);\n\n // Remove existing listeners by cloning headers and re-adding all functionality\n headers.forEach((header, columnIndex) => {\n if (header.classList.contains(this.options.draggableClass)) {\n // Clear any drag-related inline styles before cloning\n header.style.opacity = '';\n header.style.background = '';\n header.style.borderRight = '';\n\n const newHeader = header.cloneNode(true);\n header.parentNode.replaceChild(newHeader, header);\n\n // Re-add all functionality (sorting, resizing, drag and drop)\n this.makeHeaderSortable(newHeader, table, tableIndex, columnIndex);\n }\n });\n }\n\n /**\n * Update table width based on current column widths\n */\n updateTableWidth(table) {\n const headers = table.querySelectorAll('th');\n let totalWidth = 0;\n\n headers.forEach(header => {\n const width = header.style.width;\n if (width) {\n const widthValue = parseInt(width.replace('px', ''));\n totalWidth += widthValue;\n } else {\n // Fallback to estimated width if no explicit width set\n const text = header.textContent.replace(/[📊🔍]/g, '').trim();\n totalWidth += text.length;\n }\n });\n\n // Convert to percentage\n table.style.width = `${totalWidth}px`;\n }\n\n /**\n * Calculate intelligent table width based on header text length\n */\n calculateTableWidth(table) {\n const originalWidthAttr = table.getAttribute('data-original-width');\n const originalWidth = originalWidthAttr ? parseFloat(originalWidthAttr) : 0;\n const headers = table.querySelectorAll('th');\n let totalWidth = 0;\n\n const parentWidth = table.parentElement.clientWidth\n\n const headersWidth = [];\n headers.forEach(header => {\n // Get text content without icons\n const text = header.textContent.replace(/[📊🔍]/g, '').trim();\n\n let estimatedWidth = text.length * this.charWidth + 15;\n\n headersWidth.push(estimatedWidth);\n\n totalWidth += estimatedWidth;\n });\n\n const rows = table.querySelectorAll('tr');\n\n const containerWidth = table.parentElement?.getBoundingClientRect().width ?? totalWidth;\n\n var maxRowWidth = 0;\n for (const row of rows) {\n const cells = row.querySelectorAll('td');\n\n cells.forEach((cell, index) => {\n // Get text content without icons\n const text = cell.textContent;\n\n const cellWidth = text.length * this.charWidth + 15;\n if (cellWidth > headersWidth[index] && index < headersWidth.length)\n headersWidth[index] = cellWidth;\n });\n };\n\n maxRowWidth = headersWidth.reduce((prev, current) => prev += current, 0);\n\n headers.forEach((header, index) => {\n if (maxRowWidth > containerWidth) {\n const factor = headersWidth[index] / maxRowWidth;\n header.style.width = `${containerWidth * factor}px`\n }\n else {\n header.style.width = `${headersWidth[index]}px`\n }\n });\n\n // Convert to percentage or pixel value\n let finalWidth = 0\n if (maxRowWidth > containerWidth) {\n finalWidth = `100%`\n }\n else {\n // If the calculated width would shrink the table below its\n // pre-transform rendered width, preserve the original.\n const effectiveWidth = Math.max(maxRowWidth, originalWidth);\n finalWidth = `${effectiveWidth}px`;\n }\n\n return finalWidth;\n }\n\n /**\n * Apply inline styles to ensure text clipping and horizontal scroll work\n */\n applyTableStyles(table) {\n // Force table styles\n const calculatedWidth = this.calculateTableWidth(table);\n // The \"fits comfortably\" branch of calculateTableWidth used\n // to force width: 100%, which made every chat table stretch\n // edge-to-edge regardless of content. Instead, let the table\n // be content-fit (auto) but floor it at 60% of the container\n // so very narrow tables don't look orphaned next to the\n // chat gutter, and cap it at 100% so wider data still fits.\n // The overflow branch still uses the calculated pixel width\n // because it's already wider than the container would allow.\n table.style.width = calculatedWidth;\n table.style.maxWidth = '100%';\n // if (calculatedWidth === '100%') {\n // table.style.width = 'auto';\n // table.style.minWidth = '60%';\n // table.style.maxWidth = '100%';\n // } else {\n // table.style.width = `${calculatedWidth}`;\n // table.style.minWidth = 'auto';\n // table.style.maxWidth = 'auto';\n // }\n // table.style.tableLayout = 'fixed'; // Use fixed layout to respect manual widths\n }\n\n /** Fallback advance width, in px, for one character of the body font. */\n static DEFAULT_CHAR_WIDTH = 8;\n\n // Signature matches the single call site — `init()` passes (fontFamily,\n // fontMono), which used to land on a leading `char` parameter nothing read.\n getCharWidth(font, mono) {\n const context = document.createElement(\"canvas\").getContext(\"2d\");\n\n // No 2D context: a headless DOM, or a browser that refused one. This\n // runs on a 500ms timer after the chat mounts, so a throw here lands\n // outside every call stack that could catch it — it took down the test\n // runner from the macrotask queue.\n if (!context) return SortableTable.DEFAULT_CHAR_WIDTH;\n\n context.fontFamily = font;\n context.fontMono = mono;\n\n // Measure the specific character\n const metrics = context.measureText(\"A \");\n return metrics.width; // Returns width in pixels\n }\n\n /**\n * Add CSS styles for sortable tables\n */\n addStyles() {\n if (document.getElementById('sortable-table-styles')) {\n return; // Styles already added\n }\n\n const style = document.createElement('style');\n style.id = 'sortable-table-styles';\n style.textContent = ` \n .${this.options.sortableClass} {\n position: relative;\n user-select: none;\n transition: background-color 0.2s ease;\n }\n \n .${this.options.sortableClass}:hover {\n background-color: ${this.options.theme.palette.surface.hover} !important;\n }\n \n .${this.options.activeSortClass} {\n background-color: ${this.options.theme.palette.surface.raised} !important;\n font-weight: bold;\n }\n \n .${this.options.ascendingClass} {\n border-bottom: 2px solid var(${this.options.theme.palette.primary.main}, #3a3a3a);\n }\n \n .${this.options.descendingClass} {\n border-bottom: 2px solid var(${this.options.theme.palette.primary.main}, #3a3a3a);\n }\n \n .${this.options.sortableClass} .material-icons {\n transition: opacity 0.2s ease, transform 0.2s ease;\n }\n \n .${this.options.activeSortClass} .material-icons {\n color: var(${this.options.theme.palette.primary.main}, #3a3a3a);\n }\n \n .${this.options.resizableClass} .resize-handle:hover {\n background-color: var(${this.options.theme.palette.primary.light}, #64B5F6);\n }\n \n .${this.options.draggableClass} {\n cursor: move;\n position: relative;\n }\n \n .${this.options.draggableClass}::before {\n content: '';\n position: absolute;\n top: 0;\n left: -5px;\n right: -5px;\n bottom: 0;\n z-index: 1;\n pointer-events: none;\n }\n \n .${this.options.dragOverClass} {\n background-color: rgba(128, 128, 128, 0.2) !important;\n border: 2px dashed rgba(128, 128, 128, 0.8);\n }\n \n .${this.options.draggableClass}:hover {\n background-color: var(${this.options.theme.palette.surface.raised}, rgba(100, 181, 246, 0.1)) !important;\n }\n\n .sortable-table tbody td {\n width: auto\n } \n\n .sortable-table {\n /* Cross-fade bg/row stripes when the .sortable-table\n * class flip lands on a freshly-streamed markdown\n * table. Width is NOT animated: column widths set\n * by calculateTableWidth can be narrower than the\n * content currently fills, so animating them down\n * causes mid-transition cell wrap. Snap widths,\n * animate only colours. */\n transition: background-color 280ms ease-out; \n }\n\n .sortable-table th {\n transition: background-color 280ms ease-out;\n }\n\n /* Zebra striping for table rows */\n .sortable-table tbody tr:nth-child(odd) {\n background-color: ${this.options.theme.palette.background.defalt};\n color: ${this.options.theme.palette.text.primary};\n }\n\n .sortable-table tbody tr:nth-child(even) {\n background-color: ${this.options.theme.palette.background.defalt};\n color: ${this.options.theme.palette.text.primary};\n }\n\n /* One-shot arrival animation. Applied via a transient\n * class (added by makeTableSortable on first mount only)\n * so it does NOT re-fire on every destroy/init cycle.\n * scaleX with origin top-left gives the \"right edge\n * grows outward\" feel the user asked for; the 0.96\n * start is subtle enough that text compression isn't\n * obvious. */\n @keyframes sortable-table-arrive {\n from {\n opacity: 0.35;\n transform: scaleX(0.96);\n transform-origin: top left;\n }\n to {\n opacity: 1;\n transform: scaleX(1);\n }\n }\n\n .sortable-table-arriving {\n animation: sortable-table-arrive 320ms cubic-bezier(0.16, 1, 0.3, 1) both;\n }\n \n /* Ensure hover effects work with zebra striping */\n .sortable-table tbody tr:hover {\n background-color: ${this.options.theme.palette.surface.hover} !important;\n }\n \n \n /* Fix table-container overflow issue */\n .table-container {\n overflow: auto !important;\n overflow-x: auto !important;\n overflow-y: auto !important;\n }\n `;\n\n const existingStyle = document.getElementById('sortable-table-styles');\n if (!existingStyle) {\n document.head.appendChild(style);\n }\n }\n\n /**\n * Destroy the sortable functionality\n */\n destroy() {\n this.tables.forEach(table => {\n const headers = table.querySelectorAll(`.${this.options.sortableClass}`);\n headers.forEach(header => {\n header.classList.remove(\n this.options.sortableClass,\n this.options.activeSortClass,\n this.options.ascendingClass,\n this.options.descendingClass\n );\n header.style.cursor = '';\n header.style.background = '';\n\n // Remove event listeners by cloning the element\n const newHeader = header.cloneNode(true);\n header.parentNode.replaceChild(newHeader, header);\n });\n });\n\n // Remove styles\n const styleElement = document.getElementById('sortable-table-styles');\n if (styleElement) {\n styleElement.remove();\n }\n\n this.tables = [];\n this.sortStates.clear();\n initializedTables.clear();\n }\n\n /**\n * Refresh the library (useful after DOM changes)\n */\n refresh() {\n this.destroy();\n this.init();\n }\n}\n\n// // Create global instance but don't auto-initialize\n// Guard the global assignment so this module is import-safe outside the\n// browser (Node/SSR/tests). Importing it for the class export alone — as the\n// session-replay decode path does transitively — must not throw on `window`.\nif (typeof window !== 'undefined') {\n window.SortableTable = SortableTable;\n}\n\n// Export for module systems\nexport default SortableTable;\n","// Shared prompt-overlay helpers used by both the chat composer (PromptV2) and the home composer (obtapp's\n// PromptComposer): tokenize a draft into chip/plain runs, and chip server-mapped locations inline like \"@\" mentions.\n\nexport type HighlightToken = { type: 'plain' | 'slash' | 'at' | 'hash' | 'placeholder'; text: string };\n\nconst TRIGGER_CHARS: ReadonlySet<string> = new Set(['/', '@', '#']);\nconst triggerTypeFor = (ch: string): 'slash' | 'at' | 'hash' =>\n ch === '/' ? 'slash' : ch === '@' ? 'at' : 'hash';\n// A token boundary is ASCII whitespace only — NOT the non-breaking space (U+00A0). Hosts join a multi-word\n// \"@mention\" (e.g. \"@São Paulo\") with NBSPs so the whole name stays a single chip; a regular space separates tokens.\nconst HIGHLIGHT_WS = /[ \\t\\r\\n\\f\\v]/;\n// Template placeholders (#447): `[@origem]` / `[#data]` / `[texto livre]` — same shape promptTriggers parses.\nconst PLACEHOLDER_G = /\\[[^\\]\\n]+\\]/g;\n\n/** The pre-#447 tokenizer, over one placeholder-free segment. `prevCh` is the char just before the segment in the\n * full text (undefined at the very start) — it decides whether a trigger at the segment's first index leads its\n * own token, so a `@` right after a `]` stays plain exactly as it would mid-string. */\nconst tokenizeSegment = (text: string, prevCh: string | undefined, tokens: HighlightToken[]): void => {\n let i = 0;\n const boundaryBefore = (idx: number): boolean => {\n const prev = idx === 0 ? prevCh : text[idx - 1];\n return prev === undefined || HIGHLIGHT_WS.test(prev);\n };\n while (i < text.length) {\n const ch = text[i];\n if (boundaryBefore(i) && TRIGGER_CHARS.has(ch)) {\n let end = i + 1;\n while (end < text.length && !HIGHLIGHT_WS.test(text[end])) end += 1;\n tokens.push({ type: triggerTypeFor(ch), text: text.slice(i, end) });\n i = end;\n } else {\n let end = i + 1;\n while (end < text.length) {\n const c = text[end];\n if (TRIGGER_CHARS.has(c) && HIGHLIGHT_WS.test(text[end - 1])) break;\n end += 1;\n }\n tokens.push({ type: 'plain', text: text.slice(i, end) });\n i = end;\n }\n }\n};\n\n/**\n * Splits `text` into a flat list of runs so the overlay can paint chip styling around `/cmd` / `@user` / `#date`\n * tokens while keeping surrounding text plain. Boundary rule mirrors the autocomplete trigger detection (trigger\n * char at line start or after whitespace), so a `/` inside `http://` or `@` inside an email stays plain.\n * `[bracketed placeholders]` (#447) pre-empt the whitespace walk — they may contain spaces and become their own\n * `placeholder` runs, which hosts paint as \"fill me\" chips (and may make tappable).\n */\nexport const tokenizeForHighlight = (text: string): HighlightToken[] => {\n if (!text) return [];\n const tokens: HighlightToken[] = [];\n const re = new RegExp(PLACEHOLDER_G.source, 'g');\n let last = 0;\n for (let m = re.exec(text); m; m = re.exec(text)) {\n if (m.index > last) tokenizeSegment(text.slice(last, m.index), last === 0 ? undefined : text[last - 1], tokens);\n tokens.push({ type: 'placeholder', text: m[0] });\n last = m.index + m[0].length;\n }\n if (last < text.length) tokenizeSegment(text.slice(last), last === 0 ? undefined : text[last - 1], tokens);\n return tokens;\n};\n\n/**\n * Second pass: chip the locations the slow pass mapped (pasted / dictated, no typed \"@\") as if they were \"@\"\n * mentions — same inline chip style. Only PLAIN runs are scanned (real \"@\" mentions are already their own chips);\n * longest names win so \"São Paulo\" beats \"São\".\n */\nexport const chipLocations = (tokens: HighlightToken[], locTexts: readonly string[]): HighlightToken[] => {\n const needles = locTexts.filter((t) => t.trim().length > 0).sort((a, b) => b.length - a.length);\n if (needles.length === 0) return tokens;\n const out: HighlightToken[] = [];\n for (const tok of tokens) {\n if (tok.type !== 'plain') { out.push(tok); continue; }\n let rest = tok.text;\n while (rest.length > 0) {\n let at = -1;\n let len = 0;\n for (const n of needles) {\n const idx = rest.indexOf(n);\n if (idx >= 0 && (at === -1 || idx < at)) { at = idx; len = n.length; }\n }\n if (at === -1) { out.push({ type: 'plain', text: rest }); break; }\n if (at > 0) out.push({ type: 'plain', text: rest.slice(0, at) });\n out.push({ type: 'at', text: rest.slice(at, at + len) });\n rest = rest.slice(at + len);\n }\n }\n return out;\n};\n","/**\n * Put the caret somewhere and make it stay there (issue #422).\n *\n * `setSelectionRange` is enough on a desktop browser. It is not enough on iOS after a TOUCH pick: the tap blurs the\n * textarea on the way in, and when we focus back WebKit restores the selection IT remembers — asynchronously, on\n * its own schedule, after our call has already run. The caret snapped back to where the user's query had been\n * (\"Busque voos saindo de @sao\" → index 26) instead of sitting after the mention just spliced in, which put it\n * visibly inside the chip: `@(SA|O) São Paulo`.\n *\n * A one-shot re-place on the next frame was not enough either — the restore can land after the keyboard animation\n * starts. So this keeps asserting the position for a short window and stops the moment it is no longer wanted:\n *\n * - the value changed → some other edit owns the caret now;\n * - the user typed, tapped or pressed a key → their intent wins over ours, immediately;\n * - the window expired.\n *\n * Everywhere other than iOS the first assignment sticks and the watcher simply expires having done nothing.\n */\nexport function placeCaret(\n textarea: HTMLTextAreaElement,\n start: number,\n end: number = start,\n insistMs = 600,\n): () => void {\n const expected = textarea.value;\n let done = false;\n\n const stop = () => {\n if (done) return;\n done = true;\n document.removeEventListener('selectionchange', onSelectionChange);\n textarea.removeEventListener('keydown', stop);\n textarea.removeEventListener('input', stop);\n textarea.removeEventListener('pointerdown', stop);\n window.clearTimeout(timer);\n window.clearInterval(ticker);\n };\n\n const apply = () => {\n // Someone else edited the field — whatever they did outranks a caret we queued for a previous value.\n if (textarea.value !== expected) { stop(); return; }\n if (textarea.selectionStart === start && textarea.selectionEnd === end) return;\n textarea.setSelectionRange(start, end);\n };\n\n // `selectionchange` is what fires when WebKit restores its own position, so it is the direct signal to undo.\n // The interval covers browsers that move the caret without firing it.\n const onSelectionChange = () => { if (document.activeElement === textarea) apply(); };\n\n apply();\n\n const timer = window.setTimeout(stop, insistMs);\n const ticker = window.setInterval(apply, 50);\n document.addEventListener('selectionchange', onSelectionChange);\n // Any real interaction ends the argument — we must never fight a user who is repositioning their own caret.\n textarea.addEventListener('keydown', stop);\n textarea.addEventListener('input', stop);\n textarea.addEventListener('pointerdown', stop);\n\n return stop;\n}\n","/**\n * Eat the compatibility `click` that follows a `pointerdown`/`touchend` you have already acted on.\n *\n * A touch that lands on a control which then unmounts (or opens something over the spot) leaves the\n * browser's synthesised click to fall on **whatever is now under the finger** — that is how picking a\n * location once sent the prompt, the send button having slid under the tap. The same click is also\n * what a `<ClickAwayListener>` sees as \"the user clicked outside\", so a surface opened during\n * `pointerdown` is closed again microseconds later by the click of the very gesture that opened it.\n *\n * Cancelling `pointerdown` would suppress the compatibility events, but on touch that also kills\n * scrolling — so the click is intercepted instead.\n *\n * Capture phase, so it never reaches the target (or a document-level away-listener); self-removing,\n * and time-boxed in case no click arrives at all (the browser is not obliged to send one).\n *\n * `mousedown: true` eats the gesture's compatibility `mousedown` as well. Pass it when you act on\n * `pointerUP`: that mousedown arrives after your handler has already re-rendered, and its default\n * action — move focus, place the caret — lands on whatever is under the finger NOW. On Android that\n * is how a `/`-template pick lost its caret: the pick put the caret after the template's `@` and\n * opened the docked `@` panel in the spot the command list had just vacated, and the tap's mousedown\n * then hit that panel, blurring the textarea (keyboard down, caret gone), or hit the textarea itself\n * and re-homed the caret to the tap point. iOS never showed it — WebKit does not move focus to a\n * non-focusable element on tap. A new `pointerdown` disarms it, so a genuine next tap is never eaten.\n */\nexport function swallowNextClick(options: { mousedown?: boolean } = {}) {\n if (typeof document === 'undefined') return;\n const onClick = (e: Event) => {\n e.stopPropagation();\n e.preventDefault();\n cleanup();\n };\n const onMouseDown = (e: Event) => {\n e.stopPropagation();\n e.preventDefault();\n document.removeEventListener('mousedown', onMouseDown, true);\n };\n const cleanup = () => {\n document.removeEventListener('click', onClick, true);\n document.removeEventListener('mousedown', onMouseDown, true);\n document.removeEventListener('pointerdown', cleanup, true);\n window.clearTimeout(timer);\n };\n const timer = window.setTimeout(cleanup, 500);\n document.addEventListener('click', onClick, true);\n if (options.mousedown) {\n document.addEventListener('mousedown', onMouseDown, true);\n // The compatibility events of THIS gesture all precede the next one's pointerdown.\n document.addEventListener('pointerdown', cleanup, true);\n }\n}\n","// Shared `@`-mention logic (issue #112) — the source-fetching + Pessoas/Locais sectioning used by BOTH the\n// library's PromptV2 and the obtapp home PromptComposer, so the two `@` implementations don't drift. Rendering\n// stays per-component (each has its own popover markup); only the fetch + grouping + ordering is shared here.\n\nimport type { PromptTriggerItem } from '../components/v2/PromptV2';\n\n/** `'hotel'` (Issue 1139): rows the location source tagged `kind: 'hotel'` — catalog hotels by NAME — get their own\n * section (\"Hotéis\") instead of hiding under \"Locais\", because they come from a different source (TripApi\n * `GET /hotel/names/search`) and lead the list when the server's hotel-name head fires. */\nexport type MentionGroup = 'person' | 'location' | 'hotel';\n\n/** A trigger item tagged with the `@` section it belongs to. Undefined `group` ⇒ render flat (single source). */\nexport type AtMentionItem = PromptTriggerItem & { group?: MentionGroup };\n\n/** How many rows the LEADING section keeps when a slot reads as a place AND a person (`capLeading`): few enough\n * that the other section's first rows are inside a ~5-row dropdown (Ciro, 2026-10-04). Typing narrows both. */\nexport const PERSON_OR_PLACE_LEAD_ROWS = 3;\n\n/** Which vertical the location source should search (issue #876): 'hotel' → hotel places (POIs, addresses,\n * landmarks — TripApi /hotel/locations/search), 'air' → airports/cities as before. From the server's hotel-intent\n * head via the analyze pass — never re-decided client-side. */\nexport type AtQueryVertical = 'air' | 'hotel';\n\n/** Context handed to the location source alongside the query (issue #876). A second PARAMETER (not a second\n * fetcher) so hosts that don't care keep compiling untouched — a function with fewer params is assignable. */\nexport interface AtQueryContext {\n vertical: AtQueryVertical;\n /** The hotel-intent head's SCORE for the current text (0..1), not the thresholded verdict. `vertical` is that\n * score already cut at the server's 0.35; a source that merges two result sets needs the number, because the\n * cut is where \"weakest place outranks strongest airport\" flips on one hundredth of a point. Undefined only\n * when the host predates this field. */\n hotelConfidence?: number;\n /** The hotel-NAME head's score (Issue 1139): P(the traveller is naming a specific hotel — \"reserve o hotel |\").\n * At or above the server's 0.5 the location source leads with catalog hotel names (`kind: 'hotel'` rows) and\n * keeps places and airports below. Undefined when the host or the server predates the head. */\n hotelNameConfidence?: number;\n /** Aborted when this query is superseded (the next keystroke) — pass it to the HTTP calls so a stale search stops\n * competing with the current one. Undefined when the host predates it. */\n signal?: AbortSignal;\n /** A source that merges several result sets of its own can report its list so far, as each one lands, instead of\n * holding the fast ones back behind the slowest. Each call REPLACES the source's previous list; the promise's\n * value is still the final one. Optional on both sides: a source that never calls it simply arrives once. */\n onPartial?: (items: PromptTriggerItem[]) => void;\n /** Report partials in PRIORITY order rather than arrival order: only a prefix of the list whose sections are all\n * final, and never an empty one. Set while the picker already shows rows — there a partial replaces a full list,\n * so a fast low-priority source drawing first makes the list flicker on every keystroke. Off for the first\n * render, where arrival order is simply the fastest paint. */\n byPriority?: boolean;\n}\n\n/** Context handed to the person source (2026-09-11) — the mirror of {@link AtQueryContext} for the other half. */\nexport interface AtPersonQueryContext {\n /** This source's rows will LEAD the list (person-intent won). A blank query then wants a full page of the\n * directory rather than the handful that fits under a place list — Ciro asked for a top 20. */\n leading: boolean;\n /** See {@link AtQueryContext.signal}. */\n signal?: AbortSignal;\n}\n\nexport interface AtMentionFetchers {\n /** Location source (airports / cities — or hotel places when `context.vertical` says so, issue #876). */\n onAtQuery?: (query: string, context?: AtQueryContext) => Promise<PromptTriggerItem[]>;\n /** Person / passenger source (company directory). */\n onAtPersonQuery?: (query: string, context?: AtPersonQueryContext) => Promise<PromptTriggerItem[]>;\n}\n\nexport interface AtMentionOptions {\n /** Person-intent confidence from the analyze pass; orders the two sections. Default 0. */\n personConfidence?: number;\n /** Location-intent confidence from the analyze pass. When location outweighs person, the Locais section leads —\n * so an `@` accepted from a location context (\"voos saindo de @\") searches PLACES, not people. Default 0. */\n locationConfidence?: number;\n /** Confidence at/above which the person section MAY lead (it still only wins if it also outweighs location). Default 0.5. */\n personFirstThreshold?: number;\n /** The search vertical for the location source (issue #876). Default 'air' — today's behavior. */\n vertical?: AtQueryVertical;\n /** Hotel-intent confidence from the analyze pass, handed to the location source alongside `vertical` so it can\n * order its own two result sets by a score rather than by a verdict someone else thresholded. Default 0. */\n hotelConfidence?: number;\n /** Hotel-NAME confidence from the analyze pass (Issue 1139), handed to the location source the same way. Default 0. */\n hotelNameConfidence?: number;\n /** Aborted when the query is superseded; handed to both sources. */\n signal?: AbortSignal;\n /** Keep only this many rows of the LEADING source, so the other section is in view (2026-10-04). Hosts set it\n * when the slot reads as a place AND a person (`usePromptAssist().personOrPlace`): ordering alone put the\n * directory under every location row — 8 airports, 5 places, 3 hotel names — below a ~5-row dropdown. The\n * trailing source is not cut: it is the one the cap exists to bring into view. Undefined = no cap. */\n capLeading?: number;\n /** Called with the merged list every time a source (or part of one, via `onPartial`) lands, so the host can\n * draw rows as they arrive rather than when the slowest source answers. Never called after `signal` aborts. */\n onUpdate?: (items: AtMentionItem[]) => void;\n /** Draw by priority, not arrival (see {@link AtQueryContext.byPriority}): `onUpdate` fires only once the LEADING\n * source has rows, the trailing source only once the leading one is final, and never with an empty list — so\n * a list already on screen is held until the new one can replace it top-down, then only grows downward. */\n byPriority?: boolean;\n}\n\n/**\n * Fetch `@` mention items from whichever sources are wired, as one flat list. When BOTH a location and a person\n * source are present, items are tagged with their `group` and ordered by intent — the Pessoas section leads only\n * when person-intent both clears its threshold AND outweighs location-intent; otherwise Locais leads. This means an\n * `@` opened in a clear location context (\"voos saindo de @\") searches PLACES first even though `@` is dual-purpose.\n * A single wired source returns an untagged flat list (unchanged behaviour). Each source is awaited in parallel and\n * failures are isolated: one source erroring never sinks the other.\n *\n * The section ORDER is decided before anything is fetched, so it holds while rows stream in through `onUpdate`: a\n * source that answers late fills its own slot rather than reshuffling the list. With `byPriority` it does not even\n * do that: nothing is drawn above rows already drawn. The returned promise still resolves once, with the complete\n * list, for hosts that don't stream.\n */\nexport async function fetchAtMentions(\n query: string,\n { onAtQuery, onAtPersonQuery }: AtMentionFetchers,\n { personConfidence = 0, locationConfidence = 0, personFirstThreshold = 0.5, vertical = 'air', hotelConfidence = 0,\n hotelNameConfidence = 0, signal, onUpdate, byPriority = false, capLeading }: AtMentionOptions = {},\n): Promise<AtMentionItem[]> {\n // Decided BEFORE the fetch, not after: the leading source is told it leads, so it can size its own answer.\n // Same inputs the ordering below uses, so the two can never disagree.\n const personFirst = personConfidence >= personFirstThreshold && personConfidence >= locationConfidence;\n let locItems: PromptTriggerItem[] = [];\n let perItems: PromptTriggerItem[] = [];\n // A source that is not wired is final from the start.\n let locDone = !onAtQuery;\n let perDone = !onAtPersonQuery;\n let lastKey: string | null = null;\n // Only meaningful with both sources wired: a lone source has nothing to make room for. And only while the\n // OTHER section can still have rows: once it has answered empty (a guest, a company with no directory), the\n // cap would cut the only list there is for nothing, so it lifts — the list then grows downward, the direction\n // that does not move what is already drawn.\n const cap = (items: PromptTriggerItem[], leading: boolean, other: PromptTriggerItem[], otherDone: boolean) =>\n leading && capLeading !== undefined && onAtQuery && onAtPersonQuery && !(otherDone && other.length === 0)\n ? items.slice(0, capLeading) : items;\n const merge = (allLoc: PromptTriggerItem[], allPer: PromptTriggerItem[]): AtMentionItem[] => {\n const locItems = cap(allLoc, !personFirst, allPer, perDone);\n const perItems = cap(allPer, personFirst, allLoc, locDone);\n // A directory row is a person whatever the source said (Issue 1139) — the icon must not depend on every host\n // remembering to tag it. Location rows keep the source's kind: only it knows an airport from a place from a hotel.\n const people: PromptTriggerItem[] = perItems.map((i) => (i.kind ? i : { ...i, kind: 'person' as const }));\n if (onAtQuery && onAtPersonQuery) {\n const per: AtMentionItem[] = people.map((i) => ({ ...i, group: 'person' }));\n // Hotel NAMES section on their own (Issue 1139); everything else the location source returned is \"Locais\".\n const loc: AtMentionItem[] = locItems.map((i) => ({ ...i, group: i.kind === 'hotel' ? 'hotel' : 'location' }));\n return personFirst ? [...per, ...loc] : [...loc, ...per];\n }\n return [...people, ...locItems];\n };\n const publish = () => {\n if (!onUpdate || signal?.aborted) return;\n if (!byPriority) { onUpdate(merge(locItems, perItems)); return; }\n // The leading source's rows go first; the trailing source's only once the leading one is FINAL, or a late\n // section of the leader would land between them. (Location partials are already a final-sections prefix.)\n const shown = personFirst\n ? merge(perDone ? locItems : [], perItems)\n : merge(locItems, locDone ? perItems : []);\n if (shown.length === 0 && !(locDone && perDone)) return;\n const key = shown.map((i) => i.id).join('\\n');\n if (key === lastKey) return; // a held source landing changes nothing on screen — no re-render\n lastKey = key;\n onUpdate(shown);\n };\n await Promise.all([\n onAtQuery\n ? onAtQuery(query, { vertical, hotelConfidence, hotelNameConfidence, signal, byPriority,\n onPartial: (items) => { locItems = items; publish(); } })\n .catch(() => locItems) // keep whatever partial already landed\n .then((items) => { locItems = items; locDone = true; publish(); })\n : undefined,\n onAtPersonQuery\n ? onAtPersonQuery(query, { leading: personFirst, signal })\n .catch(() => [] as PromptTriggerItem[])\n .then((items) => { perItems = items; perDone = true; publish(); })\n : undefined,\n ]);\n return merge(locItems, perItems);\n}\n\n/** True when `items[idx]` opens a new `@` section (its group differs from the previous item's). */\nexport function isSectionStart(items: AtMentionItem[], idx: number): boolean {\n const g = items[idx]?.group;\n return g !== undefined && (idx === 0 || items[idx - 1]?.group !== g);\n}\n","// One mapping from a prediction to a dropdown row, shared by both composers (2026-09-10).\n//\n// The predictions list and the `@` picker are the same surface now, so the only thing a host still has to do is\n// name the fields: a `PredictionItem` is keyed and carries what to INSERT, a dropdown row is identified and\n// carries what to SHOW. Doing that inline in each host is how the two lists drifted apart the first time.\n\nimport type { PredictionItem } from '../hooks/usePromptAssist';\nimport type { DropdownItem } from '../components/v2/TriggerDropdown';\n\n/** A dropdown row that remembers the prediction it came from, so `onSelect` can hand it straight to `applyPrediction`. */\nexport type PredictionRow = DropdownItem & { pred: PredictionItem };\n\n/**\n * Predictions → dropdown rows. A disabled row keeps its reason (\"igual à origem\" — the place is already the\n * prompt's origin), which is the one thing the greying alone does not say.\n */\nexport function toPredictionRows(items: PredictionItem[] | null | undefined): PredictionRow[] {\n return (items ?? []).map((p) => ({\n id: p.key,\n label: p.label,\n value: p.insert ?? p.label,\n hint: p.hint,\n kind: p.icon,\n section: p.section,\n disabled: p.disabled,\n disabledNote: p.disabled ? 'igual à origem' : undefined,\n pred: p,\n }));\n}\n"],"names":["ABSOLUTE_URL","extractLinkAction","__name","link","sessionId","content","action","question","url","parameter","firstDash","firstPart","chunkArray","char","size","_v","i","splitBigLinesWithSpaces","limit","whiteSpaceBreak","allWords","hadOne","word","charArray","chunkedWord","chunk","parseRawNumber","text","number","finalNumber","ratio","UUID_WITH_DASHES_REGEX","UUID_WITHOUT_DASHES_REGEX","startsWithInteractionId","str","interactionId","extractInteractionId","withDashesMatch","withoutDashesMatch","prettiffyPythonFunctionName","functionName","prettyName","isValidInteractionId","initializedTables","_SortableTable","options","container","tables","table","tableIndex","thead","headerRow","headers","isFirstSortableMount","_","index","header","columnIndex","tbody","row","cell","exponentialMatch","base","exponent","fullNumber","formattedNumber","num","firstRow","td","th","attr","error","clickListener","e","mouseEnterListener","mouseLeaveListener","icon","rows","sortState","newDirection","direction","a","b","cellA","cellB","valueA","valueB","comparison","percentageMatch","currencyMatch","date","activeHeader","resizeHandle","isResizing","startX","startWidth","handleResize","stopResize","newWidth","currentPosition","headerContent","currentColumnIndex","dragImage","headerText","highlight","cells","j","fromIndex","toIndex","headerToMove","targetHeader","rowIndex","cellToMove","targetCell","currentOrder","newOrder","columnToMove","newHeader","totalWidth","width","widthValue","_a","originalWidthAttr","originalWidth","headersWidth","estimatedWidth","containerWidth","maxRowWidth","cellWidth","prev","current","factor","finalWidth","calculatedWidth","font","mono","context","style","styleElement","__publicField","SortableTable","TRIGGER_CHARS","triggerTypeFor","ch","HIGHLIGHT_WS","PLACEHOLDER_G","tokenizeSegment","prevCh","tokens","boundaryBefore","idx","end","c","tokenizeForHighlight","re","last","m","chipLocations","locTexts","needles","t","out","tok","rest","at","len","n","placeCaret","textarea","start","insistMs","expected","done","stop","onSelectionChange","timer","ticker","apply","swallowNextClick","onClick","cleanup","onMouseDown","PERSON_OR_PLACE_LEAD_ROWS","fetchAtMentions","query","onAtQuery","onAtPersonQuery","personConfidence","locationConfidence","personFirstThreshold","vertical","hotelConfidence","hotelNameConfidence","signal","onUpdate","byPriority","capLeading","personFirst","locItems","perItems","locDone","perDone","lastKey","cap","items","leading","other","otherDone","merge","allLoc","allPer","people","per","loc","publish","shown","key","isSectionStart","_b","g","toPredictionRows","p"],"mappings":";;;;AAQA,MAAMA,IAAe,4BAERC,IAAoB,gBAAAC,EAAA,CAACC,GAAcC,GAAmBC,MAA0H;AACzL,MAAIC,IAAqB,OACrBC,IAA0B,MAC1BC,IAAqB,MACrBC,IAA2B;AAC/B,MAAIN,EAAK,CAAC,KAAK,KAAK;AAChB,UAAMO,IAAYP,EAAK,QAAQ,GAAG,GAC5BQ,IAAYR,EAAK,MAAM,GAAGO,CAAS;AAEzC,YADAD,IAAYN,EAAK,MAAMO,IAAY,CAAC,GAC5BC,EAAU,eAAY;AAAA,MAC1B,KAAK;AACD,QAAAL,IAAS;AACT;AAAA,MACJ,KAAK;AACD,QAAAA,IAAS,YACTC,IAAWF;AACX;AAAA,IAAA;AAAA,EAEZ,MAAA,CACSL,EAAa,KAAKG,CAAI,KAC3BG,IAAS,OACTE,IAAML,KAEDA,EAAK,CAAC,MAAM,OAOjBG,IAAS,YACTE,IAAML,MAONA,IAAOA,EAAK,WAAW,aAAa,YAAYC,CAAS,GAAG,GAC5DE,IAAS;AAGb,SAAO,EAAE,QAAAA,GAAQ,KAAAE,GAAK,UAAAD,GAAU,WAAAE,EAAA;AACpC,GA3CiC,sBCVpBG,IAAa,gBAAAV,EAAA,CAACW,GAAgBC,MACvC,MAAM;AAAA,EAAK,EAAE,QAAQ,KAAK,KAAKD,EAAK,SAASC,CAAI,EAAA;AAAA,EAAK,CAACC,GAAIC,MACvDH,EAAK,MAAMG,IAAIF,GAAME,IAAIF,IAAOA,CAAI;AACxC,GAHsB,eAKbG,IAA0B,gBAAAf,EAAA,CAACG,MAA4B;AAEhE,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AAMtD,CAAG,MAAT,gBAAA7B,EAAY;AACtB,SAAOkG,MAAM,WAAcrE,MAAQ,OAAKoE,IAAAd,EAAMtD,IAAM,CAAC,MAAb,gBAAAoE,EAAgB,WAAUC;AACtE;AAHgBzN,EAAAuN,IAAA;ACjKT,SAASG,GAAiBhB,GAA6D;AAC1F,UAAQA,KAAS,CAAA,GAAI,IAAI,CAACiB,OAAO;AAAA,IAC7B,IAAIA,EAAE;AAAA,IACN,OAAOA,EAAE;AAAA,IACT,OAAOA,EAAE,UAAUA,EAAE;AAAA,IACrB,MAAMA,EAAE;AAAA,IACR,MAAMA,EAAE;AAAA,IACR,SAASA,EAAE;AAAA,IACX,UAAUA,EAAE;AAAA,IACZ,cAAcA,EAAE,WAAW,mBAAmB;AAAA,IAC9C,MAAMA;AAAA,EAAA,EACR;AACN;AAZgB3N,EAAA0N,IAAA;"}
|
|
1
|
+
{"version":3,"file":"predictionRows-Damfwthh.js","sources":["../src/utils/urlParser.ts","../src/utils/stringUtils.ts","../src/utils/interactionIdChecker.ts","../src/utils/sortable-table.js","../src/utils/promptHighlight.ts","../src/utils/placeCaret.ts","../src/utils/swallowNextClick.ts","../src/utils/atMentions.ts","../src/utils/predictionRows.ts"],"sourcesContent":["export type LinkAction = 'Export' | 'Question' | 'OpenDashboard' | 'URL' | 'Navigate'\n\n/**\n * Absolute http(s) URL. Deliberately anchored: the check used to be\n * `link.indexOf(\"http\") > -1`, which classified `exported/http-logs.csv` — and\n * `/blog/http-basics` — as an external URL and handed a relative string to\n * `window.open`.\n */\nconst ABSOLUTE_URL = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n\nexport const extractLinkAction = (link: string, sessionId: string, content: string | null): { action: LinkAction, url: string | null, question: string | null, parameter: string | null } => {\n let action: LinkAction = 'URL';\n let question: string | null = null;\n let url: string | null = null;\n let parameter: string | null = null;\n if (link[0] == '#') {\n const firstDash = link.indexOf(\"-\");\n const firstPart = link.slice(1, firstDash);\n parameter = link.slice(firstDash + 1);\n switch (firstPart.toLowerCase()) {\n case \"opendashboard\":\n action = 'OpenDashboard'\n break;\n case \"ask\":\n action = 'Question'\n question = content\n break;\n }\n }\n else if (ABSOLUTE_URL.test(link)) {\n action = 'URL'\n url = link\n }\n else if (link[0] === '/') {\n // A ROOT-RELATIVE path is a route in the HOST app, not a generated file.\n // Everything relative used to fall through to `Export` below, so the agent\n // writing `<a href=\"/institutional/policy-agent\">` (the first-trip tips do)\n // got the page prefixed with the agent-server base URL and DOWNLOADED —\n // while \"open in new tab\", which bypasses the click handler and follows the\n // real href, worked. The host routes this one instead (`onNavigate`).\n action = 'Navigate'\n url = link\n }\n else {\n // What is left is the export protocol: `exported/<file>`. Left exactly as it\n // was, `url` included: the caller re-derives the download address from the\n // raw href, so this stamping has never reached anyone and returning it now\n // would change every export's URL as a side effect of a link-routing fix.\n link = link.replaceAll(\"exported/\", `exported/${sessionId}/`)\n action = 'Export'\n }\n\n return { action, url, question, parameter }\n}\n","export const chunkArray = (char: string[], size: number): string[][] =>\n Array.from({ length: Math.ceil(char.length / size) }, (_v, i) =>\n char.slice(i * size, i * size + size)\n );\n\nexport const splitBigLinesWithSpaces = (content: string): string => {\n // If content already contains newlines or is short, return as-is\n content = content.replaceAll(\"\\\\n\", \"\\n\");\n\n const limit = 90;\n\n const whiteSpaceBreak = content.split(\" \");\n const allWords: string[] = []\n let hadOne = false;\n for (const word of whiteSpaceBreak) {\n if (word.length > limit) {\n hadOne = true;\n const charArray = [...word];\n const chunkedText = chunkArray(charArray, limit);\n const chunkedWord = chunkedText.map(chunk => chunk.join(\"\")).join(\"\\n\");\n allWords.push(chunkedWord);\n }\n else {\n allWords.push(word);\n }\n }\n\n return hadOne ? allWords.join(\" \") : content;\n}\n\nexport function parseRawNumber(text: string): number {\n let number = parseFloat(text);\n if (!isNaN(number)) {\n text = text.replaceAll(/[,\\.]/g, '');\n return parseInt(text);\n }\n\n var finalNumber = \"\"\n for (const char of text) {\n if (char.match(/[0-9]/)) {\n finalNumber += char;\n }\n }\n\n const ratio = finalNumber.length / text.length;\n number = parseInt(finalNumber);\n if (!isNaN(number) && ratio > 0.5) {\n return number;\n }\n\n return NaN;\n}\n\nexport function parseKnownNumbers(text?: string): { prefix?: string, suffix?: string, number?: number } {\n if (!text) return { prefix: undefined, suffix: undefined, number: undefined };\n\n const knownChars = /[$%(\\w?\\$)]/gi;\n const currencySymbol = /[a-z]?\\$/gi;\n\n let prefix = \"\";\n let suffix = \"\";\n\n if (text.match(knownChars)) {\n if (text.indexOf(\"%\") > -1) {\n suffix = \" %\"\n }\n const match = text.match(currencySymbol)\n if (match) {\n prefix = match[0] + \" \";\n }\n }\n\n let number = parseFloat(text);\n\n if (!isNaN(number)) {\n text = text.replaceAll(\".\", '').replaceAll(\",\", \".\");\n return { prefix, suffix, number: parseFloat(text) };\n }\n\n var finalNumber = \"\"\n for (const char of text) {\n if (char.match(/[0-9.,]/)) {\n let replacedChar = char;\n if (replacedChar == '.')\n replacedChar = \"\"\n else if (replacedChar == \",\")\n replacedChar = \".\"\n finalNumber += replacedChar;\n }\n }\n\n number = parseFloat(finalNumber);\n if (!isNaN(number)) {\n return { prefix, suffix, number: number };\n }\n\n return { prefix: undefined, suffix: undefined, number: undefined };;\n}","/**\n * Utility function to check if a string starts with an interaction ID (UUID)\n * Supports both formats:\n * - With dashes: ebd067ef-0dbd-49b3-8eff-c54b2a9ff314\n * - Without dashes: 62ec037ae42c439192c64dd112136583\n */\n\n/**\n * Regular expression for UUID with dashes (standard format)\n * Format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\n */\nconst UUID_WITH_DASHES_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;\n\n/**\n * Regular expression for UUID without dashes (compact format)\n * Format: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (32 hex characters)\n */\nconst UUID_WITHOUT_DASHES_REGEX = /^[0-9a-f]{32}/i;\n\n/**\n * Check if a string starts with an interaction ID (UUID)\n * @param str - The string to check\n * @returns true if the string starts with a valid UUID, false otherwise\n */\nexport function startsWithInteractionId(str: string): boolean {\n if (!str || typeof str !== 'string') {\n return false;\n }\n\n const interactionId = extractInteractionId(str);\n\n return interactionId === null ? false : str.startsWith(interactionId);\n}\n\n/**\n * Extract the interaction ID from the beginning of a string\n * @param str - The string to extract from\n * @returns The interaction ID if found, null otherwise\n */\nexport function extractInteractionId(str: string): string | null {\n if (!str || typeof str !== 'string') {\n return null;\n }\n\n // Try to match UUID with dashes first\n const withDashesMatch = str.match(UUID_WITH_DASHES_REGEX);\n if (withDashesMatch) {\n return withDashesMatch[0];\n }\n\n // Try to match UUID without dashes\n const withoutDashesMatch = str.match(UUID_WITHOUT_DASHES_REGEX);\n if (withoutDashesMatch) {\n return withoutDashesMatch[0];\n }\n\n return null;\n}\n\nexport function prettiffyFileName(fileName: string) {\n const prettyName = fileName.replaceAll(\"_\", \" \").replaceAll(\"-\", \" \");\n const userRemoved = prettyName.replaceAll(\"user:\", \"\");\n const withNoExtension = userRemoved.replace(/\\.[^/.]+$/, \"\");\n const withNoInteractionId = extractNameFromStringWithInteractionId(withNoExtension).trim();\n if (withNoInteractionId.length > 1)\n return withNoInteractionId[0].toUpperCase() + withNoInteractionId.slice(1);\n else\n return withNoInteractionId;\n}\n\nexport function prettiffyPythonFunctionName(functionName: string) {\n if (functionName.length == 0)\n return functionName;\n\n const prettyName = functionName.replaceAll(\"_\", \" \").replaceAll(\"-\", \" \");\n const withFirstCapitalLetter = prettyName[0].toUpperCase() + prettyName.slice(1);\n\n return withFirstCapitalLetter;\n}\n\nexport function extractNameFromStringWithInteractionId(str: string): string {\n // Try to match UUID with dashes first and remove it\n const withDashesMatch = str.match(UUID_WITH_DASHES_REGEX);\n if (withDashesMatch) {\n return str.replace(withDashesMatch[0], \"\");\n }\n\n // Try to match UUID without dashes\n const withoutDashesMatch = str.match(UUID_WITHOUT_DASHES_REGEX);\n if (withoutDashesMatch) {\n return str.replace(withoutDashesMatch[0], \"\");\n }\n\n return str;\n}\n\n/**\n * Check if a string is a valid interaction ID (UUID) on its own\n * @param str - The string to check\n * @returns true if the string is a valid UUID, false otherwise\n */\nexport function isValidInteractionId(str: string): boolean {\n if (!str || typeof str !== 'string') {\n return false;\n }\n\n // Check if it's exactly a UUID with dashes\n if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(str)) {\n return true;\n }\n\n // Check if it's exactly a UUID without dashes\n if (/^[0-9a-f]{32}$/i.test(str)) {\n return true;\n }\n\n return false;\n}\n","/**\n * SortableTable - A pure JavaScript library for making tables sortable\n * \n * Features:\n * - Automatically scans document for tables\n * - Supports tables with or without thead elements (converts first row to header if needed)\n * - Adds Material UI icons to column headers\n * - Supports text, number, and date sorting\n * - Visual feedback for sort direction\n * - Preserves existing table styling\n */\n\nconst initializedTables = new Set(); // Track which tables have been initialized\n\nimport { parseRawNumber } from './stringUtils';\n\nclass SortableTable {\n constructor(options = {}) {\n this.options = {\n // CSS class for sortable headers\n sortableClass: 'sortable-header',\n // CSS class for active sort\n activeSortClass: 'active-sort',\n // CSS class for ascending sort\n ascendingClass: 'sort-asc',\n // CSS class for descending sort\n descendingClass: 'sort-desc',\n // Icon for unsorted state\n unsortedIcon: 'unfold_more',\n // Icon for ascending sort\n ascendingIcon: 'keyboard_arrow_up',\n // Icon for descending sort\n descendingIcon: 'keyboard_arrow_down',\n // Whether to sort on first click (true) or cycle through states (false)\n sortOnFirstClick: true,\n // Custom sort functions for specific columns\n customSorters: {},\n // Columns to exclude from sorting (0-based index)\n excludeColumns: [],\n // Whether to preserve existing icons in headers\n preserveExistingIcons: false,\n // Enable column resizing\n enableResizing: true,\n // Enable column reordering\n enableReordering: true,\n // CSS class for resizable columns\n resizableClass: 'resizable-column',\n // CSS class for draggable columns\n draggableClass: 'draggable-column',\n // CSS class for drag placeholder\n dragPlaceholderClass: 'drag-placeholder',\n // CSS class for drag over state\n dragOverClass: 'drag-over',\n theme: {\n palette: {\n primary: {\n main: '#999',\n },\n background: {\n default: '#fff',\n paper: '#555',\n },\n text: {\n primary: \"#000\",\n secondary: \"#999\",\n disabled: \"#BBB\",\n },\n surface: {\n panel: \"#999\",\n raised: \"#999\",\n hover: \"#444\",\n },\n divider: \"#999\",\n border: {\n default: \"#999\",\n soft: \"#BBB\",\n },\n },\n shape: {\n borderRadius: 7,\n radiusSm: 1,\n radiusLg: 10,\n },\n },\n ...options\n };\n\n this.tables = [];\n this.sortStates = new Map(); // Track sort state for each table\n this.originalColumnOrder = new Map(); // Track original column order\n this.isDragging = false;\n this.dragSource = null;\n this.dragTarget = null;\n this.charWidth = 0;\n }\n\n /**\n * Initialize the library - scan document for tables and make them sortable\n * @param {HTMLElement} container - Optional container element to limit search scope\n */\n init(container = null) {\n if (this.charWidth == 0)\n this.charWidth = this.getCharWidth(this.options.theme.typography.fontFamily, this.options.theme.typography.fontMono)\n\n this.scanTables(container);\n this.makeTablesSortable();\n this.addStyles();\n }\n\n /**\n * Scan for tables in the document or within a specific container\n * @param {HTMLElement} container - Optional container element to limit search scope\n */\n scanTables(container = null) {\n const searchScope = container || document;\n const tables = searchScope.querySelectorAll('table');\n this.tables = Array.from(tables);\n }\n\n /**\n * Make all found tables sortable\n */\n makeTablesSortable() {\n this.tables.forEach((table, tableIndex) => {\n this.makeTableSortable(table, tableIndex);\n });\n }\n\n /**\n * Make a specific table sortable\n */\n makeTableSortable(table, tableIndex) {\n let thead = table.querySelector('thead');\n let headerRow = null;\n let headers = [];\n\n // Check if table has a proper thead\n if (thead) {\n headerRow = thead.querySelector('tr');\n if (headerRow) {\n headers = headerRow.querySelectorAll('th');\n }\n }\n\n if (headers.length === 0) {\n console.warn('Table has no sortable columns, skipping');\n return;\n }\n // First-time-only arrival animation. ChatPane's effect\n // destroys + re-inits the SortableTable on every `messages`\n // update, so a CSS animation tied to `.sortable-table`\n // alone would replay on each new chunk and feel jittery.\n // The DOM attribute persists across destroy/init cycles\n // (destroy() doesn't touch table attributes), so it cleanly\n // marks \"this table has already arrived once.\"\n const isFirstSortableMount = !table.hasAttribute('data-sortable-arrived');\n // Add sortable-table class for styling\n table.classList.add('sortable-table');\n if (isFirstSortableMount) {\n table.setAttribute('data-sortable-arrived', 'true');\n table.classList.add('sortable-table-arriving');\n // Drop the trigger class after the animation finishes so\n // it can't fire again if the table is somehow re-added to\n // a different DOM position.\n setTimeout(() => {\n table.classList.remove('sortable-table-arriving');\n }, 400);\n }\n\n // Calculate intelligent table width based on header text length\n //const calculatedWidth = this.calculateTableWidth(table);\n // table.style.width = 'auto';\n // table.style.minWidth = '80%';\n //table.style.tableLayout = 'fixed'; // Use fixed layout to respect manual widths\n\n // Cell styles are now handled by CSS only\n\n // Initialize sort state for this table\n this.sortStates.set(tableIndex, {\n currentColumn: -1,\n direction: 'none'\n });\n\n // Capture the table's pre-transform width once so calculateTableWidth\n // can use it as a floor. Persisted as a data attribute (like\n // data-sortable-arrived) so it survives ChatPane's destroy/init\n // cycle — re-reading on every mount would pick up the inline\n // width left behind by the previous calculation, not the\n // natural width the user originally saw.\n if (!table.hasAttribute('data-original-width')) {\n table.setAttribute('data-original-width', table.getBoundingClientRect().width);\n }\n\n this.applyTableStyles(table);\n\n // Store original column order\n this.originalColumnOrder.set(tableIndex, Array.from(headers).map((_, index) => index));\n\n // Make each header sortable\n headers.forEach((header, columnIndex) => {\n if (this.options.excludeColumns.includes(columnIndex)) {\n return;\n }\n\n this.makeHeaderSortable(header, table, tableIndex, columnIndex);\n });\n\n // Replace exponential values in all cells with full numbers\n this.replaceExponentialValues(table);\n\n // Mark this table as initialized\n initializedTables.add(table);\n }\n\n /**\n * Replace exponential values in table cells with full numbers\n * @param {HTMLElement} table - The table to process\n */\n replaceExponentialValues(table) {\n const tbody = table.querySelector('tbody');\n if (!tbody) return;\n\n const rows = tbody.querySelectorAll('tr');\n rows.forEach(row => {\n const cells = row.querySelectorAll('td, th');\n cells.forEach(cell => {\n const text = cell.textContent.trim();\n const exponentialMatch = text.match(/^([\\d,]+\\.?\\d*)[eE][+-]?(\\d+)$/);\n\n if (exponentialMatch) {\n const base = parseFloat(exponentialMatch[1].replace(/,/g, ''));\n const exponent = parseInt(exponentialMatch[2]);\n const fullNumber = base * Math.pow(10, exponent);\n\n // Format the number with commas for readability\n const formattedNumber = this.formatNumber(fullNumber);\n cell.textContent = formattedNumber;\n }\n });\n });\n }\n\n /**\n * Format a number with commas for readability\n * @param {number} num - The number to format\n * @returns {string} The formatted number\n */\n formatNumber(num) {\n if (num === 0) return '0';\n\n // Handle very large or very small numbers\n if (Math.abs(num) >= 1e12) {\n return (num / 1e12).toFixed(2) + 'T';\n } else if (Math.abs(num) >= 1e9) {\n return (num / 1e9).toFixed(2) + 'B';\n } else if (Math.abs(num) >= 1e6) {\n return (num / 1e6).toFixed(2) + 'M';\n } else if (Math.abs(num) >= 1e3) {\n return (num / 1e3).toFixed(2) + 'K';\n } else if (Math.abs(num) < 0.01 && num !== 0) {\n return num.toExponential(2);\n } else {\n return num.toLocaleString();\n }\n }\n\n /**\n * Convert the first row to a header row\n * @param {HTMLElement} firstRow - The first row to convert\n * @param {HTMLElement} thead - The thead element to append to\n * @param {HTMLElement} tbody - The tbody element to remove from\n * @returns {HTMLElement} The converted header row\n */\n convertRowToHeader(firstRow, thead, tbody) {\n try {\n // Clone the row\n const headerRow = firstRow.cloneNode(true);\n\n // Convert all td elements to th elements\n const cells = headerRow.querySelectorAll('td');\n cells.forEach(td => {\n const th = document.createElement('th');\n\n // Copy all attributes\n Array.from(td.attributes).forEach(attr => {\n th.setAttribute(attr.name, attr.value);\n });\n\n // Copy content\n th.innerHTML = td.innerHTML;\n\n // Copy styles\n th.style.cssText = td.style.cssText;\n\n // Replace td with th\n td.parentNode.replaceChild(th, td);\n });\n\n // Remove the original first row from tbody\n if (tbody && tbody.contains(firstRow)) {\n tbody.removeChild(firstRow);\n } else if (firstRow.parentNode) {\n firstRow.parentNode.removeChild(firstRow);\n }\n\n // Add the header row to thead\n thead.appendChild(headerRow);\n\n return headerRow;\n\n } catch (error) {\n console.error('Error converting row to header:', error);\n return null;\n }\n }\n\n /**\n * Make a specific header sortable\n */\n makeHeaderSortable(header, table, tableIndex, columnIndex) {\n // Add sortable class\n header.classList.add(this.options.sortableClass);\n\n // Add cursor pointer\n header.style.cursor = 'pointer';\n\n // Add sort icon if not preserving existing icons\n if (!this.options.preserveExistingIcons || !header.querySelector('.material-icons')) {\n this.addSortIcon(header);\n }\n\n // Add resizing functionality\n if (this.options.enableResizing) {\n this.addResizing(header, table, tableIndex, columnIndex);\n }\n\n // Add drag and drop functionality\n if (this.options.enableReordering) {\n this.addDragAndDrop(header, table, tableIndex, columnIndex);\n // Note: We rely on header drop targets only for better reliability\n }\n\n const clickListener = (e) => {\n e.preventDefault();\n this.sortTable(table, tableIndex, columnIndex);\n }\n\n const mouseEnterListener = (e) => {\n if (!header.classList.contains(this.options.activeSortClass)) {\n header.style.background = this.options.theme.palette.surface.hover;\n }\n }\n\n const mouseLeaveListener = (e) => {\n if (!header.classList.contains(this.options.activeSortClass)) {\n header.style.background = '';\n }\n }\n\n header.removeEventListener('click', clickListener);\n const resp = header.addEventListener('click', clickListener);\n header.removeEventListener('mouseenter', mouseEnterListener);\n header.addEventListener('mouseenter', mouseEnterListener);\n header.removeEventListener('mouseleave', mouseLeaveListener);\n header.addEventListener('mouseleave', mouseLeaveListener);\n }\n\n /**\n * Add sort icon to header\n */\n addSortIcon(header) {\n if (header.querySelector('.sortable-table-icon')) {\n return;\n }\n\n const icon = document.createElement('i');\n icon.id = 'sortable-table-icon';\n icon.className = 'material-icons';\n icon.textContent = this.options.unsortedIcon;\n icon.style.marginRight = '2px';\n icon.style.fontSize = '12px';\n icon.style.verticalAlign = 'middle';\n // Start invisible, then animate to the resting opacity on a\n // later frame so the existing `.sortable-header .material-icons\n // { transition: opacity 0.2s ease }` rule fades in instead of\n // popping in alongside the rest of the table transformation.\n // Double-rAF guarantees the browser paints the 0 state first;\n // a single rAF can be coalesced into the insertion frame in\n // some engines and skip the transition.\n icon.style.opacity = '0';\n\n const existingIcon = header.querySelector('.material-icons');\n if (!existingIcon) {\n header.insertBefore(icon, header.firstChild);\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n icon.style.opacity = '0.6';\n });\n });\n }\n }\n\n /**\n * Sort table by column\n */\n sortTable(table, tableIndex, columnIndex) {\n const tbody = table.querySelector('tbody');\n if (!tbody) {\n console.warn('Table has no tbody element');\n return;\n }\n\n const rows = Array.from(tbody.querySelectorAll('tr'));\n if (rows.length === 0) {\n console.warn('Table has no data rows');\n return;\n }\n\n const sortState = this.sortStates.get(tableIndex);\n const header = table.querySelector(`thead tr th:nth-child(${columnIndex + 1})`);\n\n // Determine sort direction\n let newDirection;\n if (this.options.sortOnFirstClick) {\n newDirection = sortState.currentColumn === columnIndex && sortState.direction === 'asc' ? 'desc' : 'asc';\n } else {\n if (sortState.currentColumn !== columnIndex) {\n newDirection = 'asc';\n } else {\n newDirection = sortState.direction === 'none' ? 'asc' :\n sortState.direction === 'asc' ? 'desc' : 'none';\n }\n }\n\n // Update sort state\n sortState.currentColumn = columnIndex;\n sortState.direction = newDirection;\n this.sortStates.set(tableIndex, sortState);\n\n // Update visual indicators\n this.updateSortIndicators(table, tableIndex, columnIndex, newDirection);\n\n // If direction is 'none', restore original order\n if (newDirection === 'none') {\n this.restoreOriginalOrder(table, rows);\n return;\n }\n\n // Sort the rows\n const sortedRows = this.sortRows(rows, columnIndex, newDirection);\n\n // Re-append sorted rows\n sortedRows.forEach(row => tbody.appendChild(row));\n }\n\n /**\n * Sort rows based on column data\n */\n sortRows(rows, columnIndex, direction) {\n return rows.sort((a, b) => {\n const cellA = a.cells[columnIndex];\n const cellB = b.cells[columnIndex];\n\n if (!cellA || !cellB) return 0;\n\n const valueA = this.extractValue(cellA);\n const valueB = this.extractValue(cellB);\n\n // Use custom sorter if available\n if (this.options.customSorters[columnIndex]) {\n return this.options.customSorters[columnIndex](valueA, valueB, direction);\n }\n\n // Default sorting logic\n const comparison = this.compareValues(valueA, valueB);\n return direction === 'asc' ? comparison : -comparison;\n });\n }\n\n /**\n * Extract sortable value from cell\n */\n extractValue(cell) {\n let text = cell.textContent.trim();\n\n let number = parseRawNumber(text);\n if (!isNaN(number)) {\n console.log(number);\n return number;\n }\n\n // Remove all material icons and common symbols from the text\n text = text.replace(/arrow_upward|arrow_downward|remove|keyboard_arrow_up|keyboard_arrow_down|unfold_more|expand_more|expand_less|trending_up|trending_down|↗|↘|↑|↓|→|←/g, '').trim();\n\n // Handle N/A, N/D, ND, blank and variants as -1\n const naVariants = /^(N\\/A|N\\/D|ND|N\\/A|n\\/a|n\\/d|nd|N\\/A|N\\/D|ND|\\s*)$/i;\n if (naVariants.test(text)) {\n return -1;\n }\n\n // Try to parse as percentage\n const percentageMatch = text.match(/^([\\d,]+\\.?\\d*)\\s*%$/);\n if (percentageMatch) {\n return parseFloat(percentageMatch[1].replace(/,/g, ''));\n }\n\n // Try to parse as exponential notation (scientific notation)\n const exponentialMatch = text.match(/^([\\d,]+\\.?\\d*)[eE][+-]?(\\d+)$/);\n if (exponentialMatch) {\n const base = parseFloat(exponentialMatch[1].replace(/,/g, ''));\n const exponent = parseInt(exponentialMatch[2]);\n return base * Math.pow(10, exponent);\n }\n\n // Try to parse as number\n const numberMatch = text.match(/^[\\d,]+\\.?\\d*[KMB]?$/);\n if (numberMatch) {\n return this.parseNumber(text);\n }\n\n // Try to parse as currency\n const currencyMatch = text.match(/^R\\$\\s*([\\d,]+\\.?\\d*)$/);\n if (currencyMatch) {\n return this.parseNumber(currencyMatch[1]);\n }\n\n // Try to parse as date\n const date = new Date(text);\n if (!isNaN(date.getTime())) {\n return date.getTime();\n }\n\n // Return as string (case-insensitive)\n return text.toLowerCase();\n }\n\n /**\n * Compare two values for sorting\n */\n compareValues(a, b) {\n // Handle null/undefined values\n if (a == null && b == null) return 0;\n if (a == null) return -1;\n if (b == null) return 1;\n\n // Handle different types\n if (typeof a !== typeof b) {\n return String(a).localeCompare(String(b));\n }\n\n // Handle numbers\n if (typeof a === 'number') {\n return a - b;\n }\n\n // Handle dates\n if (a instanceof Date) {\n return a.getTime() - b.getTime();\n }\n\n // Handle strings\n return a.localeCompare(b);\n }\n\n /**\n * Update visual indicators for sort state\n */\n updateSortIndicators(table, tableIndex, columnIndex, direction) {\n const headers = table.querySelectorAll('thead tr th');\n\n // Reset all headers\n headers.forEach((header, index) => {\n header.classList.remove(this.options.activeSortClass, this.options.ascendingClass, this.options.descendingClass);\n const icon = header.querySelector('.material-icons');\n if (icon) {\n icon.textContent = this.options.unsortedIcon;\n icon.style.opacity = '0.6';\n }\n });\n\n // Update active header\n if (direction !== 'none') {\n const activeHeader = headers[columnIndex];\n activeHeader.classList.add(this.options.activeSortClass);\n\n const icon = activeHeader.querySelector('.material-icons');\n if (icon) {\n if (direction === 'asc') {\n activeHeader.classList.add(this.options.ascendingClass);\n icon.textContent = this.options.ascendingIcon;\n } else {\n activeHeader.classList.add(this.options.descendingClass);\n icon.textContent = this.options.descendingIcon;\n }\n icon.style.opacity = '1';\n }\n }\n }\n\n /**\n * Restore original order (when sort direction is 'none')\n */\n restoreOriginalOrder(table, rows) {\n // This is a simplified implementation\n // In a real scenario, you might want to store the original order\n const tbody = table.querySelector('tbody');\n rows.forEach(row => tbody.appendChild(row));\n }\n\n /**\n * Add resizing functionality to a header\n */\n addResizing(header, table, tableIndex, columnIndex) {\n header.classList.add(this.options.resizableClass);\n header.style.position = 'relative';\n\n\n if (header.querySelector('.resize-handle')) {\n return;\n }\n\n const resizeHandle = document.createElement('div');\n resizeHandle.className = 'resize-handle';\n resizeHandle.style.cssText = `\n position: absolute;\n top: 0;\n right: 0;\n width: 4px;\n height: 100%;\n background: transparent;\n cursor: col-resize;\n z-index: 10;\n `;\n\n header.appendChild(resizeHandle);\n\n let isResizing = false;\n let startX = 0;\n let startWidth = 0;\n\n resizeHandle.addEventListener('mousedown', (e) => {\n e.preventDefault();\n e.stopPropagation();\n e.stopImmediatePropagation(); // Prevent sort from triggering\n isResizing = true;\n startX = e.clientX;\n startWidth = header.offsetWidth;\n\n // Add visual feedback\n header.style.borderRight = '2px solid var(--primary-main, #2196F3)';\n header.style.background = 'var(--background-active, rgba(255, 255, 255, 0.1))';\n\n document.addEventListener('mousemove', handleResize);\n document.addEventListener('mouseup', stopResize);\n document.body.style.cursor = 'col-resize';\n document.body.style.userSelect = 'none';\n });\n\n const handleResize = (e) => {\n if (!isResizing) return;\n const newWidth = startWidth + (e.clientX - startX);\n if (newWidth > 30) { // Minimum width\n header.style.width = newWidth + 'px';\n\n // Set the same width on all cells in this column\n const columnIndex = Array.from(header.parentNode.children).indexOf(header);\n const tbody = table.querySelector('tbody');\n if (tbody) {\n const rows = tbody.querySelectorAll('tr');\n rows.forEach(row => {\n const cell = row.children[columnIndex];\n if (cell) {\n cell.style.width = newWidth + 'px';\n }\n });\n }\n\n // Update table width if column width increased\n this.updateTableWidth(table);\n }\n };\n\n const stopResize = () => {\n isResizing = false;\n\n // Remove visual feedback\n header.style.borderRight = '';\n header.style.background = '';\n\n document.removeEventListener('mousemove', handleResize);\n document.removeEventListener('mouseup', stopResize);\n document.body.style.cursor = '';\n document.body.style.userSelect = '';\n };\n }\n\n /**\n * Add drag and drop functionality to a header\n */\n addDragAndDrop(header, table, tableIndex, columnIndex) {\n if (header.querySelector('.drag-handle')) {\n return;\n }\n\n header.classList.add(this.options.draggableClass);\n header.draggable = true;\n\n const thead = table.querySelector('thead tr');\n\n header.addEventListener('dragstart', (e) => {\n this.isDragging = true;\n // Store the current DOM position, not the original column index\n const currentPosition = Array.from(thead.children).indexOf(header);\n this.dragSource = { table, tableIndex, columnIndex: currentPosition };\n e.dataTransfer.effectAllowed = 'move';\n e.dataTransfer.setData('text/html', header.outerHTML);\n const headerContent = header.outerHTML;\n header.style.opacity = '0.5';\n\n // Create a custom drag image\n this.createCustomDragImage(e, header, headerContent);\n });\n\n header.addEventListener('dragend', (e) => {\n this.isDragging = false;\n this.dragSource = null;\n header.style.opacity = '';\n // Remove all column highlights\n this.clearAllColumnHighlights(table);\n });\n\n header.addEventListener('dragover', (e) => {\n e.preventDefault();\n e.dataTransfer.dropEffect = 'move';\n });\n\n header.addEventListener('dragenter', (e) => {\n e.preventDefault();\n if (this.dragSource && this.dragSource.tableIndex === tableIndex) {\n const currentColumnIndex = Array.from(thead.children).indexOf(header);\n if (this.dragSource.columnIndex !== currentColumnIndex) {\n // Add visual feedback to the entire column\n this.highlightColumn(table, currentColumnIndex, true);\n }\n }\n });\n\n header.addEventListener('dragleave', (e) => {\n // Only remove highlight if we're leaving the entire column\n if (!header.contains(e.relatedTarget)) {\n const currentColumnIndex = Array.from(thead.children).indexOf(header);\n this.highlightColumn(table, currentColumnIndex, false);\n }\n });\n\n header.addEventListener('drop', (e) => {\n e.preventDefault();\n\n if (this.dragSource && this.dragSource.tableIndex === tableIndex) {\n const currentColumnIndex = Array.from(thead.children).indexOf(header);\n if (this.dragSource.columnIndex !== currentColumnIndex) {\n this.reorderColumns(table, tableIndex, this.dragSource.columnIndex, currentColumnIndex);\n }\n }\n\n // Remove all column highlights\n this.clearAllColumnHighlights(table);\n });\n }\n\n /**\n * Create a custom drag image for better UX\n */\n createCustomDragImage(e, header, headerContent) {\n // Create a temporary element for the drag image\n const dragImage = document.createElement('div');\n dragImage.style.cssText = `\n position: absolute;\n top: -1000px;\n left: -1000px;\n background: var(--background-elevated, #333);\n border: 2px solid var(--primary-main, #2196F3);\n border-radius: 4px;\n padding: 8px 12px;\n font-size: 12px;\n font-weight: bold;\n color: var(--text-primary, #fff);\n white-space: nowrap;\n max-width: 150px;\n min-width: 60px;\n overflow: hidden;\n text-overflow: ellipsis;\n box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);\n z-index: 10000;\n pointer-events: none;\n min-height: 50px;\n display: flex;\n align-items: center;\n `;\n\n // Get the header text without icons and create a compact representation\n const headerText = headerContent;\n dragImage.innerHTML = `\n <div style=\"display: flex; align-items: center; gap: 5px; align-content: center;color:white;\">\n <span style=\"overflow: hidden; text-overflow: ellipsis\">${headerText}</span>\n <svg style=\"fill: grey; font-size: 10px\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" ><defs><path id=\"a\" d=\"M0 0h24v24H0V0z\"/></defs><clipPath id=\"b\"><use xlink:href=\"#a\" overflow=\"visible\"/></clipPath><path clip-path=\"url(#b)\" d=\"M9.01 14H2v2h7.01v3L13 15l-3.99-4v3zm5.98-1v-3H22V8h-7.01V5L11 9l3.99 4z\"/></svg>\n </div> \n `;\n\n // Add to document temporarily\n document.body.appendChild(dragImage);\n\n // Set as drag image with centered offset\n e.dataTransfer.setDragImage(dragImage, 50, 12);\n\n // Clean up after a short delay\n setTimeout(() => {\n if (document.body.contains(dragImage)) {\n document.body.removeChild(dragImage);\n }\n }, 100);\n }\n\n\n\n /**\n * Highlight an entire column during drag operations\n */\n highlightColumn(table, columnIndex, highlight) {\n const thead = table.querySelector('thead tr');\n const tbody = table.querySelector('tbody');\n\n if (!thead || !tbody) return;\n\n const header = thead.children[columnIndex];\n if (!header) return;\n\n if (highlight) {\n header.classList.add(this.options.dragOverClass);\n // Highlight all cells in this column\n const rows = tbody.children;\n for (let i = 0; i < rows.length; i++) {\n const cell = rows[i].children[columnIndex];\n if (cell) {\n cell.classList.add(this.options.dragOverClass);\n }\n }\n } else {\n header.classList.remove(this.options.dragOverClass);\n // Remove highlight from all cells in this column\n const rows = tbody.children;\n for (let i = 0; i < rows.length; i++) {\n const cell = rows[i].children[columnIndex];\n if (cell) {\n cell.classList.remove(this.options.dragOverClass);\n }\n }\n }\n }\n\n /**\n * Clear all column highlights\n */\n clearAllColumnHighlights(table) {\n const thead = table.querySelector('thead tr');\n const tbody = table.querySelector('tbody');\n\n if (!thead || !tbody) return;\n\n // Clear header highlights\n const headers = thead.children;\n for (let i = 0; i < headers.length; i++) {\n headers[i].classList.remove(this.options.dragOverClass);\n }\n\n // Clear cell highlights\n const rows = tbody.children;\n for (let i = 0; i < rows.length; i++) {\n const cells = rows[i].children;\n for (let j = 0; j < cells.length; j++) {\n cells[j].classList.remove(this.options.dragOverClass);\n }\n }\n }\n\n /**\n * Reorder columns in a table\n */\n reorderColumns(table, tableIndex, fromIndex, toIndex) {\n const thead = table.querySelector('thead tr');\n const tbody = table.querySelector('tbody');\n\n if (!thead || !tbody) return;\n\n const headers = Array.from(thead.children);\n const rows = Array.from(tbody.children);\n\n // Validate indices\n if (fromIndex < 0 || fromIndex >= headers.length || toIndex < 0 || toIndex >= headers.length) {\n console.warn('Invalid column indices for reordering');\n return;\n }\n\n // Don't do anything if dropping on the same position\n if (fromIndex === toIndex) {\n return;\n }\n\n // Move the header element directly in the DOM\n const headerToMove = headers[fromIndex];\n const targetHeader = headers[toIndex];\n\n if (fromIndex < toIndex) {\n // Moving right: insert after target\n thead.insertBefore(headerToMove, targetHeader.nextSibling);\n } else {\n // Moving left: insert before target\n thead.insertBefore(headerToMove, targetHeader);\n }\n\n // Move cells in each row\n rows.forEach((row, rowIndex) => {\n const cells = Array.from(row.children);\n const cellToMove = cells[fromIndex];\n const targetCell = cells[toIndex];\n\n if (fromIndex < toIndex) {\n // Moving right: insert after target\n row.insertBefore(cellToMove, targetCell.nextSibling);\n } else {\n // Moving left: insert before target\n row.insertBefore(cellToMove, targetCell);\n }\n });\n\n // Update column order tracking\n const currentOrder = this.originalColumnOrder.get(tableIndex);\n if (currentOrder) {\n const newOrder = [...currentOrder];\n const columnToMove = newOrder[fromIndex];\n newOrder.splice(fromIndex, 1);\n newOrder.splice(toIndex, 0, columnToMove);\n this.originalColumnOrder.set(tableIndex, newOrder);\n }\n\n // Reapply inline styles after reordering\n this.applyTableStyles(table);\n\n // Refresh drag and drop listeners for the reordered columns\n this.refreshDragAndDropListeners(table, tableIndex);\n }\n\n /**\n * Refresh drag and drop listeners after column reordering\n */\n refreshDragAndDropListeners(table, tableIndex) {\n const thead = table.querySelector('thead tr');\n if (!thead) return;\n\n const headers = Array.from(thead.children);\n\n // Remove existing listeners by cloning headers and re-adding all functionality\n headers.forEach((header, columnIndex) => {\n if (header.classList.contains(this.options.draggableClass)) {\n // Clear any drag-related inline styles before cloning\n header.style.opacity = '';\n header.style.background = '';\n header.style.borderRight = '';\n\n const newHeader = header.cloneNode(true);\n header.parentNode.replaceChild(newHeader, header);\n\n // Re-add all functionality (sorting, resizing, drag and drop)\n this.makeHeaderSortable(newHeader, table, tableIndex, columnIndex);\n }\n });\n }\n\n /**\n * Update table width based on current column widths\n */\n updateTableWidth(table) {\n const headers = table.querySelectorAll('th');\n let totalWidth = 0;\n\n headers.forEach(header => {\n const width = header.style.width;\n if (width) {\n const widthValue = parseInt(width.replace('px', ''));\n totalWidth += widthValue;\n } else {\n // Fallback to estimated width if no explicit width set\n const text = header.textContent.replace(/[📊🔍]/g, '').trim();\n totalWidth += text.length;\n }\n });\n\n // Convert to percentage\n table.style.width = `${totalWidth}px`;\n }\n\n /**\n * Calculate intelligent table width based on header text length\n */\n calculateTableWidth(table) {\n const originalWidthAttr = table.getAttribute('data-original-width');\n const originalWidth = originalWidthAttr ? parseFloat(originalWidthAttr) : 0;\n const headers = table.querySelectorAll('th');\n let totalWidth = 0;\n\n const parentWidth = table.parentElement.clientWidth\n\n const headersWidth = [];\n headers.forEach(header => {\n // Get text content without icons\n const text = header.textContent.replace(/[📊🔍]/g, '').trim();\n\n let estimatedWidth = text.length * this.charWidth + 15;\n\n headersWidth.push(estimatedWidth);\n\n totalWidth += estimatedWidth;\n });\n\n const rows = table.querySelectorAll('tr');\n\n const containerWidth = table.parentElement?.getBoundingClientRect().width ?? totalWidth;\n\n var maxRowWidth = 0;\n for (const row of rows) {\n const cells = row.querySelectorAll('td');\n\n cells.forEach((cell, index) => {\n // Get text content without icons\n const text = cell.textContent;\n\n const cellWidth = text.length * this.charWidth + 15;\n if (cellWidth > headersWidth[index] && index < headersWidth.length)\n headersWidth[index] = cellWidth;\n });\n };\n\n maxRowWidth = headersWidth.reduce((prev, current) => prev += current, 0);\n\n headers.forEach((header, index) => {\n if (maxRowWidth > containerWidth) {\n const factor = headersWidth[index] / maxRowWidth;\n header.style.width = `${containerWidth * factor}px`\n }\n else {\n header.style.width = `${headersWidth[index]}px`\n }\n });\n\n // Convert to percentage or pixel value\n let finalWidth = 0\n if (maxRowWidth > containerWidth) {\n finalWidth = `100%`\n }\n else {\n // If the calculated width would shrink the table below its\n // pre-transform rendered width, preserve the original.\n const effectiveWidth = Math.max(maxRowWidth, originalWidth);\n finalWidth = `${effectiveWidth}px`;\n }\n\n return finalWidth;\n }\n\n /**\n * Apply inline styles to ensure text clipping and horizontal scroll work\n */\n applyTableStyles(table) {\n // Force table styles\n const calculatedWidth = this.calculateTableWidth(table);\n // The \"fits comfortably\" branch of calculateTableWidth used\n // to force width: 100%, which made every chat table stretch\n // edge-to-edge regardless of content. Instead, let the table\n // be content-fit (auto) but floor it at 60% of the container\n // so very narrow tables don't look orphaned next to the\n // chat gutter, and cap it at 100% so wider data still fits.\n // The overflow branch still uses the calculated pixel width\n // because it's already wider than the container would allow.\n table.style.width = calculatedWidth;\n table.style.maxWidth = '100%';\n // if (calculatedWidth === '100%') {\n // table.style.width = 'auto';\n // table.style.minWidth = '60%';\n // table.style.maxWidth = '100%';\n // } else {\n // table.style.width = `${calculatedWidth}`;\n // table.style.minWidth = 'auto';\n // table.style.maxWidth = 'auto';\n // }\n // table.style.tableLayout = 'fixed'; // Use fixed layout to respect manual widths\n }\n\n /** Fallback advance width, in px, for one character of the body font. */\n static DEFAULT_CHAR_WIDTH = 8;\n\n // Signature matches the single call site — `init()` passes (fontFamily,\n // fontMono), which used to land on a leading `char` parameter nothing read.\n getCharWidth(font, mono) {\n const context = document.createElement(\"canvas\").getContext(\"2d\");\n\n // No 2D context: a headless DOM, or a browser that refused one. This\n // runs on a 500ms timer after the chat mounts, so a throw here lands\n // outside every call stack that could catch it — it took down the test\n // runner from the macrotask queue.\n if (!context) return SortableTable.DEFAULT_CHAR_WIDTH;\n\n context.fontFamily = font;\n context.fontMono = mono;\n\n // Measure the specific character\n const metrics = context.measureText(\"A \");\n return metrics.width; // Returns width in pixels\n }\n\n /**\n * Add CSS styles for sortable tables\n */\n addStyles() {\n if (document.getElementById('sortable-table-styles')) {\n return; // Styles already added\n }\n\n const style = document.createElement('style');\n style.id = 'sortable-table-styles';\n style.textContent = ` \n .${this.options.sortableClass} {\n position: relative;\n user-select: none;\n transition: background-color 0.2s ease;\n }\n \n .${this.options.sortableClass}:hover {\n background-color: ${this.options.theme.palette.surface.hover} !important;\n }\n \n .${this.options.activeSortClass} {\n background-color: ${this.options.theme.palette.surface.raised} !important;\n font-weight: bold;\n }\n \n .${this.options.ascendingClass} {\n border-bottom: 2px solid var(${this.options.theme.palette.primary.main}, #3a3a3a);\n }\n \n .${this.options.descendingClass} {\n border-bottom: 2px solid var(${this.options.theme.palette.primary.main}, #3a3a3a);\n }\n \n .${this.options.sortableClass} .material-icons {\n transition: opacity 0.2s ease, transform 0.2s ease;\n }\n \n .${this.options.activeSortClass} .material-icons {\n color: var(${this.options.theme.palette.primary.main}, #3a3a3a);\n }\n \n .${this.options.resizableClass} .resize-handle:hover {\n background-color: var(${this.options.theme.palette.primary.light}, #64B5F6);\n }\n \n .${this.options.draggableClass} {\n cursor: move;\n position: relative;\n }\n \n .${this.options.draggableClass}::before {\n content: '';\n position: absolute;\n top: 0;\n left: -5px;\n right: -5px;\n bottom: 0;\n z-index: 1;\n pointer-events: none;\n }\n \n .${this.options.dragOverClass} {\n background-color: rgba(128, 128, 128, 0.2) !important;\n border: 2px dashed rgba(128, 128, 128, 0.8);\n }\n \n .${this.options.draggableClass}:hover {\n background-color: var(${this.options.theme.palette.surface.raised}, rgba(100, 181, 246, 0.1)) !important;\n }\n\n .sortable-table tbody td {\n width: auto\n } \n\n .sortable-table {\n /* Cross-fade bg/row stripes when the .sortable-table\n * class flip lands on a freshly-streamed markdown\n * table. Width is NOT animated: column widths set\n * by calculateTableWidth can be narrower than the\n * content currently fills, so animating them down\n * causes mid-transition cell wrap. Snap widths,\n * animate only colours. */\n transition: background-color 280ms ease-out; \n }\n\n .sortable-table th {\n transition: background-color 280ms ease-out;\n }\n\n /* Zebra striping for table rows */\n .sortable-table tbody tr:nth-child(odd) {\n background-color: ${this.options.theme.palette.background.defalt};\n color: ${this.options.theme.palette.text.primary};\n }\n\n .sortable-table tbody tr:nth-child(even) {\n background-color: ${this.options.theme.palette.background.defalt};\n color: ${this.options.theme.palette.text.primary};\n }\n\n /* One-shot arrival animation. Applied via a transient\n * class (added by makeTableSortable on first mount only)\n * so it does NOT re-fire on every destroy/init cycle.\n * scaleX with origin top-left gives the \"right edge\n * grows outward\" feel the user asked for; the 0.96\n * start is subtle enough that text compression isn't\n * obvious. */\n @keyframes sortable-table-arrive {\n from {\n opacity: 0.35;\n transform: scaleX(0.96);\n transform-origin: top left;\n }\n to {\n opacity: 1;\n transform: scaleX(1);\n }\n }\n\n .sortable-table-arriving {\n animation: sortable-table-arrive 320ms cubic-bezier(0.16, 1, 0.3, 1) both;\n }\n \n /* Ensure hover effects work with zebra striping */\n .sortable-table tbody tr:hover {\n background-color: ${this.options.theme.palette.surface.hover} !important;\n }\n \n \n /* Fix table-container overflow issue */\n .table-container {\n overflow: auto !important;\n overflow-x: auto !important;\n overflow-y: auto !important;\n }\n `;\n\n const existingStyle = document.getElementById('sortable-table-styles');\n if (!existingStyle) {\n document.head.appendChild(style);\n }\n }\n\n /**\n * Destroy the sortable functionality\n */\n destroy() {\n this.tables.forEach(table => {\n const headers = table.querySelectorAll(`.${this.options.sortableClass}`);\n headers.forEach(header => {\n header.classList.remove(\n this.options.sortableClass,\n this.options.activeSortClass,\n this.options.ascendingClass,\n this.options.descendingClass\n );\n header.style.cursor = '';\n header.style.background = '';\n\n // Remove event listeners by cloning the element\n const newHeader = header.cloneNode(true);\n header.parentNode.replaceChild(newHeader, header);\n });\n });\n\n // Remove styles\n const styleElement = document.getElementById('sortable-table-styles');\n if (styleElement) {\n styleElement.remove();\n }\n\n this.tables = [];\n this.sortStates.clear();\n initializedTables.clear();\n }\n\n /**\n * Refresh the library (useful after DOM changes)\n */\n refresh() {\n this.destroy();\n this.init();\n }\n}\n\n// // Create global instance but don't auto-initialize\n// Guard the global assignment so this module is import-safe outside the\n// browser (Node/SSR/tests). Importing it for the class export alone — as the\n// session-replay decode path does transitively — must not throw on `window`.\nif (typeof window !== 'undefined') {\n window.SortableTable = SortableTable;\n}\n\n// Export for module systems\nexport default SortableTable;\n","// Shared prompt-overlay helpers used by both the chat composer (PromptV2) and the home composer (obtapp's\n// PromptComposer): tokenize a draft into chip/plain runs, and chip server-mapped locations inline like \"@\" mentions.\n\nexport type HighlightToken = { type: 'plain' | 'slash' | 'at' | 'hash' | 'placeholder'; text: string };\n\nconst TRIGGER_CHARS: ReadonlySet<string> = new Set(['/', '@', '#']);\nconst triggerTypeFor = (ch: string): 'slash' | 'at' | 'hash' =>\n ch === '/' ? 'slash' : ch === '@' ? 'at' : 'hash';\n// A token boundary is ASCII whitespace only — NOT the non-breaking space (U+00A0). Hosts join a multi-word\n// \"@mention\" (e.g. \"@São Paulo\") with NBSPs so the whole name stays a single chip; a regular space separates tokens.\nconst HIGHLIGHT_WS = /[ \\t\\r\\n\\f\\v]/;\n// Template placeholders (#447): `[@origem]` / `[#data]` / `[texto livre]` — same shape promptTriggers parses.\nconst PLACEHOLDER_G = /\\[[^\\]\\n]+\\]/g;\n\n/** The pre-#447 tokenizer, over one placeholder-free segment. `prevCh` is the char just before the segment in the\n * full text (undefined at the very start) — it decides whether a trigger at the segment's first index leads its\n * own token, so a `@` right after a `]` stays plain exactly as it would mid-string. */\nconst tokenizeSegment = (text: string, prevCh: string | undefined, tokens: HighlightToken[]): void => {\n let i = 0;\n const boundaryBefore = (idx: number): boolean => {\n const prev = idx === 0 ? prevCh : text[idx - 1];\n return prev === undefined || HIGHLIGHT_WS.test(prev);\n };\n while (i < text.length) {\n const ch = text[i];\n if (boundaryBefore(i) && TRIGGER_CHARS.has(ch)) {\n let end = i + 1;\n while (end < text.length && !HIGHLIGHT_WS.test(text[end])) end += 1;\n tokens.push({ type: triggerTypeFor(ch), text: text.slice(i, end) });\n i = end;\n } else {\n let end = i + 1;\n while (end < text.length) {\n const c = text[end];\n if (TRIGGER_CHARS.has(c) && HIGHLIGHT_WS.test(text[end - 1])) break;\n end += 1;\n }\n tokens.push({ type: 'plain', text: text.slice(i, end) });\n i = end;\n }\n }\n};\n\n/**\n * Splits `text` into a flat list of runs so the overlay can paint chip styling around `/cmd` / `@user` / `#date`\n * tokens while keeping surrounding text plain. Boundary rule mirrors the autocomplete trigger detection (trigger\n * char at line start or after whitespace), so a `/` inside `http://` or `@` inside an email stays plain.\n * `[bracketed placeholders]` (#447) pre-empt the whitespace walk — they may contain spaces and become their own\n * `placeholder` runs, which hosts paint as \"fill me\" chips (and may make tappable).\n */\nexport const tokenizeForHighlight = (text: string): HighlightToken[] => {\n if (!text) return [];\n const tokens: HighlightToken[] = [];\n const re = new RegExp(PLACEHOLDER_G.source, 'g');\n let last = 0;\n for (let m = re.exec(text); m; m = re.exec(text)) {\n if (m.index > last) tokenizeSegment(text.slice(last, m.index), last === 0 ? undefined : text[last - 1], tokens);\n tokens.push({ type: 'placeholder', text: m[0] });\n last = m.index + m[0].length;\n }\n if (last < text.length) tokenizeSegment(text.slice(last), last === 0 ? undefined : text[last - 1], tokens);\n return tokens;\n};\n\n/**\n * Second pass: chip the locations the slow pass mapped (pasted / dictated, no typed \"@\") as if they were \"@\"\n * mentions — same inline chip style. Only PLAIN runs are scanned (real \"@\" mentions are already their own chips);\n * longest names win so \"São Paulo\" beats \"São\".\n */\nexport const chipLocations = (tokens: HighlightToken[], locTexts: readonly string[]): HighlightToken[] => {\n const needles = locTexts.filter((t) => t.trim().length > 0).sort((a, b) => b.length - a.length);\n if (needles.length === 0) return tokens;\n const out: HighlightToken[] = [];\n for (const tok of tokens) {\n if (tok.type !== 'plain') { out.push(tok); continue; }\n let rest = tok.text;\n while (rest.length > 0) {\n let at = -1;\n let len = 0;\n for (const n of needles) {\n const idx = rest.indexOf(n);\n if (idx >= 0 && (at === -1 || idx < at)) { at = idx; len = n.length; }\n }\n if (at === -1) { out.push({ type: 'plain', text: rest }); break; }\n if (at > 0) out.push({ type: 'plain', text: rest.slice(0, at) });\n out.push({ type: 'at', text: rest.slice(at, at + len) });\n rest = rest.slice(at + len);\n }\n }\n return out;\n};\n","/**\n * Put the caret somewhere and make it stay there (issue #422).\n *\n * `setSelectionRange` is enough on a desktop browser. It is not enough on iOS after a TOUCH pick: the tap blurs the\n * textarea on the way in, and when we focus back WebKit restores the selection IT remembers — asynchronously, on\n * its own schedule, after our call has already run. The caret snapped back to where the user's query had been\n * (\"Busque voos saindo de @sao\" → index 26) instead of sitting after the mention just spliced in, which put it\n * visibly inside the chip: `@(SA|O) São Paulo`.\n *\n * A one-shot re-place on the next frame was not enough either — the restore can land after the keyboard animation\n * starts. So this keeps asserting the position for a short window and stops the moment it is no longer wanted:\n *\n * - the value changed → some other edit owns the caret now;\n * - the user typed, tapped or pressed a key → their intent wins over ours, immediately;\n * - the window expired.\n *\n * Everywhere other than iOS the first assignment sticks and the watcher simply expires having done nothing.\n */\nexport function placeCaret(\n textarea: HTMLTextAreaElement,\n start: number,\n end: number = start,\n insistMs = 600,\n): () => void {\n const expected = textarea.value;\n let done = false;\n\n const stop = () => {\n if (done) return;\n done = true;\n document.removeEventListener('selectionchange', onSelectionChange);\n textarea.removeEventListener('keydown', stop);\n textarea.removeEventListener('input', stop);\n textarea.removeEventListener('pointerdown', stop);\n window.clearTimeout(timer);\n window.clearInterval(ticker);\n };\n\n const apply = () => {\n // Someone else edited the field — whatever they did outranks a caret we queued for a previous value.\n if (textarea.value !== expected) { stop(); return; }\n if (textarea.selectionStart === start && textarea.selectionEnd === end) return;\n textarea.setSelectionRange(start, end);\n };\n\n // `selectionchange` is what fires when WebKit restores its own position, so it is the direct signal to undo.\n // The interval covers browsers that move the caret without firing it.\n const onSelectionChange = () => { if (document.activeElement === textarea) apply(); };\n\n apply();\n\n const timer = window.setTimeout(stop, insistMs);\n const ticker = window.setInterval(apply, 50);\n document.addEventListener('selectionchange', onSelectionChange);\n // Any real interaction ends the argument — we must never fight a user who is repositioning their own caret.\n textarea.addEventListener('keydown', stop);\n textarea.addEventListener('input', stop);\n textarea.addEventListener('pointerdown', stop);\n\n return stop;\n}\n","/**\n * Eat the compatibility `click` that follows a `pointerdown`/`touchend` you have already acted on.\n *\n * A touch that lands on a control which then unmounts (or opens something over the spot) leaves the\n * browser's synthesised click to fall on **whatever is now under the finger** — that is how picking a\n * location once sent the prompt, the send button having slid under the tap. The same click is also\n * what a `<ClickAwayListener>` sees as \"the user clicked outside\", so a surface opened during\n * `pointerdown` is closed again microseconds later by the click of the very gesture that opened it.\n *\n * Cancelling `pointerdown` would suppress the compatibility events, but on touch that also kills\n * scrolling — so the click is intercepted instead.\n *\n * Capture phase, so it never reaches the target (or a document-level away-listener); self-removing,\n * and time-boxed in case no click arrives at all (the browser is not obliged to send one).\n *\n * `mousedown: true` eats the gesture's compatibility `mousedown` as well. Pass it when you act on\n * `pointerUP`: that mousedown arrives after your handler has already re-rendered, and its default\n * action — move focus, place the caret — lands on whatever is under the finger NOW. On Android that\n * is how a `/`-template pick lost its caret: the pick put the caret after the template's `@` and\n * opened the docked `@` panel in the spot the command list had just vacated, and the tap's mousedown\n * then hit that panel, blurring the textarea (keyboard down, caret gone), or hit the textarea itself\n * and re-homed the caret to the tap point. iOS never showed it — WebKit does not move focus to a\n * non-focusable element on tap. A new `pointerdown` disarms it, so a genuine next tap is never eaten.\n */\nexport function swallowNextClick(options: { mousedown?: boolean } = {}) {\n if (typeof document === 'undefined') return;\n const onClick = (e: Event) => {\n e.stopPropagation();\n e.preventDefault();\n cleanup();\n };\n const onMouseDown = (e: Event) => {\n e.stopPropagation();\n e.preventDefault();\n document.removeEventListener('mousedown', onMouseDown, true);\n };\n const cleanup = () => {\n document.removeEventListener('click', onClick, true);\n document.removeEventListener('mousedown', onMouseDown, true);\n document.removeEventListener('pointerdown', cleanup, true);\n window.clearTimeout(timer);\n };\n const timer = window.setTimeout(cleanup, 500);\n document.addEventListener('click', onClick, true);\n if (options.mousedown) {\n document.addEventListener('mousedown', onMouseDown, true);\n // The compatibility events of THIS gesture all precede the next one's pointerdown.\n document.addEventListener('pointerdown', cleanup, true);\n }\n}\n","// Shared `@`-mention logic (issue #112) — the source-fetching + Pessoas/Locais sectioning used by BOTH the\n// library's PromptV2 and the obtapp home PromptComposer, so the two `@` implementations don't drift. Rendering\n// stays per-component (each has its own popover markup); only the fetch + grouping + ordering is shared here.\n\nimport type { PromptTriggerItem } from '../components/v2/PromptV2';\n\n/** `'hotel'` (Issue 1139): rows the location source tagged `kind: 'hotel'` — catalog hotels by NAME — get their own\n * section (\"Hotéis\") instead of hiding under \"Locais\", because they come from a different source (TripApi\n * `GET /hotel/names/search`) and lead the list when the server's hotel-name head fires. */\nexport type MentionGroup = 'person' | 'location' | 'hotel';\n\n/** A trigger item tagged with the `@` section it belongs to. Undefined `group` ⇒ render flat (single source). */\nexport type AtMentionItem = PromptTriggerItem & { group?: MentionGroup };\n\n/** How many rows the LEADING section keeps when a slot reads as a place AND a person (`capLeading`): few enough\n * that the other section's first rows are inside a ~5-row dropdown (Ciro, 2026-10-04). Typing narrows both. */\nexport const PERSON_OR_PLACE_LEAD_ROWS = 3;\n\n/** Which vertical the location source should search (issue #876): 'hotel' → hotel places (POIs, addresses,\n * landmarks — TripApi /hotel/locations/search), 'air' → airports/cities as before. From the server's hotel-intent\n * head via the analyze pass — never re-decided client-side. */\nexport type AtQueryVertical = 'air' | 'hotel';\n\n/** Context handed to the location source alongside the query (issue #876). A second PARAMETER (not a second\n * fetcher) so hosts that don't care keep compiling untouched — a function with fewer params is assignable. */\nexport interface AtQueryContext {\n vertical: AtQueryVertical;\n /** The hotel-intent head's SCORE for the current text (0..1), not the thresholded verdict. `vertical` is that\n * score already cut at the server's 0.35; a source that merges two result sets needs the number, because the\n * cut is where \"weakest place outranks strongest airport\" flips on one hundredth of a point. Undefined only\n * when the host predates this field. */\n hotelConfidence?: number;\n /** The hotel-NAME head's score (Issue 1139): P(the traveller is naming a specific hotel — \"reserve o hotel |\").\n * At or above the server's 0.5 the location source leads with catalog hotel names (`kind: 'hotel'` rows) and\n * keeps places and airports below. Undefined when the host or the server predates the head. */\n hotelNameConfidence?: number;\n /** Aborted when this query is superseded (the next keystroke) — pass it to the HTTP calls so a stale search stops\n * competing with the current one. Undefined when the host predates it. */\n signal?: AbortSignal;\n /** A source that merges several result sets of its own can report its list so far, as each one lands, instead of\n * holding the fast ones back behind the slowest. Each call REPLACES the source's previous list; the promise's\n * value is still the final one. Optional on both sides: a source that never calls it simply arrives once. */\n onPartial?: (items: PromptTriggerItem[]) => void;\n /** Report partials in PRIORITY order rather than arrival order: only a prefix of the list whose sections are all\n * final, and never an empty one. Set while the picker already shows rows — there a partial replaces a full list,\n * so a fast low-priority source drawing first makes the list flicker on every keystroke. Off for the first\n * render, where arrival order is simply the fastest paint. */\n byPriority?: boolean;\n}\n\n/** Context handed to the person source (2026-09-11) — the mirror of {@link AtQueryContext} for the other half. */\nexport interface AtPersonQueryContext {\n /** This source's rows will LEAD the list (person-intent won). A blank query then wants a full page of the\n * directory rather than the handful that fits under a place list — Ciro asked for a top 20. */\n leading: boolean;\n /** See {@link AtQueryContext.signal}. */\n signal?: AbortSignal;\n}\n\nexport interface AtMentionFetchers {\n /** Location source (airports / cities — or hotel places when `context.vertical` says so, issue #876). */\n onAtQuery?: (query: string, context?: AtQueryContext) => Promise<PromptTriggerItem[]>;\n /** Person / passenger source (company directory). */\n onAtPersonQuery?: (query: string, context?: AtPersonQueryContext) => Promise<PromptTriggerItem[]>;\n}\n\nexport interface AtMentionOptions {\n /** Person-intent confidence from the analyze pass; orders the two sections. Default 0. */\n personConfidence?: number;\n /** Location-intent confidence from the analyze pass. When location outweighs person, the Locais section leads —\n * so an `@` accepted from a location context (\"voos saindo de @\") searches PLACES, not people. Default 0. */\n locationConfidence?: number;\n /** Confidence at/above which the person section MAY lead (it still only wins if it also outweighs location). Default 0.5. */\n personFirstThreshold?: number;\n /** The search vertical for the location source (issue #876). Default 'air' — today's behavior. */\n vertical?: AtQueryVertical;\n /** Hotel-intent confidence from the analyze pass, handed to the location source alongside `vertical` so it can\n * order its own two result sets by a score rather than by a verdict someone else thresholded. Default 0. */\n hotelConfidence?: number;\n /** Hotel-NAME confidence from the analyze pass (Issue 1139), handed to the location source the same way. Default 0. */\n hotelNameConfidence?: number;\n /** Aborted when the query is superseded; handed to both sources. */\n signal?: AbortSignal;\n /** Keep only this many rows of the LEADING source, so the other section is in view (2026-10-04). Hosts set it\n * when the slot reads as a place AND a person (`usePromptAssist().personOrPlace`): ordering alone put the\n * directory under every location row — 8 airports, 5 places, 3 hotel names — below a ~5-row dropdown. The\n * trailing source is not cut: it is the one the cap exists to bring into view. Undefined = no cap. */\n capLeading?: number;\n /** Called with the merged list every time a source (or part of one, via `onPartial`) lands, so the host can\n * draw rows as they arrive rather than when the slowest source answers. Never called after `signal` aborts. */\n onUpdate?: (items: AtMentionItem[]) => void;\n /** Draw by priority, not arrival (see {@link AtQueryContext.byPriority}): `onUpdate` fires only once the LEADING\n * source has rows, the trailing source only once the leading one is final, and never with an empty list — so\n * a list already on screen is held until the new one can replace it top-down, then only grows downward. */\n byPriority?: boolean;\n}\n\n/**\n * Fetch `@` mention items from whichever sources are wired, as one flat list. When BOTH a location and a person\n * source are present, items are tagged with their `group` and ordered by intent — the Pessoas section leads only\n * when person-intent both clears its threshold AND outweighs location-intent; otherwise Locais leads. This means an\n * `@` opened in a clear location context (\"voos saindo de @\") searches PLACES first even though `@` is dual-purpose.\n * A single wired source returns an untagged flat list (unchanged behaviour). Each source is awaited in parallel and\n * failures are isolated: one source erroring never sinks the other.\n *\n * The section ORDER is decided before anything is fetched, so it holds while rows stream in through `onUpdate`: a\n * source that answers late fills its own slot rather than reshuffling the list. With `byPriority` it does not even\n * do that: nothing is drawn above rows already drawn. The returned promise still resolves once, with the complete\n * list, for hosts that don't stream.\n */\nexport async function fetchAtMentions(\n query: string,\n { onAtQuery, onAtPersonQuery }: AtMentionFetchers,\n { personConfidence = 0, locationConfidence = 0, personFirstThreshold = 0.5, vertical = 'air', hotelConfidence = 0,\n hotelNameConfidence = 0, signal, onUpdate, byPriority = false, capLeading }: AtMentionOptions = {},\n): Promise<AtMentionItem[]> {\n // Decided BEFORE the fetch, not after: the leading source is told it leads, so it can size its own answer.\n // Same inputs the ordering below uses, so the two can never disagree.\n const personFirst = personConfidence >= personFirstThreshold && personConfidence >= locationConfidence;\n let locItems: PromptTriggerItem[] = [];\n let perItems: PromptTriggerItem[] = [];\n // A source that is not wired is final from the start.\n let locDone = !onAtQuery;\n let perDone = !onAtPersonQuery;\n let lastKey: string | null = null;\n // Only meaningful with both sources wired: a lone source has nothing to make room for. And only while the\n // OTHER section can still have rows: once it has answered empty (a guest, a company with no directory), the\n // cap would cut the only list there is for nothing, so it lifts — the list then grows downward, the direction\n // that does not move what is already drawn.\n const cap = (items: PromptTriggerItem[], leading: boolean, other: PromptTriggerItem[], otherDone: boolean) =>\n leading && capLeading !== undefined && onAtQuery && onAtPersonQuery && !(otherDone && other.length === 0)\n ? items.slice(0, capLeading) : items;\n const merge = (allLoc: PromptTriggerItem[], allPer: PromptTriggerItem[]): AtMentionItem[] => {\n const locItems = cap(allLoc, !personFirst, allPer, perDone);\n const perItems = cap(allPer, personFirst, allLoc, locDone);\n // A directory row is a person whatever the source said (Issue 1139) — the icon must not depend on every host\n // remembering to tag it. Location rows keep the source's kind: only it knows an airport from a place from a hotel.\n const people: PromptTriggerItem[] = perItems.map((i) => (i.kind ? i : { ...i, kind: 'person' as const }));\n if (onAtQuery && onAtPersonQuery) {\n const per: AtMentionItem[] = people.map((i) => ({ ...i, group: 'person' }));\n // ONE \"Locais\" section for everything the location source returned (2026-10-06). Hotel names had their own\n // \"Hotéis\" section (Issue 1139) while the source drew one block per source; it now INTERLEAVES airports,\n // places and hotel names by match quality, and a section per kind would start a new header every time a\n // hotel row sat between two places. The row's own `kind` still draws its icon (✈ / pin / bed).\n const loc: AtMentionItem[] = locItems.map((i) => ({ ...i, group: 'location' }));\n return personFirst ? [...per, ...loc] : [...loc, ...per];\n }\n return [...people, ...locItems];\n };\n const publish = () => {\n if (!onUpdate || signal?.aborted) return;\n if (!byPriority) { onUpdate(merge(locItems, perItems)); return; }\n // The leading source's rows go first; the trailing source's only once the leading one is FINAL, or a late\n // section of the leader would land between them. (Location partials are already a final-sections prefix.)\n const shown = personFirst\n ? merge(perDone ? locItems : [], perItems)\n : merge(locItems, locDone ? perItems : []);\n if (shown.length === 0 && !(locDone && perDone)) return;\n const key = shown.map((i) => i.id).join('\\n');\n if (key === lastKey) return; // a held source landing changes nothing on screen — no re-render\n lastKey = key;\n onUpdate(shown);\n };\n await Promise.all([\n onAtQuery\n ? onAtQuery(query, { vertical, hotelConfidence, hotelNameConfidence, signal, byPriority,\n onPartial: (items) => { locItems = items; publish(); } })\n .catch(() => locItems) // keep whatever partial already landed\n .then((items) => { locItems = items; locDone = true; publish(); })\n : undefined,\n onAtPersonQuery\n ? onAtPersonQuery(query, { leading: personFirst, signal })\n .catch(() => [] as PromptTriggerItem[])\n .then((items) => { perItems = items; perDone = true; publish(); })\n : undefined,\n ]);\n return merge(locItems, perItems);\n}\n\n/** True when `items[idx]` opens a new `@` section (its group differs from the previous item's). */\nexport function isSectionStart(items: AtMentionItem[], idx: number): boolean {\n const g = items[idx]?.group;\n return g !== undefined && (idx === 0 || items[idx - 1]?.group !== g);\n}\n","// One mapping from a prediction to a dropdown row, shared by both composers (2026-09-10).\n//\n// The predictions list and the `@` picker are the same surface now, so the only thing a host still has to do is\n// name the fields: a `PredictionItem` is keyed and carries what to INSERT, a dropdown row is identified and\n// carries what to SHOW. Doing that inline in each host is how the two lists drifted apart the first time.\n\nimport type { PredictionItem } from '../hooks/usePromptAssist';\nimport type { DropdownItem } from '../components/v2/TriggerDropdown';\n\n/** A dropdown row that remembers the prediction it came from, so `onSelect` can hand it straight to `applyPrediction`. */\nexport type PredictionRow = DropdownItem & { pred: PredictionItem };\n\n/**\n * Predictions → dropdown rows. A disabled row keeps its reason (\"igual à origem\" — the place is already the\n * prompt's origin), which is the one thing the greying alone does not say.\n */\nexport function toPredictionRows(items: PredictionItem[] | null | undefined): PredictionRow[] {\n return (items ?? []).map((p) => ({\n id: p.key,\n label: p.label,\n value: p.insert ?? p.label,\n hint: p.hint,\n kind: p.icon,\n section: p.section,\n disabled: p.disabled,\n disabledNote: p.disabled ? 'igual à origem' : undefined,\n pred: p,\n }));\n}\n"],"names":["ABSOLUTE_URL","extractLinkAction","__name","link","sessionId","content","action","question","url","parameter","firstDash","firstPart","chunkArray","char","size","_v","i","splitBigLinesWithSpaces","limit","whiteSpaceBreak","allWords","hadOne","word","charArray","chunkedWord","chunk","parseRawNumber","text","number","finalNumber","ratio","UUID_WITH_DASHES_REGEX","UUID_WITHOUT_DASHES_REGEX","startsWithInteractionId","str","interactionId","extractInteractionId","withDashesMatch","withoutDashesMatch","prettiffyPythonFunctionName","functionName","prettyName","isValidInteractionId","initializedTables","_SortableTable","options","container","tables","table","tableIndex","thead","headerRow","headers","isFirstSortableMount","_","index","header","columnIndex","tbody","row","cell","exponentialMatch","base","exponent","fullNumber","formattedNumber","num","firstRow","td","th","attr","error","clickListener","e","mouseEnterListener","mouseLeaveListener","icon","rows","sortState","newDirection","direction","a","b","cellA","cellB","valueA","valueB","comparison","percentageMatch","currencyMatch","date","activeHeader","resizeHandle","isResizing","startX","startWidth","handleResize","stopResize","newWidth","currentPosition","headerContent","currentColumnIndex","dragImage","headerText","highlight","cells","j","fromIndex","toIndex","headerToMove","targetHeader","rowIndex","cellToMove","targetCell","currentOrder","newOrder","columnToMove","newHeader","totalWidth","width","widthValue","_a","originalWidthAttr","originalWidth","headersWidth","estimatedWidth","containerWidth","maxRowWidth","cellWidth","prev","current","factor","finalWidth","calculatedWidth","font","mono","context","style","styleElement","__publicField","SortableTable","TRIGGER_CHARS","triggerTypeFor","ch","HIGHLIGHT_WS","PLACEHOLDER_G","tokenizeSegment","prevCh","tokens","boundaryBefore","idx","end","c","tokenizeForHighlight","re","last","m","chipLocations","locTexts","needles","t","out","tok","rest","at","len","n","placeCaret","textarea","start","insistMs","expected","done","stop","onSelectionChange","timer","ticker","apply","swallowNextClick","onClick","cleanup","onMouseDown","PERSON_OR_PLACE_LEAD_ROWS","fetchAtMentions","query","onAtQuery","onAtPersonQuery","personConfidence","locationConfidence","personFirstThreshold","vertical","hotelConfidence","hotelNameConfidence","signal","onUpdate","byPriority","capLeading","personFirst","locItems","perItems","locDone","perDone","lastKey","cap","items","leading","other","otherDone","merge","allLoc","allPer","people","per","loc","publish","shown","key","isSectionStart","_b","g","toPredictionRows","p"],"mappings":";;;;AAQA,MAAMA,IAAe,4BAERC,IAAoB,gBAAAC,EAAA,CAACC,GAAcC,GAAmBC,MAA0H;AACzL,MAAIC,IAAqB,OACrBC,IAA0B,MAC1BC,IAAqB,MACrBC,IAA2B;AAC/B,MAAIN,EAAK,CAAC,KAAK,KAAK;AAChB,UAAMO,IAAYP,EAAK,QAAQ,GAAG,GAC5BQ,IAAYR,EAAK,MAAM,GAAGO,CAAS;AAEzC,YADAD,IAAYN,EAAK,MAAMO,IAAY,CAAC,GAC5BC,EAAU,eAAY;AAAA,MAC1B,KAAK;AACD,QAAAL,IAAS;AACT;AAAA,MACJ,KAAK;AACD,QAAAA,IAAS,YACTC,IAAWF;AACX;AAAA,IAAA;AAAA,EAEZ,MAAA,CACSL,EAAa,KAAKG,CAAI,KAC3BG,IAAS,OACTE,IAAML,KAEDA,EAAK,CAAC,MAAM,OAOjBG,IAAS,YACTE,IAAML,MAONA,IAAOA,EAAK,WAAW,aAAa,YAAYC,CAAS,GAAG,GAC5DE,IAAS;AAGb,SAAO,EAAE,QAAAA,GAAQ,KAAAE,GAAK,UAAAD,GAAU,WAAAE,EAA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,KAAK,CAACW,MAAU;AAAE,MAAAL,IAAWK,GAAOH,IAAU,IAAMa,EAAA;AAAA,IAAW,CAAC,IACnE;AAAA,EAAA,CACT,GACMN,EAAMV,GAAUC,CAAQ;AACnC;AAnEsBrM,EAAAqL,IAAA;AAsEf,SAASkC,GAAeb,GAAwBtD,GAAsB;AP5K7E,MAAA7B,GAAAiG;AO6KI,QAAMC,KAAIlG,IAAAmF,EAAMtD,CAAG,MAAT,gBAAA7B,EAAY;AACtB,SAAOkG,MAAM,WAAcrE,MAAQ,OAAKoE,IAAAd,EAAMtD,IAAM,CAAC,MAAb,gBAAAoE,EAAgB,WAAUC;AACtE;AAHgBzN,EAAAuN,IAAA;ACpKT,SAASG,GAAiBhB,GAA6D;AAC1F,UAAQA,KAAS,CAAA,GAAI,IAAI,CAACiB,OAAO;AAAA,IAC7B,IAAIA,EAAE;AAAA,IACN,OAAOA,EAAE;AAAA,IACT,OAAOA,EAAE,UAAUA,EAAE;AAAA,IACrB,MAAMA,EAAE;AAAA,IACR,MAAMA,EAAE;AAAA,IACR,SAASA,EAAE;AAAA,IACX,UAAUA,EAAE;AAAA,IACZ,cAAcA,EAAE,WAAW,mBAAmB;AAAA,IAC9C,MAAMA;AAAA,EAAA,EACR;AACN;AAZgB3N,EAAA0N,IAAA;"}
|
|
@@ -184,6 +184,12 @@ interface PromptV2Props {
|
|
|
184
184
|
* Return `@[Name](user:id)`-style values so the agent gets the passenger id without a lookup.
|
|
185
185
|
*/
|
|
186
186
|
onAtPersonQuery?: (query: string, context?: AtPersonQueryContext) => Promise<PromptTriggerItem[]>;
|
|
187
|
+
/**
|
|
188
|
+
* Called when an `@` row is picked — a place, a hotel, a person (not a Data row riding in the list). The obtapp
|
|
189
|
+
* home composer remembers picked places as the next blank `@`'s default (2026-09-11); without this hook a host
|
|
190
|
+
* using PromptV2 had no way to do the same, so picks on the operations page were never remembered.
|
|
191
|
+
*/
|
|
192
|
+
onMentionPicked?: (item: PromptTriggerItem) => void;
|
|
187
193
|
/**
|
|
188
194
|
* Live prompt-assist quick path (debounced ~300ms). Given the text + caret, the server
|
|
189
195
|
* (Qwen next-word + NER) categorizes what's coming so the composer can auto-open the `@`
|
package/dist/utils.js
CHANGED
|
@@ -2,7 +2,7 @@ var u = Object.defineProperty;
|
|
|
2
2
|
var a = (e, t) => u(e, "name", { value: t, configurable: !0 });
|
|
3
3
|
import { a as c, b as s } from "./environmentUtils-VZNTCzEE.js";
|
|
4
4
|
import { A as k, D as U, g as x, c as M, d as R, e as V, f as G, i as W, r as H } from "./environmentUtils-VZNTCzEE.js";
|
|
5
|
-
import { P as Y, S as Z, c as j, a as z, e as Q, b as $, f as q, i as J, d as X, p as ee, s as te, h as oe, j as ae, t as re, k as ie } from "./predictionRows-
|
|
5
|
+
import { P as Y, S as Z, c as j, a as z, e as Q, b as $, f as q, i as J, d as X, p as ee, s as te, h as oe, j as ae, t as re, k as ie } from "./predictionRows-Damfwthh.js";
|
|
6
6
|
import { a as se, b as le, c as ce, d as de, f as ue, p as me } from "./promptTriggers-xwMJ5gRj.js";
|
|
7
7
|
const m = "https://agent.tripapi.com.br", p = "http://localagent:8000", S = /* @__PURE__ */ a((e) => new URLSearchParams(e.location.search).get("local") === "true" ? p : c() ?? m, "getAgentBaseUrl"), f = "https://storage.googleapis.com/aibi_artifacts_bucket", I = /* @__PURE__ */ a(() => f, "getArtifactsBaseUrl"), n = {}, h = (n == null ? void 0 : n.VITE_CADDY) == "true";
|
|
8
8
|
function w() {
|