@8wave/ai-elements 0.125.0-beta.42 → 0.125.0-beta.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -4
- package/dist/_chunks/Chart-1vt0m6l_.js +87 -0
- package/dist/_chunks/Chart-1vt0m6l_.js.map +1 -0
- package/dist/_chunks/{PkChart-CbtMRGWc.js → PkChart-CYFx_UDq.js} +741 -623
- package/dist/_chunks/PkChart-CYFx_UDq.js.map +1 -0
- package/dist/_chunks/PkFilePreview-DfYzaj3Y.js +1745 -0
- package/dist/_chunks/PkFilePreview-DfYzaj3Y.js.map +1 -0
- package/dist/_chunks/{PkFilePreviewDialog-bcTkTcYk.js → PkFilePreviewDialog-COkwyLq6.js} +2 -2
- package/dist/_chunks/{PkFilePreviewDialog-bcTkTcYk.js.map → PkFilePreviewDialog-COkwyLq6.js.map} +1 -1
- package/dist/_chunks/{PkImageEditorDialog-FpbyhV3t.js → PkImageEditorDialog-Ceas-HZA.js} +2 -2
- package/dist/_chunks/{PkImageEditorDialog-FpbyhV3t.js.map → PkImageEditorDialog-Ceas-HZA.js.map} +1 -1
- package/dist/_chunks/{PkSelectionActions-BbfVZY0R.js → PkSelectionActions-Dl3cKb7x.js} +2 -2
- package/dist/_chunks/PkSelectionActions-Dl3cKb7x.js.map +1 -0
- package/dist/_chunks/{PkStreamingMarkdown-COSOOhCg.js → PkStreamingMarkdown-DZvLHy2l.js} +2 -2
- package/dist/_chunks/{PkStreamingMarkdown-COSOOhCg.js.map → PkStreamingMarkdown-DZvLHy2l.js.map} +1 -1
- package/dist/_chunks/{PkToolChatFile-C_gS0X1j.js → PkToolChatFile-D4ukZ9g6.js} +3 -3
- package/dist/_chunks/{PkToolChatFile-C_gS0X1j.js.map → PkToolChatFile-D4ukZ9g6.js.map} +1 -1
- package/dist/_chunks/{PkToolShowArtifact-fpFtKrZo.js → PkToolShowArtifact-wIAxyXrL.js} +2 -2
- package/dist/_chunks/{PkToolShowArtifact-fpFtKrZo.js.map → PkToolShowArtifact-wIAxyXrL.js.map} +1 -1
- package/dist/_chunks/PkToolShowChart-D3E_xBJv.js +138 -0
- package/dist/_chunks/PkToolShowChart-D3E_xBJv.js.map +1 -0
- package/dist/_chunks/{PkToolShowContactForm-BAM772bm.js → PkToolShowContactForm-BhcM-Z6m.js} +2 -2
- package/dist/_chunks/{PkToolShowContactForm-BAM772bm.js.map → PkToolShowContactForm-BhcM-Z6m.js.map} +1 -1
- package/dist/_chunks/{PkToolShowForm-DJcL0bgw.js → PkToolShowForm-D6k7_QLF.js} +3 -3
- package/dist/_chunks/{PkToolShowForm-DJcL0bgw.js.map → PkToolShowForm-D6k7_QLF.js.map} +1 -1
- package/dist/_chunks/{PkToolShowSources-GeWAMHYC.js → PkToolShowSources-Cw1ofky2.js} +2 -2
- package/dist/_chunks/{PkToolShowSources-GeWAMHYC.js.map → PkToolShowSources-Cw1ofky2.js.map} +1 -1
- package/dist/_chunks/chartFormat-B1T7y-16.js +27 -0
- package/dist/_chunks/chartFormat-B1T7y-16.js.map +1 -0
- package/dist/_chunks/{excelNumberFormat-BhQjife9.js → excelNumberFormat-CcXF_wJK.js} +101 -88
- package/dist/_chunks/excelNumberFormat-CcXF_wJK.js.map +1 -0
- package/dist/_chunks/{utils-DMvy5QRR.js → utils-C2aFWWye.js} +132 -110
- package/dist/_chunks/utils-C2aFWWye.js.map +1 -0
- package/dist/ai-elements.es.js +2939 -2882
- package/dist/ai-elements.es.js.map +1 -1
- package/dist-vue/PkChatbot.js +1 -1
- package/dist-vue/PkChatbotEmptyState.js +1 -1
- package/dist-vue/PkChatbotInput.js +1 -1
- package/dist-vue/PkChatbotMessages.js +1 -1
- package/dist-vue/PkChatbotStepPayload.js +1 -1
- package/dist-vue/PkChatbotStepToolDetail.js +1 -1
- package/dist-vue/PkChatbotSteps.js +1 -1
- package/dist-vue/PkChatbotViewChat.js +1 -1
- package/dist-vue/PkChatbotViewConversations.js +1 -1
- package/dist-vue/_chunks/Chart-DsBNs5rS.js +87 -0
- package/dist-vue/_chunks/Chart-DsBNs5rS.js.map +1 -0
- package/dist-vue/_chunks/{PkChart-D-K7nc0g.js → PkChart-CrZqhEpp.js} +112 -74
- package/dist-vue/_chunks/PkChart-CrZqhEpp.js.map +1 -0
- package/dist-vue/_chunks/{PkChatbot-DVQ-Bb7n.js → PkChatbot-CBSe9MOB.js} +6 -6
- package/dist-vue/_chunks/{PkChatbot-DVQ-Bb7n.js.map → PkChatbot-CBSe9MOB.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotEmptyState-OlgewA4_.js → PkChatbotEmptyState-DfyYZXHQ.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotEmptyState-OlgewA4_.js.map → PkChatbotEmptyState-DfyYZXHQ.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotInput-D_I0Gf_u.js → PkChatbotInput-CBalSveL.js} +4 -4
- package/dist-vue/_chunks/{PkChatbotInput-D_I0Gf_u.js.map → PkChatbotInput-CBalSveL.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotMessages-CAXnEfXK.js → PkChatbotMessages-C2AUTqk4.js} +307 -307
- package/dist-vue/_chunks/{PkChatbotMessages-CAXnEfXK.js.map → PkChatbotMessages-C2AUTqk4.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotStepPayload-EBri1L10.js → PkChatbotStepPayload-Bb3Y6kuL.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotStepPayload-EBri1L10.js.map → PkChatbotStepPayload-Bb3Y6kuL.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotStepToolDetail-DiQEa0UV.js → PkChatbotStepToolDetail-CwOxzYOe.js} +16 -16
- package/dist-vue/_chunks/{PkChatbotStepToolDetail-DiQEa0UV.js.map → PkChatbotStepToolDetail-CwOxzYOe.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotSteps-BgLnv2J1.js → PkChatbotSteps-FduD9X9i.js} +38 -38
- package/dist-vue/_chunks/{PkChatbotSteps-BgLnv2J1.js.map → PkChatbotSteps-FduD9X9i.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewChat-CmjD1IXf.js → PkChatbotViewChat-jl3ZbK7H.js} +22 -22
- package/dist-vue/_chunks/{PkChatbotViewChat-CmjD1IXf.js.map → PkChatbotViewChat-jl3ZbK7H.js.map} +1 -1
- package/dist-vue/_chunks/{PkChatbotViewConversations-CVZH5dXx.js → PkChatbotViewConversations-BtwTWqmM.js} +2 -2
- package/dist-vue/_chunks/{PkChatbotViewConversations-CVZH5dXx.js.map → PkChatbotViewConversations-BtwTWqmM.js.map} +1 -1
- package/dist-vue/_chunks/{PkFilePreview-k5gEl3n8.js → PkFilePreview-CRfDEYYo.js} +701 -624
- package/dist-vue/_chunks/PkFilePreview-CRfDEYYo.js.map +1 -0
- package/dist-vue/_chunks/{PkFilePreviewDialog-DUwZPErE.js → PkFilePreviewDialog-u-0rhuRx.js} +2 -2
- package/dist-vue/_chunks/{PkFilePreviewDialog-DUwZPErE.js.map → PkFilePreviewDialog-u-0rhuRx.js.map} +1 -1
- package/dist-vue/_chunks/{PkImageEditorDialog-DQPXePae.js → PkImageEditorDialog-CjMwpb-a.js} +2 -2
- package/dist-vue/_chunks/{PkImageEditorDialog-DQPXePae.js.map → PkImageEditorDialog-CjMwpb-a.js.map} +1 -1
- package/dist-vue/_chunks/{PkStreamingMarkdown-ZasabxE0.js → PkStreamingMarkdown-7Kl_VBH-.js} +2 -2
- package/dist-vue/_chunks/{PkStreamingMarkdown-ZasabxE0.js.map → PkStreamingMarkdown-7Kl_VBH-.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolChatFile-CD26Q2xp.js → PkToolChatFile-DcNRCVXy.js} +3 -3
- package/dist-vue/_chunks/{PkToolChatFile-CD26Q2xp.js.map → PkToolChatFile-DcNRCVXy.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowArtifact-BhVd_ZQ8.js → PkToolShowArtifact-C7CxCqVO.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowArtifact-BhVd_ZQ8.js.map → PkToolShowArtifact-C7CxCqVO.js.map} +1 -1
- package/dist-vue/_chunks/PkToolShowChart-DULlrMjq.js +133 -0
- package/dist-vue/_chunks/PkToolShowChart-DULlrMjq.js.map +1 -0
- package/dist-vue/_chunks/{PkToolShowContactForm-CackCDGD.js → PkToolShowContactForm-472d-SAE.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowContactForm-CackCDGD.js.map → PkToolShowContactForm-472d-SAE.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowDiagram-CABPsFi8.js → PkToolShowDiagram-RrqVpOaX.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowDiagram-CABPsFi8.js.map → PkToolShowDiagram-RrqVpOaX.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowForm-BStbk4Iu.js → PkToolShowForm-CgyszDEI.js} +3 -3
- package/dist-vue/_chunks/{PkToolShowForm-BStbk4Iu.js.map → PkToolShowForm-CgyszDEI.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowImageGallery-BeeHsdTp.js → PkToolShowImageGallery-LBx9JE6p.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowImageGallery-BeeHsdTp.js.map → PkToolShowImageGallery-LBx9JE6p.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowProductList-BfUiap9U.js → PkToolShowProductList-THiH4EzZ.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowProductList-BfUiap9U.js.map → PkToolShowProductList-THiH4EzZ.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowSources-CgEkcyRg.js → PkToolShowSources-CEqGXOOt.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowSources-CgEkcyRg.js.map → PkToolShowSources-CEqGXOOt.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowVideo-CqSRnDNC.js → PkToolShowVideo-8Gi3vOer.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowVideo-CqSRnDNC.js.map → PkToolShowVideo-8Gi3vOer.js.map} +1 -1
- package/dist-vue/_chunks/{PkToolShowWebPages-B-qIS8qY.js → PkToolShowWebPages-xjUPdfOU.js} +2 -2
- package/dist-vue/_chunks/{PkToolShowWebPages-B-qIS8qY.js.map → PkToolShowWebPages-xjUPdfOU.js.map} +1 -1
- package/dist-vue/_chunks/chartFormat-B1T7y-16.js +27 -0
- package/dist-vue/_chunks/chartFormat-B1T7y-16.js.map +1 -0
- package/dist-vue/_chunks/{excelNumberFormat-C1sCQrOz.js → excelNumberFormat-BxRi0Y3e.js} +101 -88
- package/dist-vue/_chunks/excelNumberFormat-BxRi0Y3e.js.map +1 -0
- package/dist-vue/_chunks/{utils-KBB6SDPn.js → utils-VVbH-Liq.js} +30 -30
- package/dist-vue/_chunks/utils-VVbH-Liq.js.map +1 -0
- package/dist-vue/apps/web-component/src/composables/useChatbotAgent.d.ts +6 -6
- package/dist-vue/apps/web-component/src/composables/useSelectionActions.d.ts +14 -4
- package/dist-vue/composables.js +9 -3
- package/dist-vue/composables.js.map +1 -1
- package/dist-vue/index.js +42 -42
- package/dist-vue/index.js.map +1 -1
- package/dist-vue/locales.js +6 -0
- package/dist-vue/packages/components/src/chat/PkAgentSettingsPanel.d.ts +6 -6
- package/dist-vue/packages/components/src/chat/PkChart.d.ts +8 -0
- package/dist-vue/packages/components/src/chat/PkChatbotMessages.d.ts +1 -1
- package/dist-vue/packages/components/src/chat/PkFileChart.d.ts +14 -0
- package/dist-vue/packages/components/src/chat/PkSelectionActionIconPicker.d.ts +2 -2
- package/dist-vue/packages/components/src/chat/PkSelectionAnswerCard.d.ts +6 -0
- package/dist-vue/packages/components/src/chat/PkWordPreviewRuns.d.ts +4 -1
- package/dist-vue/packages/components/src/chat/selectionActionEdits.d.ts +1 -1
- package/dist-vue/packages/components/src/chat/useChatFilePreview.d.ts +240 -0
- package/dist-vue/packages/components/src/chat/utils.d.ts +57 -5
- package/dist-vue/packages/composable/src/chatbot/useChatbotStore.d.ts +18 -18
- package/dist-vue/packages/composable/src/useSettledSelection.d.ts +2 -2
- package/dist-vue/packages/models/src/schema/Agent.d.ts +21 -21
- package/dist-vue/packages/models/src/schema/Chart.d.ts +91 -0
- package/dist-vue/packages/models/src/schema/ReasoningChat.d.ts +6 -6
- package/dist-vue/packages/models/src/schema/SelectionAction.d.ts +11 -11
- package/dist-vue/packages/models/src/schema/SelectionActionPreview.d.ts +3 -3
- package/dist-vue/packages/models/src/schema/SpreadsheetPreview.d.ts +381 -0
- package/dist-vue/packages/models/src/schema/SubAgent.d.ts +6 -6
- package/dist-vue/packages/models/src/schema/WordPreview.d.ts +304 -0
- package/dist-vue/style.css +1 -1
- package/package.json +1 -1
- package/dist/_chunks/PkChart-CbtMRGWc.js.map +0 -1
- package/dist/_chunks/PkFilePreview-DC4iX7Yc.js +0 -1665
- package/dist/_chunks/PkFilePreview-DC4iX7Yc.js.map +0 -1
- package/dist/_chunks/PkSelectionActions-BbfVZY0R.js.map +0 -1
- package/dist/_chunks/PkToolShowChart-DZWu3Yuo.js +0 -224
- package/dist/_chunks/PkToolShowChart-DZWu3Yuo.js.map +0 -1
- package/dist/_chunks/excelNumberFormat-BhQjife9.js.map +0 -1
- package/dist/_chunks/utils-DMvy5QRR.js.map +0 -1
- package/dist-vue/_chunks/PkChart-D-K7nc0g.js.map +0 -1
- package/dist-vue/_chunks/PkFilePreview-k5gEl3n8.js.map +0 -1
- package/dist-vue/_chunks/PkToolShowChart-BQXxaPIO.js +0 -217
- package/dist-vue/_chunks/PkToolShowChart-BQXxaPIO.js.map +0 -1
- package/dist-vue/_chunks/excelNumberFormat-C1sCQrOz.js.map +0 -1
- package/dist-vue/_chunks/utils-KBB6SDPn.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"excelNumberFormat-BhQjife9.js","names":["z.object","z.number","z.enum","z.string","z.literal","z.array","z.discriminatedUnion","z.boolean","z.record","z.object","z.string","z.number","z.literal","z.enum","z.union","z.boolean","z.array","z.discriminatedUnion","object","string","number","array","literal","_enum","boolean","discriminatedUnion","union","record","WordPreviewAnchorSchema","WordPreviewPictureSchema","WordPreviewRunSchema","WordPreviewParagraphStyleSchema","WordPreviewCellSchema","sectionStart","WordPreviewBlockSchema","WordPreviewPageSchema","WordPreviewPartsOfSectionSchema","WordPreviewSectionSchema","WordPreviewSchema","SpreadsheetPreviewBorderSchema","SpreadsheetPreviewStyleSchema","SpreadsheetPreviewCellSchema","SpreadsheetPreviewRowSchema","SpreadsheetPreviewColumnSchema","SpreadsheetPreviewSheetSchema","SpreadsheetPreviewSchema","isSpreadsheetDateFormat","code","COLORS","sectionsOf","out","current","i","ch","close","stop","parseSection","tokens","section","text","last","t","source","end","inner","condition","symbol","satisfies","op","value","than","sectionFor","first","second","third","sections","memo","kept","key","make","limit","numberFormats","intlNumber","locale","options","formatDecimal","format","x","partsOfDecimal","separatorsOf","marksOf","parts","p","textOf","MAX_DECIMALS","layInteger","chars","digits","slots","pattern","taken","laid","group","run","layFraction","convergent","p0","q0","p1","q1","rest","a","p2","q2","most","left","parsedSections","sectionsFor","formatExcelNumber","tint","signed","minus","shown","n","general","at","before","scaled","exponentAt","mantissa","pointAt","whole","fraction","plus","width","m","decimal","power","slash","gap","top","below","fixed","found","units","q","wholeText","intEnd","scale","intTokens","grouped","u","places","decimals","LCIDS","SYSTEM_DATES","parseDate","lower","elapsed","tag","k","size","short","part","after","parsedDates","dayOf","date1904","days","d","date","dateFormats","nameOf","LAST_SERIAL","formatExcelDate","serial","sources","chosen","tagged","names","ampm","unit","total","within","day","hour","minute","weekdayAt","pad","excelDateText","written","raw"],"sources":["../../../../packages/models/src/schema/WordPreview.ts","../../../../packages/models/src/schema/SpreadsheetPreview.ts","../../../../packages/components/src/chat/excelNumberFormat.ts"],"sourcesContent":["import * as z from 'zod'\n\n// The preview of a Word document stored in a chat (spec `chat-office-files.md`,\n// F6, item 3, and the viewer of its follow-ups): typed blocks the server\n// reads from the document, with the look its styles give them, and the size\n// of its page, its headers, footers and images. The chat draws them as text,\n// never as HTML, and the images as `<img>` of WebP the server wrote, so a\n// document someone uploaded cannot inject markup into the page.\n\n/**\n * Where an image anchored to the page or to a paragraph sits, in points, and\n * how the text goes around it: under or over it, beside it, or above and\n * below it.\n */\nexport const WordPreviewAnchorSchema = z.object({\n x: z.number(),\n y: z.number(),\n /** What `x` counts from: the page's edge or the left margin. */\n xFrom: z.enum(['page', 'margin']),\n /** What `y` counts from: the page's edge, the top margin or the paragraph. */\n yFrom: z.enum(['page', 'margin', 'paragraph']),\n wrap: z.enum(['behind', 'front', 'around', 'block']),\n})\n\n/** An image the preview draws, its size in points. */\nexport const WordPreviewPictureSchema = z.object({\n /** Its key in the preview's `images`. */\n ref: z.string(),\n width: z.number(),\n height: z.number(),\n /** Set for an image Word positions itself; one in the text has none. */\n anchor: WordPreviewAnchorSchema.optional(),\n})\n\nexport const WordPreviewRunSchema = z.object({\n text: z.string(),\n /** A tracked change not accepted yet, and who made it. */\n change: z.enum(['inserted', 'deleted']).optional(),\n author: z.string().optional(),\n bold: z.literal(true).optional(),\n italic: z.literal(true).optional(),\n underline: z.literal(true).optional(),\n strike: z.literal(true).optional(),\n caps: z.literal(true).optional(),\n vertAlign: z.enum(['super', 'sub']).optional(),\n /** Font, size in points and `#rrggbb` color, where not the document's. */\n font: z.string().optional(),\n size: z.number().optional(),\n color: z.string().optional(),\n /** The highlighter's color, `#rrggbb`. */\n highlight: z.string().optional(),\n /** Stands for an image, a chart or an object. */\n image: z.literal(true).optional(),\n /** The image itself, when the preview draws it; otherwise a placeholder. */\n picture: WordPreviewPictureSchema.optional(),\n /** The result of a page number field, written again on each page. */\n field: z.enum(['page', 'pages', 'sectionPages']).optional(),\n /** The number or bullet of a list item in a cell: Word's, not the text's. */\n label: z.literal(true).optional(),\n})\n\n/** How a paragraph sits on the page; lengths in points. */\nexport const WordPreviewParagraphStyleSchema = z.object({\n align: z.enum(['left', 'center', 'right', 'justify']).optional(),\n indentLeft: z.number().optional(),\n indentRight: z.number().optional(),\n /** The first line's indent; negative for a hanging one. */\n firstLine: z.number().optional(),\n spaceBefore: z.number().optional(),\n spaceAfter: z.number().optional(),\n /**\n * Line height as a multiple of the font's, `lineExact` points, or at\n * least `lineAtLeast` points (Word's \"At least\").\n */\n lineHeight: z.number().optional(),\n lineExact: z.number().optional(),\n lineAtLeast: z.number().optional(),\n /** Starts on a new page: a page break or the paragraph's setting. */\n pageBreakBefore: z.literal(true).optional(),\n /** Stays on the page of the block after it (Word's \"Keep with next\"). */\n keepNext: z.literal(true).optional(),\n /** The paragraph's shading, `#rrggbb`. */\n shading: z.string().optional(),\n /**\n * The size of its paragraph mark in points, where not the document's:\n * the height of a blank line, and the least of each line.\n */\n size: z.number().optional(),\n})\n\nexport const WordPreviewCellSchema = z.object({\n runs: z.array(WordPreviewRunSchema),\n /** The grid columns a merged cell spans, when more than one. */\n span: z.number().optional(),\n /** The cell's shading, `#rrggbb`. */\n fill: z.string().optional(),\n /** How its first paragraph is aligned, when not to the left. */\n align: z.enum(['left', 'center', 'right', 'justify']).optional(),\n /** The size of its first paragraph's mark, where not the document's. */\n size: z.number().optional(),\n /** A paragraph of it keeps its row with the next one. */\n keepNext: z.literal(true).optional(),\n /** The ids of the paragraphs it draws, as `readWordDocument` names them. */\n ids: z.array(z.string()).optional(),\n})\n\n/** The first block of a section after the first: its index in `sections`. */\nconst sectionStart = z.number().optional()\n\nexport const WordPreviewBlockSchema = z.discriminatedUnion('kind', [\n z.object({\n kind: z.literal('heading'),\n /** The paragraph's id, as `readWordDocument` names it. */\n id: z.string().optional(),\n /** 0 for the title, then the outline level from 1. */\n level: z.number(),\n /** The number Word draws before a numbered heading (\"1.\", \"Art. 2\"). */\n label: z.string().optional(),\n runs: z.array(WordPreviewRunSchema),\n style: WordPreviewParagraphStyleSchema.optional(),\n section: sectionStart,\n }),\n z.object({\n kind: z.literal('paragraph'),\n /** The paragraph's id, as `readWordDocument` names it. */\n id: z.string().optional(),\n /** The number or bullet Word draws before a list item. */\n label: z.string().optional(),\n runs: z.array(WordPreviewRunSchema),\n style: WordPreviewParagraphStyleSchema.optional(),\n section: sectionStart,\n }),\n z.object({\n kind: z.literal('table'),\n /** Rows of cells, each cell its paragraphs' runs. */\n rows: z.array(z.array(WordPreviewCellSchema)),\n /** The widths of the grid's columns in points, when the file says. */\n widths: z.array(z.number()).optional(),\n /** The table draws lines between its cells. */\n borders: z.boolean(),\n /** Starts on a new page. */\n pageBreakBefore: z.literal(true).optional(),\n section: sectionStart,\n }),\n])\n\n/** The page of the document's first section, in points. */\nexport const WordPreviewPageSchema = z.object({\n width: z.number(),\n height: z.number(),\n margins: z.object({\n top: z.number(),\n right: z.number(),\n bottom: z.number(),\n left: z.number(),\n }),\n})\n\n/** The headers or the footers of a section: keys in the preview's `parts`. */\nconst WordPreviewPartsOfSectionSchema = z.object({\n default: z.string().optional(),\n /** On the section's first page, when it has a different one. */\n first: z.string().optional(),\n /** On even pages, when the document has different ones. */\n even: z.string().optional(),\n})\n\n/** A section of the body: its page, its header and footer, its numbering. */\nexport const WordPreviewSectionSchema = z.object({\n page: WordPreviewPageSchema,\n /** From the page's top edge to the header, from the bottom to the footer. */\n headerDistance: z.number(),\n footerDistance: z.number(),\n headers: WordPreviewPartsOfSectionSchema,\n footers: WordPreviewPartsOfSectionSchema,\n /** Its first page takes the `first` header and footer. */\n titlePage: z.literal(true).optional(),\n /** The number of its first page, when it restarts the count. */\n pageStart: z.number().optional(),\n})\n\nexport const WordPreviewSchema = z.object({\n kind: z.literal('word'),\n blocks: z.array(WordPreviewBlockSchema),\n /** The body went on past what a preview shows. */\n truncated: z.boolean(),\n /** Whose tracked changes the document holds, for the legend. */\n revisionAuthors: z.array(z.string()),\n page: WordPreviewPageSchema,\n /** The font, size and color of the document's normal text. */\n defaults: z.object({\n font: z.string(),\n size: z.number(),\n color: z.string().optional(),\n }),\n /** The sections of the body in order; the first one holds `page`. */\n sections: z.array(WordPreviewSectionSchema).optional(),\n /** The headers and footers the sections use, as blocks, by part. */\n parts: z.record(z.string(), z.array(WordPreviewBlockSchema)).optional(),\n /** Even pages take the `even` header and footer. */\n evenAndOddHeaders: z.literal(true).optional(),\n /** The images the runs draw, by `ref`: `data:image/webp` URIs. */\n images: z.record(z.string(), z.string()).optional(),\n})\n\nexport type WordPreviewAnchor = z.infer<typeof WordPreviewAnchorSchema>\nexport type WordPreviewPicture = z.infer<typeof WordPreviewPictureSchema>\nexport type WordPreviewSection = z.infer<typeof WordPreviewSectionSchema>\nexport type WordPreviewRun = z.infer<typeof WordPreviewRunSchema>\nexport type WordPreviewParagraphStyle = z.infer<\n typeof WordPreviewParagraphStyleSchema\n>\nexport type WordPreviewCell = z.infer<typeof WordPreviewCellSchema>\nexport type WordPreviewBlock = z.infer<typeof WordPreviewBlockSchema>\nexport type WordPreviewPage = z.infer<typeof WordPreviewPageSchema>\nexport type WordPreview = z.infer<typeof WordPreviewSchema>\n","import * as z from 'zod'\nimport { WordPreviewSchema } from './WordPreview'\n\n// The preview of a spreadsheet stored in a chat (spec `chat-office-files.md`,\n// F6, item 4, and the viewer of its follow-ups): the rows of each sheet as\n// typed cells with the look the file gives them, which the chat draws as a\n// grid with Excel's column letters and row numbers, and formats in the\n// reader's language.\n\n/** One side of a cell's border: its color and its width in pixels. */\nexport const SpreadsheetPreviewBorderSchema = z.object({\n color: z.string(),\n width: z.number(),\n})\n\n/**\n * The look of a cell as the file sets it. Colors are `#rrggbb`, resolved\n * from the theme and the palette. The cells name a style by its index.\n */\nexport const SpreadsheetPreviewStyleSchema = z.object({\n bold: z.literal(true).optional(),\n italic: z.literal(true).optional(),\n underline: z.literal(true).optional(),\n strike: z.literal(true).optional(),\n /** Font size in points, when not the sheet's 11. */\n size: z.number().optional(),\n color: z.string().optional(),\n fill: z.string().optional(),\n align: z.enum(['left', 'center', 'right']).optional(),\n valign: z.enum(['top', 'middle']).optional(),\n wrap: z.literal(true).optional(),\n /** Indent steps of the alignment, about three characters each. */\n indent: z.number().optional(),\n borders: z\n .object({\n top: SpreadsheetPreviewBorderSchema.optional(),\n right: SpreadsheetPreviewBorderSchema.optional(),\n bottom: SpreadsheetPreviewBorderSchema.optional(),\n left: SpreadsheetPreviewBorderSchema.optional(),\n })\n .optional(),\n})\n\nexport const SpreadsheetPreviewCellSchema = z.object({\n /** Its column, from 1 for A. */\n col: z.number(),\n /** Absent for an empty cell. A date is `YYYY-MM-DD`. */\n value: z.union([z.string(), z.number(), z.boolean()]).optional(),\n format: z.enum(['currency', 'percent', 'date', 'error']).optional(),\n /** Decimals the cell's number format shows. */\n decimals: z.number().optional(),\n /** Decimals it shows at most, when some are optional (`0.0#`). */\n maxDecimals: z.number().optional(),\n /** ISO code of a currency format: EUR, USD, GBP, CAD. */\n currency: z.string().optional(),\n /** Its number format separates the thousands (`#,##0`). */\n grouped: z.literal(true).optional(),\n /**\n * Index of its number format in the preview's `numberFormats`, for a\n * number or a date; the fields above describe the same format to an\n * older client.\n */\n numFmt: z.number().optional(),\n /**\n * A date or a time as the workbook holds it: days since its day 0, in\n * its date system (`date1904` of the preview).\n */\n serial: z.number().optional(),\n /** A formula whose result the file does not hold yet. */\n missing: z.literal(true).optional(),\n /** The formula as Excel shows it in its bar, without the `=`. */\n formula: z.string().optional(),\n /** Index of its look in the preview's `styles`. */\n style: z.number().optional(),\n /** The first cell of merged cells: the rows and columns they cover. */\n span: z.object({ rows: z.number(), cols: z.number() }).optional(),\n})\n\nexport const SpreadsheetPreviewRowSchema = z.object({\n /** Its number, from 1: hidden rows are left out. */\n row: z.number(),\n /** In pixels, when not the default. */\n height: z.number().optional(),\n /** The cells that hold something or have a look, by column. */\n cells: z.array(SpreadsheetPreviewCellSchema),\n})\n\nexport const SpreadsheetPreviewColumnSchema = z.object({\n col: z.number(),\n /** In pixels, when not the default. */\n width: z.number().optional(),\n hidden: z.literal(true).optional(),\n})\n\nexport const SpreadsheetPreviewSheetSchema = z.object({\n name: z.string(),\n rows: z.array(SpreadsheetPreviewRowSchema),\n /** The columns whose width the file sets. */\n columns: z.array(SpreadsheetPreviewColumnSchema),\n /** The rows Excel hides, which the grid skips as Excel does. */\n hiddenRows: z.array(z.number()).optional(),\n /** The last row and column the preview shows. */\n lastRow: z.number(),\n lastColumn: z.number(),\n /** Rows and columns frozen at the top and at the left. */\n frozen: z.object({ rows: z.number(), cols: z.number() }).optional(),\n /** Excel draws the grid lines of the sheet. */\n gridlines: z.boolean(),\n /** Rows and columns past what the preview shows. */\n moreRows: z.number(),\n moreColumns: z.number(),\n})\n\nexport const SpreadsheetPreviewSchema = z.object({\n kind: z.literal('spreadsheet'),\n sheets: z.array(SpreadsheetPreviewSheetSchema),\n styles: z.array(SpreadsheetPreviewStyleSchema),\n /** The number format codes the cells name by `numFmt` (`#,##0.00 \"€\"`). */\n numberFormats: z.array(z.string()).optional(),\n /** The workbook counts its dates from 1904, as some Mac files do. */\n date1904: z.literal(true).optional(),\n /** Formula results old or missing until Excel opens the file. */\n staleFormulas: z.boolean(),\n /** Formula results computed in the chat, which Excel computes again. */\n computedFormulas: z.boolean(),\n})\n\n/** What the preview route answers, by the kind of file. */\nexport const ChatFilePreviewSchema = z.discriminatedUnion('kind', [\n WordPreviewSchema,\n SpreadsheetPreviewSchema,\n])\n\n/**\n * An Excel number format of dates or times: outside its text, its colors\n * and its locale tags it names days, months, years, hours, minutes or\n * seconds (`dd/mm/yyyy`, `hh:mm`, `[h]:mm`).\n */\nexport const isSpreadsheetDateFormat = (code: string): boolean =>\n /[dmyhs]|am\\/pm|a\\/p/i.test(\n code.replace(/\"[^\"]*\"|\\\\.|\\[(?![hms]+\\])[^\\]]*\\]/gi, ''),\n )\n\nexport type SpreadsheetPreviewBorder = z.infer<\n typeof SpreadsheetPreviewBorderSchema\n>\nexport type SpreadsheetPreviewStyle = z.infer<\n typeof SpreadsheetPreviewStyleSchema\n>\nexport type SpreadsheetPreviewCell = z.infer<\n typeof SpreadsheetPreviewCellSchema\n>\nexport type SpreadsheetPreviewRow = z.infer<typeof SpreadsheetPreviewRowSchema>\nexport type SpreadsheetPreviewColumn = z.infer<\n typeof SpreadsheetPreviewColumnSchema\n>\nexport type SpreadsheetPreviewSheet = z.infer<\n typeof SpreadsheetPreviewSheetSchema\n>\nexport type SpreadsheetPreview = z.infer<typeof SpreadsheetPreviewSchema>\nexport type ChatFilePreview = z.infer<typeof ChatFilePreviewSchema>\n","/**\n * A number as Excel shows it under a number format code (`#,##0.00 \"€\"`,\n * `#,##0;[Red](#,##0)`, `0.0,\"k\"`), with the reader's separators: the\n * section for the value's sign or condition, its literal text, its color,\n * grouping, decimals, percent, thousands scaling, leading zeros, digits\n * mixed with text (`000-000`), fractions and scientific notation; and a date\n * or a time in the order, digits and names its code writes. Checked cell by\n * cell against Excel for Mac (the widget's `excelNumberFormat.test.ts`).\n */\n\n/** Excel's eight color names, as a number format writes them. */\nconst COLORS: Record<string, string> = {\n black: '#000000',\n blue: '#0000ff',\n cyan: '#00ffff',\n green: '#00ff00',\n magenta: '#ff00ff',\n red: '#ff0000',\n white: '#ffffff',\n yellow: '#ffff00',\n}\n\ntype Token =\n | { kind: 'digit'; char: '0' | '#' | '?' }\n | { kind: 'point' }\n | { kind: 'comma' }\n | { kind: 'percent' }\n | { kind: 'exponent'; plus: boolean }\n | { kind: 'text'; text: string }\n | { kind: 'general' }\n\ntype Section = {\n tokens: Token[]\n color?: string\n condition?: { op: string; than: number }\n}\n\n/** The code's sections, split outside quotes, escapes and brackets. */\nconst sectionsOf = (code: string): string[] => {\n const out: string[] = []\n let current = ''\n for (let i = 0; i < code.length; i++) {\n const ch = code[i]\n const close =\n ch === '\"'\n ? code.indexOf('\"', i + 1)\n : ch === '['\n ? code.indexOf(']', i)\n : -2\n if (close !== -2) {\n const stop = close === -1 ? code.length : close\n current += code.slice(i, stop + 1)\n i = stop\n } else if (ch === '\\\\' || ch === '_' || ch === '*') {\n current += code.slice(i, i + 2)\n i++\n } else if (ch === ';') {\n out.push(current)\n current = ''\n } else {\n current += ch\n }\n }\n return [...out, current]\n}\n\n/** The tokens of one section, with its color and condition. */\nconst parseSection = (source: string): Section => {\n const tokens: Token[] = []\n const section: Section = { tokens }\n const text = (t: string) => {\n const last = tokens[tokens.length - 1]\n if (last?.kind === 'text') {\n last.text += t\n } else if (t) {\n tokens.push({ kind: 'text', text: t })\n }\n }\n for (let i = 0; i < source.length; i++) {\n const ch = source[i]\n if (ch === '\"') {\n const end = source.indexOf('\"', i + 1)\n const stop = end === -1 ? source.length : end\n text(source.slice(i + 1, stop))\n i = stop\n } else if (ch === '\\\\') {\n text(source[i + 1] ?? '')\n i++\n } else if (ch === '_') {\n // Room for a character: a space comes near enough\n text(' ')\n i++\n } else if (ch === '*') {\n // A character repeated across the column: once is enough here\n text(source[i + 1] ?? '')\n i++\n } else if (ch === '[') {\n const end = source.indexOf(']', i)\n const inner = source.slice(i + 1, end === -1 ? undefined : end)\n i = end === -1 ? source.length : end\n const condition = /^(<=|>=|<>|<|>|=)\\s*(-?[\\d.]+)$/.exec(inner)\n const symbol = /^\\$([^-]*)(?:-[0-9a-f]+)?$/i.exec(inner)\n if (condition) {\n section.condition = {\n op: condition[1],\n than: Number(condition[2]),\n }\n } else if (COLORS[inner.toLowerCase()]) {\n section.color = COLORS[inner.toLowerCase()]\n } else if (symbol) {\n text(symbol[1])\n }\n // `[Color10]`, `[h]` and the like draw nothing here\n } else if (ch === '0' || ch === '#' || ch === '?') {\n tokens.push({ kind: 'digit', char: ch })\n } else if (ch === '.') {\n tokens.push({ kind: 'point' })\n } else if (ch === ',') {\n tokens.push({ kind: 'comma' })\n } else if (ch === '%') {\n tokens.push({ kind: 'percent' })\n text('%')\n } else if (/[eE][+-]/.test(source.slice(i, i + 2))) {\n tokens.push({ kind: 'exponent', plus: source[i + 1] === '+' })\n i++\n } else if (/^general/i.test(source.slice(i, i + 7))) {\n tokens.push({ kind: 'general' })\n i += 6\n } else if (ch === '@') {\n // A number under the text format shows as General\n tokens.push({ kind: 'general' })\n } else {\n text(ch)\n }\n }\n return section\n}\n\nconst satisfies = (\n value: number,\n { op, than }: { op: string; than: number },\n): boolean =>\n op === '<'\n ? value < than\n : op === '<='\n ? value <= than\n : op === '>'\n ? value > than\n : op === '>='\n ? value >= than\n : op === '='\n ? value === than\n : value !== than\n\n/**\n * The section that shows `value`, and whether Excel writes the minus sign\n * itself: not in the section for negatives, nor in one a condition chose,\n * whose own text carries the sign.\n */\nconst sectionFor = (\n sections: Section[],\n value: number,\n): { section: Section; minus: boolean } => {\n const [first, second, third] = sections\n if (first.condition || second?.condition) {\n if (first.condition && satisfies(value, first.condition)) {\n return { section: first, minus: false }\n }\n if (second?.condition && satisfies(value, second.condition)) {\n return { section: second, minus: false }\n }\n const rest = third ?? (second && !second.condition ? second : first)\n return { section: rest, minus: value < 0 }\n }\n if (value < 0 && second) {\n return { section: second, minus: false }\n }\n if (value === 0 && third) {\n return { section: third, minus: false }\n }\n return { section: first, minus: value < 0 }\n}\n\n/** Kept results that a grid asks for again and again, emptied past a size. */\nconst memo = <T>(limit = 2000) => {\n const kept = new Map<string, T>()\n return (key: string, make: () => T): T => {\n let value = kept.get(key)\n if (value === undefined) {\n value = make()\n if (kept.size >= limit) {\n kept.clear()\n }\n kept.set(key, value)\n }\n return value\n }\n}\n\nconst numberFormats = memo<Intl.NumberFormat>()\nconst intlNumber = (locale: string, options: Intl.NumberFormatOptions) =>\n numberFormats(\n `${locale}|${JSON.stringify(options)}`,\n () => new Intl.NumberFormat(locale, options),\n )\n\n/**\n * `x` formatted from its 15 significant digits, as Excel holds a number:\n * 1.005, stored as 1.00499…, rounds to 1.01 as in Excel. Intl formats the\n * decimal string exactly where the browser can, the number elsewhere.\n */\nconst formatDecimal = (format: Intl.NumberFormat, x: number): string =>\n format.format(\n (Number.isFinite(x) ? x.toPrecision(15) : x) as unknown as number,\n )\n\nconst partsOfDecimal = (format: Intl.NumberFormat, x: number) =>\n format.formatToParts(\n (Number.isFinite(x) ? x.toPrecision(15) : x) as unknown as number,\n )\n\n/** The reader's decimal point and thousands separator. */\nconst separatorsOf = memo<{ decimal: string; group: string }>()\nconst marksOf = (locale: string) =>\n separatorsOf(locale, () => {\n const parts = intlNumber(locale, {}).formatToParts(12345.6)\n return {\n decimal: parts.find((p) => p.type === 'decimal')?.value ?? '.',\n group: parts.find((p) => p.type === 'group')?.value ?? ',',\n }\n })\n\nconst textOf = (tokens: Token[]): string =>\n tokens.map((t) => (t.kind === 'text' ? t.text : '')).join('')\n\n/** Excel shows at most 30 decimals; a code asking more draws 20 here. */\nconst MAX_DECIMALS = 20\n\n/**\n * The digits of a whole number laid right to left into the placeholders of\n * `pattern`, with its text between them (`000-000`): `0` writes a zero where\n * no digit is left, `?` a space, `#` nothing; the digits past the first\n * placeholder all go there, as in Excel.\n */\nconst layInteger = (\n digits: string,\n pattern: Token[],\n group: string | undefined,\n): string => {\n const chars = [...(digits === '0' ? '' : digits)]\n let slots = pattern.filter((t) => t.kind === 'digit').length\n const out: string[] = []\n for (let i = pattern.length - 1; i >= 0; i--) {\n const t = pattern[i]\n if (t.kind === 'text') {\n out.unshift(t.text)\n } else if (t.kind === 'digit') {\n slots--\n const taken = slots === 0 ? chars.splice(0).join('') : chars.pop()\n out.unshift(\n taken || (t.char === '0' ? '0' : t.char === '?' ? ' ' : ''),\n )\n }\n }\n const laid = out.join('')\n return group\n ? laid.replace(/\\d+/, (run) => run.replace(/\\B(?=(\\d{3})+$)/g, group))\n : laid\n}\n\n/**\n * Decimal digits laid left to right into the placeholders after the point,\n * with their text (`0.0\"x\"0` shows 1.23 as 1.2x3): a `?` left over is a\n * space, as Excel keeps the column of decimals in line.\n */\nconst layFraction = (digits: string, pattern: Token[]): string => {\n const chars = [...digits]\n return pattern\n .map((t) =>\n t.kind === 'text'\n ? t.text\n : t.kind === 'digit'\n ? (chars.shift() ??\n (t.char === '0' ? '0' : t.char === '?' ? ' ' : ''))\n : '',\n )\n .join('')\n}\n\n/**\n * The fraction of `x` Excel writes with a denominator up to `most`: the last\n * convergent of its continued fraction that fits, as Excel's results show\n * (0.07 under `?/?` is 0, not 1/9).\n */\nconst convergent = (x: number, most: number): { p: number; q: number } => {\n let [p0, q0, p1, q1] = [0, 1, 1, 0]\n let rest = x\n for (let i = 0; i < 64; i++) {\n const a = Math.floor(rest)\n const p2 = a * p1 + p0\n const q2 = a * q1 + q0\n if (q2 > most) {\n break\n }\n ;[p0, q0, p1, q1] = [p1, q1, p2, q2]\n const left = rest - a\n if (left < 1e-12) {\n break\n }\n rest = 1 / left\n }\n return q1 === 0 ? { p: 0, q: 1 } : { p: p1, q: q1 }\n}\n\n/** The sections of each code met, read once: a grid repeats a few codes. */\nconst parsedSections = memo<Section[]>()\nconst sectionsFor = (code: string): Section[] =>\n parsedSections(code, () => sectionsOf(code).slice(0, 3).map(parseSection))\n\n/**\n * `value` as Excel shows it under `code`, with the separators of `locale`,\n * and the color the section names, if any.\n */\nexport const formatExcelNumber = (\n code: string,\n value: number,\n locale: string,\n): { text: string; color?: string } => {\n const { section, minus } = sectionFor(sectionsFor(code), value)\n const { tokens } = section\n const tint = section.color ? { color: section.color } : {}\n const signed = (text: string, shown: boolean) => ({\n text: (minus && shown ? '-' : '') + text,\n ...tint,\n })\n const n = Math.abs(value)\n\n if (!tokens.length) {\n // An empty section hides the value, as `;;;` does\n return { text: '', ...tint }\n }\n if (tokens.some((t) => t.kind === 'general')) {\n const general = formatDecimal(\n intlNumber(locale, {\n maximumFractionDigits: 10,\n useGrouping: false,\n }),\n n,\n )\n const words = tokens.map((t) =>\n t.kind === 'general' ? general : t.kind === 'text' ? t.text : '',\n )\n return signed(words.join(''), n !== 0)\n }\n const first = tokens.findIndex((t) => t.kind === 'digit')\n if (first === -1) {\n // Text alone, as the `\"-\"` an accounting format writes for a zero\n return signed(textOf(tokens), n !== 0)\n }\n const { decimal, group } = marksOf(locale)\n const last = tokens.reduce((at, t, i) => (t.kind === 'digit' ? i : at), -1)\n const before = textOf(tokens.slice(0, first))\n const percent = tokens.filter((t) => t.kind === 'percent').length\n const scaled = n * 100 ** percent\n\n const exponentAt = tokens.findIndex((t) => t.kind === 'exponent')\n if (exponentAt !== -1) {\n const mantissa = tokens.slice(first, exponentAt)\n const pointAt = mantissa.findIndex((t) => t.kind === 'point')\n const whole = (\n pointAt === -1 ? mantissa : mantissa.slice(0, pointAt)\n ).filter((t) => t.kind === 'digit').length\n const fraction =\n pointAt === -1\n ? []\n : mantissa.slice(pointAt).filter((t) => t.kind === 'digit')\n const plus = (tokens[exponentAt] as { plus: boolean }).plus\n const width = tokens\n .slice(exponentAt)\n .filter((t) => t.kind === 'digit').length\n // `##0.0E+0` keeps the exponent a multiple of three, as Excel does\n const parts = partsOfDecimal(\n intlNumber('en-US', {\n notation: whole >= 3 ? 'engineering' : 'scientific',\n minimumFractionDigits: Math.min(\n fraction.filter((t) => t.kind === 'digit' && t.char === '0')\n .length,\n MAX_DECIMALS,\n ),\n maximumFractionDigits: Math.min(fraction.length, MAX_DECIMALS),\n useGrouping: false,\n }),\n scaled,\n )\n const at = parts.findIndex((p) => p.type === 'exponentSeparator')\n const m = parts\n .slice(0, at)\n .map((p) => (p.type === 'decimal' ? decimal : p.value))\n .join('')\n const power = Number(\n parts\n .slice(at + 1)\n .map((p) => (p.type === 'exponentMinusSign' ? '-' : p.value))\n .join(''),\n )\n const sign = power < 0 ? '-' : plus ? '+' : ''\n return signed(\n `${before}${m}E${sign}${String(Math.abs(power)).padStart(width, '0')}${textOf(tokens.slice(last + 1))}`,\n n !== 0,\n )\n }\n\n const slash = tokens.findIndex(\n (t, i) =>\n t.kind === 'text' &&\n t.text.includes('/') &&\n i > first &&\n i <= last + 1,\n )\n if (slash !== -1) {\n // `# ?/?`: a whole part, then a fraction; `# ?/8` names its denominator\n const gap = tokens.findIndex(\n (t, i) => t.kind === 'text' && i > first && i < slash,\n )\n const top = tokens.slice(gap === -1 ? first : gap + 1, slash)\n const below = tokens.slice(slash + 1, last + 1)\n const fixed = /\\/\\s*(\\d+)/.exec(\n (tokens[slash] as { text: string }).text,\n )\n const whole = gap === -1 ? 0 : Math.floor(n)\n const rest = n - whole\n const found = fixed\n ? { p: Math.round(rest * Number(fixed[1])), q: Number(fixed[1]) }\n : convergent(\n rest,\n 10 **\n Math.min(\n below.filter((t) => t.kind === 'digit').length,\n 6,\n ) -\n 1,\n )\n const { q } = found\n let { p } = found\n let units = whole\n // A fraction that rounds to a whole one adds a unit, as 2.99 to 3\n if (p === q && gap !== -1) {\n units++\n p = 0\n }\n const wholeText =\n gap === -1\n ? ''\n : layInteger(String(units), tokens.slice(first, gap), undefined)\n const body = p\n ? `${wholeText}${gap === -1 ? '' : textOf([tokens[gap]])}${layInteger(String(p), top, undefined)}${fixed ? textOf([tokens[slash]]) : `/${layFraction(String(q), below)}`}`\n : wholeText || '0'\n // A named denominator is the text after the last placeholder\n return signed(\n before + body + textOf(tokens.slice(Math.max(last, slash) + 1)),\n units !== 0 || p !== 0,\n )\n }\n\n const pointAt = tokens.findIndex(\n (t, i) => t.kind === 'point' && i > first && i <= last,\n )\n const intEnd = pointAt === -1 ? last : pointAt - 1\n // Commas right after the last placeholder divide by a thousand each\n let scale = 0\n while (tokens[last + 1 + scale]?.kind === 'comma') {\n scale++\n }\n const intTokens = tokens.slice(first, intEnd + 1)\n const grouped = intTokens.some(\n (t, i) =>\n t.kind === 'comma' &&\n intTokens.slice(0, i).some((u) => u.kind === 'digit') &&\n intTokens.slice(i + 1).some((u) => u.kind === 'digit'),\n )\n const fraction = pointAt === -1 ? [] : tokens.slice(pointAt + 1, last + 1)\n const places = fraction.filter((t) => t.kind === 'digit')\n const fixed = formatDecimal(\n intlNumber('en-US', {\n minimumFractionDigits: Math.min(\n places.filter((t) => t.kind === 'digit' && t.char === '0')\n .length,\n MAX_DECIMALS,\n ),\n maximumFractionDigits: Math.min(places.length, MAX_DECIMALS),\n useGrouping: false,\n }),\n scaled / 1000 ** scale,\n )\n const [whole, decimals = ''] = fixed.split('.')\n const integer = layInteger(\n whole,\n intTokens.filter((t) => t.kind !== 'comma'),\n grouped ? group : undefined,\n )\n const body =\n integer +\n (pointAt === -1 ? '' : decimal + layFraction(decimals, fraction))\n return signed(\n before + body + textOf(tokens.slice(last + 1 + scale)),\n Number(whole) !== 0 || Number(decimals) !== 0,\n )\n}\n\n/** The locales of the tags dates name their months in (`[$-410]`). */\nconst LCIDS: Record<string, string> = {\n '409': 'en-US',\n '809': 'en-GB',\n '410': 'it-IT',\n '40c': 'fr-FR',\n '407': 'de-DE',\n c0a: 'es-ES',\n '416': 'pt-BR',\n}\n\ntype DatePart =\n | { kind: 'text'; text: string }\n | { kind: 'year'; size: number }\n | { kind: 'month'; size: number }\n | { kind: 'day'; size: number }\n | { kind: 'hour'; size: number; elapsed: boolean }\n | { kind: 'minute'; size: number; elapsed: boolean }\n | { kind: 'second'; size: number; elapsed: boolean; decimals: number }\n | { kind: 'ampm'; short: boolean }\n\n/**\n * The codes Excel keeps for the system's short date, as the file loader\n * names its built-in formats 14 and 22: the reader's date, as Excel shows\n * them in the reader's language.\n */\nconst SYSTEM_DATES = new Set(['mm-dd-yy', 'm/d/yy h:mm'])\n\n/** The parts of one section of a date format, with the locale it tags. */\nconst parseDate = (source: string): { parts: DatePart[]; locale?: string } => {\n const parts: DatePart[] = []\n let locale: string | undefined\n const text = (t: string) => {\n const last = parts[parts.length - 1]\n if (last?.kind === 'text') {\n last.text += t\n } else if (t) {\n parts.push({ kind: 'text', text: t })\n }\n }\n for (let i = 0; i < source.length; i++) {\n const rest = source.slice(i)\n const ch = source[i]\n const run = (/^([a-z])\\1*/i.exec(rest)?.[0] ?? ch).length\n const lower = ch.toLowerCase()\n if (ch === '\"') {\n const end = source.indexOf('\"', i + 1)\n const stop = end === -1 ? source.length : end\n text(source.slice(i + 1, stop))\n i = stop\n } else if (ch === '\\\\') {\n text(source[i + 1] ?? '')\n i++\n } else if (ch === '_' || ch === '*') {\n text(ch === '_' ? ' ' : (source[i + 1] ?? ''))\n i++\n } else if (ch === '[') {\n const end = source.indexOf(']', i)\n const inner = source.slice(i + 1, end === -1 ? undefined : end)\n i = end === -1 ? source.length : end\n const elapsed = /^(h+|m+|s+)$/i.exec(inner)\n const tag = /^\\$[^-]*-([0-9a-f]+)$/i.exec(inner)\n if (elapsed) {\n const k = elapsed[1][0].toLowerCase()\n const size = elapsed[1].length\n // `[s].00`: hundredths of the elapsed seconds\n const decimals =\n k === 's'\n ? (/^\\.(0+)/.exec(source.slice(i + 1))?.[1].length ?? 0)\n : 0\n i += decimals ? decimals + 1 : 0\n parts.push(\n k === 'h'\n ? { kind: 'hour', size, elapsed: true }\n : k === 'm'\n ? { kind: 'minute', size, elapsed: true }\n : { kind: 'second', size, elapsed: true, decimals },\n )\n } else if (tag) {\n locale = LCIDS[tag[1].toLowerCase().slice(-3)] ?? locale\n }\n } else if (/^(am\\/pm|a\\/p)/i.test(rest)) {\n const short = /^a\\/p/i.test(rest)\n parts.push({ kind: 'ampm', short })\n i += short ? 2 : 4\n } else if (lower === 'y') {\n parts.push({ kind: 'year', size: run })\n i += run - 1\n } else if (lower === 'd') {\n parts.push({ kind: 'day', size: run })\n i += run - 1\n } else if (lower === 'h') {\n parts.push({ kind: 'hour', size: run, elapsed: false })\n i += run - 1\n } else if (lower === 's') {\n // `ss.00`: tenths and hundredths of a second\n const decimals = /^s+\\.(0+)/i.exec(rest)?.[1].length ?? 0\n parts.push({ kind: 'second', size: run, elapsed: false, decimals })\n i += run - 1 + (decimals ? decimals + 1 : 0)\n } else if (lower === 'm') {\n parts.push({ kind: 'month', size: run })\n i += run - 1\n } else {\n text(ch)\n }\n }\n // An `m` after an hour or before a second is a minute, as in Excel\n parts.forEach((part, i) => {\n if (part.kind !== 'month' || part.size > 2) {\n return\n }\n const before = parts\n .slice(0, i)\n .reverse()\n .find((p) => p.kind !== 'text')\n const after = parts.slice(i + 1).find((p) => p.kind !== 'text')\n if (before?.kind === 'hour' || after?.kind === 'second') {\n parts[i] = { kind: 'minute', size: part.size, elapsed: false }\n }\n })\n return { parts, locale }\n}\n\nconst parsedDates = memo<{ parts: DatePart[]; locale?: string }>()\n\n/**\n * The day of a serial: in Excel's 1900 system, which counts a 29 February\n * 1900 that never was and a day 0 (`{ y: 1900, m: 1, d: 0 }` for serial 0),\n * or in the 1904 system some Mac workbooks use.\n */\nconst dayOf = (days: number, date1904: boolean) => {\n if (!date1904 && days < 61) {\n const d = days === 60 ? 29 : days > 31 ? days - 31 : days\n const m = days === 60 || days > 31 ? 2 : 1\n return { y: 1900, m, d, weekday: (days + 6) % 7 }\n }\n const date = new Date(\n (date1904 ? Date.UTC(1904, 0, 1) : Date.UTC(1899, 11, 30)) +\n days * 86_400_000,\n )\n return {\n y: date.getUTCFullYear(),\n m: date.getUTCMonth() + 1,\n d: date.getUTCDate(),\n weekday: date.getUTCDay(),\n }\n}\n\nconst dateFormats = memo<Intl.DateTimeFormat>()\nconst nameOf = (\n locale: string,\n options: Intl.DateTimeFormatOptions,\n at: Date,\n) =>\n dateFormats(\n `${locale}|${JSON.stringify(options)}`,\n () => new Intl.DateTimeFormat(locale, { ...options, timeZone: 'UTC' }),\n ).format(at)\n\n/** Excel's last day, 31 December 9999: past it Excel shows `#####`. */\nconst LAST_SERIAL = 2_958_466\n\n/**\n * A date or a time Excel holds as `serial` (days since its day 0, the time\n * as the fraction), as `code` writes it: the section for the value and its\n * color, the order, digits and names of the format, with the month and day\n * names of the locale it tags or else of the reader. Undefined for a serial\n * Excel cannot show as a date.\n */\nexport const formatExcelDate = (\n code: string,\n serial: number,\n locale: string,\n date1904 = false,\n): { text: string; color?: string } | undefined => {\n if (!Number.isFinite(serial) || serial < 0 || serial >= LAST_SERIAL) {\n return undefined\n }\n const sources = sectionsOf(code).slice(0, 3)\n const sections = sectionsFor(code)\n const chosen = sectionFor(sections, serial).section\n const source = sources[sections.indexOf(chosen)] ?? sources[0]\n const tint = chosen.color ? { color: chosen.color } : {}\n const { parts, locale: tagged } = parsedDates(source, () =>\n parseDate(source),\n )\n const names = tagged ?? locale\n const ampm = parts.some((p) => p.kind === 'ampm')\n // Seconds rounded as Excel shows them, to the decimals the code asks\n const decimals = Math.max(\n 0,\n ...parts.map((p) => (p.kind === 'second' ? p.decimals : 0)),\n )\n const unit = 86_400 * 10 ** decimals\n const total = Math.round(serial * unit)\n const days = Math.floor(total / unit)\n const within = total - days * unit\n const second = Math.floor(within / 10 ** decimals)\n const day = dayOf(days, date1904)\n const hour = Math.floor(second / 3600)\n const minute = Math.floor((second % 3600) / 60)\n if (SYSTEM_DATES.has(source.replace(/\\[[^\\]]*\\]/g, '').trim())) {\n const date = new Date(Date.UTC(day.y, day.m - 1, Math.max(day.d, 1)))\n const short = nameOf(\n locale,\n /^en(-US)?$/i.test(locale)\n ? { year: 'numeric', month: 'numeric', day: 'numeric' }\n : { year: 'numeric', month: '2-digit', day: '2-digit' },\n date,\n )\n const time = /h/i.test(source)\n ? ` ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`\n : ''\n return { text: short + time, ...tint }\n }\n const at = new Date(Date.UTC(2000, day.m - 1, Math.max(day.d, 1)))\n const weekdayAt = new Date(Date.UTC(2023, 0, 1 + day.weekday))\n const pad = (n: number, size: number) =>\n String(n).padStart(Math.min(size, 2), '0')\n const text = parts\n .map((p) => {\n switch (p.kind) {\n case 'text':\n return p.text\n case 'year':\n return p.size <= 2\n ? String(day.y % 100).padStart(2, '0')\n : String(day.y)\n case 'month':\n return p.size <= 2\n ? pad(day.m, p.size)\n : p.size === 3\n ? nameOf(names, { month: 'short' }, at).replace(\n /\\.$/,\n '',\n )\n : p.size === 4\n ? nameOf(names, { month: 'long' }, at)\n : nameOf(names, { month: 'long' }, at)[0]\n case 'day':\n return p.size <= 2\n ? pad(day.d, p.size)\n : nameOf(\n names,\n { weekday: p.size === 3 ? 'short' : 'long' },\n weekdayAt,\n ).replace(/\\.$/, '')\n case 'hour': {\n if (p.elapsed) {\n return pad(days * 24 + hour, p.size)\n }\n return pad(ampm ? hour % 12 || 12 : hour, p.size)\n }\n case 'minute':\n return pad(\n p.elapsed ? (days * 24 + hour) * 60 + minute : minute,\n p.size,\n )\n case 'second': {\n const whole = p.elapsed\n ? Math.floor(total / 10 ** decimals)\n : second % 60\n const fraction = p.decimals\n ? `.${String(within % 10 ** decimals)\n .padStart(decimals, '0')\n .slice(0, p.decimals)}`\n : ''\n return pad(whole, p.size) + fraction\n }\n case 'ampm':\n return p.short\n ? hour < 12\n ? 'A'\n : 'P'\n : hour < 12\n ? 'AM'\n : 'PM'\n }\n })\n .join('')\n return { text, ...tint }\n}\n\n/**\n * A date or a time written as Excel holds it (`46000.5`), as `YYYY-MM-DD`,\n * `YYYY-MM-DD HH:mm` or `HH:mm`, as its format shows it; undefined for\n * anything else.\n */\nexport const excelDateText = (\n raw: string,\n code: string,\n locale: string,\n): string | undefined => {\n const written =\n /^(?:(\\d{4}-\\d{2}-\\d{2}))?[ T]?(?:(\\d{1,2}):(\\d{2})(?::(\\d{2}))?)?$/.exec(\n raw.trim(),\n )\n const serial = /^-?\\d+(\\.\\d+)?$/.test(raw)\n ? Number(raw)\n : written && (written[1] || written[2])\n ? (written[1]\n ? Date.parse(`${written[1]}T00:00:00Z`) / 86_400_000 + 25_569\n : 0) +\n (Number(written[2] ?? 0) * 3600 +\n Number(written[3] ?? 0) * 60 +\n Number(written[4] ?? 0)) /\n 86_400\n : undefined\n return serial === undefined || Number.isNaN(serial)\n ? undefined\n : formatExcelDate(code, serial, locale)?.text\n}\n"],"mappings":";;AAcA,IAAa4B,IAA0B5B,EAAS;CAC5C,GAAGC,EAAS;CACZ,GAAGA,EAAS;CAEZ,OAAOC,EAAO,CAAC,QAAQ,QAAQ,CAAC;CAEhC,OAAOA,EAAO;EAAC;EAAQ;EAAU;CAAW,CAAC;CAC7C,MAAMA,EAAO;EAAC;EAAU;EAAS;EAAU;CAAO,CAAC;AACvD,CAAC,GAGY2B,IAA2B7B,EAAS;CAE7C,KAAKG,EAAS;CACd,OAAOF,EAAS;CAChB,QAAQA,EAAS;CAEjB,QAAQ2B,EAAwB,SAAS;AAC7C,CAAC,GAEYE,IAAuB9B,EAAS;CACzC,MAAMG,EAAS;CA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AAWxC,EAAE,WACb,IAAI,OAAO2F,IAAS,MAAM9B,CAAQ,CAAC,CAC9B,SAASA,GAAU,GAAG,CAAC,CACvB,MAAM,GAAG7D,EAAE,QAAQ,MACxB;KACN,OAAOgG,EAAIzD,GAAOvC,EAAE,IAAI,IAAIwC;IAChC;IACA,KAAK,QACD,OAAOxC,EAAE,QACH6F,IAAO,KACH,MACA,MACJA,IAAO,KACL,OACA;GAChB;EACJ,CAAC,CAAC,CACD,KAAK,EACD;EAAM,GAAGlE;CAAK;AAC3B,GAOasE,MACT,GACA,GACA,MACqB;CACrB,IAAMC,IACF,qEAAqE,KACjEC,EAAI,KAAK,CACb,GACEhB,IAAS,kBAAkB,KAAKgB,CAAG,IACnC,OAAOA,CAAG,IACVD,MAAYA,EAAQ,MAAMA,EAAQ,OAC/BA,EAAQ,KACH,KAAK,MAAM,GAAGA,EAAQ,GAAG,WAAW,IAAI,QAAa,QACrD,MACL,OAAOA,EAAQ,MAAM,CAAC,IAAI,OACvB,OAAOA,EAAQ,MAAM,CAAC,IAAI,KAC1B,OAAOA,EAAQ,MAAM,CAAC,KACtB,QACJ,KAAA;CACR,OAAOf,MAAW,KAAA,KAAa,OAAO,MAAMA,CAAM,IAC5C,KAAA,IACAD,EAAgB/H,GAAMgI,GAAQ5F,CAAM,CAAC,EAAE;AACjD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils-DMvy5QRR.js","names":["isHostToolPart","isPresentationTool","MCP_TOOL_PREFIX","SUBAGENT_TOOL_PREFIX","API_TOOL_PREFIX","WEB_SEARCH_TOOL_KEYS","fromAnyCase","capitalizeFirstLetter","isTextPart","part","isToolPart","getToolPartName","isFilePart","getFilePartMedia","media","getFilePartTranscript","transcript","withAudioTranscripts","messages","own","updates","update","message","storedFileName","isReasoningPart","hasTextPart","getTextPart","parts","mergeConsecutiveTextParts","merged","prev","isWidgetPart","dropCorrectedWidgetErrors","lastDrawn","index","isStreamingPart","FILE_OUTPUT_PARTS","moveFileOutputsLast","files","feedPartKey","toolCallId","getHostCallPart","PAGE_TOOL_STEPS","HOST_STEP_TITLES","HOST_STEP_CHANGES","FORM_TOOL_STEP","pageToolStep","host","isHostActionPart","LIVE_REASONING_TAIL_LENGTH","FENCE_LINE","getMarkdownTail","markdown","maxLength","from","limit","boundary","length","cut","openFence","match","marker","rest","TOOL_APPROVAL_STATES","isToolApprovalPart","CONFIRM_TOOL_NAME","isToolConfirmPart","isConfirmationCardPart","getToolApprovalId","getPartState","getContrast","hex","hexcolor","char","r","g","b","linearize","c","isAchromaticColor","channels","at","channelsToHex","value","readCssColor","expression","computed","probe","srgb","rgb","resolveGlowTints","readGlowTints","source","mainColor","sourceHex","neutral","middle","color","hueShift","first","second","secondColor","tones","resolveContrastColor","textColor","agentThemeStyle","contrastColor","formatDuration","ms","$n","stringifyPayload","json","hasPayload","formAnswerAsSpoken","input","answer","question","questionById","step","said","id","formStepOptions","option","formAnswerSlots","slots","output","steps","assign","list","WEB_SEARCH_TOOL_TYPES","key","RICH_DETAIL_TOOL_TYPES","hasRichToolDetail","asRecord","pickString","keys","record","getToolPartSummary","queries","valid","query","sheet","range","getPartIcon","TOOL_KEY_PREFIXES","toolLabel","te","name","prefix","p","bare","PART_TYPE_LABELS","t","getPartTypeLabel","translator","label","localizeSummaryLabels","summary","labels","colon","getToolPartLabel","live","hostStepTitles","page","$t","WORD_FONT_STACKS","WORD_LINE_FACTORS","wordLineFactor","font","wordFontStack","WORD_PREVIEW_IMAGES","wordPictureSrc","src","images","ref","wordPageAnchorCss","anchor","picture","wordPicturePlacement","wordKeptRuns","runs","mode","hasWordText","wordFlowItems","out","breakPending","sectionPending","push","opens","section","row","breakBefore","keepNext","skip","blocks","block","breaks","cell","cells","wordPageAnchors","run","chatFileName","version","filename","EDITABLE_IMAGE_TYPES","isEditableImage","mediaType","isImeComposing","event","chatCoversPageControlBar","center","windowWidth","chat","selectionBarPosition","above","start","gap","bar","placement","touch","bounds","margin","bottom"],"sources":["../../../../packages/utils/src/message.ts","../../../../packages/components/src/chat/utils.ts"],"sourcesContent":["import type { UIMessage } from 'ai'\nimport type { ChatAudioTranscript, MediaSource, UIChatMessage } from 'models'\n\ntype MessagePart = UIMessage['parts'][number]\n\nexport function isTextPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'text' }> {\n if (!part) {\n return false\n }\n return part.type === 'text'\n}\n\nexport function isToolPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: `tool-${string}` }> {\n if (!part) {\n return false\n }\n return part.type.startsWith('tool-')\n}\n\nexport function getToolPartName(part?: MessagePart): string {\n if (!isToolPart(part)) {\n return ''\n }\n return part.type.slice('tool-'.length)\n}\n\nexport function isFilePart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'file' }> {\n if (!part) {\n return false\n }\n return part.type === 'file'\n}\n\n/**\n * Returns the persisted `MediaSource` carried by a file part, when present.\n * Uploaded attachments stash the full upload metadata (size, extension,\n * storage handle…) under `providerMetadata['8bot'].media`, which survives\n * persistence — so saved messages can surface size/details without a schema\n * change or extra request.\n */\nexport function getFilePartMedia(\n part?: MessagePart | null | undefined,\n): MediaSource | undefined {\n if (!isFilePart(part)) {\n return undefined\n }\n const container = part.providerMetadata?.['8bot'] as\n { media?: unknown } | undefined\n const media = container?.media\n return media && typeof media === 'object' && !Array.isArray(media)\n ? (media as MediaSource)\n : undefined\n}\n\n/**\n * Returns the transcript a chat turn stamped on an audio file part, under\n * `providerMetadata['8bot'].transcript` (spec `audio-file-transcription.md`,\n * D4), when present.\n */\nexport function getFilePartTranscript(\n part?: MessagePart | null | undefined,\n): ChatAudioTranscript | undefined {\n if (!isFilePart(part)) {\n return undefined\n }\n const container = part.providerMetadata?.['8bot'] as\n { transcript?: unknown } | undefined\n const transcript = container?.transcript\n return transcript &&\n typeof transcript === 'object' &&\n !Array.isArray(transcript)\n ? (transcript as ChatAudioTranscript)\n : undefined\n}\n\n/** The transcript a turn made of one audio the client sent, as streamed. */\nexport interface AudioTranscriptUpdate {\n messageId: string\n storedFileName: string\n transcript: ChatAudioTranscript\n}\n\n/**\n * The messages with the transcripts a turn streamed (`data-audioTranscripts`)\n * stamped on their audio parts: the stored message has them, the client's\n * copy of the message it sent gets them here. What the updates do not name is\n * returned as it was, the same objects.\n */\nexport function withAudioTranscripts<T extends UIMessage>(\n messages: T[],\n updates: AudioTranscriptUpdate[],\n): T[] {\n return messages.map((message) => {\n const own = updates.filter((update) => update.messageId === message.id)\n if (own.length === 0) {\n return message\n }\n return {\n ...message,\n parts: message.parts.map((part) => {\n const update = own.find(\n ({ storedFileName }) =>\n storedFileName ===\n getFilePartMedia(part)?.storedFileName,\n )\n return update && isFilePart(part)\n ? {\n ...part,\n providerMetadata: {\n ...part.providerMetadata,\n '8bot': {\n ...part.providerMetadata?.['8bot'],\n transcript: update.transcript,\n },\n },\n }\n : part\n }),\n }\n })\n}\n\nexport function isReasoningPart(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { type: 'reasoning' }> {\n if (!part) {\n return false\n }\n return part.type === 'reasoning'\n}\n\nexport function hasPartText(\n part?: MessagePart | null | undefined,\n): part is Extract<MessagePart, { text: string }> {\n if (!part) {\n return false\n }\n if (isTextPart(part)) {\n return true\n }\n return (\n 'text' in part &&\n part.text !== undefined &&\n part.text !== null &&\n part.text !== ''\n )\n}\n\nexport function hasTextPart(\n message?: UIMessage | UIChatMessage | null | undefined,\n): boolean {\n if (!message) {\n return false\n }\n return (message as UIMessage).parts.some((part) => isTextPart(part))\n}\n\nexport function getTextPart(\n message?: UIMessage | UIChatMessage | null | undefined,\n): string | undefined {\n if (!message) {\n return undefined\n }\n const parts = (message as UIMessage).parts\n if (!Array.isArray(parts)) {\n return undefined\n }\n const textPart = parts.find((part) => isTextPart(part))\n return textPart?.text\n}\n\nexport function getMessageText(\n message?: UIMessage | UIChatMessage | null | undefined,\n): string {\n if (!message) {\n return ''\n }\n const parts = (message as UIMessage).parts\n if (!Array.isArray(parts)) {\n return ''\n }\n return parts\n .filter((p): p is Extract<MessagePart, { type: 'text' }> =>\n isTextPart(p),\n )\n .map((p) => p.text)\n .join('')\n}\n","import type { UIMessage } from 'ai'\nimport type { CSSProperties, InjectionKey, Ref } from 'vue'\nimport {\n API_TOOL_PREFIX,\n MCP_TOOL_PREFIX,\n SUBAGENT_TOOL_PREFIX,\n WEB_SEARCH_TOOL_KEYS,\n isHostToolPart,\n isPresentationTool,\n type WordPreviewBlock,\n type WordPreviewPage,\n type WordPreviewPicture,\n type WordPreviewRun,\n} from 'models'\nimport {\n isTextPart,\n isFilePart,\n isToolPart,\n isReasoningPart,\n hasPartText,\n hasTextPart,\n getTextPart,\n getMessageText,\n getToolPartName,\n capitalizeFirstLetter,\n fromAnyCase,\n} from 'utils'\n\nexport {\n isTextPart,\n isFilePart,\n isToolPart,\n isReasoningPart,\n hasPartText,\n hasTextPart,\n getTextPart,\n getMessageText,\n}\n\n/**\n * Merges consecutive text parts into a single text part.\n * Claude (and other models) often produce multiple text parts during streaming\n * that should logically be a single block of text.\n */\nexport function mergeConsecutiveTextParts(\n parts: UIMessage['parts'],\n): UIMessage['parts'] {\n const merged: UIMessage['parts'] = []\n for (const part of parts) {\n if (!isTextPart(part)) {\n merged.push(part)\n continue\n }\n const prev = merged[merged.length - 1]\n if (prev && isTextPart(prev)) {\n merged[merged.length - 1] = { ...prev, text: prev.text + part.text }\n } else {\n merged.push(part)\n }\n }\n return merged\n}\n\nconst isWidgetPart = (\n part: UIMessage['parts'][number],\n): part is Extract<UIMessage['parts'][number], { type: `tool-${string}` }> =>\n isToolPart(part) && isPresentationTool(getToolPartName(part))\n\n/**\n * Drops a widget call refused for its arguments when a later call of the same\n * widget in the message was drawn: the turn corrected it (the backend's\n * `correctableInputRefusals`), and the refusal would sit next to the working\n * widget, `showForm` drawing its render error above the form. A refusal with\n * nothing drawn after it stays. Only the feed reads this: the steps timeline\n * keeps every call, the refused one included.\n */\nexport function dropCorrectedWidgetErrors(\n parts: UIMessage['parts'],\n): UIMessage['parts'] {\n const lastDrawn = new Map<string, number>()\n for (const [index, part] of parts.entries()) {\n if (\n isWidgetPart(part) &&\n part.state !== 'output-error' &&\n !isStreamingPart(part)\n ) {\n lastDrawn.set(part.type, index)\n }\n }\n return parts.filter(\n (part, index) =>\n !(\n isWidgetPart(part) &&\n part.state === 'output-error' &&\n (lastDrawn.get(part.type) ?? -1) > index\n ),\n )\n}\n\n/**\n * Tool calls whose output is a file for the user to download. The feed draws\n * them after the answer, where the reader arrives, wherever in the message the\n * model made the call: a version written before a long answer sat above it,\n * out of sight.\n */\nconst FILE_OUTPUT_PARTS: ReadonlySet<string> = new Set([\n 'tool-editSpreadsheet',\n 'tool-shareDocument',\n 'tool-editWordDocument',\n 'tool-createSpreadsheet',\n 'tool-createWordDocument',\n])\n\n/** The parts with the file outputs moved last, in their own order. */\nexport function moveFileOutputsLast(\n parts: UIMessage['parts'],\n): UIMessage['parts'] {\n const files = parts.filter((part) => FILE_OUTPUT_PARTS.has(part.type))\n return files.length > 0\n ? [\n ...parts.filter((part) => !FILE_OUTPUT_PARTS.has(part.type)),\n ...files,\n ]\n : parts\n}\n\n/**\n * The key of a part in the feed. Its position, except for a file output: that\n * one is always last, so its position moves as the answer grows, and keyed by\n * it the card would be redrawn at every new part.\n */\nexport function feedPartKey(\n part: UIMessage['parts'][number],\n index: number,\n): string | number {\n const toolCallId = (part as { toolCallId?: string }).toolCallId\n return FILE_OUTPUT_PARTS.has(part.type) && toolCallId\n ? `file-${toolCallId}`\n : index\n}\n\n/** A call the embedding page runs, as the backend stamped it (spec `host-tools.md`). */\ninterface HostCallPart {\n toolCallId?: string\n toolName: string\n title?: string\n state?: string\n errorText?: string\n toolMetadata?: { readOnly?: boolean; provider?: 'app' | 'page' }\n}\n\nexport function getHostCallPart(\n part: UIMessage['parts'][number] | null | undefined,\n): HostCallPart | undefined {\n return isHostToolPart(part) ? (part as unknown as HostCallPart) : undefined\n}\n\n/**\n * The page tools of the widget (spec `page-tools.md`): defined by the backend,\n * so their step is ours to name, in the user's language. A tool the app\n * registered is named by its own `title`.\n */\nconst PAGE_TOOL_STEPS: Record<string, { icon: string; label: string }> = {\n page_snapshot: {\n icon: 'ri:pages-line',\n label: 'messagePart.pageTool.snapshot',\n },\n page_read: {\n icon: 'ri:file-text-line',\n label: 'messagePart.pageTool.read',\n },\n page_click: { icon: 'ri:cursor-line', label: 'messagePart.pageTool.click' },\n page_fill: { icon: 'ri:edit-line', label: 'messagePart.pageTool.fill' },\n page_scroll: {\n icon: 'ri:arrow-up-down-line',\n label: 'messagePart.pageTool.scroll',\n },\n page_find: { icon: 'ri:search-line', label: 'messagePart.pageTool.find' },\n page_wait: { icon: 'ri:time-line', label: 'messagePart.pageTool.wait' },\n page_hover: {\n icon: 'ri:cursor-line',\n label: 'messagePart.pageTool.hover',\n },\n page_press: {\n icon: 'ri:keyboard-line',\n label: 'messagePart.pageTool.press',\n },\n page_back: {\n icon: 'ri:arrow-go-back-line',\n label: 'messagePart.pageTool.back',\n },\n page_navigate: {\n icon: 'ri:links-line',\n label: 'messagePart.pageTool.navigate',\n },\n}\n\n/**\n * The titles the widget gave this page's steps, by call, naming what each\n * acts on (spec `page-tools-improvements.md`, M8): provided by the chat view\n * from its store, read by the views that list the steps.\n */\nexport const HOST_STEP_TITLES: InjectionKey<Ref<Record<string, string>>> =\n Symbol('hostStepTitles')\n\n/** A setting a step changes: what it was, what it becomes. */\nexport type StepFieldChange = { label: string; value: string; before?: string }\n\n/**\n * What the steps the automatic confirmations ran without a card changed, by\n * call (spec `auto-confirmations.md`): provided by the chat view from its\n * store, shown under each step's line.\n */\nexport const HOST_STEP_CHANGES: InjectionKey<\n Ref<\n Record<\n string,\n {\n details?: StepFieldChange[]\n unchanged?: { label: string; value: string }[]\n }\n >\n >\n> = Symbol('hostStepChanges')\n\n/** A form the site annotated for agents: its tool is named `form_<toolname>`. */\nconst FORM_TOOL_STEP = {\n icon: 'ri:survey-line',\n label: 'messagePart.pageTool.form',\n}\n\nconst pageToolStep = (host: HostCallPart) =>\n host.toolMetadata?.provider === 'page'\n ? (PAGE_TOOL_STEPS[host.toolName] ??\n (host.toolName.startsWith('form_') ? FORM_TOOL_STEP : undefined))\n : undefined\n\n/**\n * A host call that changes something in the app or on the page: the feed\n * shows it even without the steps timeline, because what it did stays done.\n */\nexport function isHostActionPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n return getHostCallPart(part)?.toolMetadata?.readOnly === false\n}\n\nexport function isStreamingPart(\n part: UIMessage['parts'][number] | null | undefined,\n): part is Extract<UIMessage['parts'][number], { streaming?: boolean }> {\n if (!part) {\n return false\n }\n if ('state' in part) {\n return part.state === 'streaming' || part.state === 'input-streaming'\n }\n return false\n}\n\n/**\n * How much of a reasoning still being written its live box renders. The box is\n * a few lines tall and follows the bottom, while the reasoning of one turn runs\n * to tens of kilobytes: chat `st0Eg8iG0zUX0HQN` wrote 92KB, and parsing all of\n * it at every delta froze the tab. Four thousand characters leave a few screens\n * to scroll back through, and a finished step renders all of it.\n */\nexport const LIVE_REASONING_TAIL_LENGTH = 4000\n\n// A fence opener or closer, also inside a list item or a quote, whose markers\n// and indentation are skipped. The rest of the line tells them apart: a\n// closing fence carries no info string.\nconst FENCE_LINE =\n /^[ \\t]*(?:(?:[-*+]|\\d{1,9}[.)])[ \\t]+|>[ \\t]?)*(`{3,}|~{3,})(.*)$/gm\n\n/**\n * The end of a markdown text, at most `maxLength` characters long, cut on a\n * blank line (a line break when there is none) so it does not open on half a\n * paragraph. A table or a formula can still be cut in two. An ellipsis marks\n * the cut. A cut inside a fenced code block reopens the fence, or the rest of\n * the text would render as code and the code as prose.\n */\nexport function getMarkdownTail(markdown: string, maxLength: number): string {\n if (markdown.length <= maxLength) {\n return markdown\n }\n const from = markdown.length - maxLength\n // The boundary is looked for in the first half of the window only: the one\n // blank line of the window can be the last thing written, and cutting there\n // would leave nothing to render.\n const limit = from + maxLength / 2\n const boundary = (index: number, length: number) =>\n index !== -1 && index < limit ? index + length : undefined\n const cut =\n boundary(markdown.indexOf('\\n\\n', from), 2) ??\n boundary(markdown.indexOf('\\n', from), 1) ??\n from\n let openFence: string | undefined\n for (const match of markdown.matchAll(FENCE_LINE)) {\n if (match.index >= cut) {\n break\n }\n const [, marker, rest] = match\n if (!openFence) {\n // A backtick in a backtick fence's info string makes it inline\n // code, not a fence.\n if (marker[0] === '`' && rest.includes('`')) {\n continue\n }\n openFence = marker\n } else if (\n marker[0] === openFence[0] &&\n marker.length >= openFence.length &&\n !rest.trim()\n ) {\n openFence = undefined\n }\n }\n const reopen = openFence ? `${openFence}\\n` : ''\n return `…\\n\\n${reopen}${markdown.slice(cut)}`\n}\n\n/**\n * States a tool part goes through when it needs the user's approval. They are\n * rendered by `PkToolApprovalCard` whatever the tool is, so the decision (and\n * its outcome) stays visible in the transcript.\n */\nconst TOOL_APPROVAL_STATES = new Set([\n 'approval-requested',\n 'approval-responded',\n 'output-denied',\n])\n\nexport function isToolApprovalPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n if (!isToolPart(part)) {\n return false\n }\n if (TOOL_APPROVAL_STATES.has(part.state)) {\n return true\n }\n // An executed (or errored) call that went through the gate keeps its\n // verdict in `approval`: the card stays in the transcript, so the user's\n // decision remains visible in the chat and in the log viewers (parity\n // with requestConfirm, whose 'confirmed' output is persisted).\n return (part as { approval?: unknown }).approval != null\n}\n\n/**\n * The client-side tool the model uses to have an action it described approved.\n * It predates the SDK's approval gate and keeps its own round-trip (it resolves\n * through `addToolOutput`), but it asks the user the very same question, so it\n * shares `PkToolApprovalCard` instead of having a card of its own.\n */\nexport const CONFIRM_TOOL_NAME = 'requestConfirm'\n\nexport function isToolConfirmPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n return isToolPart(part) && part.type === `tool-${CONFIRM_TOOL_NAME}`\n}\n\n/** True for any part the confirmation card is responsible for. */\nexport function isConfirmationCardPart(\n part: UIMessage['parts'][number] | null | undefined,\n): boolean {\n return isToolApprovalPart(part) || isToolConfirmPart(part)\n}\n\n/** The id of the pending approval request on a tool part, if any. */\nexport function getToolApprovalId(\n part: UIMessage['parts'][number] | null | undefined,\n): string | undefined {\n if (!isToolPart(part)) {\n return undefined\n }\n return (part as { approval?: { id?: string } }).approval?.id\n}\n\nexport function getPartState(\n part: UIMessage['parts'][number] | null | undefined,\n): string | undefined {\n if (!part) {\n return undefined\n }\n if ('state' in part) {\n return part.state\n }\n return undefined\n}\n\nexport function isLoadingState(state?: string): boolean {\n if (!state) {\n return false\n }\n return ['streaming'].includes(state)\n}\n\nexport function getContrast(hexcolor: string = '000000'): 'black' | 'white' {\n let hex = hexcolor.replace('#', '')\n\n // Expand 3-character hex to 6-character (e.g., #ccc -> #cccccc)\n if (hex.length === 3) {\n hex = hex\n .split('')\n .map((char) => char + char)\n .join('')\n }\n\n // WCAG relative luminance\n const r = parseInt(hex.substring(0, 2), 16) / 255\n const g = parseInt(hex.substring(2, 4), 16) / 255\n const b = parseInt(hex.substring(4, 6), 16) / 255\n\n const linearize = (c: number) =>\n c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4\n\n const luminance =\n 0.2126 * linearize(r) + 0.7152 * linearize(g) + 0.0722 * linearize(b)\n\n return luminance > 0.179 ? 'black' : 'white'\n}\n\n/**\n * True for a hex color with almost no hue: black, white and the grays between.\n * Anything else, a color the function cannot read included, counts as colored.\n */\nexport function isAchromaticColor(hexcolor: string | undefined): boolean {\n let hex = hexcolor?.trim().replace('#', '') ?? ''\n if (/^[0-9a-f]{3}$/i.test(hex)) {\n hex = hex\n .split('')\n .map((char) => char + char)\n .join('')\n }\n if (!/^[0-9a-f]{6}$/i.test(hex)) {\n return false\n }\n const channels = [0, 2, 4].map((at) =>\n parseInt(hex.substring(at, at + 2), 16),\n )\n return Math.max(...channels) - Math.min(...channels) < 32\n}\n\n/** A color as the glow's shader takes it: three channels, 0-255. */\nexport type RgbChannels = [number, number, number]\n\n/** The two tints of the empty chat's glow, and whether the second shows. */\nexport type GlowTints = {\n first: RgbChannels\n second: RgbChannels\n duo: boolean\n}\n\n/** `#rrggbb` from three 0-255 channels. */\nexport const channelsToHex = (channels: RgbChannels) =>\n `#${channels.map((value) => value.toString(16).padStart(2, '0')).join('')}`\n\n/**\n * The color a CSS expression resolves to where `probe` sits. Mixed into sRGB\n * first, it computes to `color(srgb r g b)` whatever syntax it was written in\n * (the design system's tokens derive with the relative color syntax). A\n * browser without `color-mix()` would drop the mix and leave the inherited\n * color for every expression: it reads the bare one, which computes to `rgb()`.\n */\nfunction readCssColor(\n probe: HTMLElement,\n expression: string,\n): RgbChannels | null {\n probe.style.color = CSS.supports(\n 'color',\n 'color-mix(in srgb, red 100%, transparent)',\n )\n ? `color-mix(in srgb, ${expression} 100%, transparent)`\n : expression\n const computed = getComputedStyle(probe).color\n probe.style.color = ''\n const srgb = computed.match(/^color\\(srgb ([^\\s)]+) ([^\\s)]+) ([^\\s)]+)/)\n const rgb = computed.match(/rgba?\\(([\\d.]+)[,\\s]+([\\d.]+)[,\\s]+([\\d.]+)/)\n if (srgb) {\n return [srgb[1], srgb[2], srgb[3]].map((value) =>\n Math.round(Math.min(1, Math.max(0, Number(value))) * 255),\n ) as RgbChannels\n }\n if (rgb) {\n return [rgb[1], rgb[2], rgb[3]].map((value) =>\n Math.round(Number(value)),\n ) as RgbChannels\n }\n return null\n}\n\n/**\n * The two tints of the glow behind the empty chat's input. A color without a\n * hue (black, the default, white, a gray) drew a grey smudge on the light\n * theme and nothing on the dark one: the platform's accent lights it instead,\n * with its info color as the second tone, as the working beam does. Any other\n * color gives its neighbour 40° along the hue wheel as the second tone,\n * unless the agent chose one. Every tone is held to a middle lightness, like\n * the beam's, so a chosen second color that matches the one shown keeps the\n * glow as it was. `auto` shows the second tone only for a color without a hue.\n *\n * The colors resolve where `host` sits (its tokens, its theme); without\n * `mainColor` the glow starts from the host's own color. Null when the\n * browser cannot read them.\n */\nexport function resolveGlowTints(\n host: HTMLElement,\n {\n mainColor,\n tones = 'auto',\n secondColor,\n }: {\n mainColor?: string\n tones?: 'auto' | 'one' | 'two'\n secondColor?: string\n },\n): GlowTints | null {\n // A throwaway child inherits the host's color and custom properties, and\n // reading through it leaves the host's own style alone\n const probe = document.createElement('span')\n probe.hidden = true\n host.append(probe)\n try {\n return readGlowTints(probe, { mainColor, tones, secondColor })\n } finally {\n probe.remove()\n }\n}\n\nfunction readGlowTints(\n probe: HTMLElement,\n {\n mainColor,\n tones,\n secondColor,\n }: {\n mainColor?: string\n tones: 'auto' | 'one' | 'two'\n secondColor?: string\n },\n): GlowTints | null {\n const source = readCssColor(probe, mainColor ?? 'currentcolor')\n if (!source) {\n return null\n }\n const sourceHex = channelsToHex(source)\n const neutral = isAchromaticColor(sourceHex)\n // Where the browser can derive it; the color as it is otherwise\n const middle = (color: string, hueShift = 0) =>\n CSS.supports('color', 'oklch(from red l c h)')\n ? `oklch(from ${color} clamp(0.55, l, 0.75) c calc(h + ${hueShift}))`\n : color\n const first = readCssColor(\n probe,\n middle(neutral ? 'var(--color-accent)' : sourceHex),\n )\n const second = readCssColor(\n probe,\n secondColor\n ? middle(secondColor)\n : neutral\n ? middle('var(--color-info)')\n : middle(sourceHex, 40),\n )\n if (!first || !second) {\n return null\n }\n return {\n first,\n second,\n duo: tones === 'two' || (tones === 'auto' && neutral),\n }\n}\n\n/**\n * Resolves the contrast color based on the user's `textColor` preference.\n * Falls back to WCAG auto-detection via `getContrast` when set to `'auto'` or `undefined`.\n */\nexport function resolveContrastColor(\n textColor: 'auto' | 'white' | 'black' | undefined,\n mainColor: string | undefined,\n): 'black' | 'white' {\n if (textColor === 'white' || textColor === 'black') {\n return textColor\n }\n return getContrast(mainColor)\n}\n\n/**\n * The style of a chat root (PkChatbot, the widget's shell): the agent's color\n * as the brand. Volver derives every role of the brand (graphic, readable,\n * contrast, tinted surface) on any element with `.theme`, which both roots\n * carry, so the focus ring, the primary buttons, the links and the checkboxes\n * take the agent's color with the contrast each theme needs, instead of the\n * platform's purple. The fields' focus takes the brand's graphic role in both\n * themes, since the dark theme's accent is the platform's too.\n */\nexport function agentThemeStyle(\n mainColor: string | undefined,\n contrastColor: 'black' | 'white',\n): Record<string, string> | undefined {\n if (!mainColor) {\n return undefined\n }\n return {\n '--chatbot-main-color': mainColor,\n '--chatbot-contrast-color': contrastColor,\n '--color-brand': mainColor,\n '--color-brand-contrast': contrastColor,\n '--input-focus-color': 'var(--color-brand-graphic)',\n }\n}\n\n/**\n * Formats a duration in milliseconds using the i18n `seconds` number format\n * (e.g. \"12,4 secondi\" / \"12.4 seconds\"). Returns undefined for durations\n * that would render as \"0 seconds\" (less than 0.05s).\n */\nexport function formatDuration(\n $n: (value: number, format: string) => string,\n ms?: number,\n): string | undefined {\n if (ms === undefined || ms < 50) {\n return undefined\n }\n return $n(ms / 1000, 'seconds')\n}\n\n/**\n * Stringifies a tool payload for the raw fallback view. Returns undefined for\n * empty values so the caller can skip rendering the block entirely.\n */\nexport function stringifyPayload(value: unknown): string | undefined {\n if (value === undefined) {\n return undefined\n }\n if (typeof value === 'string') {\n return value.trim() || undefined\n }\n try {\n const json = JSON.stringify(value, null, 2)\n return json === '{}' || json === '[]' ? undefined : json\n } catch {\n return undefined\n }\n}\n\n/**\n * True when a tool payload carries something worth rendering, so a caller can\n * skip the block without stringifying the value twice.\n */\nexport function hasPayload(value: unknown): boolean {\n return stringifyPayload(value) !== undefined\n}\n\n/**\n * Turns the answers of a form into the sentence the caller would have said.\n *\n * On a call the tool loop is over by the time the form is on screen, so the\n * answers go back to the agent as a user message (see `sendUserMessage` in\n * `useVoiceSession`). Each answer is paired with its question, because that is\n * how a person would say it and because the agent hears it with no widget\n * attached.\n */\nexport function formAnswerAsSpoken(\n part: unknown,\n answer: string | { answers: { id: string; value: unknown }[] },\n): string {\n const input = (\n part as {\n input?: {\n steps?: { id: string; question?: string }[]\n question?: string\n }\n }\n )?.input\n\n if (typeof answer === 'string') {\n const question = input?.question ?? input?.steps?.[0]?.question\n return question ? `${question} ${answer}` : answer\n }\n\n const questionById = new Map(\n (input?.steps ?? []).map((step) => [step.id, step.question]),\n )\n const lines = answer.answers\n .filter(\n ({ value }) =>\n value !== null &&\n value !== '' &&\n !(Array.isArray(value) && !value.length),\n )\n .map(({ id, value }) => {\n const said = Array.isArray(value) ? value.join(', ') : String(value)\n const question = questionById.get(id)\n return question ? `${question} ${said}` : said\n })\n\n return lines.join('. ')\n}\n\n/**\n * The choices of a form step, as the radio and checkbox editors take them.\n *\n * The `value` is the LABEL and not the position, because it is what travels\n * back to the model as the answer: it reads the words it wrote, not an index.\n * Nothing here caps the list, and nothing should: the number of options an\n * agent configures is advice to the model, so a step can legitimately carry\n * more (see `showForm.tool.ts`).\n */\nexport function formStepOptions(\n step: { options?: { label: string; description?: string }[] } | undefined,\n): { label: string; value: string; description?: string }[] {\n if (!step?.options) {\n return []\n }\n return step.options.map((option) => ({\n label: option.label,\n value: option.label,\n description: option.description,\n }))\n}\n\n/**\n * Spreads the answers a form comes back with onto one slot PER STEP.\n *\n * A form's answers travel paired with step ids, and the tool schema does not\n * enforce that those ids are unique: a `.refine()` there would refuse the whole\n * form over a duplicate, which is the failure the schema was just cured of (see\n * the gotchas entry \"A configurable cap does not belong in an inputSchema\").\n * So the duplicate has to be survivable here. Keyed by id, two steps sharing\n * one collapsed onto a single answer: the second question showed the first\n * one's reply, and submitting sent that reply twice. Keyed by position, each\n * step keeps its own.\n *\n * A duplicated id restores the same incoming value to every step claiming it,\n * which is as much as the payload allows: the ids are all it says.\n */\nexport function formAnswerSlots(\n steps: { id: string }[],\n output: unknown,\n): Record<number, unknown> {\n const slots: Record<number, unknown> = {}\n if (output === undefined || output === null) {\n return slots\n }\n // A legacy single-choice answer is the plain string, and it can only\n // belong to a single-step form.\n if (typeof output === 'string') {\n if (steps.length === 1) {\n slots[0] = output\n }\n return slots\n }\n const assign = (id: string, value: unknown) => {\n steps.forEach((step, index) => {\n if (step.id === id) {\n slots[index] = value\n }\n })\n }\n const list = (output as { answers?: unknown }).answers\n if (Array.isArray(list)) {\n for (const answer of list as { id?: unknown; value?: unknown }[]) {\n if (typeof answer?.id === 'string') {\n assign(answer.id, answer.value)\n }\n }\n return slots\n }\n // Forms answered on a platform channel (the Teams modal) come back as a\n // flat record keyed by step id.\n for (const [id, value] of Object.entries(\n output as Record<string, unknown>,\n )) {\n if (value !== undefined) {\n assign(id, value)\n }\n }\n return slots\n}\n\n// Web search tool part types, gateway and provider-native\nexport const WEB_SEARCH_TOOL_TYPES: string[] = WEB_SEARCH_TOOL_KEYS.map(\n (key) => `tool-${key}`,\n)\n\n// Tool part types with a dedicated rich rendering in PkChatbotStepToolDetail\nconst RICH_DETAIL_TOOL_TYPES = new Set([\n 'tool-searchInKnowledgeBase',\n 'tool-retrieveRevisedAnswers',\n 'tool-expandChunkContext',\n 'tool-readDocumentFile',\n 'tool-getWeather',\n 'tool-geocode',\n 'tool-recallUserMemory',\n 'tool-saveUserMemory',\n ...WEB_SEARCH_TOOL_TYPES,\n])\n\nexport function hasRichToolDetail(\n part?: UIMessage['parts'][number] | null,\n): boolean {\n return isToolPart(part) && RICH_DETAIL_TOOL_TYPES.has(part.type)\n}\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined\n\nconst pickString = (\n record: Record<string, unknown> | undefined,\n ...keys: string[]\n): string | undefined => {\n for (const key of keys) {\n const value = record?.[key]\n if (typeof value === 'string' && value.trim()) {\n return value\n }\n }\n return undefined\n}\n\n/**\n * Returns a short inline summary for a tool part (search queries, location,\n * document name, ...) to be shown next to the step label without expanding\n * the step body.\n */\nexport function getToolPartSummary(\n part?: UIMessage['parts'][number] | null,\n): string | undefined {\n if (!isToolPart(part)) {\n return undefined\n }\n const input = asRecord('input' in part ? part.input : undefined)\n const output = asRecord('output' in part ? part.output : undefined)\n if (\n part.type === 'tool-searchInKnowledgeBase' ||\n WEB_SEARCH_TOOL_TYPES.includes(part.type)\n ) {\n const queries = input?.queries\n if (Array.isArray(queries)) {\n const valid = queries.filter(\n (query): query is string =>\n typeof query === 'string' && Boolean(query.trim()),\n )\n return valid.length ? valid.join(' · ') : undefined\n }\n return pickString(input, 'query', 'objective')\n }\n if (part.type === 'tool-retrieveRevisedAnswers') {\n return pickString(input, 'query')\n }\n if (part.type === 'tool-getWeather') {\n return (\n pickString(output, 'location') ?? pickString(input, 'locationName')\n )\n }\n if (part.type === 'tool-geocode') {\n return pickString(input, 'locationName')\n }\n if (part.type === 'tool-expandChunkContext') {\n return pickString(output, 'documentName')\n }\n if (\n part.type === 'tool-readDocumentFile' ||\n part.type === 'tool-readChatAttachment' ||\n part.type === 'tool-sendChatFile' ||\n part.type === 'tool-shareDocument'\n ) {\n return pickString(output, 'name')\n }\n if (part.type === 'tool-readSpreadsheet') {\n const sheet = pickString(input, 'sheet')\n const range = pickString(input, 'range')\n return sheet && range ? `${sheet}!${range}` : sheet\n }\n if (part.type === 'tool-editSpreadsheet') {\n return pickString(output, 'filename')\n }\n if (part.type === 'tool-readWordDocument') {\n return pickString(input, 'search') ?? pickString(input, 'from')\n }\n if (part.type === 'tool-editWordDocument') {\n return pickString(output, 'filename')\n }\n if (\n part.type === 'tool-createSpreadsheet' ||\n part.type === 'tool-createWordDocument'\n ) {\n // The name the file got, or while the call runs the one asked for.\n return pickString(output, 'filename') ?? pickString(input, 'filename')\n }\n if (part.type === 'tool-querySpreadsheet') {\n // The file when the step asked for the schema; a query has no name.\n return pickString(output, 'file')\n }\n if (part.type === 'tool-recallUserMemory') {\n return pickString(input, 'query')\n }\n if (part.type === 'tool-saveUserMemory') {\n return pickString(input, 'content', 'query')\n }\n return undefined\n}\n\n// Get part icon\nexport function getPartIcon(\n part?: UIMessage['parts'][number] | null,\n): string | undefined {\n const host = getHostCallPart(part)\n if (host) {\n return pageToolStep(host)?.icon ?? 'ri:apps-line'\n }\n if (isToolPart(part)) {\n if (part.type.includes('tool-subagent')) {\n return 'ri:robot-2-line'\n }\n if (part.type === 'tool-runWorker') {\n return 'ri:flow-chart'\n }\n if (part.type === 'tool-scheduleWakeup') {\n return 'ri:alarm-line'\n }\n if (part.type === 'tool-fetchTeamsChannelHistory') {\n return 'ri:chat-history-line'\n }\n if (part.type === 'tool-readEarlierMessages') {\n return 'ri:history-line'\n }\n if (part.type === 'tool-readChatAttachment') {\n return 'ri:attachment-line'\n }\n if (part.type === 'tool-sendChatFile') {\n return 'ri:send-plane-line'\n }\n if (part.type === 'tool-enableTools') {\n return 'ri:toggle-line'\n }\n if (part.type.includes('tool-mcp')) {\n return 'mcp'\n }\n if (part.type === 'tool-retrieveRevisedAnswers') {\n return 'ri:file-edit-line'\n }\n if (part.type === 'tool-searchInKnowledgeBase') {\n return 'ri:search-line'\n }\n if (part.type === 'tool-expandChunkContext') {\n return 'ri:file-search-line'\n }\n if (part.type === 'tool-readDocumentFile') {\n return 'ri:file-text-line'\n }\n if (part.type === 'tool-readSpreadsheet') {\n return 'ri:table-line'\n }\n if (\n part.type === 'tool-editSpreadsheet' ||\n part.type === 'tool-createSpreadsheet'\n ) {\n return 'ri:file-excel-2-line'\n }\n if (part.type === 'tool-shareDocument') {\n return 'ri:file-download-line'\n }\n if (part.type === 'tool-readWordDocument') {\n return 'ri:file-text-line'\n }\n if (\n part.type === 'tool-editWordDocument' ||\n part.type === 'tool-createWordDocument'\n ) {\n return 'ri:file-word-2-line'\n }\n if (part.type === 'tool-querySpreadsheet') {\n return 'ri:database-2-line'\n }\n if (part.type === 'tool-geocode') {\n return 'ri:map-2-line'\n }\n if (part.type === 'tool-getWeather') {\n return 'ri:sun-cloudy-line'\n }\n if (part.type === 'tool-recallUserMemory') {\n return 'ri:brain-line'\n }\n if (part.type === 'tool-saveUserMemory') {\n return 'ri:save-3-line'\n }\n if (part.type === 'tool-showWeather') {\n return 'ri:sun-line'\n }\n if (part.type === 'tool-showChart') {\n return 'ri:bar-chart-2-line'\n }\n if (part.type === 'tool-showDiagram') {\n return 'ri:flow-chart'\n }\n if (part.type === 'tool-showSources') {\n return 'ri:book-2-line'\n }\n if (part.type === 'tool-showForm') {\n return 'ri:survey-line'\n }\n if (part.type === 'tool-showMultipleChoice') {\n return 'ri:checkbox-multiple-line'\n }\n if (part.type === 'tool-showArtifact') {\n return 'ri:file-code-line'\n }\n if (part.type === 'tool-showEmail') {\n return 'ri:mail-line'\n }\n if (part.type === 'tool-showMessage') {\n return 'ri:chat-1-line'\n }\n if (part.type === 'tool-showWebPages') {\n return 'ri:pages-line'\n }\n if (part.type === 'tool-showProductList') {\n return 'ri:shopping-bag-line'\n }\n if (part.type === 'tool-showContactForm') {\n return 'ri:send-plane-2-line'\n }\n if (part.type === 'tool-showCalendarEvent') {\n return 'ri:calendar-event-line'\n }\n if (part.type === 'tool-showComparison') {\n return 'ri:scales-line'\n }\n if (part.type === 'tool-showLocation') {\n return 'ri:map-pin-line'\n }\n if (part.type === 'tool-showQrCode') {\n return 'ri:qr-code-line'\n }\n if (part.type === 'tool-showImageGallery') {\n return 'ri:image-line'\n }\n if (part.type === 'tool-showVideo') {\n return 'ri:film-line'\n }\n if (part.type === 'tool-showSuggestedReply') {\n return 'ri:corner-down-right-line'\n }\n if (part.type === 'tool-requestGeolocation') {\n return 'ri:map-pin-user-line'\n }\n if (part.type === 'tool-disconnectOAuthConnection') {\n return 'ri:link-unlink'\n }\n if (part.type === 'tool-requestAccountLink') {\n return 'ri:link'\n }\n if (part.type === 'tool-unlinkAccount') {\n return 'ri:link-unlink'\n }\n if (WEB_SEARCH_TOOL_TYPES.includes(part.type)) {\n return 'ri:global-line'\n }\n return 'ri:tools-line'\n }\n if (isReasoningPart(part)) {\n return 'ri:lightbulb-line'\n }\n if (isTextPart(part)) {\n return 'ri:double-quotes-r'\n }\n return undefined\n}\n\n/** What `toolLabel` and `getPartTypeLabel` need from vue-i18n. */\nexport interface LabelTranslator {\n t: (key: string) => string\n te: (key: string) => boolean\n}\n\nconst TOOL_KEY_PREFIXES = [\n API_TOOL_PREFIX,\n MCP_TOOL_PREFIX,\n SUBAGENT_TOOL_PREFIX,\n] as const\n\n/**\n * The name a person reads for a tool of the turn: the translated label of a\n * built-in tool, otherwise the name the agent configured, without its\n * tool-set prefix and in words (`api-festivita_nazionali` reads \"Festivita\n * nazionali\"). Never the raw key, and never an i18n key with no translation,\n * which vue-i18n would print as the key itself.\n */\nexport function toolLabel(name: string, { t, te }: LabelTranslator): string {\n if (te(`agent.tool.${name}`)) {\n return t(`agent.tool.${name}`)\n }\n const prefix = TOOL_KEY_PREFIXES.find((p) => name.startsWith(p))\n const bare = prefix ? name.slice(prefix.length) : name\n return capitalizeFirstLetter(fromAnyCase(bare).trim().toLowerCase())\n}\n\n/**\n * The kinds of message part a person can meet, each with its label. Written\n * as literal keys so the widget's library build, which keeps only the keys it\n * finds written out (apps/web-component/vite-plugins/chatLocales.ts), ships\n * them too.\n */\nconst PART_TYPE_LABELS: Record<string, (t: LabelTranslator['t']) => string> = {\n custom: (t) => t('messagePart.type.custom'),\n data: (t) => t('messagePart.type.data'),\n file: (t) => t('messagePart.type.file'),\n reasoning: (t) => t('messagePart.type.reasoning'),\n 'source-document': (t) => t('messagePart.type.sourceDocument'),\n 'source-url': (t) => t('messagePart.type.sourceUrl'),\n 'step-start': (t) => t('messagePart.type.stepStart'),\n text: (t) => t('messagePart.type.text'),\n}\n\n/**\n * The label of a message part in the message details: the tool for a tool\n * call, the translated kind otherwise (text, reasoning, provider data...),\n * and the kind in words for one the catalog does not know yet.\n */\nexport function getPartTypeLabel(\n part: UIMessage['parts'][number],\n translator: LabelTranslator,\n): string {\n if (isToolPart(part)) {\n return toolLabel(getToolPartName(part), translator)\n }\n if (part.type === 'dynamic-tool') {\n return toolLabel(part.toolName, translator)\n }\n const kind = part.type.startsWith('data-') ? 'data' : part.type\n const label = PART_TYPE_LABELS[kind]\n return label\n ? label(translator.t)\n : capitalizeFirstLetter(fromAnyCase(part.type))\n}\n\n/**\n * The commercial name of a provider the gateway routed a turn through, from\n * its slug (`anthropic`, `bedrock`): proper nouns, so no translation. A slug\n * not listed here shows with a capital, never as the bare id.\n */\nconst PROVIDER_NAMES: Record<string, string> = {\n alibaba: 'Alibaba Cloud',\n anthropic: 'Anthropic',\n azure: 'Microsoft Azure',\n baseten: 'Baseten',\n bedrock: 'Amazon Bedrock',\n cerebras: 'Cerebras',\n cohere: 'Cohere',\n deepinfra: 'DeepInfra',\n deepseek: 'DeepSeek',\n fireworks: 'Fireworks AI',\n google: 'Google',\n groq: 'Groq',\n mistral: 'Mistral AI',\n moonshotai: 'Moonshot AI',\n openai: 'OpenAI',\n perplexity: 'Perplexity',\n togetherai: 'Together AI',\n vertex: 'Google Vertex AI',\n xai: 'xAI',\n zai: 'Z.ai',\n}\n\n/** The name of a provider slug, see `PROVIDER_NAMES`. */\nexport function providerLabel(slug: string): string {\n return (\n PROVIDER_NAMES[slug.toLowerCase()] ??\n capitalizeFirstLetter(fromAnyCase(slug))\n )\n}\n\n/**\n * The conversation summary in the reader's language. The analysis asks the\n * model for four bold labels (`SUMMARY_FORMAT` in\n * apps/backend/src/prompts/analysis.prompt.ts) and the model copies them in\n * English whatever the conversation's language, so every stored summary\n * holds them: they are translated where a summary is read. An empty summary\n * comes back as it is, so a `??` fallback after it still works.\n */\nexport function localizeSummaryLabels<T extends string | null | undefined>(\n summary: T,\n t: (key: string) => string,\n): T {\n if (!summary) {\n return summary\n }\n const labels: Record<string, string> = {\n Intent: t('conversationSummary.intent'),\n 'Topics covered': t('conversationSummary.topicsCovered'),\n 'Key facts': t('conversationSummary.keyFacts'),\n 'Open questions': t('conversationSummary.openQuestions'),\n }\n return summary.replace(\n /\\*\\*(Intent|Topics covered|Key facts|Open questions)(:?)\\*\\*/g,\n (_, label: string, colon: string) => `**${labels[label]}${colon}**`,\n ) as T\n}\n\n// Get part label\nexport function getToolPartLabel(\n $t: (key: string) => string,\n part?: UIMessage['parts'][number] | null,\n /** The live titles of the page's steps, by call: they win when present. */\n hostStepTitles?: Record<string, string>,\n): string | undefined {\n const host = getHostCallPart(part)\n if (host) {\n const live = host.toolCallId\n ? hostStepTitles?.[host.toolCallId]\n : undefined\n if (live) {\n return live\n }\n const page = pageToolStep(host)\n return page ? $t(page.label) : host.title || host.toolName\n }\n if (isToolPart(part)) {\n if (part.type.includes('tool-subagent')) {\n return $t(`messagePart.runSubagent`)\n }\n if (part.type === 'tool-runWorker') {\n return $t(`messagePart.runWorker`)\n }\n if (part.type === 'tool-scheduleWakeup') {\n return $t(`messagePart.scheduleWakeup`)\n }\n if (part.type === 'tool-fetchTeamsChannelHistory') {\n return $t(`messagePart.fetchTeamsChannelHistory`)\n }\n if (part.type === 'tool-readEarlierMessages') {\n return $t(`messagePart.readEarlierMessages`)\n }\n if (part.type === 'tool-readChatAttachment') {\n return $t(`messagePart.readChatAttachment`)\n }\n if (part.type === 'tool-sendChatFile') {\n return $t(`messagePart.sendChatFile`)\n }\n if (part.type === 'tool-enableTools') {\n return $t(`messagePart.enableTools`)\n }\n if (part.type === 'tool-retrieveRevisedAnswers') {\n return $t(`messagePart.revisedAnswers`)\n }\n if (part.type === 'tool-searchInKnowledgeBase') {\n return $t(`messagePart.searchingDocuments`)\n }\n if (part.type === 'tool-expandChunkContext') {\n return $t(`messagePart.expandChunkContext`)\n }\n if (part.type === 'tool-readDocumentFile') {\n return $t(`messagePart.readDocumentFile`)\n }\n if (part.type === 'tool-readSpreadsheet') {\n return $t(`messagePart.readSpreadsheet`)\n }\n if (part.type === 'tool-editSpreadsheet') {\n return $t(`messagePart.editSpreadsheet`)\n }\n if (part.type === 'tool-shareDocument') {\n return $t(`messagePart.shareDocument`)\n }\n if (part.type === 'tool-readWordDocument') {\n return $t(`messagePart.readWordDocument`)\n }\n if (part.type === 'tool-editWordDocument') {\n return $t(`messagePart.editWordDocument`)\n }\n if (part.type === 'tool-createSpreadsheet') {\n return $t(`messagePart.createSpreadsheet`)\n }\n if (part.type === 'tool-createWordDocument') {\n return $t(`messagePart.createWordDocument`)\n }\n if (part.type === 'tool-querySpreadsheet') {\n return $t(`messagePart.querySpreadsheet`)\n }\n if (part.type === 'tool-geocode') {\n return $t(`messagePart.geocode`)\n }\n if (part.type === 'tool-getWeather') {\n return $t(`messagePart.getWeather`)\n }\n if (part.type === 'tool-recallUserMemory') {\n return $t(`messagePart.recallUserMemory`)\n }\n if (part.type === 'tool-saveUserMemory') {\n return $t(`messagePart.saveUserMemory`)\n }\n if (part.type === 'tool-showWeather') {\n return $t(`messagePart.showWeather`)\n }\n if (part.type === 'tool-showForm') {\n return $t(`messagePart.showForm`)\n }\n if (part.type === 'tool-showChart') {\n return $t(`messagePart.showChart`)\n }\n if (part.type === 'tool-showDiagram') {\n return $t(`messagePart.showDiagram`)\n }\n if (part.type === 'tool-showSources') {\n return $t(`messagePart.showSources`)\n }\n if (part.type === 'tool-showMultipleChoice') {\n return $t(`messagePart.showMultipleChoice`)\n }\n if (part.type === 'tool-showArtifact') {\n return $t(`messagePart.showArtifact`)\n }\n if (part.type === 'tool-showEmail') {\n return $t(`messagePart.showEmail`)\n }\n if (part.type === 'tool-showMessage') {\n return $t(`messagePart.showMessage`)\n }\n if (part.type === 'tool-showWebPages') {\n return $t(`messagePart.showWebPages`)\n }\n if (part.type === 'tool-showProducts') {\n return $t(`messagePart.showProducts`)\n }\n if (part.type === 'tool-showContactForm') {\n return $t(`messagePart.showContactForm`)\n }\n if (part.type === 'tool-showCalendarEvent') {\n return $t(`messagePart.showCalendarEvent`)\n }\n if (part.type === 'tool-showComparison') {\n return $t(`messagePart.showComparison`)\n }\n if (part.type === 'tool-showLocation') {\n return $t(`messagePart.showLocation`)\n }\n if (part.type === 'tool-showQrCode') {\n return $t(`messagePart.showQrCode`)\n }\n if (part.type === 'tool-showImageGallery') {\n return $t(`messagePart.showImageGallery`)\n }\n if (part.type === 'tool-showVideo') {\n return $t(`messagePart.showVideo`)\n }\n if (part.type === 'tool-showSuggestedReply') {\n return $t(`messagePart.showSuggestedReply`)\n }\n if (part.type === 'tool-requestGeolocation') {\n return $t(`messagePart.requestGeolocation`)\n }\n if (part.type === 'tool-disconnectOAuthConnection') {\n return $t(`messagePart.disconnectOAuthConnection`)\n }\n if (part.type === 'tool-requestAccountLink') {\n return $t(`messagePart.requestAccountLink`)\n }\n if (part.type === 'tool-unlinkAccount') {\n return $t(`messagePart.unlinkAccount`)\n }\n if (WEB_SEARCH_TOOL_TYPES.includes(part.type)) {\n return $t(`messagePart.webSearch`)\n }\n return $t(`messagePart.tool`)\n }\n if (isReasoningPart(part)) {\n return $t(`messagePart.reasoning`)\n }\n return $t(`messagePart.streaming`)\n}\n\n/** The version of a file stored in the chat that a preview opens. */\nexport type ChatFilePreviewTarget = {\n kind: 'word' | 'spreadsheet'\n storedFileName: string\n /** The name of the file, not of its version. */\n filename: string\n version?: number\n /** The file all its versions belong to, as the agent names it. */\n fileId?: string\n}\n\n/**\n * How the viewer draws a Word document's tracked changes: marked as Word\n * marks them, as if accepted, or as before them.\n */\nexport type WordPreviewMode = 'markup' | 'accepted' | 'original'\n\n/**\n * The fonts that stand in for Office's where the reader's system lacks them:\n * the metric-compatible ones of Linux and Chrome OS first, so the lines break\n * where Word breaks them, then the closest common ones.\n */\nconst WORD_FONT_STACKS: Record<string, string> = {\n calibri: 'Calibri, Carlito, \"Segoe UI\", Arial, sans-serif',\n 'calibri light':\n '\"Calibri Light\", Calibri, Carlito, \"Segoe UI\", sans-serif',\n aptos: 'Aptos, Calibri, Carlito, \"Segoe UI\", Arial, sans-serif',\n 'aptos display': '\"Aptos Display\", Aptos, Calibri, Carlito, sans-serif',\n cambria: 'Cambria, Caladea, Georgia, serif',\n 'times new roman':\n '\"Times New Roman\", Tinos, \"Liberation Serif\", Times, serif',\n arial: 'Arial, Arimo, \"Liberation Sans\", Helvetica, sans-serif',\n helvetica: 'Helvetica, Arial, Arimo, sans-serif',\n 'courier new': '\"Courier New\", Cousine, \"Liberation Mono\", monospace',\n garamond: 'Garamond, \"EB Garamond\", Georgia, serif',\n georgia: 'Georgia, serif',\n verdana: 'Verdana, \"DejaVu Sans\", sans-serif',\n tahoma: 'Tahoma, Verdana, sans-serif',\n}\n\n/**\n * Word's single line as a multiple of the font size, from the font's ascent,\n * descent and line gap: the lines keep the height of the document's font\n * where another font stands in for it.\n */\nconst WORD_LINE_FACTORS: Record<string, number> = {\n calibri: 1.22,\n 'calibri light': 1.22,\n cambria: 1.17,\n 'times new roman': 1.15,\n arial: 1.15,\n helvetica: 1.15,\n 'courier new': 1.13,\n georgia: 1.14,\n verdana: 1.22,\n tahoma: 1.21,\n}\n\n/** Word's single line for a font a Word document names. */\nexport const wordLineFactor = (font: string): number =>\n WORD_LINE_FACTORS[font.toLowerCase()] ?? 1.17\n\n/** The CSS font stack for a font a Word document names. */\nexport const wordFontStack = (font: string): string =>\n WORD_FONT_STACKS[font.toLowerCase()] ??\n `\"${font.replace(/\"/g, '')}\", ${\n /roman|garamond|cambria|georgia|serif|book|times/i.test(font)\n ? 'Georgia, serif'\n : 'Calibri, Carlito, \"Segoe UI\", Arial, sans-serif'\n }`\n\n/**\n * The images of the Word document in the viewer, by reference, which its\n * runs draw (`PkWordPreview` provides them).\n */\nexport const WORD_PREVIEW_IMAGES: InjectionKey<\n Ref<Record<string, string> | undefined>\n> = Symbol('wordPreviewImages')\n\n/**\n * The image a run draws, only a WebP the server wrote: anything else in the\n * map is not drawn.\n */\nexport const wordPictureSrc = (\n images: Record<string, string> | undefined,\n ref: string,\n): string | undefined => {\n const src = images?.[ref]\n return src?.startsWith('data:image/webp;base64,') ? src : undefined\n}\n\n/** The numbers the page number fields of a page show. */\nexport type WordPageNumbers = {\n page: number\n pages: number\n sectionPages: number\n}\n\n/**\n * Where an image Word positions on the page sits on it: from the page's top\n * left corner, in points, under the text or over it.\n */\nexport const wordPageAnchorCss = (\n picture: WordPreviewPicture,\n page: WordPreviewPage,\n): CSSProperties => {\n const anchor = picture.anchor!\n return {\n left: `${anchor.xFrom === 'page' ? anchor.x : page.margins.left + anchor.x}pt`,\n top: `${anchor.yFrom === 'page' ? anchor.y : page.margins.top + anchor.y}pt`,\n width: `${picture.width}pt`,\n height: `${picture.height}pt`,\n zIndex: anchor.wrap === 'behind' ? -1 : 1,\n }\n}\n\n/**\n * How an image of a run is placed: in the text, beside the text of its\n * paragraph, on a line of its own, from its paragraph, or on the page,\n * which the page draws.\n */\nexport const wordPicturePlacement = (\n picture: WordPreviewPicture,\n): 'inline' | 'around' | 'block' | 'paragraph' | 'page' => {\n const anchor = picture.anchor\n return !anchor\n ? 'inline'\n : anchor.wrap === 'around'\n ? 'around'\n : anchor.wrap === 'block'\n ? 'block'\n : anchor.yFrom === 'paragraph'\n ? 'paragraph'\n : 'page'\n}\n\n/** The runs a mode keeps: a deletion is gone once accepted. */\nexport const wordKeptRuns = (\n runs: WordPreviewRun[],\n mode: WordPreviewMode,\n): WordPreviewRun[] =>\n runs.filter((r) =>\n mode === 'accepted'\n ? r.change !== 'deleted'\n : mode === 'original'\n ? r.change !== 'inserted'\n : true,\n )\n\nconst hasWordText = (runs: WordPreviewRun[]) =>\n runs.some((r) => r.image || r.text.trim())\n\n/** A piece of a Word document's flow: a paragraph or a table row. */\nexport type WordFlowItem = {\n key: string\n block: number\n row?: number\n breakBefore: boolean\n /** The section it opens. */\n section?: number\n /** Stays on the page of the next piece (Word's \"Keep with next\"). */\n keepNext?: true\n}\n\n/**\n * The pieces of `blocks` in order, as the pages hold them. A paragraph or a\n * table row a mode empties is gone (a row inserted, as the original); one\n * empty in the document stays, a blank line as in Word. A section a gone\n * piece opened, with its page break, passes to the next one.\n */\nexport const wordFlowItems = (\n blocks: WordPreviewBlock[],\n mode: WordPreviewMode,\n): WordFlowItem[] => {\n const out: WordFlowItem[] = []\n let breakPending = false\n let sectionPending: number | undefined\n const push = (\n key: string,\n block: number,\n row: number | undefined,\n breakBefore: boolean,\n section: number | undefined,\n keepNext: boolean,\n ) => {\n const opens = section ?? sectionPending\n out.push({\n key,\n block,\n ...(row !== undefined ? { row } : {}),\n breakBefore: breakBefore || breakPending,\n ...(opens !== undefined ? { section: opens } : {}),\n ...(keepNext ? { keepNext: true as const } : {}),\n })\n breakPending = false\n sectionPending = undefined\n }\n // A gone piece's own page break goes with it; a section's start stays\n const skip = (breakBefore: boolean, section: number | undefined) => {\n breakPending ||= breakBefore && section !== undefined\n sectionPending = section ?? sectionPending\n }\n blocks.forEach((block, b) => {\n if (block.kind === 'table') {\n // The table's break and section go with its first row shown\n let breaks = !!block.pageBreakBefore\n let opens = block.section\n block.rows.forEach((cells, r) => {\n const filled = cells.some((cell) => cell.runs.length)\n if (\n filled &&\n !cells.some((cell) =>\n hasWordText(wordKeptRuns(cell.runs, mode)),\n )\n ) {\n return\n }\n push(\n `${b}:${r}`,\n b,\n r,\n breaks,\n opens,\n cells.some((cell) => cell.keepNext),\n )\n breaks = false\n opens = undefined\n })\n skip(breaks, opens)\n } else if (\n !block.runs.length ||\n hasWordText(wordKeptRuns(block.runs, mode))\n ) {\n push(\n `${b}`,\n b,\n undefined,\n !!block.style?.pageBreakBefore,\n block.section,\n !!block.style?.keepNext,\n )\n } else {\n skip(!!block.style?.pageBreakBefore, block.section)\n }\n })\n return out\n}\n\n/** The images Word positions on the page among the paragraphs of `blocks`. */\nexport const wordPageAnchors = (\n blocks: WordPreviewBlock[],\n mode: WordPreviewMode,\n): WordPreviewPicture[] =>\n blocks.flatMap((block) =>\n block.kind === 'table'\n ? []\n : wordKeptRuns(block.runs, mode).flatMap((run) =>\n run.picture && wordPicturePlacement(run.picture) === 'page'\n ? [run.picture]\n : [],\n ),\n )\n\n/** An earlier version of a file of the chat, for the agent to restore. */\nexport type ChatFileRestoreTarget = {\n /** The id the agent names the file with: the stored name of version 1. */\n fileId: string\n version: number\n filename: string\n}\n\n/**\n * The name of a file, not of its version: `listino (v2).xlsx` is version 2\n * of `listino.xlsx`.\n */\nexport const chatFileName = (filename: string, version?: number): string =>\n version\n ? filename.replace(new RegExp(` \\\\(v${version}\\\\)(\\\\.\\\\w+)$`), '$1')\n : filename\n\nconst EDITABLE_IMAGE_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])\n\n/**\n * Whether the image editor (spec `chat-image-editor.md`) opens on a file of\n * this type: one a canvas reads and writes back as the same type, so not a\n * GIF, an SVG or a HEIC. Here and not in `imageEdits.ts`, which the\n * composer would otherwise pull into the main bundle of the widget.\n */\nexport function isEditableImage(mediaType: string): boolean {\n return EDITABLE_IMAGE_TYPES.has(mediaType)\n}\n\n/**\n * An input method (Japanese, Chinese, Korean) is composing a word: its\n * Enter and Esc confirm or drop the word. Safari reports the Enter that\n * confirms it with `isComposing` already false, hence the 229.\n */\nexport function isImeComposing(event: KeyboardEvent): boolean {\n return event.isComposing || event.keyCode === 229\n}\n\n/**\n * Whether a chat stands in front of the place of the bar that shows the\n * agent acting on the page (`PkPageControlBar`): the top centre of the\n * window, from the bar's `top` of 48px to about its 44px of height below.\n * There the bar would only cover the chat's header, and the chat shows the\n * steps and their stop itself.\n */\nexport function chatCoversPageControlBar(\n chat: Pick<DOMRect, 'left' | 'right' | 'top' | 'bottom'>,\n windowWidth: number,\n): boolean {\n const center = windowWidth / 2\n return (\n chat.left <= center &&\n chat.right >= center &&\n chat.top <= 92 &&\n chat.bottom >= 48\n )\n}\n\n/** Where a selection bar goes, in the coordinates of its `bounds`. */\nexport type SelectionBarPosition = {\n top: number\n left: number\n placement: 'above' | 'below'\n}\n\n/**\n * Where the bar of a selection goes (spec `selection-actions.md`, \"Dove\"):\n * above the start of the selection, where it covers what was already read,\n * and below it only without room above; always below on a touch screen, away\n * from the menu the system opens above a selection. `start` is the box of the\n * selection's first line, `bottom` its lowest edge, `bounds` the box the bar\n * stays in, all in one coordinate space, the result's too.\n */\nexport function selectionBarPosition({\n start,\n bottom,\n bar,\n bounds,\n touch = false,\n gap = 8,\n margin = 8,\n}: {\n start: Pick<DOMRect, 'top' | 'left'>\n bottom: number\n bar: { width: number; height: number }\n bounds: Pick<DOMRect, 'top' | 'left' | 'width' | 'height'>\n touch?: boolean\n gap?: number\n margin?: number\n}): SelectionBarPosition {\n const above = start.top - gap - bar.height\n const placement = !touch && above >= bounds.top + margin ? 'above' : 'below'\n const top =\n placement === 'above'\n ? above\n : Math.max(\n bounds.top + margin,\n Math.min(\n bottom + gap,\n bounds.top + bounds.height - margin - bar.height,\n ),\n )\n const left = Math.max(\n bounds.left + margin,\n Math.min(start.left, bounds.left + bounds.width - margin - bar.width),\n )\n return { top, left, placement }\n}\n"],"mappings":";;;;;AAKA,SAAgBQ,EACZ,GAC8C;CAI9C,OAHKC,IAGEA,EAAK,SAAS,SAFV;AAGf;AAEA,SAAgBC,EACZ,GACwD;CAIxD,OAHKD,IAGEA,EAAK,KAAK,WAAW,OAAO,IAFxB;AAGf;AAEA,SAAgBE,EAAgB,GAA4B;CAIxD,OAHKD,EAAWD,CAAI,IAGbA,EAAK,KAAK,MAAM,CAAc,IAF1B;AAGf;AAEA,SAAgBG,EACZ,GAC8C;CAI9C,OAHKH,IAGEA,EAAK,SAAS,SAFV;AAGf;AASA,SAAgBI,EACZ,GACuB;CACvB,IAAI,CAACD,EAAWH,CAAI,GAChB;CAIJ,IAAMK,IAFYL,EAAK,mBAAmB,OAAA,EAEjB;CACzB,OAAOK,KAAS,OAAOA,KAAU,YAAY,CAAC,MAAM,QAAQA,CAAK,IAC1DA,IACD,KAAA;AACV;AAOA,SAAgBC,EACZ,GAC+B;CAC/B,IAAI,CAACH,EAAWH,CAAI,GAChB;CAIJ,IAAMO,IAFYP,EAAK,mBAAmB,OAAA,EAEZ;CAC9B,OAAOO,KACH,OAAOA,KAAe,YACtB,CAAC,MAAM,QAAQA,CAAU,IACtBA,IACD,KAAA;AACV;AAeA,SAAgBC,EACZ,GACA,GACG;CACH,OAAOC,EAAS,KAAK,MAAY;EAC7B,IAAMC,IAAMC,EAAQ,QAAQ,MAAWC,EAAO,cAAcC,EAAQ,EAAE;EAItE,OAHIH,EAAI,WAAW,IACRG,IAEJ;GACH,GAAGA;GACH,OAAOA,EAAQ,MAAM,KAAK,MAAS;IAC/B,IAAMD,IAASF,EAAI,MACd,EAAE,wBACCI,MAC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M,GACN,YAAS,KASY;CACrB,IAAMC,IAAQC,EAAM,MAAMC,IAAMC,EAAI,QAC9BC,IAAY,CAACC,KAASL,KAASM,EAAO,MAAMC,IAAS,UAAU;CAerE,OAAO;EAAE,KAbLH,MAAc,UACRJ,IACA,KAAK,IACDM,EAAO,MAAMC,GACb,KAAK,IACDC,IAASN,GACTI,EAAO,MAAMA,EAAO,SAASC,IAASJ,EAAI,MAC9C,CACJ;EAKI,MAJD,KAAK,IACdG,EAAO,OAAOC,GACd,KAAK,IAAIN,EAAM,MAAMK,EAAO,OAAOA,EAAO,QAAQC,IAASJ,EAAI,KAAK,CAE1D;EAAM;CAAU;AAClC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PkChart-D-K7nc0g.js","names":["ChartJS","_openBlock","_createElementBlock","_createElementVNode","_sfc_main","chartValueFormatter","isRoundChart","pixel","supportsColorRoles","channel","value","parseSrgb","match","computed","parseOnCanvas","r","g","b","a","readColor","expression","probe","resolveCssColorsIn","element","expressions","hexString","_hoisted_1","PkChart_default","defineComponent","__expose","ArcElement","BarController","BarElement","CategoryScale","DoughnutController","Legend","LinearScale","LineController","LineElement","PieController","PointElement","Tooltip","props","__props","useI18n","root","useTemplateRef","canvas","instance","ROLES","CATEGORICAL","strength","toward","role","TONES","INK","fallbackColors","dark","readColors","hex","categorical","tones","tone","i","text","tick","grid","surface","configuration","colors","font","format","locale","chart","reducedMotion","round","untoned","datasets","series","color","axisTitle","valueAxis","categoryAxis","horizontal","item","total","v","sum","share","draw","nextTick","Chart","copy","context","resolve","onMounted","watch","onBeforeUnmount","openBlock","createElementBlock","createElementVNode","s"],"sources":["../../../../packages/composable/src/cssColor.ts","../../../../packages/components/src/chat/PkChart.vue","../../../../packages/components/src/chat/PkChart.vue"],"sourcesContent":["/** A color as a canvas draws it: channels 0-255, alpha 0-1. */\nexport type RgbaColor = { r: number; g: number; b: number; a: number }\n\nlet scopes: Record<'light' | 'dark', HTMLElement> | undefined\nlet pixel: CanvasRenderingContext2D | null | undefined\nlet memoRevision = ''\nconst memo = new Map<string, RgbaColor>()\n\n/**\n * Whether this browser computes the color roles of the design system, which\n * derive from the palette with the relative color syntax and `color-mix()`.\n */\nexport const supportsColorRoles = () =>\n typeof CSS !== 'undefined' &&\n CSS.supports('color', 'color(from red xyz-d65 x y z)') &&\n CSS.supports('color', 'color-mix(in srgb, red 50%, blue)')\n\n/**\n * A hidden element per theme, with the classes that pin it: the colors of a\n * theme resolve inside it whatever the document's own theme is at that\n * moment, which during a switch is not yet the one being drawn.\n */\nfunction scopeOf(theme: 'light' | 'dark') {\n if (!scopes) {\n const make = (name: 'light' | 'dark') => {\n const element = document.createElement('span')\n element.className = `theme theme--${name}`\n element.setAttribute('aria-hidden', 'true')\n element.style.cssText =\n 'position:fixed;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none'\n document.body.append(element)\n return element\n }\n scopes = { light: make('light'), dark: make('dark') }\n }\n return scopes[theme]\n}\n\nconst channel = (value: string) =>\n Math.round(Math.min(1, Math.max(0, Number(value))) * 255)\n\n/** `color(srgb r g b / a)`, the form a color mixed in sRGB computes to. */\nfunction parseSrgb(computed: string): RgbaColor | null {\n const match = computed.match(\n /^color\\(srgb (\\S+) (\\S+) (\\S+)(?: \\/ (\\S+))?\\)$/,\n )\n if (!match) {\n return null\n }\n return {\n r: channel(match[1]),\n g: channel(match[2]),\n b: channel(match[3]),\n a: match[4] === undefined ? 1 : Number(match[4]),\n }\n}\n\n/** Any other form the browser computed, read back from one pixel. */\nfunction parseOnCanvas(computed: string): RgbaColor {\n pixel ??= document\n .createElement('canvas')\n .getContext('2d', { willReadFrequently: true })\n if (!pixel) {\n return { r: 0, g: 0, b: 0, a: 1 }\n }\n pixel.clearRect(0, 0, 1, 1)\n pixel.fillStyle = computed\n pixel.fillRect(0, 0, 1, 1)\n const [r, g, b, a] = pixel.getImageData(0, 0, 1, 1).data\n return { r, g, b, a: Math.round((a / 255) * 1000) / 1000 }\n}\n\n/**\n * The color a CSS expression (`var(--color-accent-graphic)`, a `color-mix()`)\n * resolves to in a theme, in channels a canvas understands. Chart.js draws on\n * a canvas, which reads no custom property, and the design system derives its\n * roles in XYZ with the relative color syntax: the expression is mixed into\n * sRGB first, so the browser hands it back as `color(srgb ...)`.\n *\n * Results are kept while `revision` stays the same: the caller passes what\n * changes the colors, the theme's version and its stylesheet.\n */\nexport function resolveCssColor(\n expression: string,\n theme: 'light' | 'dark',\n revision: string,\n): RgbaColor {\n if (revision !== memoRevision) {\n memo.clear()\n memoRevision = revision\n }\n const id = `${theme}|${expression}`\n const known = memo.get(id)\n if (known) {\n return known\n }\n const color = readColor(scopeOf(theme), expression)\n memo.set(id, color)\n return color\n}\n\n/** The expression mixed into sRGB on `probe`, read back as channels. */\nfunction readColor(probe: HTMLElement, expression: string): RgbaColor {\n probe.style.color = `color-mix(in srgb, ${expression} 100%, transparent)`\n const computed = getComputedStyle(probe).color\n return parseSrgb(computed) ?? parseOnCanvas(computed)\n}\n\n/**\n * The colors of CSS expressions as they resolve inside `element`, with the\n * theme and the custom properties that reach it there. In the widget that is\n * its shadow root, which the theme scopes of {@link resolveCssColor}, on the\n * document's body, never see. Nothing is memoized: the caller reads again\n * when the theme changes.\n */\nexport function resolveCssColorsIn(\n element: Element,\n expressions: readonly string[],\n): RgbaColor[] {\n const probe = document.createElement('span')\n probe.setAttribute('aria-hidden', 'true')\n probe.style.cssText =\n 'position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none'\n element.append(probe)\n try {\n return expressions.map((expression) => readColor(probe, expression))\n } finally {\n probe.remove()\n }\n}\n\n/** `#rrggbb`, ready for the hex alpha some charts append. */\nexport const hexString = ({ r, g, b }: RgbaColor) =>\n `#${[r, g, b].map((value) => value.toString(16).padStart(2, '0')).join('')}`\n\n/** A `#rrggbb` color as an `rgba()` string with the alpha given. */\nexport function hexWithAlpha(hex: string, alpha: number) {\n const value = Number.parseInt(hex.slice(1, 7), 16)\n return `rgba(${(value >> 16) & 255}, ${(value >> 8) & 255}, ${value & 255}, ${alpha})`\n}\n\nconst channelsOf = (hex: string) => {\n const value = Number.parseInt(hex.slice(1, 7), 16)\n return [(value >> 16) & 255, (value >> 8) & 255, value & 255]\n}\n\n/** WCAG relative luminance of a `#rrggbb` color. */\nconst luminanceOf = (hex: string) => {\n const [r, g, b] = channelsOf(hex).map((channel) => {\n const value = channel / 255\n return value <= 0.03928\n ? value / 12.92\n : ((value + 0.055) / 1.055) ** 2.4\n })\n return 0.2126 * r + 0.7152 * g + 0.0722 * b\n}\n\nconst contrastOf = (a: string, b: string) => {\n const [high, low] = [luminanceOf(a), luminanceOf(b)].sort((x, y) => y - x)\n return (high + 0.05) / (low + 0.05)\n}\n\n/**\n * `color` as a chart mark on `ground`: unchanged when it already stands 3:1\n * off it, the contrast WCAG asks of a graphic (1.4.11), otherwise mixed\n * toward `toward` (white on a dark ground, black on a light one) a tenth at\n * a time until it does. An agent's own color is often black, which vanished\n * from the bars of the dark theme, and the palette's two dark teals did too.\n * A color that is not `#rgb` or `#rrggbb` is returned as it is.\n */\nexport function readableOn(color: string, ground: string, toward: string) {\n const short = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color)\n const hex = short\n ? `#${short[1]}${short[1]}${short[2]}${short[2]}${short[3]}${short[3]}`\n : color\n if (!/^#[0-9a-f]{6}$/i.test(hex) || contrastOf(hex, ground) >= 3) {\n return color\n }\n const from = channelsOf(hex)\n const to = channelsOf(toward)\n for (let step = 1; step <= 10; step++) {\n const mixed = hexString({\n r: Math.round(from[0] + ((to[0] - from[0]) * step) / 10),\n g: Math.round(from[1] + ((to[1] - from[1]) * step) / 10),\n b: Math.round(from[2] + ((to[2] - from[2]) * step) / 10),\n a: 1,\n })\n if (contrastOf(mixed, ground) >= 3) {\n return mixed\n }\n }\n return toward\n}\n","<script setup lang=\"ts\">\n import {\n nextTick,\n onBeforeUnmount,\n onMounted,\n useTemplateRef,\n watch,\n } from 'vue'\n import { useI18n } from 'vue-i18n'\n import {\n ArcElement,\n BarController,\n BarElement,\n CategoryScale,\n Chart as ChartJS,\n DoughnutController,\n Legend,\n LinearScale,\n LineController,\n LineElement,\n PieController,\n PointElement,\n Tooltip,\n type ChartConfiguration,\n type TooltipItem,\n } from 'chart.js'\n import {\n hexString,\n resolveCssColorsIn,\n supportsColorRoles,\n } from 'composables'\n import { isRoundChart, type Chart, type ChartTone } from 'models'\n import { chartValueFormatter } from './chartFormat'\n\n ChartJS.register(\n ArcElement,\n BarController,\n BarElement,\n CategoryScale,\n DoughnutController,\n Legend,\n LinearScale,\n LineController,\n LineElement,\n PieController,\n PointElement,\n Tooltip,\n )\n\n /**\n * Draws a chart described as data (spec `chat-charts.md`) with Chart.js,\n * in the colors of the theme it sits in: the categorical palette from the\n * design system's graphic roles, the tones from its semantic ones. The\n * colors are read inside this element, so in the widget they are the\n * widget's own and not the host page's.\n */\n const props = defineProps<{\n chart: Chart\n isDark?: boolean\n }>()\n\n const { locale } = useI18n({ useScope: 'global' })\n\n const root = useTemplateRef<HTMLElement>('root')\n const canvas = useTemplateRef<HTMLCanvasElement>('canvas')\n let instance: ChartJS | undefined\n\n const ROLES = ['accent', 'brand', 'info'] as const\n /**\n * Twelve categorical colors, enough for the slices of a pie: the three\n * graphic roles, then the same roles toward the surface (a tint in the\n * light theme, a shade in the dark one), then toward the text, then\n * further toward the surface. Mixing the default brand, a near black\n * navy, toward the text alone gave two slices nobody could tell apart.\n * Interleaved, so neighbours never share a hue.\n */\n const CATEGORICAL = (\n [\n [100, 'surface'],\n [55, 'surface'],\n [70, 'word'],\n [30, 'surface'],\n ] as const\n ).flatMap(([strength, toward]) =>\n ROLES.map((role) =>\n strength === 100\n ? `var(--color-${role}-graphic)`\n : `color-mix(in srgb, var(--color-${role}-graphic) ${strength}%, var(--color-${toward}))`,\n ),\n )\n const TONES: Record<ChartTone, string> = {\n positive: 'var(--color-success-graphic)',\n warning: 'var(--color-warning-graphic)',\n negative: 'var(--color-danger-graphic)',\n critical:\n 'color-mix(in srgb, var(--color-danger-graphic) 60%, var(--color-word))',\n neutral:\n 'color-mix(in srgb, var(--color-word) 35%, var(--color-surface))',\n }\n const INK = [\n 'var(--color-word-2)',\n 'var(--color-word-3)',\n 'var(--color-surface-3)',\n 'var(--color-surface)',\n ]\n\n /**\n * A browser that cannot compute the design system's roles (no\n * `color-mix()` or relative colors) would draw every series in the text\n * color: it gets the dashboard's colors for the default theme instead.\n */\n const fallbackColors = (dark: boolean) => ({\n categorical: [\n '#9365ff',\n '#004775',\n '#6e66ed',\n '#003d5c',\n '#4b63d9',\n '#0058a8',\n '#285ec1',\n '#00508f',\n ],\n tones: {\n positive: '#5cb327',\n warning: '#e0a800',\n negative: '#fe4242',\n critical: '#991b1b',\n neutral: dark ? '#4b4b5c' : '#c4c9d4',\n } satisfies Record<ChartTone, string>,\n text: dark ? '#d1d5db' : '#4b5563',\n tick: dark ? '#9ca3af' : '#6b7280',\n grid: dark ? '#374151' : '#f3f4f6',\n surface: dark ? '#1f2937' : '#ffffff',\n })\n\n const readColors = () => {\n if (!supportsColorRoles()) {\n return fallbackColors(!!props.isDark)\n }\n const expressions = [...CATEGORICAL, ...Object.values(TONES), ...INK]\n const hex = resolveCssColorsIn(root.value!, expressions).map(hexString)\n const categorical = hex.slice(0, CATEGORICAL.length)\n const tones = Object.fromEntries(\n Object.keys(TONES).map((tone, i) => [\n tone,\n hex[CATEGORICAL.length + i],\n ]),\n ) as Record<ChartTone, string>\n const [text, tick, grid, surface] = hex.slice(-INK.length)\n return { categorical, tones, text, tick, grid, surface }\n }\n\n const configuration = (): ChartConfiguration => {\n const { chart } = props\n const colors = readColors()\n const font = {\n family: getComputedStyle(root.value!).fontFamily,\n size: 11,\n }\n const format = chartValueFormatter(locale.value, chart.format)\n const reducedMotion = window.matchMedia(\n '(prefers-reduced-motion: reduce)',\n ).matches\n const round = isRoundChart(chart.type)\n let untoned = 0\n const datasets = chart.series.map((series) => {\n if (round) {\n return {\n label: series.name,\n data: series.values,\n backgroundColor: chart.categories.map(\n (_, i) =>\n colors.categorical[i % colors.categorical.length],\n ),\n borderColor: colors.surface,\n borderWidth: 2,\n }\n }\n const color = series.tone\n ? colors.tones[series.tone]\n : colors.categorical[untoned++ % colors.categorical.length]\n return chart.type === 'line'\n ? {\n label: series.name,\n data: series.values,\n borderColor: color,\n backgroundColor: color,\n borderWidth: 2,\n pointRadius: 3,\n // Smooth without overshooting a value\n cubicInterpolationMode: 'monotone',\n // A missing value stays a gap, not a guess\n spanGaps: false,\n }\n : {\n label: series.name,\n data: series.values,\n backgroundColor: color,\n borderRadius: 3,\n maxBarThickness: 48,\n }\n })\n const axisTitle = (text?: string) => ({\n display: !!text,\n text: text ?? '',\n color: colors.tick,\n font,\n })\n const valueAxis = {\n beginAtZero: true,\n stacked: !!chart.stacked,\n ticks: {\n color: colors.tick,\n font,\n callback: (value: string | number) => format(Number(value)),\n },\n grid: { color: colors.grid, drawTicks: false },\n border: { display: false },\n title: axisTitle(chart.valueLabel),\n }\n const categoryAxis = {\n stacked: !!chart.stacked,\n ticks: { color: colors.tick, font, autoSkip: true },\n grid: { display: false },\n border: { display: false },\n title: axisTitle(chart.categoryLabel),\n }\n const horizontal = chart.type === 'bar' && !!chart.horizontal\n return {\n type: chart.type,\n data: { labels: chart.categories, datasets },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n animation: reducedMotion ? false : { duration: 400 },\n indexAxis: horizontal ? 'y' : 'x',\n // The hole of a doughnut, and the slices drawn whole in a pie\n ...(round && {\n cutout: chart.type === 'doughnut' ? '55%' : 0,\n }),\n scales: round\n ? {}\n : horizontal\n ? { x: valueAxis, y: categoryAxis }\n : { x: categoryAxis, y: valueAxis },\n plugins: {\n legend: {\n display: round || chart.series.length > 1,\n position: 'bottom',\n labels: {\n color: colors.text,\n font,\n boxWidth: 10,\n boxHeight: 10,\n useBorderRadius: true,\n borderRadius: 2,\n },\n },\n tooltip: {\n callbacks: {\n label: (item: TooltipItem<typeof chart.type>) => {\n const value = Number(item.raw)\n if (!round) {\n return `${item.dataset.label}: ${format(value)}`\n }\n const total = (item.dataset.data as number[])\n .filter((v) => typeof v === 'number')\n .reduce((sum, v) => sum + v, 0)\n const share = total\n ? new Intl.NumberFormat(locale.value, {\n style: 'percent',\n maximumFractionDigits: 1,\n }).format(value / total)\n : ''\n return `${item.label}: ${format(value)}${share ? ` (${share})` : ''}`\n },\n },\n },\n },\n },\n } as ChartConfiguration\n }\n\n const draw = async () => {\n await nextTick()\n if (!canvas.value || !root.value) {\n return\n }\n instance?.destroy()\n instance = new ChartJS(canvas.value, configuration())\n }\n\n /**\n * The chart as a PNG on the surface it is drawn on: the canvas itself is\n * transparent, and a transparent PNG pasted on a dark slide loses its\n * text.\n */\n const toBlob = async (): Promise<Blob | null> => {\n if (!canvas.value || !root.value) {\n return null\n }\n const copy = document.createElement('canvas')\n copy.width = canvas.value.width\n copy.height = canvas.value.height\n const context = copy.getContext('2d')\n if (!context) {\n return null\n }\n context.fillStyle = readColors().surface\n context.fillRect(0, 0, copy.width, copy.height)\n context.drawImage(canvas.value, 0, 0)\n return new Promise((resolve) => copy.toBlob(resolve, 'image/png'))\n }\n\n defineExpose({ toBlob })\n\n onMounted(draw)\n // Redrawn when the numbers or the theme change, not when the parent hands\n // over the same chart as a new object (each update of the message parses\n // the input again): that replayed the animation. The colors are read\n // again with the theme classes.\n watch(() => `${props.isDark}|${JSON.stringify(props.chart)}`, draw)\n onBeforeUnmount(() => {\n instance?.destroy()\n instance = undefined\n })\n</script>\n\n<template>\n <div ref=\"root\" class=\"pk-chart\">\n <canvas\n ref=\"canvas\"\n role=\"img\"\n :aria-label=\"\n chart.title || chart.series.map((s) => s.name).join(', ')\n \" />\n </div>\n</template>\n\n<style lang=\"scss\">\n .pk-chart {\n position: relative;\n width: 100%;\n height: 100%;\n min-height: 0;\n }\n</style>\n","<script setup lang=\"ts\">\n import {\n nextTick,\n onBeforeUnmount,\n onMounted,\n useTemplateRef,\n watch,\n } from 'vue'\n import { useI18n } from 'vue-i18n'\n import {\n ArcElement,\n BarController,\n BarElement,\n CategoryScale,\n Chart as ChartJS,\n DoughnutController,\n Legend,\n LinearScale,\n LineController,\n LineElement,\n PieController,\n PointElement,\n Tooltip,\n type ChartConfiguration,\n type TooltipItem,\n } from 'chart.js'\n import {\n hexString,\n resolveCssColorsIn,\n supportsColorRoles,\n } from 'composables'\n import { isRoundChart, type Chart, type ChartTone } from 'models'\n import { chartValueFormatter } from './chartFormat'\n\n ChartJS.register(\n ArcElement,\n BarController,\n BarElement,\n CategoryScale,\n DoughnutController,\n Legend,\n LinearScale,\n LineController,\n LineElement,\n PieController,\n PointElement,\n Tooltip,\n )\n\n /**\n * Draws a chart described as data (spec `chat-charts.md`) with Chart.js,\n * in the colors of the theme it sits in: the categorical palette from the\n * design system's graphic roles, the tones from its semantic ones. The\n * colors are read inside this element, so in the widget they are the\n * widget's own and not the host page's.\n */\n const props = defineProps<{\n chart: Chart\n isDark?: boolean\n }>()\n\n const { locale } = useI18n({ useScope: 'global' })\n\n const root = useTemplateRef<HTMLElement>('root')\n const canvas = useTemplateRef<HTMLCanvasElement>('canvas')\n let instance: ChartJS | undefined\n\n const ROLES = ['accent', 'brand', 'info'] as const\n /**\n * Twelve categorical colors, enough for the slices of a pie: the three\n * graphic roles, then the same roles toward the surface (a tint in the\n * light theme, a shade in the dark one), then toward the text, then\n * further toward the surface. Mixing the default brand, a near black\n * navy, toward the text alone gave two slices nobody could tell apart.\n * Interleaved, so neighbours never share a hue.\n */\n const CATEGORICAL = (\n [\n [100, 'surface'],\n [55, 'surface'],\n [70, 'word'],\n [30, 'surface'],\n ] as const\n ).flatMap(([strength, toward]) =>\n ROLES.map((role) =>\n strength === 100\n ? `var(--color-${role}-graphic)`\n : `color-mix(in srgb, var(--color-${role}-graphic) ${strength}%, var(--color-${toward}))`,\n ),\n )\n const TONES: Record<ChartTone, string> = {\n positive: 'var(--color-success-graphic)',\n warning: 'var(--color-warning-graphic)',\n negative: 'var(--color-danger-graphic)',\n critical:\n 'color-mix(in srgb, var(--color-danger-graphic) 60%, var(--color-word))',\n neutral:\n 'color-mix(in srgb, var(--color-word) 35%, var(--color-surface))',\n }\n const INK = [\n 'var(--color-word-2)',\n 'var(--color-word-3)',\n 'var(--color-surface-3)',\n 'var(--color-surface)',\n ]\n\n /**\n * A browser that cannot compute the design system's roles (no\n * `color-mix()` or relative colors) would draw every series in the text\n * color: it gets the dashboard's colors for the default theme instead.\n */\n const fallbackColors = (dark: boolean) => ({\n categorical: [\n '#9365ff',\n '#004775',\n '#6e66ed',\n '#003d5c',\n '#4b63d9',\n '#0058a8',\n '#285ec1',\n '#00508f',\n ],\n tones: {\n positive: '#5cb327',\n warning: '#e0a800',\n negative: '#fe4242',\n critical: '#991b1b',\n neutral: dark ? '#4b4b5c' : '#c4c9d4',\n } satisfies Record<ChartTone, string>,\n text: dark ? '#d1d5db' : '#4b5563',\n tick: dark ? '#9ca3af' : '#6b7280',\n grid: dark ? '#374151' : '#f3f4f6',\n surface: dark ? '#1f2937' : '#ffffff',\n })\n\n const readColors = () => {\n if (!supportsColorRoles()) {\n return fallbackColors(!!props.isDark)\n }\n const expressions = [...CATEGORICAL, ...Object.values(TONES), ...INK]\n const hex = resolveCssColorsIn(root.value!, expressions).map(hexString)\n const categorical = hex.slice(0, CATEGORICAL.length)\n const tones = Object.fromEntries(\n Object.keys(TONES).map((tone, i) => [\n tone,\n hex[CATEGORICAL.length + i],\n ]),\n ) as Record<ChartTone, string>\n const [text, tick, grid, surface] = hex.slice(-INK.length)\n return { categorical, tones, text, tick, grid, surface }\n }\n\n const configuration = (): ChartConfiguration => {\n const { chart } = props\n const colors = readColors()\n const font = {\n family: getComputedStyle(root.value!).fontFamily,\n size: 11,\n }\n const format = chartValueFormatter(locale.value, chart.format)\n const reducedMotion = window.matchMedia(\n '(prefers-reduced-motion: reduce)',\n ).matches\n const round = isRoundChart(chart.type)\n let untoned = 0\n const datasets = chart.series.map((series) => {\n if (round) {\n return {\n label: series.name,\n data: series.values,\n backgroundColor: chart.categories.map(\n (_, i) =>\n colors.categorical[i % colors.categorical.length],\n ),\n borderColor: colors.surface,\n borderWidth: 2,\n }\n }\n const color = series.tone\n ? colors.tones[series.tone]\n : colors.categorical[untoned++ % colors.categorical.length]\n return chart.type === 'line'\n ? {\n label: series.name,\n data: series.values,\n borderColor: color,\n backgroundColor: color,\n borderWidth: 2,\n pointRadius: 3,\n // Smooth without overshooting a value\n cubicInterpolationMode: 'monotone',\n // A missing value stays a gap, not a guess\n spanGaps: false,\n }\n : {\n label: series.name,\n data: series.values,\n backgroundColor: color,\n borderRadius: 3,\n maxBarThickness: 48,\n }\n })\n const axisTitle = (text?: string) => ({\n display: !!text,\n text: text ?? '',\n color: colors.tick,\n font,\n })\n const valueAxis = {\n beginAtZero: true,\n stacked: !!chart.stacked,\n ticks: {\n color: colors.tick,\n font,\n callback: (value: string | number) => format(Number(value)),\n },\n grid: { color: colors.grid, drawTicks: false },\n border: { display: false },\n title: axisTitle(chart.valueLabel),\n }\n const categoryAxis = {\n stacked: !!chart.stacked,\n ticks: { color: colors.tick, font, autoSkip: true },\n grid: { display: false },\n border: { display: false },\n title: axisTitle(chart.categoryLabel),\n }\n const horizontal = chart.type === 'bar' && !!chart.horizontal\n return {\n type: chart.type,\n data: { labels: chart.categories, datasets },\n options: {\n responsive: true,\n maintainAspectRatio: false,\n animation: reducedMotion ? false : { duration: 400 },\n indexAxis: horizontal ? 'y' : 'x',\n // The hole of a doughnut, and the slices drawn whole in a pie\n ...(round && {\n cutout: chart.type === 'doughnut' ? '55%' : 0,\n }),\n scales: round\n ? {}\n : horizontal\n ? { x: valueAxis, y: categoryAxis }\n : { x: categoryAxis, y: valueAxis },\n plugins: {\n legend: {\n display: round || chart.series.length > 1,\n position: 'bottom',\n labels: {\n color: colors.text,\n font,\n boxWidth: 10,\n boxHeight: 10,\n useBorderRadius: true,\n borderRadius: 2,\n },\n },\n tooltip: {\n callbacks: {\n label: (item: TooltipItem<typeof chart.type>) => {\n const value = Number(item.raw)\n if (!round) {\n return `${item.dataset.label}: ${format(value)}`\n }\n const total = (item.dataset.data as number[])\n .filter((v) => typeof v === 'number')\n .reduce((sum, v) => sum + v, 0)\n const share = total\n ? new Intl.NumberFormat(locale.value, {\n style: 'percent',\n maximumFractionDigits: 1,\n }).format(value / total)\n : ''\n return `${item.label}: ${format(value)}${share ? ` (${share})` : ''}`\n },\n },\n },\n },\n },\n } as ChartConfiguration\n }\n\n const draw = async () => {\n await nextTick()\n if (!canvas.value || !root.value) {\n return\n }\n instance?.destroy()\n instance = new ChartJS(canvas.value, configuration())\n }\n\n /**\n * The chart as a PNG on the surface it is drawn on: the canvas itself is\n * transparent, and a transparent PNG pasted on a dark slide loses its\n * text.\n */\n const toBlob = async (): Promise<Blob | null> => {\n if (!canvas.value || !root.value) {\n return null\n }\n const copy = document.createElement('canvas')\n copy.width = canvas.value.width\n copy.height = canvas.value.height\n const context = copy.getContext('2d')\n if (!context) {\n return null\n }\n context.fillStyle = readColors().surface\n context.fillRect(0, 0, copy.width, copy.height)\n context.drawImage(canvas.value, 0, 0)\n return new Promise((resolve) => copy.toBlob(resolve, 'image/png'))\n }\n\n defineExpose({ toBlob })\n\n onMounted(draw)\n // Redrawn when the numbers or the theme change, not when the parent hands\n // over the same chart as a new object (each update of the message parses\n // the input again): that replayed the animation. The colors are read\n // again with the theme classes.\n watch(() => `${props.isDark}|${JSON.stringify(props.chart)}`, draw)\n onBeforeUnmount(() => {\n instance?.destroy()\n instance = undefined\n })\n</script>\n\n<template>\n <div ref=\"root\" class=\"pk-chart\">\n <canvas\n ref=\"canvas\"\n role=\"img\"\n :aria-label=\"\n chart.title || chart.series.map((s) => s.name).join(', ')\n \" />\n </div>\n</template>\n\n<style lang=\"scss\">\n .pk-chart {\n position: relative;\n width: 100%;\n height: 100%;\n min-height: 0;\n }\n</style>\n"],"mappings":";;;;;AAIA,IAAIO,GAQSC,UACT,OAAO,MAAQ,OACf,IAAI,SAAS,SAAS,+BAA+B,KACrD,I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