@svgrid/enterprise 3.1.34 → 3.1.36

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.
Files changed (250) hide show
  1. package/dist/ExpressionEditorHarness.svelte +1 -1
  2. package/dist/SvAdvancedFilter.svelte +1 -1
  3. package/dist/SvAlertRuleEditor.svelte +1 -1
  4. package/dist/SvAlertsManager.svelte +1 -1
  5. package/dist/SvAlertsPanel.svelte +1 -1
  6. package/dist/SvExpressionEditor.svelte +1 -1
  7. package/dist/SvGridBoard.svelte +1 -1
  8. package/dist/SvGridBulkEditDrawer.svelte +1 -1
  9. package/dist/SvGridEditPanel.svelte +1 -1
  10. package/dist/SvGridGallery.svelte +1 -1
  11. package/dist/SvGridMasterDetail.svelte +1 -1
  12. package/dist/SvGridScheduler.svelte +1 -1
  13. package/dist/SvGridSelectionBar.svelte +1 -1
  14. package/dist/SvPivotDesigner.svelte +1 -1
  15. package/dist/SvSchemaChart.svelte +1 -1
  16. package/dist/SvSchemaDashboard.svelte +1 -1
  17. package/dist/SvSheet.svelte +1 -1
  18. package/dist/SvSheetChartSetup.svelte +1 -1
  19. package/dist/SvSheetConditionalFormat.svelte +1 -1
  20. package/dist/SvSheetDataValidation.svelte +1 -1
  21. package/dist/SvSheetEditRanges.svelte +1 -1
  22. package/dist/SvSheetErrors.svelte +1 -1
  23. package/dist/SvSheetEvaluate.svelte +1 -1
  24. package/dist/SvSheetFindReplace.svelte +1 -1
  25. package/dist/SvSheetFormatCells.svelte +1 -1
  26. package/dist/SvSheetGoalSeek.svelte +1 -1
  27. package/dist/SvSheetInsertFunction.svelte +1 -1
  28. package/dist/SvSheetIteration.svelte +1 -1
  29. package/dist/SvSheetLink.svelte +1 -1
  30. package/dist/SvSheetManageRules.svelte +1 -1
  31. package/dist/SvSheetNameManager.svelte +1 -1
  32. package/dist/SvSheetPageSetup.svelte +1 -1
  33. package/dist/SvSheetPasteSpecial.svelte +1 -1
  34. package/dist/SvSheetPivot.svelte +1 -1
  35. package/dist/SvSheetProtectSheet.svelte +1 -1
  36. package/dist/SvSheetRemoveDuplicates.svelte +1 -1
  37. package/dist/SvSheetRibbon.svelte +1 -1
  38. package/dist/SvSheetSizeDialog.svelte +1 -1
  39. package/dist/SvSheetSort.svelte +1 -1
  40. package/dist/SvSheetSparklines.svelte +1 -1
  41. package/dist/SvSheetTable.svelte +1 -1
  42. package/dist/SvSheetTabs.svelte +1 -1
  43. package/dist/SvSheetTextToColumns.svelte +1 -1
  44. package/dist/SvSheetValidationAlert.svelte +1 -1
  45. package/dist/cdn/svgrid-enterprise.svelte-external.js +2 -2
  46. package/dist/designer/assets/{index-v61ZvIWw.js → index-CsdyIRos.js} +3 -3
  47. package/dist/designer/assets/{src-DkFgWld_.js → src-CSmsOfsG.js} +15 -15
  48. package/dist/designer/index.html +2 -2
  49. package/dist/fields/AiCell.svelte +41 -0
  50. package/dist/fields/AiCell.svelte.d.ts +5 -0
  51. package/dist/fields/AttachmentCell.svelte +1 -1
  52. package/dist/fields/AttachmentDialog.svelte +1 -1
  53. package/dist/fields/AttachmentEditor.svelte +1 -1
  54. package/dist/fields/AttachmentPreview.svelte +1 -1
  55. package/dist/fields/BaseAutomations.svelte +1 -1
  56. package/dist/fields/BaseChartView.svelte +1 -1
  57. package/dist/fields/BaseDashboardView.svelte +133 -0
  58. package/dist/fields/BaseDashboardView.svelte.d.ts +17 -0
  59. package/dist/fields/BaseImport.svelte +89 -0
  60. package/dist/fields/BaseImport.svelte.d.ts +15 -0
  61. package/dist/fields/BaseInboxView.svelte +112 -0
  62. package/dist/fields/BaseInboxView.svelte.d.ts +8 -0
  63. package/dist/fields/BaseListView.svelte +90 -0
  64. package/dist/fields/BaseListView.svelte.d.ts +8 -0
  65. package/dist/fields/BaseSearch.svelte +78 -0
  66. package/dist/fields/BaseSearch.svelte.d.ts +10 -0
  67. package/dist/fields/BaseTableView.svelte +28 -3
  68. package/dist/fields/BaseTableView.svelte.d.ts +5 -1
  69. package/dist/fields/BaseTabs.svelte +45 -8
  70. package/dist/fields/BaseTabs.svelte.d.ts +25 -1
  71. package/dist/fields/BaseTrash.svelte +63 -0
  72. package/dist/fields/BaseTrash.svelte.d.ts +15 -0
  73. package/dist/fields/CheckboxCell.svelte +1 -1
  74. package/dist/fields/ChecklistCell.svelte +22 -0
  75. package/dist/fields/ChecklistCell.svelte.d.ts +10 -0
  76. package/dist/fields/ChecklistEditor.svelte +81 -0
  77. package/dist/fields/ChecklistEditor.svelte.d.ts +12 -0
  78. package/dist/fields/ColorCell.svelte +13 -0
  79. package/dist/fields/ColorCell.svelte.d.ts +8 -0
  80. package/dist/fields/ColorEditor.svelte +60 -0
  81. package/dist/fields/ColorEditor.svelte.d.ts +11 -0
  82. package/dist/fields/DashboardRecords.svelte +35 -0
  83. package/dist/fields/DashboardRecords.svelte.d.ts +11 -0
  84. package/dist/fields/DashboardTileEditor.svelte +138 -0
  85. package/dist/fields/DashboardTileEditor.svelte.d.ts +15 -0
  86. package/dist/fields/DeleteFieldConfirm.svelte +1 -1
  87. package/dist/fields/DeleteRecordConfirm.svelte +1 -1
  88. package/dist/fields/FieldEditor.svelte +32 -3
  89. package/dist/fields/FieldInput.svelte +1 -1
  90. package/dist/fields/FieldsHeaderEnd.svelte +1 -1
  91. package/dist/fields/FootRowAdder.svelte +1 -1
  92. package/dist/fields/GroupHeader.svelte +3 -3
  93. package/dist/fields/LinkPickerEditor.svelte +1 -1
  94. package/dist/fields/LinkPreview.svelte +1 -1
  95. package/dist/fields/LinkedRecordView.svelte +1 -1
  96. package/dist/fields/LinkedRecordsCell.svelte +1 -1
  97. package/dist/fields/ListChips.svelte +21 -0
  98. package/dist/fields/ListChips.svelte.d.ts +9 -0
  99. package/dist/fields/LongTextEditor.svelte +1 -1
  100. package/dist/fields/MentionInput.svelte +59 -0
  101. package/dist/fields/MentionInput.svelte.d.ts +11 -0
  102. package/dist/fields/NumberEditor.svelte +1 -1
  103. package/dist/fields/OptionsEditor.svelte +1 -1
  104. package/dist/fields/PercentCell.svelte +1 -1
  105. package/dist/fields/PropertyInput.svelte +13 -10
  106. package/dist/fields/RatingCell.svelte +1 -1
  107. package/dist/fields/RatingEditor.svelte +1 -1
  108. package/dist/fields/RecordView.svelte +20 -25
  109. package/dist/fields/RowHeader.svelte +1 -1
  110. package/dist/fields/SelectCell.svelte +1 -1
  111. package/dist/fields/SelectEditor.svelte +1 -1
  112. package/dist/fields/SummaryCell.svelte +1 -1
  113. package/dist/fields/SvBase.svelte +48 -9
  114. package/dist/fields/SvBase.svelte.d.ts +33 -1
  115. package/dist/fields/SvBaseForm.svelte +2 -2
  116. package/dist/fields/SvBaseForm.svelte.d.ts +14 -0
  117. package/dist/fields/SvBaseViewBar.svelte +33 -12
  118. package/dist/fields/SvBaseViewBar.svelte.d.ts +2 -0
  119. package/dist/fields/TimeOfDayEditor.svelte +39 -0
  120. package/dist/fields/TimeOfDayEditor.svelte.d.ts +12 -0
  121. package/dist/fields/UserCell.svelte +1 -1
  122. package/dist/fields/activity.svelte.d.ts +29 -0
  123. package/dist/fields/activity.svelte.js +1 -1
  124. package/dist/fields/ai-field.svelte.d.ts +91 -0
  125. package/dist/fields/ai-field.svelte.js +1 -0
  126. package/dist/fields/ai-prompt.d.ts +64 -0
  127. package/dist/fields/ai-prompt.js +7 -0
  128. package/dist/fields/airtable.d.ts +90 -0
  129. package/dist/fields/airtable.js +1 -0
  130. package/dist/fields/bar-request.svelte.d.ts +1 -1
  131. package/dist/fields/base-history.d.ts +56 -0
  132. package/dist/fields/base-history.js +1 -0
  133. package/dist/fields/base-import.d.ts +54 -0
  134. package/dist/fields/base-import.js +2 -0
  135. package/dist/fields/base-search.d.ts +34 -0
  136. package/dist/fields/base-search.js +1 -0
  137. package/dist/fields/base-share.d.ts +45 -0
  138. package/dist/fields/base-share.js +1 -0
  139. package/dist/fields/base-sql.js +3 -3
  140. package/dist/fields/base-trash.d.ts +51 -0
  141. package/dist/fields/base-trash.js +1 -0
  142. package/dist/fields/builtin-types.js +1 -1
  143. package/dist/fields/chart-view.d.ts +12 -0
  144. package/dist/fields/chart-view.js +1 -1
  145. package/dist/fields/checklist.d.ts +36 -0
  146. package/dist/fields/checklist.js +4 -0
  147. package/dist/fields/color-value.d.ts +14 -0
  148. package/dist/fields/color-value.js +1 -0
  149. package/dist/fields/convert.js +1 -1
  150. package/dist/fields/copy-text.d.ts +1 -1
  151. package/dist/fields/copy-text.js +1 -1
  152. package/dist/fields/dashboard.d.ts +143 -0
  153. package/dist/fields/dashboard.js +1 -0
  154. package/dist/fields/field-access.svelte.d.ts +37 -0
  155. package/dist/fields/field-access.svelte.js +1 -0
  156. package/dist/fields/field-ops.js +1 -1
  157. package/dist/fields/filter-model.d.ts +4 -11
  158. package/dist/fields/filter-model.js +1 -1
  159. package/dist/fields/form-logic.d.ts +69 -0
  160. package/dist/fields/form-logic.js +1 -0
  161. package/dist/fields/formula.js +1 -1
  162. package/dist/fields/grid-access.d.ts +8 -0
  163. package/dist/fields/grid-access.js +1 -1
  164. package/dist/fields/index.d.ts +16 -0
  165. package/dist/fields/index.js +1 -1
  166. package/dist/fields/list-view.d.ts +40 -0
  167. package/dist/fields/list-view.js +1 -0
  168. package/dist/fields/mentions.d.ts +50 -0
  169. package/dist/fields/mentions.js +1 -0
  170. package/dist/fields/palette.d.ts +4 -2
  171. package/dist/fields/palette.js +1 -1
  172. package/dist/fields/record-menu.js +1 -1
  173. package/dist/fields/registry.svelte.d.ts +5 -0
  174. package/dist/fields/registry.svelte.js +1 -1
  175. package/dist/fields/time-of-day.d.ts +28 -0
  176. package/dist/fields/time-of-day.js +1 -0
  177. package/dist/fields/view-model.d.ts +24 -2
  178. package/dist/fields/view-model.js +1 -1
  179. package/dist/fields/viewbar/ChartPanel.svelte +1 -1
  180. package/dist/fields/viewbar/ColorPanel.svelte +1 -1
  181. package/dist/fields/viewbar/ConditionValue.svelte +4 -4
  182. package/dist/fields/viewbar/FilterPanel.svelte +1 -1
  183. package/dist/fields/viewbar/GanttPanel.svelte +1 -1
  184. package/dist/fields/viewbar/HideFieldsPanel.svelte +1 -1
  185. package/dist/fields/viewbar/ListPanel.svelte +36 -0
  186. package/dist/fields/viewbar/ListPanel.svelte.d.ts +11 -0
  187. package/dist/fields/viewbar/SortPanel.svelte +1 -1
  188. package/dist/fields/viewbar/ViewsMenu.svelte +27 -4
  189. package/dist/fields/viewbar/ViewsMenu.svelte.d.ts +6 -0
  190. package/dist/gantt/SvGridGantt.svelte +1 -1
  191. package/dist/node/studio.js +1 -1
  192. package/dist/review/RichCellMark.svelte +1 -1
  193. package/dist/review/SvReviewPanel.svelte +1 -1
  194. package/dist/server/SvGroupCell.svelte +1 -1
  195. package/dist/server/SvRowGroupPanel.svelte +1 -1
  196. package/dist/version.d.ts +2 -2
  197. package/dist/version.js +1 -1
  198. package/dist/wc/GridFind-DsTvdUXq.js +1 -0
  199. package/dist/wc/GridFooter-D-i8boBh.js +1 -0
  200. package/dist/wc/GridMenus-CYe9Fw2I.js +20 -0
  201. package/dist/wc/PinSplitter-LvyyrLhe.js +6 -0
  202. package/dist/wc/SvChartMenu-XKW_LOYw.js +1 -0
  203. package/dist/wc/SvDateRangeInput-CSOxqTB1.js +1 -0
  204. package/dist/wc/SvDateTimePicker-DvvFs2T9.js +4 -0
  205. package/dist/wc/SvField-BmQphyOs.js +20 -0
  206. package/dist/wc/SvForm-HD7y5vmk.js +46 -0
  207. package/dist/wc/SvGridCellEditor-776KAOe1.js +3 -0
  208. package/dist/wc/SvGridChart-DC7ZUhp8.js +171 -0
  209. package/dist/wc/SvGridChartBuilder-Dd3vWBvq.js +7 -0
  210. package/dist/wc/SvGridChartPanel-CwYjF46U.js +5 -0
  211. package/dist/wc/SvGridChartView-CSF38rBs.js +3 -0
  212. package/dist/wc/SvGridDropdown-4S1G7gsP.js +30 -0
  213. package/dist/wc/SvMenuList-D3ZLXjL_.js +1 -0
  214. package/dist/wc/SvModal-Dk0YwPWp.js +7 -0
  215. package/dist/wc/SvSwitchButton-DdZmc3ew.js +1 -0
  216. package/dist/wc/SvTabs-BI2cQHyw.js +2 -0
  217. package/dist/wc/base-react.d.ts +38 -0
  218. package/dist/wc/base-react.js +1 -0
  219. package/dist/wc/base-vue.d.ts +29 -0
  220. package/dist/wc/base-vue.js +1 -0
  221. package/dist/wc/board-RQp5fHPR.js +21 -0
  222. package/dist/wc/board-view.svelte-CpxuZcEg.js +1 -0
  223. package/dist/wc/card-marks.svelte-QwxIcKcZ.js +1 -0
  224. package/dist/wc/client-DNdLmGcu.js +3 -0
  225. package/dist/wc/createOverlay.svelte-CDw3RXgs.js +1 -0
  226. package/dist/wc/custom-filter-Dp8JxlQu.js +2 -0
  227. package/dist/wc/date-format-DtSmFyEB.js +18 -0
  228. package/dist/wc/editor-registry-CkKfcVLc.js +1 -0
  229. package/dist/wc/export-format-CGfE9_O5.js +5 -0
  230. package/dist/wc/gallery-CNOHNWEJ.js +4 -0
  231. package/dist/wc/gallery-view.svelte-27X-wCQH.js +1 -0
  232. package/dist/wc/grid-extension.svelte-hgqOteka.js +1 -0
  233. package/dist/wc/import-B9mIERCl.js +4 -0
  234. package/dist/wc/js-scroller.svelte-BP8Up6_q.js +1 -0
  235. package/dist/wc/license-CWVWqb-i.js +27 -0
  236. package/dist/wc/list-option-CI4nMshZ.js +1 -0
  237. package/dist/wc/react.d.ts +1 -0
  238. package/dist/wc/react.js +1 -1
  239. package/dist/wc/scheduler-CkVY4od-.js +147 -0
  240. package/dist/wc/scheduler-view.svelte-SzG7rU8b.js +1 -0
  241. package/dist/wc/sparkline-DWRBQubt.js +1 -0
  242. package/dist/wc/sv-base-element.d.ts +87 -0
  243. package/dist/wc/sv-base-element.js +273 -0
  244. package/dist/wc/sv-sheet-element.d.ts +2 -0
  245. package/dist/wc/sv-sheet-element.js +55 -55
  246. package/dist/wc/svelte-virtualizer.svelte-CSBwEZt9.js +1 -0
  247. package/dist/wc/types/sv-base-element.d.ts +87 -0
  248. package/dist/wc/vue.d.ts +1 -0
  249. package/dist/wc/vue.js +1 -1
  250. package/package.json +19 -4
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import{tableFeatures,renderSnippet,buildFillPattern}from"@svgrid/grid";import{tick,untrack,mount,unmount,flushSync}from"svelte";import{downloadBlobFile}from"@svgrid/grid";import{documentToXlsx}from"./sheet/xlsx-document";import{xlsxCanCarryPicture}from"./sheet/xlsx-drawing";import{csvText}from"./sheet/csv";import{documentFromFile}from"./sheet/open-file";import{documentToOds}from"./sheet/ods-document";import{documentToXls}from"./sheet/xls-document";import{sortOrder,guessHeaderRow}from"./sheet/sort";import{currentRegion}from"./sheet/navigate";import{freezeAtActiveCell,freezeTopRow,freezeFirstColumn,applyFreeze}from"./sheet/freeze";import{gridOf}from"./sheet/shortcuts";import{enableSheet}from"./sheet-enable";import{createSheetDocument}from"./sheet/document";import{setWorkbook,setFormatTarget,setFindReplaceHandler,setFormatDialogHandler,setPasteSpecialHandler,setRibbonActionHandler,setShortcutOwner,getShortcutOwner,getFormatTarget,withFormatUndo,applyFormat,clearFormats}from"./sheet/shortcuts";import{applyBorders}from"./sheet/ribbon";import{RIBBON_ICONS}from"./sheet/ribbon-icons";import{planPaste,resolvePasteCell,buildClipboardPayload,parseClipboard,parseClipboardText,parseClipboardHtml,readClipboardOrigin,anchorForeignFormulas}from"./sheet/paste-special";import{setStructureTarget,insertRows,insertColumns,deleteRows,deleteColumns,axisForSelection}from"./sheet/structure";import{setFindTarget}from"./sheet/find-replace";import{setFillTranslator,setSheetValueProbe}from"./sheet/commands";import{translateFormula}from"./sheet/refs";import{compileNumberFormat,formatCategory}from"./sheet/number-format";import{colToLetters,lettersToCol,parseA1,quoteSheet}from"./sheet/address";import{isValidName}from"./sheet/names";import{referenceSpans}from"./sheet/refs";import{balanceParens,suggestFunctions,applySuggestion}from"./sheet/autocomplete";import{parseEntry,completeEntry}from"./sheet/entry";import{isError}from"./sheet/ast";import{parseFormula}from"./sheet/parse";import{isLocked,cellLocked,rectsHaveLocked,rectsMixLocked,rangeText}from"./sheet/protection";import{chartSpecOf,chartFromRange,copyObject,objectId,paneOf,paneClip}from"./sheet/objects";import{sparklinesFromRange,sparklineAt,sparklineSeries,sparklineScale,clearSparklines,copySparkline,sparklineSvg}from"./sheet/sparklines";import{pivotFields,pivotBlock,pivotDrill,pivotFromRange,pivotWrittenRect,copyPivot,ALL_VALUES}from"./sheet/pivot-range";import{linkAt,setLink,removeLink,parseLinkTarget,isSafeLinkTarget,hyperlinkArgument}from"./sheet/links";import{imageCall,isDrawableImageSource}from"./sheet/cell-images";import{isValidTableName}from"./sheet/tables";import{tableStyleColours,tableStyleLabel,findTableStyle,DEFAULT_TABLE_STYLE}from"./sheet/table-styles";import{livePresence,presenceOnSheet,presenceAnchor}from"./sheet/presence";import{SvChart,chartToSvgString}from"@svgrid/grid";import{MARGIN_PRESETS,marginPresetOf,copyPageSetup}from"./sheet/page-setup";import{sheetPrintHtml}from"./sheet/print";import{resolveSheetMessages}from"./sheet/messages";import{INVARIANT_CULTURE,cultureFromLocale,isInvariant,formulaToCulture,formulaFromCulture}from"./sheet/culture";import{groupLines,ungroupLines,clearOutline,autoOutline,toggleCollapsed,hiddenByOutline,detailRange,outlineLevel,isOutlined,deepestLevel}from"./sheet/outline";import{cellTypeAt,toggledValue,applyCellType,removeCellTypes,newCellTypeId}from"./sheet/cell-types";import{projectGridSheet,coerceFieldValue}from"./sheet/sheet-kinds";import{provideSheetText,useSheetText}from"./sheet-text";import{commentAt,withComment,withThread,threadAt,threadText,notesOf,nextComment,listComments}from"./sheet/comments";import{ruleStats,evaluateCf,removeCf,cfId,COLOR_SCALES,DATA_BAR_COLOR}from"./sheet/conditional-formats";import{rectsIntersect}from"./sheet/rects";import{mergePlan,unmergePlan,toGridMerges,isCoveredCell,selectionMerged,mergesIn,sortBlockedByMerges,reorderMerges,mergeAt as sheetMergeAt,normalRect,expandToMerges}from"./sheet/merges";import{distinctValues,hiddenRowsFor,withColumnFilter,isFiltering,isDateColumn,distinctFills}from"./sheet/auto-filter";import{ruleAt,checkEntry,listChoices,removeValidation,validationId,invalidCells}from"./sheet/validation";let{document:sheetDocument,workbook,data,rows:minRows=50,columns:minCols=12,height=420,columnWidth=96,rowHeight=22,look="theme",columnWidths,formats,extras=[],localization,commentAuthor,showRibbon=true,showFormulaBar=true,showTabs=true,showStatusBar=true,gridSheets,onAction,onCellAction,onReady,onChange,presence,onPresence}=$props();enableSheet();const messages=$derived(resolveSheetMessages(localization?.text));provideSheetText(()=>messages);const t=useSheetText();const gridLocalization=$derived(localization?.locale?{locale:localization.locale}:void 0);const culture=$derived.by(()=>{if(localization?.culture===false)return INVARIANT_CULTURE;const base=cultureFromLocale(localization?.locale??INVARIANT_CULTURE.locale);return localization?.culture?{...base,...localization.culture}:base});const toCulture=text=>text.startsWith("=")?formulaToCulture(text,culture):numberToCulture(text);const fromCulture=text=>text.startsWith("=")?formulaFromCulture(text,culture):text;const marks=$derived({decimal:culture.decimal,group:culture.group});function numberToCulture(text){if(isInvariant(culture)||text==="")return text;return/^[+-]?\d+\.\d+$/.test(text)?text.replace(".",culture.decimal):text}const doc=sheetDocument??createSheetDocument(workbook?{workbook}:{sheets:data?[...data]:gridSheets?Object.keys(gridSheets).map(name=>({name,cells:[]})):[{name:"Sheet1",cells:[]}]});const wb=doc.workbook;if(gridSheets){for(const[name,spec]of Object.entries(gridSheets)){const exists=wb.sheets.some(sheet=>sheet.toLowerCase()===name.toLowerCase());if(!exists)wb.addSheet(name);const state=doc.get(name);state.kind="grid";state.grid=spec}for(const[name,spec]of Object.entries(gridSheets))projectGridSheetInto(name,spec)}const selfReported=new Set;const changed=reason=>{selfReported.add(reason.kind);doc.changed(reason)};let restoringSelf=false;$effect(()=>doc.subscribe(reasons=>{const outside=reasons.filter(r=>!selfReported.has(r.kind));selfReported.clear();const restored=outside.some(r=>r.kind==="restore");if(restored&&!restoringSelf){afterRestore()}else if(outside.some(r=>r.kind==="sheets")){registerSheetTargets()}else if(outside.some(r=>r.kind==="sizes"||r.kind==="hidden"||r.kind==="freeze")){applyLive(wb.active);const cmd=cmdOf();if(cmd)applyFreeze(cmd,doc.get(wb.active).freeze)}if(restored)restoringSelf=false;bump();onChange?.(reasons)}));function afterRestore(){targetsBoundTo=wb.active;registerSheetTargets();applyLive(wb.active);const cmd=cmdOf();if(cmd)applyFreeze(cmd,doc.get(wb.active).freeze);api?.clearHistory();active={rowIndex:0,colIndex:0}}export function getState(){stashLive(wb.active);return doc.getState()}export function setState(state){restoringSelf=true;doc.setState(state);afterRestore();bump()}let fileName=$state("Workbook");export async function open(file){setState(await documentFromFile(file));const name=file.name??"";if(name)fileName=name.replace(/\.(xlsx|xls|ods|csv|tsv|txt)$/i,"")}export function toXlsx(){stashLive(wb.active);return documentToXlsx(doc)}export function toOds(){stashLive(wb.active);return documentToOds(doc)}export function toXls(){stashLive(wb.active);return new Blob([documentToXls(doc)],{type:"application/vnd.ms-excel"})}export function toCsv(){const rows=[];const lastRow=wb.rowCount(wb.active);const lastCol=wb.colCount(wb.active);for(let r=0;r<lastRow;r+=1){const line=[];for(let c=0;c<lastCol;c+=1)line.push(wb.getRaw(wb.active,r,c)===""?"":display(r,c).text);rows.push(line)}return csvText(rows)}function chartSvgFor(object){if(typeof document==="undefined")return null;const host=document.createElement("div");host.setAttribute("aria-hidden","true");host.style.cssText=`position:fixed;left:-10000px;top:0;width:${object.anchor.width}px;height:${object.anchor.height}px`;document.body.appendChild(host);let drawn=null;let chart=null;try{const spec=specOf(object);chart=mount(SvChart,{target:host,props:{spec,width:object.anchor.width,height:object.anchor.height,legend:spec.series.length>1,interactive:false}});flushSync();drawn=chartToSvgString(host)}catch{drawn=null}finally{if(chart)unmount(chart);host.remove()}return drawn}function printTableLook(row,col){const part=tablePartAt(row,col);if(!part)return null;const table=activeTables.find(t2=>col>=t2.firstCol&&col<=t2.lastCol&&row>=t2.headerRow&&row<=t2.lastRow+(t2.hasTotals?1:0));const colours=tableStyleColours(table?.style??DEFAULT_TABLE_STYLE);if(!colours)return null;if(part.part==="header"){return{fill:colours.header,...colours.headerText==="inherit"?{}:{color:colours.headerText},bold:true,borderBottom:colours.border}}if(part.part==="totals")return{fill:colours.totals,bold:true,borderTop:colours.border};if(part.part==="band")return{fill:colours.band};return null}function printObjects(name){const out=[];for(const object of doc.get(name).objects??[]){const html=object.kind==="chart"?chartSvgFor(object):`<img src="${escapeHtml(object.src)}" alt="${escapeHtml(object.alt??"")}">`;if(!html)continue;out.push({row:object.anchor.row,col:object.anchor.col,dx:object.anchor.dx,dy:object.anchor.dy,width:object.anchor.width,height:object.anchor.height,html})}return out}const HTML_ESCAPES={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};const escapeHtml=text=>text.replace(/[&<>"']/g,c=>HTML_ESCAPES[c]);export function printHtml(){const name=wb.active;const state=doc.get(name);return sheetPrintHtml({name,rowCount:wb.rowCount(name),colCount:wb.colCount(name),cellAt:(r,c)=>{const value=wb.getValue(name,r,c);const shown=wb.getRaw(name,r,c)===""?{text:""}:display(r,c);const entry=storeFor().get(`r${r}`,colToLetters(c));const cf=cfAt(r,c,value)?.style;const picture=imageAt(r,c);const image=picture?`<img src="${escapeHtml(picture.src)}" alt="${escapeHtml(picture.alt)}">`:"";const spark=sparkAt(r,c);const sparkline=spark?sparklineSvg(spark.values,{type:spark.group.type,width:Math.max(16,(state.widths[colToLetters(c)]??columnWidth)-8),height:Math.max(10,(state.heights.get(r)??rowHeight)-8),color:spark.group.color,negativeColor:spark.group.negativeColor,min:spark.min,max:spark.max,markers:spark.group.markers}):"";const table=printTableLook(r,c);return{text:shown.text,...shown.color?{color:shown.color}:{},align:typeof value==="number"?"right":typeof value==="boolean"||isError(value)?"center":"left",...entry?{entry}:{},...cf?{cf}:{},...sparkline?{sparkline}:{},...image?{image}:{},...table?{table}:{}}},widths:api?api.getColumnWidths():state.widths,defaultWidth:columnWidth,heights:state.heights,defaultHeight:rowHeight,hidden:{rows:new Set([...state.hidden.rows,...state.filterHidden]),cols:state.hidden.cols},merges:state.merges,setup:state.pageSetup,objects:printObjects(name)})}export function print(){const html=printHtml();const w=typeof window==="undefined"?null:window.open("","_blank","width=900,height=700");if(!w){say(t("couldNotPrint"));return}w.document.open();w.document.write(html);w.document.close();w.focus();w.addEventListener("load",()=>setTimeout(()=>w.print(),50));setTimeout(()=>{try{w.print()}catch{}},300)}export function newWorkbook(){setState({version:1,workbook:{sheets:[{name:"Sheet1",cells:[]}],active:"Sheet1",names:{}},sheets:{}});fileName="Workbook"}let newConfirm=$state(false);let fileInput=$state(null);function documentHasContent(){for(const name of wb.sheets){for(let r=0;r<wb.rowCount(name);r+=1){for(let c=0;c<wb.colCount(name);c+=1)if(wb.getRaw(name,r,c).trim()!=="")return true}}return false}async function openPicked(event){const input=event.currentTarget;const file=input.files?.[0];input.value="";if(!file)return;try{await open(file);say(t("openedFile",{name:file.name}))}catch(e){say(e instanceof Error?e.message:t("couldNotOpen",{name:file.name}))}}async function saveXlsx(){try{downloadBlobFile(await toXlsx(),`${fileName}.xlsx`);let left=0;for(const name of wb.sheets){for(const object of doc.get(name).objects??[]){if(object.kind==="image"&&!xlsxCanCarryPicture(object.src))left+=1}}if(left>0)say(t("picturesNotSaved",{count:left,unit:t(left===1?"unitPicture":"unitPictures")}))}catch(e){say(e instanceof Error?e.message:t("couldNotSave"))}}function saveXls(){try{downloadBlobFile(toXls(),`${fileName}.xls`)}catch(e){say(e instanceof Error?e.message:t("couldNotSave"))}}async function saveOds(){try{downloadBlobFile(await toOds(),`${fileName}.ods`)}catch(e){say(e instanceof Error?e.message:t("couldNotSave"))}}let version=$state(0);let sheetsSeen="";const bump=()=>{if(wb.active!==targetsBoundTo)registerSheetTargets();const signature=wb.sheets.join("\0")+"\0"+wb.active;if(sheetsSeen&&signature!==sheetsSeen)changed({kind:"sheets"});sheetsSeen=signature;cfStatsCache.clear();refreshAutoFilter();version+=1};let traces=$state([]);let traceSheet="";let traceFrontier=null;let traceLines=$state([]);function trace(kind){const here=`${active.rowIndex},${active.colIndex}`;if(traceSheet!==wb.active){traces=[];traceFrontier=null;traceSheet=wb.active}const fromFrontier=traceFrontier&&traceFrontier.kind===kind&&traceFrontier.at===here&&traceFrontier.cells.length>0;const starts=fromFrontier?traceFrontier.cells:[{row:active.rowIndex,col:active.colIndex}];const next=[];const seen=new Set(traces.map(t2=>`${t2.from.row},${t2.from.col}>${t2.to.row},${t2.to.col}`));const added=[];for(const start of starts){const linked=kind==="precedents"?wb.precedents(wb.active,start.row,start.col):wb.dependents(wb.active,start.row,start.col);for(const cell of linked){if(cell.sheet.toLowerCase()!==wb.active.toLowerCase())continue;const arrow=kind==="precedents"?{from:{row:cell.row,col:cell.col},to:start}:{from:start,to:{row:cell.row,col:cell.col}};const key=`${arrow.from.row},${arrow.from.col}>${arrow.to.row},${arrow.to.col}`;if(seen.has(key))continue;seen.add(key);added.push(arrow);next.push({row:cell.row,col:cell.col})}}if(!added.length&&!fromFrontier){say(t(kind==="precedents"?"noPrecedents":"noDependents"))}traces=[...traces,...added];traceFrontier={kind,at:here,cells:next};void tick().then(()=>requestAnimationFrame(measureTraces))}function removeArrows(){traces=[];traceFrontier=null;traceLines=[]}let outlineBrackets=$state([]);function measureOutline(){const host=gridHost;const state=doc.get(wb.active);if(!host||!isOutlined(state.outline.rows)){outlineBrackets=[];return}const b=host.getBoundingClientRect();const rowBox=r=>host.querySelector(`td[data-svgrid-row="${r}"]`)?.getBoundingClientRect()??null;const out=[];const rows=state.outline.rows;const folded=hiddenByOutline(rows,{summaryBelow:true});for(let line=0;line<rowCount;line+=1){const range=detailRange(rows,line,{summaryBelow:true});if(!range)continue;const summaryBox=rowBox(line);if(!summaryBox)continue;const collapsed=rows.collapsed.includes(line);const buttonY=summaryBox.top-b.top+summaryBox.height/2;let top=buttonY;let bottom=buttonY;if(!collapsed){for(let r=range.from;r<=range.to;r+=1){if(folded.has(r))continue;const box=rowBox(r);if(!box)continue;top=Math.min(top,box.top-b.top);bottom=Math.max(bottom,box.bottom-b.top)}}out.push({summary:line,top,bottom,buttonY,collapsed,level:outlineLevel(rows,line)+1})}outlineBrackets=out}const outlineLevels=$derived.by(()=>{void version;const rows=doc.get(wb.active).outline.rows;return isOutlined(rows)?deepestLevel(rows)+1:0});function measureTraces(){const host=gridHost;if(!host||!traces.length){traceLines=[];return}const b=host.getBoundingClientRect();const centre=cell=>{const td=host.querySelector(`td[data-svgrid-row="${cell.row}"][data-svgrid-col="${cell.col}"]`);if(!td)return null;const a=td.getBoundingClientRect();return{x:a.left-b.left+a.width/2,y:a.top-b.top+a.height/2}};const lines=[];for(const arrow of traces){const from=centre(arrow.from);const to=centre(arrow.to);if(from&&to)lines.push({x1:from.x,y1:from.y,x2:to.x,y2:to.y})}traceLines=lines}$effect(()=>{void version;void traces;if(!traces.length)return;if(traceSheet&&traceSheet.toLowerCase()!==wb.active.toLowerCase()){removeArrows();return}void tick().then(()=>requestAnimationFrame(measureTraces))});$effect(()=>{void version;void outlineLevels;void tick().then(()=>requestAnimationFrame(measureOutline))});const hiddenSheets=$derived.by(()=>{void version;return wb.sheets.filter(name=>doc.get(name).sheetHidden)});function hideSheet(name){const visible=wb.sheets.filter(n=>!doc.get(n).sheetHidden);if(visible.length<2||!wb.sheets.some(n=>n.toLowerCase()===name.toLowerCase()))return;doc.get(name).sheetHidden=true;if(wb.active.toLowerCase()===name.toLowerCase()){const at=visible.findIndex(n=>n.toLowerCase()===name.toLowerCase());const next=visible[at+1]??visible[at-1];if(next){wb.setActive(next);active={rowIndex:0,colIndex:0}}}changed({kind:"sheets"});bump()}function unhideSheet(name){if(!wb.sheets.some(n=>n.toLowerCase()===name.toLowerCase()))return;doc.get(name).sheetHidden=false;wb.setActive(name);active={rowIndex:0,colIndex:0};changed({kind:"sheets"});bump()}function duplicateSheet(name){const made=doc.duplicate(name);if(made===null){say(t("couldNotCopySheet",{name}));return}active={rowIndex:0,colIndex:0};bump()}export function refresh(){bump()}export function act(action){const context=cmdOf();if(!context)return;handleAction(action,context)}const definedNames=$derived.by(()=>{void version;return wb.names.list()});let active=$state({rowIndex:0,colIndex:0});let selection=$state([]);let api=$state(null);let showFormulas=$state(false);let gridlinesOn=$state(true);let formulaBarOn=$state(true);let headingsOn=$state(true);let ribbonCollapsed=$state(false);function storeFor(sheet=wb.active){return doc.get(sheet).formats}function splitSheet(address){const bang=address.lastIndexOf("!");if(bang<0)return{sheet:null,cell:address};const sheet=address.slice(0,bang).replace(/^'(.*)'$/,"$1");return{sheet,cell:address.slice(bang+1)}}for(const[address,entry]of Object.entries(formats??{})){const{sheet,cell}=splitSheet(address);const ref=parseA1(cell);if(!ref||ref.row===null)continue;storeFor(sheet??wb.active).set([[ref.row,ref.col,ref.row,ref.col]],entry,{rowIdAt:i=>`r${i}`,columnIdAt:i=>colToLetters(i)})}const rowCount=$derived.by(()=>{void version;return Math.max(minRows,wb.rowCount(wb.active)+1)});const colCount=$derived.by(()=>{void version;return Math.max(minCols,wb.colCount(wb.active)+1)});const gridRows=$derived.by(()=>{void version;return Array.from({length:rowCount},(_,index)=>{const row={id:`r${index}`,index};for(let c=0;c<colCount;c+=1){row[colToLetters(c)]=wb.getRaw(wb.active,index,c)}return row})});const lookup={rowIdAt:i=>i>=0&&i<rowCount?`r${i}`:null,columnIdAt:i=>i>=0&&i<colCount?colToLetters(i):null};const protectedNow=()=>doc.get(wb.active).protected;const isProtected=$derived.by(()=>{void version;return protectedNow()});const protectionNow=()=>doc.get(wb.active).protection;const allowNow=key=>!protectedNow()||Boolean(protectionNow().allow[key]);const lineKey=axis2=>axis2==="rows"?"formatRows":"formatColumns";const protectionState=$derived.by(()=>{void version;return protectionNow()});const canResizeRows=$derived.by(()=>{void version;return allowNow("formatRows")});const canResizeCols=$derived.by(()=>{void version;return allowNow("formatColumns")});function locked(r,c){return protectedNow()&&cellLocked(storeFor().get(`r${r}`,colToLetters(c)),protectionNow().ranges,r,c)}function refuse(){say(t("protectedCell"))}function selectedRects(cmd){if(cmd?.ranges.length)return cmd.ranges;if(selection.length)return selection;return[[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex]]}const notesNow=()=>doc.get(wb.active).notes;const activeNotes=$derived.by(()=>{void version;const out={};for(const[rowId,line]of Object.entries(notesOf(notesNow())))out[rowId.slice(1)]=line;return out});const popoverThread=$derived.by(()=>{void version;const pop=cellPopover;return pop?.kind==="comment"?threadAt(notesNow(),pop.r,pop.c)??null:null});let cellPopover=$state(null);let anchorRect=$state(null);let gridHost=$state(null);let tabs=$state(null);let showComments=$state(false);const allComments=$derived.by(()=>{void version;return listComments(notesNow())});function putComments(after){const sheet=wb.active;const before=doc.get(sheet).notes;const put=notes=>{doc.get(sheet).notes=notes;bump();changed({kind:"comments"})};put(after);cmdOf()?.recordUndo(()=>put(before),()=>put(after))}function setComment(r,c,text){const before=notesNow();const fresh=text.trim()&&commentAuthor&&!threadAt(before,r,c);putComments(fresh?withThread(before,r,c,{text,author:commentAuthor,at:new Date().toISOString()}):withComment(before,r,c,text))}function setThread(r,c,thread){putComments(withThread(notesNow(),r,c,thread))}function openCommentEditor(r,c){const cmd=cmdOf();if(!cmd)return;if(cellPopover)closeCellPopover();cmd.setActiveCell(r,c);cmd.setSelection(r,c);cmd.scrollIntoView(r,c);active={rowIndex:r,colIndex:c};const initial=commentAt(notesNow(),r,c)??"";cellPopover={kind:"comment",r,c,draft:initial,initial};void tick().then(()=>requestAnimationFrame(measureAnchor))}function measureAnchor(){const pop=cellPopover;const host=gridHost;if(!pop||!host){anchorRect=null;return}const td=host.querySelector(`td[data-svgrid-row="${pop.r}"][data-svgrid-col="${pop.c}"]`);if(!td){closeCellPopover();return}const a=td.getBoundingClientRect();const b=host.getBoundingClientRect();anchorRect={left:a.left-b.left,top:a.top-b.top,width:a.width,height:a.height}}function closeCellPopover(keep=true){const pop=cellPopover;if(!pop)return;cellPopover=null;anchorRect=null;if(pop.kind==="comment"&&keep&&pop.draft!==pop.initial)setComment(pop.r,pop.c,pop.draft);const cmd=cmdOf();if(cmd)focusSheet(cmd)}function walkComments(dir){const to=nextComment(notesNow(),{row:active.rowIndex,col:active.colIndex},dir);if(!to){say(t("noComments"));return}openCommentEditor(to.row,to.col)}const rulesNow=()=>doc.get(wb.active).validation;const validationCtx={evaluate:(text,entry)=>wb.evaluateText(wb.active,text,entry),range:text=>wb.evaluateRange(wb.active,text)};let pendingAlert=$state(null);let dataValidationOpen=$state(false);let circlesOn=$state(null);const circled=$derived.by(()=>{void version;const out=new Set;if(circlesOn===null||circlesOn.toLowerCase()!==wb.active.toLowerCase())return out;const hits=invalidCells(rulesNow(),validationCtx,(r,c)=>wb.getRaw(wb.active,r,c),wb.rowCount(wb.active),wb.colCount(wb.active));for(const hit of hits)out.add(`${hit.row},${hit.col}`);return out});const inputMessage=$derived.by(()=>{void version;if(cellPopover)return null;const rule=ruleAt(rulesNow(),active.rowIndex,active.colIndex);if(!rule?.input)return null;return{r:active.rowIndex,c:active.colIndex,title:rule.input.title,message:rule.input.message}});let messageRect=$state(null);function measureMessage(){const at=inputMessage;const host=gridHost;if(!at||!host){messageRect=null;return}const td=host.querySelector(`td[data-svgrid-row="${at.r}"][data-svgrid-col="${at.c}"]`);if(!td){messageRect=null;return}const a=td.getBoundingClientRect();const b=host.getBoundingClientRect();messageRect={left:a.left-b.left,top:a.top-b.top,height:a.height}}$effect(()=>{void inputMessage;void version;void tick().then(()=>requestAnimationFrame(measureMessage))});const cfNow=()=>doc.get(wb.active).conditionalFormats;const cfCtx={evaluate:(text,at)=>wb.evaluateText(wb.active,text,void 0,at)};const cfStatsCache=new Map;function cfStatsFor(rule){let stats=cfStatsCache.get(rule.id);if(!stats){stats=ruleStats(rule,(r,c)=>wb.getValue(wb.active,r,c),(r,c)=>display(r,c).text);cfStatsCache.set(rule.id,stats)}return stats}function cfAt(r,c,value){const rules=cfNow();if(!rules.length)return null;return evaluateCf(rules,r,c,value,display(r,c).text,cfStatsFor,cfCtx)}let cfDialog=$state(null);let manageRulesOpen=$state(false);const cfRules=$derived.by(()=>{void version;return cfNow()});const cfSelection=$derived.by(()=>{void version;void selection;void active;return cfRects()});const mergesNow=()=>doc.get(wb.active).merges;const activeMerges=$derived.by(()=>{void version;return toGridMerges(mergesNow())});let mergeConfirm=$state(null);function setMerges(next){const sheet=wb.active;const before=doc.get(sheet).merges;const put=merges=>{doc.get(sheet).merges=merges;bump();changed({kind:"merges"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}function covered(r,c){return isCoveredCell(mergesNow(),r,c)}const liveWidths=$state({});$effect(()=>{const next=api?.getColumnWidths()??{};for(const[letter,px]of Object.entries(next)){if(untrack(()=>liveWidths[letter])!==px)liveWidths[letter]=px}});const widthOf=col=>{const letter=colToLetters(col);return liveWidths[letter]??columnWidths?.[letter]??columnWidth};function cellWidth(r,c){const one=widthOf;const m=sheetMergeAt(mergesNow(),r,c);if(!m||m[0]!==r||m[1]!==c)return one(c);let total=0;for(let col=m[1];col<=m[3];col+=1)total+=one(col);return total}function runMerge(kind,cmd){const rects=selectedRects(cmd).map(normalRect);if(!allowNow("formatCells")&&rectsHaveLocked(storeFor(),lookup,rects,protectionNow().ranges)){refuse();return}if(kind==="center"&&rects.length===1&&mergesIn(mergesNow(),rects).some(m=>m.join()===rects[0].join())){runUnmerge(cmd);return}const plan=mergePlan(mergesNow(),rects,kind,(r,c)=>wb.getRaw(wb.active,r,c)==="");if(plan.merges.length===mergesNow().length&&plan.merges.every((m,i)=>m===mergesNow()[i]))return;if(plan.clear.length){mergeConfirm={plan,rects};return}applyMerge(plan,cmd)}function applyMerge(plan,cmd){const target=getFormatTarget();cmd.batch(()=>{for(const[r,c]of plan.clear)cmd.setCellValue(r,c,"");if(plan.center&&target&&plan.origins.length){const rects=plan.origins.map(([r,c])=>[r,c,r,c]);withFormatUndo(cmd,target,rects,()=>target.store.set(rects,{align:"center"},target.lookup))}setMerges(plan.merges)});if(plan.origins[0]){cmd.setActiveCell(plan.origins[0][0],plan.origins[0][1]);cmd.setSelection(plan.origins[0][0],plan.origins[0][1])}focusSheet(cmd)}function runUnmerge(cmd){const rects=selectedRects(cmd).map(normalRect);const next=unmergePlan(mergesNow(),rects);if(next.length===mergesNow().length)return;cmd.batch(()=>setMerges(next));focusSheet(cmd)}const selectionHasMerge=()=>selectionMerged(mergesNow(),selectedRects(cmdOf()).map(normalRect));const autoFilterNow=()=>doc.get(wb.active).autoFilter;const activeFilter=$derived.by(()=>{void version;return autoFilterNow()});const displayOnActive=(r,c)=>display(r,c).text;const valueOnActive=(r,c)=>wb.getValue(wb.active,r,c);const fillOnActive=(r,c)=>{const value=wb.getValue(wb.active,r,c);return cfAt(r,c,value)?.style?.fill??storeFor().get(`r${r}`,colToLetters(c))?.fill??null};const filterCtx=()=>({fillAt:fillOnActive});const colourOnActive=(r,c,on)=>{if(on==="fill")return fillOnActive(r,c);const value=wb.getValue(wb.active,r,c);return cfAt(r,c,value)?.style?.color??storeFor().get(`r${r}`,colToLetters(c))?.color??null};function displayOn(name,r,c){const value=wb.getValue(name,r,c);if(isError(value))return value.error;const entry=doc.get(name).formats.get(`r${r}`,colToLetters(c));if(entry?.numFmt)return compileNumberFormat(entry.numFmt,marks).format(value).text;if(value===""||value==null)return"";if(typeof value==="boolean")return value?"TRUE":"FALSE";return String(value)}function settleFilterRows(next){const state=doc.get(wb.active);const before=state.filterHidden;if(api){for(const r of before)if(!next.has(r)&&!state.hidden.rows.has(r))api.setRowCollapsed(r,false);for(const r of next)if(!before.has(r))api.setRowCollapsed(r,true)}state.filterHidden=new Set(next);tellWorkbookWhatIsHidden()}function tellWorkbookWhatIsHidden(){wb.setHiddenRows((sheet,row)=>{const state=doc.get(sheet);if(state.filterHidden.has(row))return"filter";return state.hidden.rows.has(row)?"hand":null})}function applyAutoFilter(next,cmd){const sheet=wb.active;const before=doc.get(sheet).autoFilter;const put=state=>{doc.get(sheet).autoFilter=state;settleFilterRows(hiddenRowsFor(state,valueOnActive,displayOnActive,filterCtx()));bump();changed({kind:"filter"})};put(next);cmd?.recordUndo(()=>put(before),()=>put(next))}function toggleAutoFilter(cmd){if(!allowNow("autoFilter")){refuse();return}if(autoFilterNow()){applyAutoFilter(null,cmd);return}const region=currentRegion(gridOf(cmd),{row:active.rowIndex,col:active.colIndex});const last=selection[selection.length-1];const isRange=last&&(last[0]!==last[2]||last[1]!==last[3]);const range=isRange?normalRect(last):region;applyAutoFilter({range,filters:{}},cmd)}function filterArrowAt(r,c){const af=activeFilter;if(!af||r!==af.range[0]||c<af.range[1]||c>af.range[3])return null;return af.filters[c]?"filtered":"plain"}function filterMenuFor(col){const af=autoFilterNow();const others=hiddenRowsFor(withColumnFilter(af,col,null),valueOnActive,displayOnActive,filterCtx());const values=distinctValues(af,col,valueOnActive,displayOnActive,r=>!others.has(r));const numeric=values.some(v=>v.numeric!==null)&&values.every(v=>v.numeric!==null||v.text==="");const dates=isDateColumn(values);const fills=distinctFills(af,col,fillOnActive);const header=display(af.range[0],col).text||colToLetters(col);return{values,numeric,dates,fills,header,filter:af.filters[col]??null}}function openFilterMenu(col){const af=autoFilterNow();const cmd=cmdOf();if(!af||!cmd)return;if(!allowNow("autoFilter")){refuse();return}if(cellPopover)closeCellPopover();cellPopover={kind:"filter",r:af.range[0],c:col,...filterMenuFor(col)};void tick().then(()=>requestAnimationFrame(measureAnchor))}function refreshAutoFilter(){const state=doc.get(wb.active);if(!state.autoFilter||!api)return;const next=hiddenRowsFor(state.autoFilter,valueOnActive,displayOnActive,filterCtx());if(next.size===state.filterHidden.size&&[...next].every(r=>state.filterHidden.has(r)))return;settleFilterRows(next)}const filterSummary=$derived.by(()=>{void version;const af=autoFilterNow();if(!isFiltering(af))return null;const total=af.range[2]-af.range[0];return t("statusRecordsFound",{shown:total-doc.get(wb.active).filterHidden.size,total})});function setCf(next){const sheet=wb.active;const before=doc.get(sheet).conditionalFormats;const put=rules=>{doc.get(sheet).conditionalFormats=rules;bump();changed({kind:"conditional-formats"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}function cfRects(){return selectedRects(cmdOf()).map(([r1,c1,r2,c2])=>[Math.min(r1,r2),Math.min(c1,c2),Math.max(r1,r2),Math.max(c1,c2)])}function addCf(body){const rule={id:cfId(),rects:cfRects(),...body};setCf([rule,...cfNow()])}function applyCfBody(body){const dialog=cfDialog;cfDialog=null;if(dialog?.rule&&dialog.replace){dialog.replace({...body,id:dialog.rule.id,rects:dialog.rule.rects,stopIfTrue:dialog.rule.stopIfTrue});return}addCf(body)}const CF_PRESETS={"cf-greater":"greater","cf-less":"less","cf-between":"between","cf-equal":"equal","cf-text":"text","cf-duplicates":"duplicates","cf-top10":"top10","cf-bottom10":"bottom10","cf-above-average":"aboveAverage","cf-below-average":"belowAverage","cf-formula":"formula"};function cfAction(action,context){const preset=CF_PRESETS[action];if(preset){cfDialog={preset,rule:null};return true}switch(action){case"cf-data-bar":addCf({kind:"dataBar",color:DATA_BAR_COLOR});break;case"cf-color-scale-3":addCf({kind:"colorScale",colors:COLOR_SCALES["green-yellow-red"]});break;case"cf-color-scale-2":addCf({kind:"colorScale",colors:COLOR_SCALES["green-white"]});break;case"cf-icon-set":addCf({kind:"iconSet",set:"arrows"});break;case"cf-clear-selection":{const next=removeCf(cfNow(),cfRects());if(next.length!==cfNow().length||next.some((rule,i)=>rule!==cfNow()[i]))setCf(next);break}case"cf-clear-sheet":if(cfNow().length)setCf([]);break;case"cf-manage":manageRulesOpen=true;return true;default:return false}focusSheet(context);return true}const PLAIN_NUMBER=/^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;function storedTextFor(r,c,text){const parsed=parseEntry(text,culture);if(parsed)return parsed.value;if(text.startsWith("="))return text;const entry=storeFor().get(`r${r}`,colToLetters(c));if(entry?.numFmt&&formatCategory(entry.numFmt).category==="percent"&&PLAIN_NUMBER.test(text.trim())){return String(Number(text.trim())/100)}return text}function admits(r,c,text){const rule=ruleAt(rulesNow(),r,c);if(!rule)return true;const judged=rule.allow==="list"?text:storedTextFor(r,c,text);const verdict=checkEntry(rule,judged,{row:r,col:c},validationCtx);if(verdict.ok)return true;pendingAlert={r,c,text,verdict};const cmd=cmdOf();if(cmd)void tick().then(()=>{cmd.setActiveCell(r,c);cmd.setSelection(r,c)});return false}function setValidation(next){const sheet=wb.active;const before=doc.get(sheet).validation;const put=rules=>{doc.get(sheet).validation=rules;bump();changed({kind:"validation"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}function applyValidation(spec){const rects=selectedRects(cmdOf()).map(([r1,c1,r2,c2])=>[Math.min(r1,r2),Math.min(c1,c2),Math.max(r1,r2),Math.max(c1,c2)]);const kept=removeValidation(rulesNow(),rects);setValidation([...kept,{id:validationId(),rects,...spec}])}function clearValidation(){const rects=selectedRects(cmdOf()).map(([r1,c1,r2,c2])=>[Math.min(r1,r2),Math.min(c1,c2),Math.max(r1,r2),Math.max(c1,c2)]);const next=removeValidation(rulesNow(),rects);if(next.length!==rulesNow().length||next.some((rule,i)=>rule!==rulesNow()[i]))setValidation(next)}function listRuleAt(r,c){const rule=ruleAt(rulesNow(),r,c);return rule&&rule.allow==="list"&&rule.inCellDropdown?rule:void 0}function openListPicker(r,c){const rule=listRuleAt(r,c);const cmd=cmdOf();if(!rule||!cmd)return;if(cellPopover)closeCellPopover();cellPopover={kind:"list",r,c,choices:listChoices(rule,validationCtx)};void tick().then(()=>requestAnimationFrame(measureAnchor))}function pickChoice(choice){const pop=cellPopover;closeCellPopover();const cmd=cmdOf();if(!pop||!cmd)return;if(locked(pop.r,pop.c)){refuse();return}cmd.batch(()=>cmd.setCellValue(pop.r,pop.c,choice))}function retryEntry(){const alert=pendingAlert;pendingAlert=null;const cmd=cmdOf();if(!alert||!cmd)return;void tick().then(()=>{cmd.startEditing(alert.r,alert.c,alert.text)})}function acceptEntry(){const alert=pendingAlert;pendingAlert=null;const cmd=cmdOf();if(!alert||!cmd)return;cmd.batch(()=>cmd.setCellValue(alert.r,alert.c,balanceParens(alert.text)));focusSheet(cmd)}function setProtected(on,cmd,allow){const sheet=wb.active;const state=doc.get(sheet);const before={on:state.protected,allow:{...state.protection.allow}};const after={on,allow:allow?{...allow}:before.allow};if(before.on===on&&!allow)return;const put=value=>{const target=doc.get(sheet);target.protected=value.on;target.protection={allow:{...value.allow},ranges:target.protection.ranges};bump();changed({kind:"protection"})};put(after);cmd?.recordUndo(()=>put(before),()=>put(after));say(t(on?"sheetProtected":"sheetUnprotected"))}function setEditRanges(ranges){const sheet=wb.active;const state=doc.get(sheet);const before=state.protection.ranges;const put=value=>{const target=doc.get(sheet);target.protection={allow:target.protection.allow,ranges:value};bump();changed({kind:"protection"})};put(ranges);cmdOf()?.recordUndo(()=>put(before),()=>put(ranges))}let protectSheetOpen=$state(false);let editRangesOpen=$state(false);const objectsNow=()=>doc.get(wb.active).objects;const activeObjects=$derived.by(()=>{void version;return objectsNow()});let selectedObject=$state(null);let chartSetup=$state(null);let objectBoxes=$state({});let draggingObject=$state(null);let dragging=null;let imageInput=$state(null);function putObjects(next){if(protectedNow()){refuse();return}const sheet=wb.active;const before=doc.get(sheet).objects;const put=value=>{doc.get(sheet).objects=value;bump();changed({kind:"objects"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}let objectSheet="";$effect(()=>{void version;if(wb.active===objectSheet)return;objectSheet=wb.active;untrack(()=>{selectedObject=null})});const addObject=object=>{putObjects([...objectsNow(),object]);selectedObject=object.id};const replaceObject=object=>putObjects(objectsNow().map(o=>o.id===object.id?object:o));function removeObject(id){if(!objectsNow().some(o=>o.id===id))return;putObjects(objectsNow().filter(o=>o.id!==id));if(selectedObject===id)selectedObject=null}const sparklinesNow=()=>doc.get(wb.active).sparklines;const activeSparklines=$derived.by(()=>{void version;return sparklinesNow()});let sparklineSetup=$state(null);function putSparklines(next){if(protectedNow()){refuse();return}const sheet=wb.active;const before=doc.get(sheet).sparklines;const put=value=>{doc.get(sheet).sparklines=value;bump();changed({kind:"sparklines"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}const addSparklines=group=>putSparklines([...sparklinesNow(),group]);const replaceSparklines=group=>putSparklines(sparklinesNow().map(g=>g.id===group.id?group:g));const sparklineHere=()=>sparklineAt(sparklinesNow(),active.rowIndex,active.colIndex);function startSparklines(type){if(protectedNow()){refuse();return}const here=sparklineHere();if(here){replaceSparklines({...copySparkline(here),type,markers:type==="line"?here.markers:void 0});return}const rects=selectedRects().map(normalRect);const rect=rects[rects.length-1];if(!rect||rect[0]===rect[2]&&rect[1]===rect[3]){say(t("selectRangeForSparklines"));return}sparklineSetup={group:sparklinesFromRange(rect,type),existing:false}}function setupSparklines(){if(protectedNow()){refuse();return}const here=sparklineHere();if(!here){say(t("noSparklinesHere"));return}sparklineSetup={group:here,existing:true}}function clearSparklinesHere(){if(protectedNow()){refuse();return}const rects=selectedRects().map(normalRect);const next=clearSparklines(sparklinesNow(),rects);if(next.length===sparklinesNow().length){say(t("noSparklinesHere"));return}putSparklines(next);say(t("sparklinesCleared"))}function imageAt(row,col){const call=imageCall(raw(row,col));if(!call)return null;const value=wb.getValue(wb.active,row,col);if(isError(value))return null;const src=String(value??"");if(!isDrawableImageSource(src))return null;let alt="";if(call.alt){const answered=wb.evaluateText(wb.active,`=${call.alt}`,void 0,{row,col});alt=isError(answered)?"":String(answered??"")}return{src,alt}}function sparkAt(row,col){const group=sparklineAt(activeSparklines,row,col);if(!group)return null;const read=(r,c)=>wb.getValue(wb.active,r,c);const values=sparklineSeries(group,row,col,read);if(!values)return null;const scale=sparklineScale(group,read);return{group,values,min:scale?.min,max:scale?.max}}const tablesNow=()=>wb.tables.list();const activeTables=$derived.by(()=>{void version;return tablesNow().filter(t2=>t2.sheet.toLowerCase()===wb.active.toLowerCase())});let tableSetup=$state(null);function putTables(next){if(protectedNow()){refuse();return}const before=tablesNow().map(t2=>({...t2}));const put=value=>{wb.tables.clear();for(const table of value)wb.tables.define({...table});wb.recalculate();bump();changed({kind:"tables"})};const after=next.map(t2=>({...t2}));put(after);cmdOf()?.recordUndo(()=>put(before),()=>put(after))}const tableHere=()=>wb.tables.at(wb.active,active.rowIndex,active.colIndex);function nextTableName(){const taken=new Set(tablesNow().map(t2=>t2.name.toLowerCase()));for(let i=1;;i+=1){const name=`Table${i}`;if(!taken.has(name.toLowerCase()))return name}}function insertTable(){if(protectedNow()){refuse();return}const here=tableHere();if(here){tableSetup={range:[here.headerRow,here.firstCol,here.lastRow+(here.hasTotals?1:0),here.lastCol],name:here.name,headers:true,totals:here.hasTotals,style:here.style??DEFAULT_TABLE_STYLE,existing:here.name};return}const block=blockAround(cmdOf());if(!block||block[0]===block[2]){say(t("selectBlockToTable"));return}tableSetup={range:block,name:nextTableName(),headers:true,totals:false,style:DEFAULT_TABLE_STYLE,existing:null}}function blockAround(cmd){const rects=selectedRects(cmd).map(normalRect);const last=rects[rects.length-1];if(last&&(last[0]!==last[2]||last[1]!==last[3]))return last;const region=cmd?currentRegion(gridOf(cmd),{row:active.rowIndex,col:active.colIndex}):null;return region??last??null}function applyTable(next){const cmd=cmdOf();const[r1,c1,r2,c2]=next.range;const existing=tableSetup?.existing;if(!isValidTableName(next.name)){say(t("table.badName"));return}const clash=tablesNow().find(t2=>t2.name.toLowerCase()===next.name.toLowerCase()&&t2.name!==existing);if(clash){say(t("tableNameTaken",{name:next.name}));return}const hadTotals=existing?tablesNow().find(t2=>t2.name===existing)?.hasTotals??false:false;const lastRow=hadTotals?r2-1:r2;const addingTotals=next.totals&&!hadTotals;const table={name:next.name,sheet:wb.active,headerRow:r1,firstCol:c1,lastCol:c2,lastRow,hasTotals:next.totals,style:next.style};const rest=tablesNow().filter(t2=>t2.name!==existing);cmd?.batch(()=>{putTables([...rest,table]);if(!next.headers){wb.applyStructuralEdit(wb.active,{kind:"insertRows",at:r1,count:1});doc.shift(wb.active,{kind:"insertRows",at:r1,count:1});for(let c=c1;c<=c2;c+=1)cmd.setCellValue(r1,c,`Column${c-c1+1}`)}if(addingTotals){const totalsRow=lastRow+1;let taken=false;for(let c=c1;c<=c2&&!taken;c+=1)taken=wb.getRaw(wb.active,totalsRow,c).trim()!=="";if(taken){wb.applyStructuralEdit(wb.active,{kind:"insertRows",at:totalsRow,count:1});doc.shift(wb.active,{kind:"insertRows",at:totalsRow,count:1})}cmd.setCellValue(totalsRow,c1,t("table.totalLabel"));if(c2>c1)cmd.setCellValue(totalsRow,c2,`=SUBTOTAL(109,[${wb.getRaw(wb.active,r1,c2).trim()||`Column${c2-c1+1}`}])`)}else if(!next.totals&&hadTotals){for(let c=c1;c<=c2;c+=1)if(wb.getRaw(wb.active,r2,c)!=="")cmd.setCellValue(r2,c,"")}applyAutoFilter({range:[r1,c1,lastRow,c2],filters:{}},cmd)});bump();const range=`${colToLetters(c1)}${r1+1}:${colToLetters(c2)}${(next.totals?lastRow+1:lastRow)+1}`;const look2=findTableStyle(next.style);say(existing?t("tableUpdated",{name:next.name,range,style:look2?tableStyleLabel(look2):t("table.styleNoneShort")}):t("tableMade",{name:next.name,range}))}function removeTableHere(){if(protectedNow()){refuse();return}const here=tableHere();if(!here){say(t("noTableHere"));return}putTables(tablesNow().filter(t2=>t2.name!==here.name));say(t("tableRemoved",{name:here.name}))}function fillTableFormulas(row,col){const table=wb.tables.at(wb.active,row,col);if(!table||row<=table.headerRow+1)return;for(let c=table.firstCol;c<=table.lastCol;c+=1){if(wb.getRaw(wb.active,row,c)!=="")continue;const above=wb.getRaw(wb.active,row-1,c);if(!above.startsWith("="))continue;const filled=translateFormula(above,1,0);if(typeof filled==="string")wb.setRaw(wb.active,row,c,filled)}}function tablePartAt(row,col){for(const table of activeTables){if(col<table.firstCol||col>table.lastCol)continue;const colours=tableStyleColours(table.style??DEFAULT_TABLE_STYLE);if(!colours)return null;const css=`--sheet-table-header:${colours.header};--sheet-table-header-text:${colours.headerText};--sheet-table-band:${colours.band};--sheet-table-totals:${colours.totals};--sheet-table-border:${colours.border}`;if(row===table.headerRow){return{part:"header",style:css,text:colours.headerText,fill:colours.headerText==="inherit"?"":colours.header}}const last=table.lastRow+(table.hasTotals?1:0);if(row<table.headerRow||row>last)continue;if(table.hasTotals&&row===last)return{part:"totals",style:css,text:"inherit",fill:""};return{part:(row-table.headerRow)%2===0?"band":"row",style:css,text:"inherit",fill:""}}return null}const linksNow=()=>doc.get(wb.active).links;const activeLinks=$derived.by(()=>{void version;return linksNow()});let linkSetup=$state(null);function putLinks(next){if(protectedNow()){refuse();return}const sheet=wb.active;const before=doc.get(sheet).links;const put=value=>{doc.get(sheet).links=value;bump();changed({kind:"links"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}function linkOf(row,col){const own=linkAt(linksNow(),row,col);if(own)return own;const argument=hyperlinkArgument(raw(row,col));if(!argument)return void 0;const value=wb.evaluateText(wb.active,`=${argument}`,void 0,{row,col});const target=typeof value==="string"?value:typeof value==="number"?String(value):"";return target.trim()?{target}:void 0}function insertLink(){if(protectedNow()){refuse();return}const{rowIndex,colIndex}=active;const here=linkAt(linksNow(),rowIndex,colIndex);linkSetup={link:here??{target:""},text:raw(rowIndex,colIndex),where:`${colToLetters(colIndex)}${rowIndex+1}`,row:rowIndex,col:colIndex,existing:Boolean(here)}}function applyLink(link,text){const setup=linkSetup;const cmd=cmdOf();if(!setup||!cmd)return;cmd.batch(()=>{if(text!==raw(setup.row,setup.col))cmd.setCellValue(setup.row,setup.col,text);putLinks(setLink(linksNow(),setup.row,setup.col,link))});bump()}function removeLinksIn(){if(protectedNow()){refuse();return}let next=linksNow();for(const[r1,c1,r2,c2]of selectedRects().map(normalRect)){for(let r=r1;r<=r2;r+=1)for(let c=c1;c<=c2;c+=1)next=removeLink(next,r,c)}if(next===linksNow()){say(t("noLinkHere"));return}putLinks(next);say(t("linkRemoved"))}async function followLink(link){const target=parseLinkTarget(link.target);if(!target){say(t(isSafeLinkTarget(link.target)?"cannotOpenLink":"linkNotFollowed"));return}if(target.kind==="external"){window.open(target.href,"_blank","noopener,noreferrer");return}if(target.kind==="name"){if(!wb.names.resolve(target.name)){say(t("cannotOpenLink"));return}await jumpToName(target.name);return}const sheet=target.sheet;if(sheet&&sheet.toLowerCase()!==wb.active.toLowerCase()){if(!wb.sheets.some(n=>n.toLowerCase()===sheet.toLowerCase())){say(t("cannotOpenLink"));return}wb.setActive(sheet);bump();await tick()}const cmd=cmdOf();if(!cmd)return;cmd.setActiveCell(target.row,target.col);cmd.setSelection(target.row,target.col);focusSheet(cmd);bump()}const pivotsNow=()=>doc.get(wb.active).pivots;let pivotSetup=$state(null);function putPivots(next){if(protectedNow()){refuse();return}const sheet=wb.active;const before=doc.get(sheet).pivots;const put=value=>{doc.get(sheet).pivots=value;bump();changed({kind:"pivots"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}const cellValueAt=(r,c)=>wb.getValue(wb.active,r,c);const cellTextAt=(r,c)=>String(wb.getValue(wb.active,r,c)??"");function pivotAt(row,col){for(const pivot of pivotsNow()){const w=pivot.written;if(w&&row>=w[0]&&row<=w[2]&&col>=w[1]&&col<=w[3])return pivot;if(!w&&row===pivot.target.row&&col===pivot.target.col)return pivot}return null}let writingPivot=false;function writePivot(pivot,replacing){const cmd=cmdOf();if(!cmd)return;if(protectedNow()){refuse();return}const block=pivotBlock(pivot,cellValueAt,cellTextAt);if(!block.length){say(t("pivot.needValue"));return}const rect=pivotWrittenRect(pivot,block);const next={...copyPivot(pivot),written:rect};writingPivot=true;try{cmd.batch(()=>{const old=pivot.written;if(old){for(let r=old[0];r<=old[2];r+=1){for(let c=old[1];c<=old[3];c+=1)cmd.setCellValue(r,c,"")}}block.forEach((line,i)=>{line.forEach((text,j)=>cmd.setCellValue(pivot.target.row+i,pivot.target.col+j,text))});putPivots(replacing?pivotsNow().map(p=>p.id===next.id?next:p):[...pivotsNow(),next])})}finally{writingPivot=false}wb.recalculate();bump();say(t("pivotWritten",{range:`${colToLetters(rect[1])}${rect[0]+1}:${colToLetters(rect[3])}${rect[2]+1}`}))}function insertPivot(){if(protectedNow()){refuse();return}const here=pivotAt(active.rowIndex,active.colIndex);if(here){pivotSetup={pivot:here,fields:pivotFields(here.source,cellTextAt),existing:true};return}const rect=blockAround(cmdOf());if(!rect||rect[0]===rect[2]||rect[1]===rect[3]){say(t("selectBlockToPivot"));return}const fields=pivotFields(rect,cellTextAt);pivotSetup={pivot:pivotFromRange(rect,fields),fields,existing:false}}function refreshPivot(){const here=pivotAt(active.rowIndex,active.colIndex);if(!here){say(t("noPivotHere"));return}writePivot(here,true);say(t("pivotRefreshed"))}function showPivotDetails(){const here=pivotAt(active.rowIndex,active.colIndex);if(!here){say(t("noPivotHere"));return}const drill=pivotDrill(here,active.rowIndex,active.colIndex,cellValueAt,cellTextAt);if(!drill||!drill.records.length){say(t("noPivotDetails"));return}const name=wb.addSheet(nextDetailSheetName());drill.fields.forEach((field,c)=>wb.setRaw(name,0,c,field));drill.records.forEach((record,r)=>{drill.fields.forEach((field,c)=>{const value=record[field];wb.setRaw(name,r+1,c,value===null||value===void 0?"":String(value))})});doc.get(name).formats.set([[0,0,0,Math.max(0,drill.fields.length-1)]],{bold:true,fill:"#e2e8f0"},{rowIdAt:i=>`r${i}`,columnIdAt:i=>colToLetters(i)});doc.get(name).freeze={rows:1,cols:0};wb.setActive(name);changed({kind:"sheets"});bump();say(t("pivotDetails",{count:drill.records.length,name}))}function nextDetailSheetName(){const taken=new Set(wb.sheets.map(n=>n.toLowerCase()));const base=t("pivotDetailsSheet");if(!taken.has(base.toLowerCase()))return base;for(let i=2;;i+=1)if(!taken.has(`${base}${i}`.toLowerCase()))return`${base}${i}`}function specOf(object){void version;return chartSpecOf(object,(r,c)=>wb.getValue(wb.active,r,c),(r,c)=>display(r,c).text)}function sheetIsRtl(){return Boolean(gridHost)&&getComputedStyle(gridHost).direction==="rtl"}function startOf(a,b){return sheetIsRtl()?b.right-a.right:a.left-b.left}function xOfStart(start,b){return sheetIsRtl()?b.right-start:b.left+start}function paneEdges(host,b){const grid=host.querySelector(".sv-grid-container");if(!grid)return null;const g=grid.getBoundingClientRect();const rtl=sheetIsRtl();const endOf=r=>rtl?b.right-r.left:r.right-b.left;let start=startOf(g,b);const row=grid.querySelector("td[data-svgrid-row]")?.parentElement;for(const el of row?.querySelectorAll('td[data-pinned="left"], td.sv-grid-row-number-cell')??[]){const r=el.getBoundingClientRect();if(r.width)start=Math.max(start,endOf(r))}let top=g.top-b.top;const head=grid.querySelector(".sv-grid-head");if(head)top=Math.max(top,head.getBoundingClientRect().bottom-b.top);for(const tr of grid.querySelectorAll("tr.sv-grid-row-frozen"))top=Math.max(top,tr.getBoundingClientRect().bottom-b.top);return{start,top,end:endOf(g),bottom:g.bottom-b.top,rtl}}function measureObjects(){const host=gridHost;const objects=objectsNow();if(!host||!objects.length){objectBoxes={};return}const b=host.getBoundingClientRect();const edges=paneEdges(host,b);const freeze=doc.get(wb.active).freeze;const next={};for(const object of objects){const td=host.querySelector(`td[data-svgrid-row="${object.anchor.row}"][data-svgrid-col="${object.anchor.col}"]`);if(!td)continue;const a=td.getBoundingClientRect();const box={left:startOf(a,b)+object.anchor.dx,top:a.top-b.top+object.anchor.dy,width:object.anchor.width,height:object.anchor.height};const pane=paneOf(object.anchor,freeze);let clip=null;if(edges){const cut=paneClip(pane,box,edges);if(cut.start||cut.top||cut.end||cut.bottom){const side=n=>n>0?`${n}px`:"-12px";const[left,right]=edges.rtl?[cut.end,cut.start]:[cut.start,cut.end];clip=`inset(${side(cut.top)} ${side(right)} ${side(cut.bottom)} ${side(left)})`}}next[object.id]={...box,frozen:pane!=="body",clip}}objectBoxes=next}$effect(()=>{void version;void activeObjects;if(!activeObjects.length){objectBoxes={};return}void tick().then(()=>requestAnimationFrame(measureObjects))});$effect(()=>{const host=gridHost;if(!host||!activeObjects.length)return;let frame=0;const rows=new MutationObserver(()=>{if(frame||activeObjects.every(o=>objectBoxes[o.id]))return;frame=requestAnimationFrame(()=>{frame=0;measureObjects()})});rows.observe(host,{childList:true,subtree:true});return()=>{rows.disconnect();cancelAnimationFrame(frame)}});const peersHere=$derived.by(()=>presenceOnSheet(livePresence(presence??[]),wb.active));let peerBoxes=$state({});function measurePeers(){const host=gridHost;if(!host||!peersHere.length){peerBoxes={};return}const b=host.getBoundingClientRect();const cellBox=(row,col)=>host.querySelector(`td[data-svgrid-row="${row}"][data-svgrid-col="${col}"]`)?.getBoundingClientRect()??null;const headerBottom=host.querySelector("thead")?.getBoundingClientRect().bottom??b.top;const TAG_HEIGHT=20;const next={};for(const person of peersHere){const[r1,c1,r2,c2]=person.rect;const first=cellBox(r1,c1);const last=cellBox(r2,c2)??first;if(!first||!last)continue;const left=Math.min(startOf(first,b),startOf(last,b));const top=Math.min(first.top,last.top)-b.top;const width=Math.max(startOf(first,b)+first.width,startOf(last,b)+last.width)-left;const height2=Math.max(first.bottom,last.bottom)-b.top-top;const anchor=presenceAnchor(person);const tag=cellBox(anchor.row,anchor.col)??first;const tagBelow=tag.top-headerBottom<TAG_HEIGHT;next[person.id]={left,top,width,height:height2,tagLeft:startOf(tag,b),tagTop:(tagBelow?tag.bottom:tag.top)-b.top,tagBelow}}peerBoxes=next}$effect(()=>{void version;void peersHere;if(!peersHere.length){peerBoxes={};return}void tick().then(()=>requestAnimationFrame(measurePeers))});function reportPresence(){if(!onPresence)return;const rects=selection.length?selection.map(normalRect):[];const rect=rects[rects.length-1]??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];onPresence({sheet:wb.active,rect,active:{row:active.rowIndex,col:active.colIndex}})}function onObjectPointerDown(event,object,kind){if(event.button!==0)return;if(protectedNow()){refuse();return}event.preventDefault();event.stopPropagation();selectedObject=object.id;dragging={id:object.id,kind,x:event.clientX,y:event.clientY,anchor:{...object.anchor}};event.currentTarget.setPointerCapture(event.pointerId)}function onObjectPointerMove(event){const drag=dragging;if(!drag)return;const dx=event.clientX-drag.x;const dy=event.clientY-drag.y;const object=objectsNow().find(o=>o.id===drag.id);if(!object)return;const box=objectBoxes[drag.id];if(!box)return;if((dx||dy)&&draggingObject!==drag.id)draggingObject=drag.id;objectBoxes={...objectBoxes,[drag.id]:drag.kind==="move"?{...box,left:box.left+(sheetIsRtl()?-(event.movementX||0):event.movementX||0),top:box.top+(event.movementY||0)}:{...box,width:Math.max(80,drag.anchor.width+(sheetIsRtl()?-dx:dx)),height:Math.max(60,drag.anchor.height+dy)}}}function onObjectPointerCancel(){dragging=null;draggingObject=null;measureObjects()}function onObjectPointerUp(event){const drag=dragging;dragging=null;if(!drag)return;if(draggingObject){draggingObject=null;void tick().then(measureObjects)}const object=objectsNow().find(o2=>o2.id===drag.id);const box=objectBoxes[drag.id];if(!object||!box)return;if(event.clientX===drag.x&&event.clientY===drag.y)return;if(drag.kind==="resize"){const width=Math.round(box.width);const height2=Math.round(box.height);if(width===object.anchor.width&&height2===object.anchor.height)return;replaceObject({...copyObject(object),anchor:{...object.anchor,width,height:height2}});return}const host=gridHost;if(!host)return;const b=host.getBoundingClientRect();const rtl=sheetIsRtl();const corner=xOfStart(box.left,b)+(rtl?-1:1);const under=host.ownerDocument.elementsFromPoint(corner,b.top+box.top+1).find(el=>el instanceof HTMLElement&&el.matches("td[data-svgrid-row]"));const anchor={...object.anchor};if(under){const a=under.getBoundingClientRect();anchor.row=Number(under.dataset.svgridRow);anchor.col=Number(under.dataset.svgridCol);anchor.dx=Math.round(box.left-startOf(a,b));anchor.dy=Math.round(b.top+box.top-a.top)}else{anchor.dx=Math.round(anchor.dx+(box.left-(objectBoxes[drag.id]?.left??box.left)))}const o=object.anchor;if(anchor.row===o.row&&anchor.col===o.col&&anchor.dx===o.dx&&anchor.dy===o.dy)return;replaceObject({...copyObject(object),anchor})}function insertChart(cmd){if(protectedNow()){refuse();return}const rect=blockAround(cmd);if(!rect||rect[0]===rect[2]&&rect[1]===rect[3]){say(t("selectBlockToChart"));return}addObject(chartFromRange(rect,(r,c)=>wb.getValue(wb.active,r,c)))}async function pictureAsPng(src,width,height2){const image=new Image;await new Promise((resolve,reject)=>{image.onload=()=>resolve();image.onerror=()=>reject(new Error("decode failed"));image.src=src});const vector=/^data:image\/svg\+xml/i.test(src);const natural={w:image.naturalWidth||width,h:image.naturalHeight||height2};const scale=vector?Math.max(1,width*2/natural.w,height2*2/natural.h):1;const canvas=document.createElement("canvas");canvas.width=Math.max(1,Math.round(natural.w*scale));canvas.height=Math.max(1,Math.round(natural.h*scale));const context=canvas.getContext("2d");if(!context)throw new Error("no canvas");context.drawImage(image,0,0,canvas.width,canvas.height);return canvas.toDataURL("image/png")}async function insertPicture(file){if(protectedNow()){refuse();return}let src=await new Promise((resolve,reject)=>{const reader=new FileReader;reader.onload=()=>resolve(String(reader.result??""));reader.onerror=()=>reject(reader.error??new Error("read failed"));reader.readAsDataURL(file)});if(!xlsxCanCarryPicture(src)){try{src=await pictureAsPng(src,240,180)}catch{}}addObject({id:objectId(),kind:"image",anchor:{row:active.rowIndex,col:active.colIndex,dx:8,dy:8,width:240,height:180},src,alt:file.name??""})}async function pickedPicture(event){const input=event.currentTarget;const file=input.files?.[0];input.value="";if(!file)return;try{await insertPicture(file)}catch{say(t("couldNotReadPicture"))}}const pageSetupNow=()=>doc.get(wb.active).pageSetup;const pageSetupState=$derived.by(()=>{void version;return pageSetupNow()});let pageSetupOpen=$state(false);function setPageSetup(next){const sheet=wb.active;const before=copyPageSetup(doc.get(sheet).pageSetup);const after=copyPageSetup(next);const put=value=>{doc.get(sheet).pageSetup=copyPageSetup(value);bump();changed({kind:"page-setup"})};put(after);cmdOf()?.recordUndo(()=>put(before),()=>put(after))}const PAPER_ACTIONS={"paper-a4":"A4","paper-a3":"A3","paper-a5":"A5","paper-letter":"Letter","paper-legal":"Legal","paper-tabloid":"Tabloid"};const selectionText=$derived.by(()=>{void selection;void active;return rangeText(selectedRects().map(normalRect))});function stashWidths(name=wb.active){if(!api)return;doc.get(name).widths={...api.getColumnWidths()}}function applyWidths(name=wb.active){if(!api)return;const saved=doc.get(name).widths;for(let c=0;c<colCount;c+=1){const letter=colToLetters(c);api.setColumnWidth(letter,saved[letter]??columnWidths?.[letter]??columnWidth)}}function ownRowHeights(keep=new Map){const out=new Map;if(!api)return out;for(let r=0;r<rowCount;r+=1){if(api.isRowCollapsed(r)){const before=keep.get(r);if(before!==void 0)out.set(r,before);continue}const h=api.getRowHeight(r);if(h!==rowHeight)out.set(r,h)}return out}function stashHeights(name=wb.active){if(!api)return;doc.get(name).heights=ownRowHeights(doc.get(name).heights)}function applyHeights(name=wb.active){if(!api)return;const saved=doc.get(name).heights;for(let r=0;r<rowCount;r+=1)api.setRowHeight(r,saved.get(r)??null)}const activeGridSheet=$derived.by(()=>{void version;const state=doc.get(wb.active);return state.kind==="grid"?state.grid??null:null});const gridSheetColumns=$derived.by(()=>{const spec=activeGridSheet;if(!spec)return[];return spec.fields.map(field=>({id:field.field,field:field.field,header:field.label??field.field,...field.width!==void 0?{width:field.width}:{},editable:field.editable??spec.editable===true,...field.type==="number"?{align:"right"}:{}}))});function projectGridSheetInto(name,spec){const cells=projectGridSheet(spec);for(let r=0;r<cells.length;r+=1){const line=cells[r];for(let c=0;c<line.length;c+=1)wb.setRaw(name,r,c,line[c])}}function projectActiveGridSheet(){const spec=activeGridSheet;if(spec)projectGridSheetInto(wb.active,spec)}function onBoundGridReady(next){onReady?.(next,doc)}function onGridSheetEdit(change){const spec=activeGridSheet;if(!spec)return;const record=spec.rows[change.rowIndex];const field=spec.fields.find(f=>f.field===change.columnId);if(!record||!field)return;record[field.field]=coerceFieldValue(field,change.newValue);projectActiveGridSheet();changed({kind:"cells"});bump()}function cellTypeHere(r,c){void version;return cellTypeAt(doc.get(wb.active).cellTypes,r,c)}function setCellText(r,c,text){if(locked(r,c)){refuse();return}const cmd=cmdOf();if(cmd)cmd.batch(()=>cmd.setCellValue(r,c,text));else{wb.setRaw(wb.active,r,c,text);bump()}}function toggleCheckbox(r,c){const region=cellTypeHere(r,c);if(!region)return;setCellText(r,c,toggledValue(region,raw(r,c)))}function pressCellButton(r,c,region){onCellAction?.({row:r,col:c,action:region.action??region.id,sheet:wb.active})}const cellAddress=(r,c)=>`${colToLetters(c)}${r+1}`;function selectedLines(axis2,cmd){const rects=cmd.ranges.length?cmd.ranges:cmd.activeCell?[[cmd.activeCell.rowIndex,cmd.activeCell.colIndex,cmd.activeCell.rowIndex,cmd.activeCell.colIndex]]:[];if(!rects.length)return null;let from=Infinity;let to=-Infinity;for(const[r1,c1,r2,c2]of rects){from=Math.min(from,axis2==="rows"?r1:c1);to=Math.max(to,axis2==="rows"?r2:c2)}return Number.isFinite(from)&&to>=0?{from,to}:null}function summaryLineFor(state,line){const side={summaryBelow:true};if(detailRange(state,line,side))return line;const own=outlineLevel(state,line);if(own===0)return null;let at=line;while(outlineLevel(state,at+1)>=own)at+=1;return detailRange(state,at+1,side)?at+1:null}function afterOutlineChange(){const state=doc.get(wb.active);applyHidden(state.hidden,state.filterHidden);changed({kind:"hidden"});bump()}function outlineHidden(name=wb.active){const state=doc.get(name);return{rows:hiddenByOutline(state.outline.rows,{summaryBelow:true}),cols:hiddenByOutline(state.outline.cols,{summaryBelow:true})}}function ownHidden(){const out={rows:new Set,cols:new Set};if(!api)return out;const filtered=doc.get(wb.active).filterHidden;const outlined=outlineHidden();for(let r=0;r<rowCount;r+=1)if(api.isRowCollapsed(r)&&!filtered.has(r)&&!outlined.rows.has(r))out.rows.add(r);for(let c=0;c<colCount;c+=1)if(api.isColumnCollapsed(colToLetters(c))&&!outlined.cols.has(c))out.cols.add(c);return out}function applyHidden(hidden,filtered=new Set){if(!api)return;const outlined=outlineHidden();for(let r=0;r<rowCount;r+=1)api.setRowCollapsed(r,hidden.rows.has(r)||filtered.has(r)||outlined.rows.has(r));for(let c=0;c<colCount;c+=1)api.setColumnCollapsed(colToLetters(c),hidden.cols.has(c)||outlined.cols.has(c))}function stashHidden(name=wb.active){if(!api)return;doc.get(name).hidden=ownHidden()}function stashLive(name=wb.active){stashWidths(name);stashHeights(name);stashHidden(name)}function applyLive(name=wb.active){applyWidths(name);applyHeights(name);const state=doc.get(name);state.filterHidden=hiddenRowsFor(state.autoFilter,(r,c)=>wb.getValue(name,r,c),(r,c)=>displayOn(name,r,c));applyHidden(state.hidden,state.filterHidden)}function hideLines(axis2,hide,cmd){if(!api)return;if(!allowNow(lineKey(axis2))){refuse();return}const count=axis2==="rows"?rowCount:colCount;const isHidden=i=>axis2==="rows"?api.isRowCollapsed(i):api.isColumnCollapsed(colToLetters(i));const setHidden=(i,on)=>axis2==="rows"?api.setRowCollapsed(i,on):api.setColumnCollapsed(colToLetters(i),on);const rects=cmd.ranges.length?cmd.ranges:cmd.activeCell?[[cmd.activeCell.rowIndex,cmd.activeCell.colIndex,cmd.activeCell.rowIndex,cmd.activeCell.colIndex]]:[];const targets=new Set;let lo=count,hi=-1;for(const[r1,c1,r2,c2]of rects){const from=axis2==="rows"?r1:c1;const to=Math.min(axis2==="rows"?r2:c2,count-1);lo=Math.min(lo,from);hi=Math.max(hi,to);for(let i=from;i<=to;i+=1)if(isHidden(i)!==hide)targets.add(i)}if(!hide&&targets.size===0&&hi>=0){for(let i=lo-1;i>=0&&isHidden(i);i-=1)targets.add(i);for(let i=hi+1;i<count&&isHidden(i);i+=1)targets.add(i)}if(axis2==="rows"&&!hide)for(const r of doc.get(wb.active).filterHidden)targets.delete(r);if(targets.size===0){say(t(hide?"nothingToHide":"nothingHidden"));return}const apply=on=>{for(const i of targets)setHidden(i,on);stashHidden();tellWorkbookWhatIsHidden();bump();changed({kind:"hidden"})};apply(hide);cmd.recordUndo(()=>apply(!hide),()=>apply(hide));if(hide&&cmd.activeCell){const at=axis2==="rows"?cmd.activeCell.rowIndex:cmd.activeCell.colIndex;if(isHidden(at)){let next=hi+1;while(next<count&&isHidden(next))next+=1;if(next>=count){next=lo-1;while(next>=0&&isHidden(next))next-=1}if(next>=0){const r=axis2==="rows"?next:cmd.activeCell.rowIndex;const c=axis2==="rows"?cmd.activeCell.colIndex:next;cmd.setActiveCell(r,c);cmd.setSelection(r,c)}}}const unit=axis2==="rows"?targets.size===1?"unitRow":"unitRows":targets.size===1?"unitColumn":"unitColumns";say(t("linesToggled",{count:targets.size,unit:t(unit),state:t(hide?"stateHidden":"stateShown")}))}let targetsBoundTo="";function registerSheetTargets(){if(targetsBoundTo&&targetsBoundTo!==wb.active){if(doc.has(targetsBoundTo))stashLive(targetsBoundTo);applyLive(wb.active);const cmd=cmdOf();if(cmd)applyFreeze(cmd,doc.get(wb.active).freeze)}targetsBoundTo=wb.active;api?.setHistoryTag(doc.get(wb.active));const store=storeFor();setFormatTarget({store,lookup,onChange:()=>{bump();fitWrappedRows();changed({kind:"formats"})},guard:rects=>allowNow("formatCells")||!rectsHaveLocked(store,lookup,rects,protectionNow().ranges),refused:refuse});tellWorkbookWhatIsHidden();setStructureTarget({canApply:edit=>allowNow(edit.kind==="insertRows"?"insertRows":edit.kind==="insertCols"?"insertColumns":edit.kind==="deleteRows"?"deleteRows":"deleteColumns"),refused:refuse,getRaw:(r,c)=>wb.getRaw(wb.active,r,c),setRaw:(r,c,text)=>wb.setRaw(wb.active,r,c,text),apply:edit=>{const sheet=wb.active;stashLive(sheet);doc.shift(sheet,edit);wb.applyStructuralEdit(sheet,edit);applyLive(sheet);marquee=null;changed({kind:"structure",sheet,edit})},rewritesReferences:true,names:wb.names,format:{store,lookup},onChange:bump,snapshot:()=>getState(),restore:state=>{doc.setState(state);targetsBoundTo=wb.active;registerSheetTargets();applyLive(wb.active)}})}const me={};function ensureShortcuts(){if(getShortcutOwner()!==me)claimShortcuts()}function releaseShortcuts(){if(getShortcutOwner()!==me)return;setShortcutOwner(null);setWorkbook(null);setFormatTarget(null);setStructureTarget(null);setFindTarget(null);setFillTranslator(null);setSheetValueProbe(null);setFindReplaceHandler(null);setFormatDialogHandler(null);setPasteSpecialHandler(null);setRibbonActionHandler(null)}function claimShortcuts(){setShortcutOwner(me);setWorkbook(wb,()=>{active={rowIndex:0,colIndex:0};bump()},name=>doc.get(name).sheetHidden);registerSheetTargets();setFindTarget({getRaw:(r,c)=>wb.getRaw(wb.active,r,c),getDisplay:(r,c)=>display(r,c).text,setRaw:(r,c,text)=>{const cmd=cmdOf();if(cmd)cmd.setCellValue(r,c,text);else wb.setRaw(wb.active,r,c,text)},isEditable:(r,c)=>!locked(r,c),onChange:bump});setFillTranslator((value,delta)=>typeof value==="string"&&value.startsWith("=")?translateFormula(value,delta.rows,delta.cols):value);setFindReplaceHandler(context=>delegate("find-replace",context));setFormatDialogHandler(context=>delegate("format-cells",context));setPasteSpecialHandler(context=>delegate("paste-special",context));setRibbonActionHandler((action,context)=>{handleAction(action,context);return true});setSheetValueProbe((r,c)=>wb.getValue(wb.active,r,c))}$effect(()=>{void wb;claimShortcuts();return releaseShortcuts});function raw(r,c){void version;return wb.getRaw(wb.active,r,c)}function display(r,c,numFmt){void version;const text=raw(r,c);if(showFormulas)return{text};const value=wb.getValue(wb.active,r,c);if(isError(value))return{text:value.error,color:"var(--sg-danger, #dc2626)"};const entry=storeFor().get(`r${r}`,colToLetters(c));const fmt=numFmt??entry?.numFmt;if(fmt)return compileNumberFormat(fmt,marks).format(value);if(value===""||value==null)return{text:""};if(typeof value==="boolean")return{text:value?"TRUE":"FALSE"};if(typeof value==="number")return{text:numberToCulture(String(value))};return{text:String(value)}}let hashMeasure=null;function hashesFor(text,c,entry,r=-1,general){if(!text)return null;if(typeof document==="undefined")return null;hashMeasure??=document.createElement("canvas").getContext("2d");if(!hashMeasure)return null;const size=entry?.fontSize??13;const family=entry?.fontFamily||(root?getComputedStyle(root).fontFamily:"sans-serif");hashMeasure.font=`${entry?.bold?"bold ":""}${size}px ${family}`;const width=(r>=0?cellWidth(r,c):widthOf(c))-9;const fits=s=>hashMeasure.measureText(s).width<=width;if(fits(text))return null;if(general!==void 0&&Number.isFinite(general)){const decimals=(text.split(".")[1]??"").length;for(let d=decimals-1;d>=0;d-=1){const s=String(Number(general.toFixed(d)));if(fits(s))return s}for(let m=5;m>=0;m-=1){const[mantissa,exp]=general.toExponential(m).split("e");const e=Number(exp);const s=`${mantissa}E${e<0?"-":"+"}${String(Math.abs(e)).padStart(2,"0")}`;if(fits(s))return s}}const hash=hashMeasure.measureText("#").width||8;return"#".repeat(Math.max(1,Math.floor(width/hash)))}const activeRaw=$derived.by(()=>{void version;return raw(active.rowIndex,active.colIndex)});function spillWidth(r,c,value,entry){if(typeof value!=="string"||value===""||entry?.wrap)return 0;if(sheetMergeAt(mergesNow(),r,c))return 0;if(entry?.align==="right"||entry?.align==="center")return 0;const fill=entry?.fill??"";const store=storeFor();let extra=0;for(let next=c+1;next<colCount;next+=1){if(wb.getRaw(wb.active,r,next)!=="")break;if((store.get(`r${r}`,colToLetters(next))?.fill??"")!==fill)break;extra+=widthOf(next)}return extra}function commit(raw2,cell,via="enter"){const text=fromCulture(raw2);if(locked(cell.rowIndex,cell.colIndex)){refuse();return}if(!admits(cell.rowIndex,cell.colIndex,text))return;const cmd=cmdOf();if(cmd){cmd.batch(()=>cmd.setCellValue(cell.rowIndex,cell.colIndex,balanceParens(text)));if(via==="enter"){const next=Math.min(cell.rowIndex+1,rowCount-1);cmd.setActiveCell(next,cell.colIndex);cmd.setSelection(next,cell.colIndex);cmd.scrollIntoView(next,cell.colIndex);focusSheet(cmd)}return}wb.setRaw(wb.active,cell.rowIndex,cell.colIndex,balanceParens(text));bump()}function goTo(cell){const cmd=cmdOf();if(!cmd)return;cmd.setActiveCell(cell.rowIndex,cell.colIndex);cmd.setSelection(cell.rowIndex,cell.colIndex);cmd.scrollIntoView(cell.rowIndex,cell.colIndex);active=cell;cmd.focus()}function defineNameHere(name){if(!isValidName(name)){say(t("nameBoxBadName",{name}));cmdOf()?.focus();return}const rects=selectedRects().map(normalRect);const[r1,c1,r2,c2]=rects[rects.length-1]??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];const cellRef=(r,c)=>`${colToLetters(c)}${r+1}`;const refersTo=`${quoteSheet(wb.active)}!${cellRef(r1,c1)}${r1===r2&&c1===c2?"":`:${cellRef(r2,c2)}`}`;const put=value=>{if(value===null)wb.names.remove(name);else wb.names.define(name,value);wb.recalculate();doc.changed({kind:"workbook"});bump()};put(refersTo);const cmd=cmdOf();cmd?.recordUndo(()=>put(null),()=>put(refersTo));say(t("nameDefined",{name,refersTo:refersTo.replace(/^.*!/,"")}));cmd?.focus()}async function jumpToName(name){const node=wb.names.resolve(name);if(node)await selectNode(node)}function jumpToReference(text){let node;try{node=parseFormula(`=${text}`)}catch{return false}if(node.k!=="ref"&&node.k!=="range")return false;void selectNode(node);return true}async function selectNode(node){const from=node.k==="ref"?node.ref:node.k==="range"?node.from:null;const to=node.k==="range"?node.to:from;if(!from||from.row===null)return;const target=from.sheet??wb.active;if(target.toLowerCase()!==wb.active.toLowerCase()){if(!wb.sheets.some(s=>s.toLowerCase()===target.toLowerCase()))return;wb.setActive(target);bump();await tick()}const cmd=api?.getCommandContext();if(!cmd)return;cmd.setActiveCell(from.row,from.col);cmd.setSelection(from.row,from.col);if(to&&to.row!==null&&(to.row!==from.row||to.col!==from.col)){cmd.extendSelection(to.row,to.col)}cmd.scrollIntoView(from.row,from.col);active={rowIndex:from.row,colIndex:from.col};cmd.focus()}function lineHidden(r,c){const state=doc.get(wb.active);return state.hidden.rows.has(r)||state.filterHidden.has(r)||state.hidden.cols.has(c)}const aggregate=$derived.by(()=>{void version;const rects=selection.length?selection:[[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex]];let count=0;let numeric=0;let sum=0;for(const[minRow,minCol,maxRow,maxCol]of rects){for(let r=minRow;r<=maxRow;r+=1){for(let c=minCol;c<=maxCol;c+=1){if(lineHidden(r,c))continue;const value=wb.getValue(wb.active,r,c);if(value===""||value==null||isError(value))continue;count+=1;if(typeof value==="number"){numeric+=1;sum+=value}}}}return{count,numeric,sum,average:numeric?sum/numeric:null}});const money=n=>n.toLocaleString(localization?.locale??"en-US",{maximumFractionDigits:2});let root=$state(null);$effect(()=>{void version;const rects=selection.length?selection:[[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex]];const cols=new Set;for(const rect of rects){const[,minCol,,maxCol]=expandToMerges(mergesNow(),[rect[0],rect[1],rect[2],rect[3]]);for(let c=minCol;c<=maxCol;c+=1)cols.add(colToLetters(c))}const host=root;if(!host)return;const wholeCols=new Set;const wholeRows=new Set;for(const rect of rects){const[r1,c1,r2,c2]=expandToMerges(mergesNow(),[rect[0],rect[1],rect[2],rect[3]]);if(r1===0&&r2>=rowCount-1)for(let c=c1;c<=c2;c+=1)wholeCols.add(colToLetters(c));if(c1===0&&c2>=colCount-1)for(let r=r1;r<=r2;r+=1)wholeRows.add(r)}const paint=()=>{for(const th of host.querySelectorAll("th[data-svgrid-header-col]")){const letter=th.dataset.svgridHeaderCol??"";th.classList.toggle("sheet-col-selected",cols.has(letter));th.classList.toggle("sheet-col-whole",wholeCols.has(letter))}for(const td of host.querySelectorAll("td.sv-grid-row-number-cell")){const row=td.parentElement?.querySelector("td[data-svgrid-row]")?.dataset.svgridRow;td.classList.toggle("sheet-row-whole",row!==void 0&&wholeRows.has(Number(row)))}};const frame=requestAnimationFrame(paint);return()=>cancelAnimationFrame(frame)});const features=tableFeatures({});const columns=$derived.by(()=>Array.from({length:colCount},(_,c)=>({id:colToLetters(c),field:colToLetters(c),header:colToLetters(c),width:columnWidths?.[colToLetters(c)]??columnWidth,headerAlign:"center",editable:ctx=>!locked(ctx.row.original.index,c)&&!covered(ctx.row.original.index,c),tooltip:ctx=>{const thread=threadAt(notesNow(),ctx.row.original.index,c);return thread?threadText(thread):null},valueParser:params=>admits(params.data.index,c,params.rawInput)?params.newValue:params.oldValue,editorType:"text",editorMultiline:true,cell:ctx=>renderSnippet(Cell,{r:ctx.row.original.index,c})})));function cmdOf(){return api?api.getCommandContext():null}function sheetOfTag(tag){if(!tag)return null;return wb.sheets.find(name=>doc.get(name)===tag)??null}function historyIsElsewhere(direction){const next=direction==="undo"?api?.peekUndo():api?.peekRedo();if(!next)return false;const sheet=sheetOfTag(next.tag);return sheet!==null&&sheet.toLowerCase()!==wb.active.toLowerCase()}async function undoRedo(direction){const a=api;if(!a)return false;const next=direction==="undo"?a.peekUndo():a.peekRedo();if(!next)return false;const sheet=sheetOfTag(next.tag);if(sheet!==null&&sheet.toLowerCase()!==wb.active.toLowerCase()){wb.setActive(sheet);bump();await tick()}const done=direction==="undo"?a.undo():a.redo();cmdOf()?.focus();return done}function handleAction(action,context){switch(action){case"recalculate":wb.recalculate();bump();return;case"toggle-formulas":showFormulas=!showFormulas;bump();return;case"toggle-gridlines":if(onAction?.(action,context)===true)return;gridlinesOn=!gridlinesOn;focusSheet(context);return;case"toggle-formula-bar":if(onAction?.(action,context)===true)return;formulaBarOn=!formulaBarOn;focusSheet(context);return;case"toggle-headings":if(onAction?.(action,context)===true)return;headingsOn=!headingsOn;focusSheet(context);return;case"toggle-ribbon":if(onAction?.(action,context)===true)return;ribbonCollapsed=!ribbonCollapsed;focusSheet(context);return;case"toggle-filter":if(onAction?.(action,context)===true)return;toggleAutoFilter(context);focusSheet(context);return;case"sort-asc":case"sort-desc":if(onAction?.(action,context)===true)return;sortRegion(action==="sort-asc"?"asc":"desc");return;case"paste-values":case"paste-formulas":case"paste-formats":case"paste-transpose":if(onAction?.(action,context)===true)return;void pasteSpecial(action==="paste-transpose"?{transpose:true}:{what:action.slice("paste-".length)});return;case"format-painter":if(onAction?.(action,context)===true)return;if(painter)painter=null;else armPainter();focusSheet(context);return;case"row-height":case"column-width":if(onAction?.(action,context)===true)return;openSizeDialog(action==="row-height"?"rows":"cols");return;case"protect-sheet":if(onAction?.(action,context)===true)return;protectSheetOpen=true;return;case"unprotect-sheet":if(onAction?.(action,context)===true)return;setProtected(false,context);focusSheet(context);return;case"allow-edit-ranges":if(onAction?.(action,context)===true)return;editRangesOpen=true;return;case"new-comment":case"edit-comment":if(onAction?.(action,context)===true)return;openCommentEditor(active.rowIndex,active.colIndex);return;case"delete-comment":if(onAction?.(action,context)===true)return;if(cellPopover)closeCellPopover(false);if(commentAt(notesNow(),active.rowIndex,active.colIndex)!==void 0)setComment(active.rowIndex,active.colIndex,"");focusSheet(context);return;case"prev-comment":case"next-comment":if(onAction?.(action,context)===true)return;walkComments(action==="next-comment"?1:-1);return;case"toggle-comments":if(onAction?.(action,context)===true)return;showComments=!showComments;focusSheet(context);return;case"open-list":if(onAction?.(action,context)===true)return;if(filterArrowAt(active.rowIndex,active.colIndex)){openFilterMenu(active.colIndex);return}openListPicker(active.rowIndex,active.colIndex);return;case"cf-greater":case"cf-less":case"cf-between":case"cf-equal":case"cf-text":case"cf-duplicates":case"cf-top10":case"cf-bottom10":case"cf-above-average":case"cf-below-average":case"cf-data-bar":case"cf-color-scale-3":case"cf-color-scale-2":case"cf-icon-set":case"cf-formula":case"cf-clear-selection":case"cf-clear-sheet":case"cf-manage":if(onAction?.(action,context)===true)return;cfAction(action,context);return;case"merge-center":case"merge-across":case"merge-cells":if(onAction?.(action,context)===true)return;runMerge(action==="merge-center"?"center":action==="merge-across"?"across":"cells",context);return;case"unmerge-cells":if(onAction?.(action,context)===true)return;runUnmerge(context);return;case"toggle-lock":{if(onAction?.(action,context)===true)return;const wasLocked=isLocked(storeFor().get(`r${active.rowIndex}`,colToLetters(active.colIndex)));applyFormat(context,{locked:wasLocked?false:void 0});focusSheet(context);return}case"autofit-rows":case"autofit-columns":if(onAction?.(action,context)===true)return;autofitLines(action==="autofit-rows"?"rows":"cols",context);focusSheet(context);return;case"hide-rows":case"hide-columns":case"unhide-rows":case"unhide-columns":{if(onAction?.(action,context)===true)return;hideLines(action.endsWith("rows")?"rows":"cols",action.startsWith("hide"),context);focusSheet(context);return}case"group-rows":case"group-cols":case"ungroup-rows":case"ungroup-cols":{if(onAction?.(action,context)===true)return;const axis2=action.endsWith("rows")?"rows":"cols";const span=selectedLines(axis2,context);if(!span){say(t("selectLinesToGroup"));return}const state=doc.get(wb.active);const change=action.startsWith("group")?groupLines:ungroupLines;state.outline=axis2==="rows"?{rows:change(state.outline.rows,span.from,span.to),cols:state.outline.cols}:{rows:state.outline.rows,cols:change(state.outline.cols,span.from,span.to)};afterOutlineChange();focusSheet(context);return}case"insert-checkbox":case"insert-cell-button":case"clear-cell-type":{if(onAction?.(action,context)===true)return;const rects=context.ranges.length?context.ranges.map(r=>[...r]):context.activeCell?[[context.activeCell.rowIndex,context.activeCell.colIndex,context.activeCell.rowIndex,context.activeCell.colIndex]]:[];if(!rects.length){say(t("selectCellsForControl"));return}const state=doc.get(wb.active);if(action==="clear-cell-type"){state.cellTypes=removeCellTypes(state.cellTypes,rects)}else{const kind=action==="insert-checkbox"?"checkbox":"button";state.cellTypes=applyCellType(state.cellTypes,{id:newCellTypeId(),kind,rects})}changed({kind:"validation"});bump();focusSheet(context);return}case"clear-outline":{if(onAction?.(action,context)===true)return;const state=doc.get(wb.active);state.outline={rows:clearOutline(),cols:clearOutline()};afterOutlineChange();focusSheet(context);return}case"auto-outline":{if(onAction?.(action,context)===true)return;const state=doc.get(wb.active);const isSummary=r=>{for(let c=0;c<colCount;c+=1)if(raw(r,c).startsWith("="))return true;return false};state.outline={rows:autoOutline(0,rowCount-1,isSummary,{summaryBelow:true}),cols:state.outline.cols};afterOutlineChange();focusSheet(context);return}case"show-detail":case"hide-detail":{if(onAction?.(action,context)===true)return;const wanted=action==="hide-detail";const state=doc.get(wb.active);const row=context.activeCell?.rowIndex??0;const summary=summaryLineFor(state.outline.rows,row);if(summary===null){say(t("noGroupHere"));return}const already=state.outline.rows.collapsed.includes(summary);if(already!==wanted){state.outline={rows:toggleCollapsed(state.outline.rows,summary),cols:state.outline.cols};afterOutlineChange()}focusSheet(context);return}case"freeze-panes":case"freeze-top-row":case"freeze-first-column":case"unfreeze-panes":{if(onAction?.(action,context)===true)return;const before=doc.get(wb.active).freeze;const put=state2=>{applyFreeze(context,state2);doc.get(wb.active).freeze=state2;changed({kind:"freeze"})};const state=action==="freeze-panes"?freezeAtActiveCell(context):action==="freeze-top-row"?freezeTopRow(context):action==="freeze-first-column"?freezeFirstColumn(context):applyFreeze(context,{rows:0,cols:0});doc.get(wb.active).freeze=state;changed({kind:"freeze"});context.recordUndo(()=>put(before),()=>put(state));focusSheet(context);return}default:delegate(action,context)}}const without=$derived.by(()=>{const out=[];out.push(isProtected?"protect-sheet":"unprotect-sheet");return out});function sortBlock(over){const cmd=cmdOf();if(!cmd||!cmd.activeCell)return null;const last=selection[selection.length-1];const isRange=last&&(last[0]!==last[2]||last[1]!==last[3]);const chosen=over?over.rect:isRange?last:currentRegion(gridOf(cmd),{row:active.rowIndex,col:active.colIndex});const top=chosen[0];const left=chosen[1];const bottom=Math.min(chosen[2],Math.max(wb.rowCount(wb.active)-1,top));const right=Math.min(chosen[3],Math.max(wb.colCount(wb.active)-1,left));if(over)return{top,left,bottom,right};const rect=expandToMerges(mergesNow(),[top,left,bottom,right]);return{top:rect[0],left:rect[1],bottom:rect[2],right:rect[3]}}function sortRegion(direction,over){const block=sortBlock(over);if(!block)return;const keyCol=Math.min(Math.max(over?.keyCol??active.colIndex,block.left),block.right);const headerRow=over?true:guessHeaderRow((r,c)=>wb.getValue(wb.active,r,c),block.top,keyCol,block);sortBy(block,[{col:keyCol,direction}],headerRow)}function sortBy(block,keys,headerRow){const cmd=cmdOf();const target=getFormatTarget();if(!cmd||!cmd.activeCell||!target||!keys.length)return;const r1=block.top;const c1=block.left;const r2=block.bottom;const c2=block.right;if(r2<=r1)return;if(!allowNow("sort")||protectedNow()&&rectsHaveLocked(storeFor(),lookup,[[r1,c1,r2,c2]],protectionNow().ranges)){refuse();return}if(sortBlockedByMerges(mergesNow(),[r1,c1,r2,c2])){say(t("mergeSameSize"));return}const valueAt=(r,c)=>wb.getValue(wb.active,r,c);const start=headerRow?r1+1:r1;if(r2<=start)return;const span=Array.from({length:r2-start+1},(_,i)=>start+i);const rows=span.filter(r=>!lineHidden(r,c1));const skipped=span.length-rows.length;if(rows.length<2)return;const order=sortOrder(rows,keys,valueAt,colourOnActive);if(order.every((r,i)=>r===rows[i]))return;const store=target.store;const before=new Map(rows.map(r=>[r,{raw:Array.from({length:c2-c1+1},(_,i)=>wb.getRaw(wb.active,r,c1+i)),formats:Array.from({length:c2-c1+1},(_,i)=>store.get(`r${r}`,colToLetters(c1+i)))}]));const sheet=wb.active;const valueBefore=rows.map(row=>Array.from({length:c2-c1+1},(_,k)=>wb.getRaw(sheet,row,c1+k)));cmd.batch(()=>{withFormatUndo(cmd,target,[[start,c1,r2,c2]],()=>{order.forEach((source,i)=>{const row=rows[i];const from=before.get(source);for(let k=0;k<=c2-c1;k+=1){const c=c1+k;wb.setRaw(sheet,row,c,String(translateFormula(from.raw[k],row-source,0)??""));const one=[[row,c,row,c]];store.clear(one,target.lookup);if(from.formats[k])store.set(one,from.formats[k],target.lookup)}})});wb.recalculate();const valueAfter=rows.map(row=>Array.from({length:c2-c1+1},(_,k)=>wb.getRaw(sheet,row,c1+k)));const putValues=grid=>{rows.forEach((row,i)=>grid[i].forEach((text,k)=>wb.setRaw(sheet,row,c1+k,text)));wb.recalculate();bump();changed({kind:"cells"})};cmd.recordUndo(()=>putValues(valueBefore),()=>putValues(valueAfter));changed({kind:"cells"});if(mergesIn(mergesNow(),[[start,c1,r2,c2]]).length){const rowFor=oldRow=>{const i=order.indexOf(oldRow);return i<0?oldRow:rows[i]};setMerges(reorderMerges(mergesNow(),[start,c1,r2,c2],rowFor))}});if(skipped>0)say(t("sortKeptHidden",{count:skipped,unit:t(skipped===1?"unitRow":"unitRows")}));cmd.setSelection(r1,c1);cmd.extendSelection(r2,c2);bump();fitWrappedRows()}let statusMessage=$state(null);let statusTimer=null;function say(message){statusMessage=message;if(statusTimer)clearTimeout(statusTimer);statusTimer=setTimeout(()=>statusMessage=null,8e3)}let findOpen=$state(false);let pasteSpecialOpen=$state(false);let formatCellsOpen=$state(false);let insertFunctionOpen=$state(false);let nameManagerOpen=$state(false);let goalSeekOpen=$state(false);let iterationOpen=$state(false);let evaluateOpen=$state(false);let evaluateCell=$state({row:0,col:0});let errorsOpen=$state(false);let textToColumnsOpen=$state(false);let removeDuplicatesOpen=$state(false);let sortDialog=$state(null);function delegate(action,context){if(onAction?.(action,context)===true)return;switch(action){case"undo":void undoRedo("undo");return;case"delete-sheet":tabs?.deleteSheet(wb.active);return;case"redo":void undoRedo("redo");return;case"find-replace":findOpen=true;return;case"paste-special":void openPasteSpecial();return;case"format-cells":formatCellsOpen=true;return;case"insert-function":insertFunctionOpen=true;return;case"name-manager":nameManagerOpen=true;return;case"goal-seek":goalSeekOpen=true;return;case"calc-options":iterationOpen=true;return;case"evaluate-formula":evaluateCell={row:active.rowIndex,col:active.colIndex};evaluateOpen=true;return;case"cut":cutSelection(context);return;case"error-checking":errorsOpen=true;return;case"text-to-columns":textToColumnsOpen=true;return;case"remove-duplicates":removeDuplicatesOpen=true;return;case"sort-custom":{const block=sortBlock();if(!block||block.bottom<=block.top){say(t("selectBlockToSort"));return}const keyCol=Math.min(Math.max(active.colIndex,block.left),block.right);sortDialog={block,headerGuess:guessHeaderRow((r,c)=>wb.getValue(wb.active,r,c),block.top,keyCol,block)};return}case"data-validation":dataValidationOpen=true;return;case"file-new":if(documentHasContent())newConfirm=true;else newWorkbook();return;case"file-open":fileInput?.click();return;case"file-save-xlsx":void saveXlsx();return;case"file-save-ods":void saveOds();return;case"file-save-xls":saveXls();return;case"file-export-csv":{try{downloadBlobFile(new Blob([toCsv()],{type:"text/csv;charset=utf-8"}),`${wb.active}.csv`)}catch(e){say(e instanceof Error?e.message:t("couldNotExport"))}return}case"file-print":if(onAction?.(action,context)===true)return;print();return;case"page-portrait":case"page-landscape":if(onAction?.(action,context)===true)return;setPageSetup({...pageSetupNow(),orientation:action==="page-portrait"?"portrait":"landscape"});focusSheet(context);return;case"paper-a4":case"paper-a3":case"paper-a5":case"paper-letter":case"paper-legal":case"paper-tabloid":if(onAction?.(action,context)===true)return;setPageSetup({...pageSetupNow(),paper:PAPER_ACTIONS[action]});focusSheet(context);return;case"margins-normal":case"margins-narrow":case"margins-wide":if(onAction?.(action,context)===true)return;setPageSetup({...pageSetupNow(),margins:{...MARGIN_PRESETS[action.slice("margins-".length)]}});focusSheet(context);return;case"print-area-set":{if(onAction?.(action,context)===true)return;const rects=selectedRects(context).map(normalRect);setPageSetup({...pageSetupNow(),printArea:rects});say(t("printAreaSet",{range:rangeText(rects)}));focusSheet(context);return}case"print-area-clear":if(onAction?.(action,context)===true)return;setPageSetup({...pageSetupNow(),printArea:null});say(t("printAreaCleared"));focusSheet(context);return;case"print-gridlines":case"print-headings":if(onAction?.(action,context)===true)return;setPageSetup(action==="print-gridlines"?{...pageSetupNow(),gridlines:!pageSetupNow().gridlines}:{...pageSetupNow(),headings:!pageSetupNow().headings});focusSheet(context);return;case"print-titles":case"page-setup":if(onAction?.(action,context)===true)return;pageSetupOpen=true;return;case"insert-chart":if(onAction?.(action,context)===true)return;insertChart(context);return;case"insert-picture":if(onAction?.(action,context)===true)return;if(protectedNow()){refuse();return}imageInput?.click();return;case"chart-setup":{if(onAction?.(action,context)===true)return;if(protectedNow()){refuse();return}const object=objectsNow().find(o=>o.id===selectedObject);if(object?.kind==="chart")chartSetup=object;else say(t("selectChartFirst"));return}case"delete-object":{if(onAction?.(action,context)===true)return;if(protectedNow()){refuse();return}if(selectedObject)removeObject(selectedObject);return}case"sparkline-line":case"sparkline-column":case"sparkline-winloss":if(onAction?.(action,context)===true)return;startSparklines(action==="sparkline-line"?"line":action==="sparkline-column"?"column":"winloss");return;case"sparkline-setup":if(onAction?.(action,context)===true)return;setupSparklines();return;case"clear-sparklines":if(onAction?.(action,context)===true)return;clearSparklinesHere();return;case"insert-table":if(onAction?.(action,context)===true)return;insertTable();return;case"remove-table":if(onAction?.(action,context)===true)return;removeTableHere();return;case"table-style":if(onAction?.(action,context)===true)return;if(!tableHere()){say(t("noTableHere"));return}insertTable();return;case"insert-link":if(onAction?.(action,context)===true)return;insertLink();return;case"remove-link":if(onAction?.(action,context)===true)return;removeLinksIn();return;case"insert-pivot":if(onAction?.(action,context)===true)return;insertPivot();return;case"refresh-pivot":if(onAction?.(action,context)===true)return;refreshPivot();return;case"pivot-details":if(onAction?.(action,context)===true)return;showPivotDetails();return;case"trace-precedents":trace("precedents");return;case"trace-dependents":trace("dependents");return;case"remove-arrows":removeArrows();return;case"circle-invalid":{circlesOn=wb.active;bump();const count=circled.size;say(count===0?t("noInvalidData"):t(count===1?"invalidCellFound":"invalidCellsFound",{count}));return}case"clear-circles":circlesOn=null;bump();return}}function afterDialog(message){bump();if(message)say(message);const c=cmdOf();if(c)focusSheet(c)}const activeEntry=$derived.by(()=>{void version;return storeFor().get(`r${active.rowIndex}`,colToLetters(active.colIndex))});const activeValue=$derived.by(()=>{void version;return wb.getValue(wb.active,active.rowIndex,active.colIndex)});const activeRule=$derived.by(()=>{void version;return ruleAt(rulesNow(),active.rowIndex,active.colIndex)});const selectionAddress=$derived.by(()=>{void version;void selection;void active;const rects=selectedRects();return rects.map(([r1,c1,r2,c2])=>{const a=`${colToLetters(Math.min(c1,c2))}${Math.min(r1,r2)+1}`;const b=`${colToLetters(Math.max(c1,c2))}${Math.max(r1,r2)+1}`;return a===b?a:`${a}:${b}`}).join(", ")});const mixedLocked=$derived.by(()=>{void version;void selection;void active;return rectsMixLocked(storeFor(),lookup,selectedRects())});function applyFormatCells(patch,border){const cmd=cmdOf();if(!cmd)return;cmd.batch(()=>{if(Object.keys(patch).length)applyFormat(cmd,patch);if(border)applyBorders(cmd,border)});bump();focusSheet(cmd)}function insertFunction(name){const cmd=cmdOf();if(!cmd)return;const{rowIndex,colIndex}=active;void tick().then(()=>cmd.startEditing(rowIndex,colIndex,`=${name}(`))}function pasteBlock(grid,origin,opts,merges=[]){const cmd=cmdOf();const target=getFormatTarget();if(!cmd||!target)return false;const last=selection[selection.length-1];const dest={row:last?Math.min(last[0],last[2]):active.rowIndex,col:last?Math.min(last[1],last[3]):active.colIndex};const fill=last?{rows:Math.abs(last[2]-last[0])+1,cols:Math.abs(last[3]-last[1])+1}:void 0;const plan=planPaste(grid,dest,opts,origin,fill);if(!plan.length)return false;const beyond=entry=>entry.row>=rowCount||entry.col>=colCount;if(protectedNow()&&plan.some(entry=>locked(entry.row,entry.col))){refuse();return true}const laying=(opts.what==="all"||opts.what==="formats")&&merges.length>0?merges.map(m=>opts.transpose?[dest.row+m[1],dest.col+m[0],dest.row+m[3],dest.col+m[2]]:[dest.row+m[0],dest.col+m[1],dest.row+m[2],dest.col+m[3]]).filter(m=>m[2]<rowCount&&m[3]<colCount):[];const landingRect=plan.length?[Math.min(...plan.map(e=>e.row)),Math.min(...plan.map(e=>e.col)),Math.max(...plan.map(e=>e.row)),Math.max(...plan.map(e=>e.col))]:null;const replacing=laying.length&&landingRect?mergesNow().filter(m=>rectsIntersect(m,landingRect)):[];const landing=plan.filter(entry=>!covered(entry.row,entry.col)||replacing.some(m=>entry.row>=m[0]&&entry.row<=m[2]&&entry.col>=m[1]&&entry.col<=m[3]));const rects=[];for(const entry of landing)rects.push([entry.row,entry.col,entry.row,entry.col]);const moving=origin===null&&copied?.cut?copied:null;const before=moving?getState():null;pasting=true;try{cmd.batch(()=>{if(laying.length){const gone=new Set(replacing);if(moving)for(const m of moving.merges)gone.add(mergesNow().find(own=>own[0]===m[0]&&own[1]===m[1]&&own[2]===m[2]&&own[3]===m[3])??m);setMerges([...mergesNow().filter(m=>!gone.has(m)),...laying])}const sheet=wb.active;const bulk=landing.some(beyond);const direct=[];withFormatUndo(cmd,target,rects,()=>{for(const entry of landing){const at={row:entry.row,col:entry.col};const decision=resolvePasteCell(entry.source,wb.getValue(wb.active,entry.row,entry.col),opts,entry.offset,at,entry.turn);if(decision.kind==="skip")continue;const one=[[entry.row,entry.col,entry.row,entry.col]];if(decision.kind==="value"||decision.kind==="both"){if(bulk){const before2=wb.getRaw(sheet,entry.row,entry.col);const after=String(decision.value??"");if(before2!==after){wb.setRaw(sheet,entry.row,entry.col,after);direct.push({row:entry.row,col:entry.col,before:before2,after})}}else cmd.setCellValue(entry.row,entry.col,decision.value)}if(decision.kind==="format"||decision.kind==="both"){if(decision.format)target.store.set(one,decision.format,target.lookup);else target.store.clear(one,target.lookup)}}});if(direct.length){wb.recalculate();const put=which=>{for(const d of direct)wb.setRaw(sheet,d.row,d.col,d[which]);wb.recalculate();bump();changed({kind:"cells"})};cmd.recordUndo(()=>put("before"),()=>put("after"));changed({kind:"cells"})}})}finally{pasting=false}if(moving&&before)finishMove(cmd,moving,dest,landing,before);if(origin===null)marquee=null;bump();return true}function finishMove(cmd,block,dest,landing,before){const height2=block.cells.length;const width=block.cells.reduce((max,line)=>Math.max(max,line.length),0);if(height2===0||width===0)return;const move={sheet:block.sheet,toSheet:wb.active,top:block.origin.row,left:block.origin.col,bottom:block.origin.row+height2-1,right:block.origin.col+width-1,dRow:dest.row-block.origin.row,dCol:dest.col-block.origin.col};if(move.sheet===move.toSheet&&move.dRow===0&&move.dCol===0)return;const written=new Set(landing.map(at=>`${at.row}:${at.col}`));const sameSheet=move.sheet===move.toSheet;for(let r=move.top;r<=move.bottom;r+=1){for(let c=move.left;c<=move.right;c+=1){if(sameSheet&&written.has(`${r}:${c}`))continue;if(wb.getRaw(move.sheet,r,c)!=="")wb.setRaw(move.sheet,r,c,"")}}wb.repointAfterMove(move);if(!sameSheet&&block.merges.length){const source=doc.get(move.sheet);source.merges=source.merges.filter(m=>!block.merges.some(b=>b[0]===m[0]&&b[1]===m[1]&&b[2]===m[2]&&b[3]===m[3]))}const after=getState();cmd.recordUndo?.(()=>{doc.setState(before);registerSheetTargets();applyLive(wb.active);bump()},()=>{doc.setState(after);registerSheetTargets();applyLive(wb.active);bump()})}function cutSelection(cmd){const rects=selectedRects(cmd);if(protectedNow()&&rectsHaveLocked(storeFor(),lookup,rects,protectionNow().ranges)){refuse();return}cmd.copy();if(copied)copied.cut=true}async function readSystemClipboard(){if(typeof navigator==="undefined"||!navigator.clipboard)return null;try{let text="";let html=null;for(const item of await navigator.clipboard.read()){if(item.types.includes("text/html"))html=await(await item.getType("text/html")).text();if(item.types.includes("text/plain"))text=await(await item.getType("text/plain")).text()}return text||html?{text,html}:null}catch{try{const text=await navigator.clipboard.readText();return text?{text,html:null}:null}catch{return null}}}let pendingPaste=$state(null);async function openPasteSpecial(){pendingPaste=copied?null:await readSystemClipboard();pasteSpecialOpen=true}async function pasteSpecial(opts){const cmd=cmdOf();if(!cmd)return;const block=copied;if(block&&block.cells.length){if(pasteBlock(copiedGrid(block,"plain"),block.cut?null:block.origin,opts,blockMerges(block)))focusSheet(cmd);return}const payload=pendingPaste??await readSystemClipboard();pendingPaste=null;const grid=payload?parseClipboard({text:payload.text,html:payload.html??void 0}):null;if(!grid||!grid.length||grid.every(line=>line.every(c=>c.text===""&&!c.formula))){say(t("nothingToPaste"));return}const origin=payload?.html?readClipboardOrigin(payload.html):null;const placed=origin?{grid,origin}:anchorForeignFormulas(grid);if(pasteBlock(placed.grid,placed.origin,opts))focusSheet(cmd)}function focusSheet(cmd){void tick().then(()=>cmd.focus())}const activeActions=$derived.by(()=>{void version;void selection;const on=[];if(showFormulas)on.push("toggle-formulas");if(autoFilterNow())on.push("toggle-filter");if(painter)on.push("format-painter");if(isLocked(activeEntry))on.push("toggle-lock");if(showComments)on.push("toggle-comments");if(gridlinesOn)on.push("toggle-gridlines");if(formulaBarOn)on.push("toggle-formula-bar");if(headingsOn)on.push("toggle-headings");const ps=pageSetupNow();on.push(ps.orientation==="landscape"?"page-landscape":"page-portrait");on.push(`paper-${ps.paper.toLowerCase()}`);const preset=marginPresetOf(ps.margins);if(preset)on.push(`margins-${preset}`);if(ps.gridlines)on.push("print-gridlines");if(ps.headings)on.push("print-headings");if(sheetMergeAt(mergesNow(),active.rowIndex,active.colIndex))on.push("merge-center");return on});let painter=$state(null);function armPainter(){const target=getFormatTarget();if(!target)return;const last=selection[selection.length-1];const[r1,c1,r2,c2]=last??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];const entries=[];for(let r=r1;r<=r2;r+=1){const line=[];for(let c=c1;c<=c2;c+=1){const rowId=target.lookup.rowIdAt(r);const columnId=target.lookup.columnIdAt(c);line.push(rowId!=null&&columnId!=null?target.store.get(rowId,columnId):void 0)}entries.push(line)}painter={rows:r2-r1+1,cols:c2-c1+1,entries};say(t("formatPainterHint"))}function paintFormats(){const src=painter;const cmd=cmdOf();const target=getFormatTarget();painter=null;if(!src||!cmd||!target)return;const last=selection[selection.length-1];let[r1,c1,r2,c2]=last??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];if(r1===r2&&c1===c2){r2=Math.min(r1+src.rows-1,rowCount-1);c2=Math.min(c1+src.cols-1,colCount-1)}const rect=[r1,c1,r2,c2];withFormatUndo(cmd,target,[rect],()=>{target.store.clear([rect],target.lookup);for(let r=r1;r<=r2;r+=1){for(let c=c1;c<=c2;c+=1){const entry=src.entries[(r-r1)%src.rows]?.[(c-c1)%src.cols];if(entry)target.store.set([[r,c,r,c]],entry,target.lookup)}}});bump();fitWrappedRows();statusMessage=null}function onSheetPointerUp(event){pointDrag=null;const press=linkPress;linkPress=null;if(press&&event.button===0&&Math.abs(event.clientX-press.x)<=4&&Math.abs(event.clientY-press.y)<=4){void followLink(press.link)}if(!painter)return;const el=event.target;if(!el?.closest("td.sv-grid-cell"))return;setTimeout(paintFormats,0)}function onSheetKeyDownCapture(event){if(functionListKey(event))return;acceptSuggestion(event);if(selectedObject&&!editorOf(event.target)){if(event.key==="Delete"||event.key==="Backspace"){event.preventDefault();event.stopPropagation();if(protectedNow()){refuse();return}removeObject(selectedObject);return}if(event.key==="Escape")selectedObject=null}if((event.ctrlKey||event.metaKey)&&!event.altKey&&!event.shiftKey&&(event.key==="x"||event.key==="X")&&!editorOf(event.target)&&!painter){const cmd=cmdOf();if(cmd){event.preventDefault();event.stopPropagation();cutSelection(cmd);return}}if((event.ctrlKey||event.metaKey)&&!event.altKey&&!editorOf(event.target)){const key=event.key.toLowerCase();const direction=key==="z"?event.shiftKey?"redo":"undo":key==="y"&&!event.shiftKey?"redo":null;if(direction&&historyIsElsewhere(direction)){event.preventDefault();event.stopPropagation();void undoRedo(direction);return}}if(protectedNow()&&!editorOf(event.target)&&wouldEdit(event)&&locked(active.rowIndex,active.colIndex))refuse();if(event.key==="Backspace"&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!editorOf(event.target)&&!selectedObject&&!painter){const cmd=cmdOf();if(cmd&&!(protectedNow()&&locked(active.rowIndex,active.colIndex))){event.preventDefault();event.stopPropagation();cmd.startEditing(active.rowIndex,active.colIndex,"");return}}if(event.key==="Escape"&&marquee&&!editorOf(event.target))marquee=null;if(event.key==="Enter"&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.shiftKey&&marquee&&marquee.sheet===wb.active&&copied&&!editorOf(event.target)&&!painter){event.preventDefault();event.stopPropagation();const block=copied;pasteBlock(copiedGrid(block,"plain"),block.cut?null:block.origin,{what:"all"},blockMerges(block));marquee=null;return}if(!painter)return;if(event.key==="Escape"){painter=null;statusMessage=null;event.preventDefault();return}if(event.key==="Enter"&&!editorOf(event.target)){event.preventDefault();paintFormats()}}const PASS_THROUGH_FUNCTIONS=new Set(["SUM","AVERAGE","MIN","MAX","MEDIAN","ROUND","ROUNDUP","ROUNDDOWN","ABS","IF","IFERROR","IFNA","SUMIF","SUMIFS","AVERAGEIF","AVERAGEIFS","MINIFS","MAXIFS","SUMPRODUCT","PRODUCT","SUBTOTAL","INDEX","VLOOKUP","HLOOKUP","XLOOKUP","LOOKUP","CHOOSE","N","OFFSET","INDIRECT","LARGE","SMALL","MOD","INT","TRUNC","CEILING","FLOOR","MROUND"]);const DATE_FUNCTIONS=new Set(["TODAY","DATE","EOMONTH","EDATE","WORKDAY","DATEVALUE"]);const ISO_DATE_TEXT=/^\d{4}-\d{2}-\d{2}$/;function inheritedNumFmt(formula){const names=[...formula.matchAll(/([A-Za-z][A-Za-z0-9_.]*)\s*\(/g)].map(m=>m[1].toUpperCase());if(names.some(name=>!PASS_THROUGH_FUNCTIONS.has(name)&&!DATE_FUNCTIONS.has(name)))return void 0;if(names.some(name=>DATE_FUNCTIONS.has(name)))return"yyyy-mm-dd";const spans=referenceSpans(formula);const first=spans[0];if(!first)return void 0;const dateAt=span=>{const[r2,c2]=span.rect;const fmt2=storeFor().get(`r${r2}`,colToLetters(c2))?.numFmt;const category=fmt2?formatCategory(fmt2).category:void 0;return category==="date"||category==="time"||fmt2===void 0&&ISO_DATE_TEXT.test(wb.getRaw(wb.active,r2,c2).trim())};if(spans.length===2&&dateAt(first)&&dateAt(spans[1])&&/^=\s*\$?[A-Za-z]{1,3}\$?\d+\s*-\s*\$?[A-Za-z]{1,3}\$?\d+\s*$/.test(formula))return void 0;const[r,c]=first.rect;const fmt=storeFor().get(`r${r}`,colToLetters(c))?.numFmt;if(fmt)return fmt;return dateAt(first)?"yyyy-mm-dd":void 0}function onCellWritten(change){if(change.oldValue!==void 0&&change.oldValue===change.newValue)return;const ref=parseA1(`${change.columnId}1`);if(!ref)return;const text=balanceParens(fromCulture(change.newValue==null?"":String(change.newValue)));if(copied?.fresh&&text===""&&!copied.cut){const dr=change.rowIndex-copied.origin.row;const dc=ref.col-copied.origin.col;if(copied.cells[dr]?.[dc])copied.cut=true}else if(!pasting){marquee=null}formulaDraft=null;const r=change.rowIndex;const c=ref.col;let stored=text;const target=getFormatTarget();const cmd=cmdOf();const entry=storeFor().get(`r${r}`,colToLetters(c));const patch={};const parsed=parseEntry(text,culture);if(parsed){stored=parsed.value;if(parsed.numFmt&&(!entry?.numFmt||formatCategory(entry.numFmt).category!==formatCategory(parsed.numFmt).category))patch.numFmt=parsed.numFmt}if(!entry?.numFmt&&text.startsWith("=")){const inherited=inheritedNumFmt(text);if(inherited)patch.numFmt=inherited}if(!parsed&&!text.startsWith("=")&&entry?.numFmt&&formatCategory(entry.numFmt).category==="percent"){const plain=text.trim();if(PLAIN_NUMBER.test(plain))stored=String(Number(plain)/100)}if(text.includes("\n")&&!entry?.wrap)patch.wrap=true;if(Object.keys(patch).length&&target&&cmd){withFormatUndo(cmd,target,[[r,c,r,c]],()=>target.store.set([[r,c,r,c]],patch,target.lookup))}if(wb.getRaw(wb.active,r,c)===stored){if(patch.wrap){bump();fitWrappedRows()}return}wb.setRaw(wb.active,r,c,stored);if(stored!==""&&wb.tables.growToInclude(wb.active,r,c)){fillTableFormulas(r,c);wb.recalculate();changed({kind:"tables"})}bump();changed({kind:"cells"});refilterPivot(r,c,stored);if(patch.wrap||entry?.wrap)fitWrappedRows()}function refilterPivot(row,col,text){if(writingPivot)return;const pivot=pivotsNow().find(p=>{const filters=p.filters??[];if(!filters.length||col!==p.target.col+1)return false;return row>=p.target.row&&row<p.target.row+filters.length});if(!pivot)return;const index=row-pivot.target.row;const filter=(pivot.filters??[])[index];if(!filter)return;const wanted=text.trim()===ALL_VALUES?"":text.trim();if(wanted===filter.value)return;const next={...copyPivot(pivot),filters:(pivot.filters??[]).map((f,i)=>i===index?{...f,value:wanted}:{...f})};writePivot(next,true)}const autoFitRows=new Map;const autoFitOn=sheet=>{let set=autoFitRows.get(sheet);if(!set){set=new Set;autoFitRows.set(sheet,set)}return set};function fitWrappedRows(){void tick().then(()=>{if(!api||!root)return;const auto=autoFitOn(wb.active);const tallest=new Map;for(const span of root.querySelectorAll(".sheet-cell.wrap")){const td=span.closest("td");const r=Number(td?.dataset.svgridRow);if(!Number.isInteger(r))continue;const needed=span.scrollHeight+2;if(needed>(tallest.get(r)??0))tallest.set(r,needed)}for(const[r,needed]of tallest){const current=api.getRowHeight(r);if(needed>current){api.setRowHeight(r,needed);auto.add(r)}}for(const r of[...auto]){if(tallest.has(r)&&tallest.get(r)>=api.getRowHeight(r))continue;if(!root.querySelector(`td[data-svgrid-row="${r}"]`))continue;const needed=tallest.get(r);if(needed!==void 0&&needed>rowHeight)api.setRowHeight(r,needed);else{api.setRowHeight(r,null);auto.delete(r)}}})}let copied=$state(null);let marquee=$state(null);const activeSpill=$derived.by(()=>{void version;return wb.spillOf(wb.active,active.rowIndex,active.colIndex)?.rect??null});function spillEdges(r,c){const rect=activeSpill;if(!rect)return null;const[r1,c1,r2,c2]=rect;if(r<r1||r>r2||c<c1||c>c2)return null;const edges=[];if(r===r1)edges.push("top");if(r===r2)edges.push("bottom");if(c===c1)edges.push("left");if(c===c2)edges.push("right");return edges.length?edges.join(" "):null}function marqueeEdges(r,c){void version;const m=marquee;if(!m||m.sheet!==wb.active)return null;const[r1,c1,r2,c2]=m.rect;if(r<r1||r>r2||c<c1||c>c2)return null;const edges=[];if(r===r1)edges.push("top");if(r===r2)edges.push("bottom");if(c===c1)edges.push("left");if(c===c2)edges.push("right");return edges.length?edges.join(" "):null}let pasting=false;function toClipboard(params){const col=lettersToCol(params.columnId);const r=params.rowIndex;if(col<0)return"";const shown=display(r,col).text;const rects=selection.length?selection:[[r,col,r,col]];const first=rects[0];const whole=first[0]===first[2]&&first[1]===first[3]?sheetMergeAt(mergesNow(),r,col):null;const[minRow,minCol,maxRow,maxCol]=whole&&whole[0]===r&&whole[1]===col?whole:first;if(r===minRow&&col===minCol){copied={origin:{row:r,col},sheet:wb.active,cells:[],rowAt:new Map,colAt:new Map,fresh:true,cut:false,merges:mergesNow().filter(m=>m[0]>=minRow&&m[2]<=maxRow&&m[1]>=minCol&&m[3]<=maxCol).map(m=>[...m])};queueMicrotask(()=>{if(copied)copied.fresh=false});marquee={sheet:wb.active,rect:[minRow,minCol,Math.min(maxRow,rowCount-1),Math.min(maxCol,colCount-1)]};if(whole&&whole[0]===r&&whole[1]===col){for(let rr=minRow;rr<=maxRow;rr+=1){copied.rowAt.set(rr,rr-minRow);copied.cells[rr-minRow]=[];for(let cc=minCol;cc<=maxCol;cc+=1){copied.colAt.set(cc,cc-minCol);if(rr!==r||cc!==col)copied.cells[rr-minRow][cc-minCol]={shown:"",raw:"",value:"",format:storeFor().get(`r${rr}`,colToLetters(cc))}}}}}if(copied&&!copied.cut){let dr=copied.rowAt.get(r);if(dr===void 0){dr=copied.rowAt.size;copied.rowAt.set(r,dr)}let dc=copied.colAt.get(col);if(dc===void 0){dc=copied.colAt.size;copied.colAt.set(col,dc)}if(!copied.cells[dr])copied.cells[dr]=[];const line=copied.cells[dr];line[dc]={shown,raw:raw(r,col),value:plainValue(r,col),format:storeFor().get(`r${r}`,params.columnId)}}return shown}function plainValue(r,c){const value=wb.getValue(wb.active,r,c);if(isError(value))return value.error;if(value===""||value==null)return"";return String(value)}const EMPTY_COPIED={shown:"",raw:"",value:"",format:void 0};function blockMerges(block){const out=[];for(const[r1,c1,r2,c2]of block.merges){const dr1=block.rowAt.get(r1),dc1=block.colAt.get(c1),dr2=block.rowAt.get(r2),dc2=block.colAt.get(c2);if(dr1===void 0||dc1===void 0||dr2===void 0||dc2===void 0)continue;out.push([dr1,dc1,dr2,dc2])}return out}function copiedGrid(block,text){const width=block.cells.reduce((max,line)=>Math.max(max,line.length),0);return block.cells.map(line=>Array.from({length:width},(_,i)=>{const cell=line[i]??EMPTY_COPIED;const formula=cell.raw.startsWith("=");const numeric=cell.value!==""&&Number.isFinite(Number(cell.value));return{text:text==="shown"?cell.shown:formula?cell.value:cell.raw,...text==="shown"&&numeric?{value:cell.value}:{},...formula?{formula:cell.raw}:{},...cell.format?{format:cell.format}:{}}}))}function copiedText(block){return copiedGrid(block,"shown").map(line=>line.map(cell=>cell.text).join(" ")).join("\n")}function copiedHtml(){const block=copied;if(!block||!block.cells.length)return null;return buildClipboardPayload(copiedGrid(block,"shown"),block.origin).html}function pasteFromSystem(payload){const block=copied;const text=payload.text.replace(/\r\n/g,"\n").replace(/\n$/,"");if(block&&block.cells.length&&copiedText(block)===text){return pasteBlock(copiedGrid(block,"plain"),block.cut?null:block.origin,{what:"all"},blockMerges(block))}const grid=payload.html?parseClipboardHtml(payload.html):null;if(!grid){const lines=parseClipboardText(text);const width=lines.reduce((max,line)=>Math.max(max,line.length),0);const past=lines.length+active.rowIndex>rowCount||width+active.colIndex>colCount;return past?pasteBlock(lines,null,{what:"all"}):void 0}const origin=readClipboardOrigin(payload.html);if(origin)return pasteBlock(grid,origin,{what:"all"});const foreign=anchorForeignFormulas(grid);return pasteBlock(foreign.grid,foreign.origin,{what:"all"})}function withCmd(fn){const c=cmdOf();if(!c)return;fn(c);queueMicrotask(()=>c.focus())}const hasComment=()=>commentAt(notesNow(),active.rowIndex,active.colIndex)!==void 0;const hasLink=()=>linkOf(active.rowIndex,active.colIndex)!==void 0;const axis=()=>{const c=cmdOf();if(!c||!c.ranges.length)return"ambiguous";return axisForSelection(c)};const glyph=name=>({paths:RIBBON_ICONS[name]});const contextMenu=$derived.by(()=>[{key:"cut",icon:glyph("cut"),action:()=>withCmd(c=>cutSelection(c))},{key:"copy",icon:glyph("copy")},{key:"paste",icon:glyph("paste")},{key:"paste-special",label:t("menuPasteSpecial"),icon:glyph("paste-special"),action:()=>withCmd(c=>delegate("paste-special",c))},"separator",{key:"insert-rows",label:t("menuInsertRows"),icon:glyph("insert-cells"),hidden:()=>axis()==="cols",action:()=>withCmd(c=>insertRows(c))},{key:"insert-columns",label:t("menuInsertColumns"),icon:glyph("insert-cells"),hidden:()=>axis()==="rows",action:()=>withCmd(c=>insertColumns(c))},{key:"delete-rows",label:t("menuDeleteRows"),icon:glyph("delete-cells"),hidden:()=>axis()==="cols",action:()=>withCmd(c=>deleteRows(c))},{key:"delete-columns",label:t("menuDeleteColumns"),icon:glyph("delete-cells"),hidden:()=>axis()==="rows",action:()=>withCmd(c=>deleteColumns(c))},"separator",{key:"clear-contents",label:t("menuClearContents"),icon:glyph("clear"),action:()=>withCmd(c=>{const rects=c.ranges.length?c.ranges:c.activeCell?[[c.activeCell.rowIndex,c.activeCell.colIndex,c.activeCell.rowIndex,c.activeCell.colIndex]]:[];if(protectedNow()&&rectsHaveLocked(storeFor(),lookup,rects,protectionNow().ranges)){refuse();return}c.batch(()=>{for(const[r1,c1,r2,c2]of rects){for(let r=r1;r<=r2;r+=1){for(let col=c1;col<=c2;col+=1){if(lineHidden(r,col))continue;c.setCellValue(r,col,"")}}}})})},{key:"clear-formats",label:t("menuClearFormats"),icon:glyph("clear-formats"),action:()=>withCmd(c=>clearFormats(c))},"separator",{key:"merge-center",label:t("menuMergeCenter"),icon:glyph("merge"),hidden:()=>axis()!=="ambiguous"||selectionHasMerge(),action:()=>withCmd(c=>handleAction("merge-center",c))},{key:"unmerge-cells",label:t("menuUnmergeCells"),icon:glyph("unmerge"),hidden:()=>axis()!=="ambiguous"||!selectionHasMerge(),action:()=>withCmd(c=>handleAction("unmerge-cells",c))},"separator",{key:"new-comment",label:t("menuNewComment"),icon:glyph("comment"),hidden:()=>axis()!=="ambiguous"||hasComment(),action:()=>withCmd(c=>handleAction("new-comment",c))},{key:"edit-comment",label:t("menuEditComment"),icon:glyph("comment"),hidden:()=>axis()!=="ambiguous"||!hasComment(),action:()=>withCmd(c=>handleAction("edit-comment",c))},{key:"delete-comment",label:t("menuDeleteComment"),icon:glyph("comment-delete"),hidden:()=>axis()!=="ambiguous"||!hasComment(),action:()=>withCmd(c=>handleAction("delete-comment",c))},"separator",{key:"insert-link",label:t("menuLink"),icon:glyph("link"),hidden:()=>axis()!=="ambiguous"||hasLink(),action:()=>withCmd(c=>handleAction("insert-link",c))},{key:"edit-link",label:t("menuEditLink"),icon:glyph("link"),hidden:()=>axis()!=="ambiguous"||!hasLink(),action:()=>withCmd(c=>handleAction("insert-link",c))},{key:"open-link",label:t("menuOpenLink"),icon:glyph("link"),hidden:()=>axis()!=="ambiguous"||!hasLink(),action:()=>{const link=linkOf(active.rowIndex,active.colIndex);if(link)void followLink(link)}},{key:"remove-link",label:t("menuRemoveLink"),icon:glyph("unlink"),hidden:()=>axis()!=="ambiguous"||!hasLink(),action:()=>withCmd(c=>handleAction("remove-link",c))},"separator",{key:"format-cells",label:t("menuFormatCells"),icon:glyph("format-cells"),action:()=>withCmd(c=>delegate("format-cells",c))},{key:"column-width",label:t("menuColumnWidth"),icon:glyph("column-width"),hidden:()=>axis()!=="cols",action:()=>openSizeDialog("cols")},{key:"row-height",label:t("menuRowHeight"),icon:glyph("row-height"),hidden:()=>axis()!=="rows",action:()=>openSizeDialog("rows")},{key:"hide-columns",label:t("menuHide"),icon:glyph("hide"),hidden:()=>axis()!=="cols",action:()=>withCmd(c=>handleAction("hide-columns",c))},{key:"unhide-columns",label:t("menuUnhide"),icon:glyph("unhide"),hidden:()=>axis()!=="cols",action:()=>withCmd(c=>handleAction("unhide-columns",c))},{key:"hide-rows",label:t("menuHide"),icon:glyph("hide"),hidden:()=>axis()!=="rows",action:()=>withCmd(c=>handleAction("hide-rows",c))},{key:"unhide-rows",label:t("menuUnhide"),icon:glyph("unhide"),hidden:()=>axis()!=="rows",action:()=>withCmd(c=>handleAction("unhide-rows",c))}]);let sizeDialog=$state(null);const sizeDialogOpen=$derived(sizeDialog!==null);function sizeTargets(){return lineTargets(sizeDialog==="cols"?"cols":"rows")}function lineTargets(axis2){const last=selection[selection.length-1];if(!last)return[axis2==="cols"?active.colIndex:active.rowIndex];const[r1,c1,r2,c2]=last;const from=axis2==="cols"?c1:r1;const to=Math.min(axis2==="cols"?c2:r2,(axis2==="cols"?colCount:rowCount)-1);return Array.from({length:to-from+1},(_,i)=>from+i)}function autofitLines(axis2,cmd){if(!api)return;if(!allowNow(lineKey(axis2))){refuse();return}const targets=lineTargets(axis2);if(axis2==="cols"){const widths=()=>targets.map(c=>[c,api.getColumnWidths()[colToLetters(c)]??columnWidth]);const before=widths();for(const c of targets)api.autosizeColumn(colToLetters(c));const after=widths();const put=list=>{for(const[c,w]of list)api.setColumnWidth(colToLetters(c),w);stashWidths();changed({kind:"sizes"})};cmd.recordUndo(()=>put(before),()=>put(after))}else{const before=targets.map(r=>[r,api.getRowHeight(r)]);const fit=()=>{for(const r of targets)api.setRowHeight(r,null);fitWrappedRows();changed({kind:"sizes"})};fit();cmd.recordUndo(()=>{for(const[r,h]of before)api.setRowHeight(r,h===rowHeight?null:h);stashHeights();changed({kind:"sizes"})},fit)}stashLive();bump()}const sizeCurrent=$derived.by(()=>{void version;void selection;void active;if(!api||!sizeDialog)return 0;const first=sizeTargets()[0]??0;return sizeDialog==="cols"?api.getColumnWidths()[colToLetters(first)]??columnWidths?.[colToLetters(first)]??columnWidth:api.getRowHeight(first)});function openSizeDialog(kind){if(!allowNow(lineKey(kind))){refuse();return}sizeDialog=kind}function applySize(px){if(!api)return;if(!allowNow(lineKey(sizeDialog??"rows"))){refuse();return}const kind=sizeDialog;const targets=sizeTargets();const read=()=>targets.map(i=>[i,kind==="cols"?api.getColumnWidths()[colToLetters(i)]??columnWidth:api.getRowHeight(i)]);const put=list=>{for(const[i,size]of list){if(kind==="cols")api.setColumnWidth(colToLetters(i),size);else api.setRowHeight(i,size===rowHeight?null:size)}stashLive();bump();changed({kind:"sizes"})};const before=read();put(targets.map(i=>[i,px]));if(kind==="rows")for(const r of targets)autoFitOn(wb.active).delete(r);const after=read();const c=cmdOf();c?.recordUndo(()=>put(before),()=>put(after));if(c)focusSheet(c)}function onSheetContextMenu(event){const el=event.target;const th=el.closest("th[data-svgrid-header-col]");const gutter=el.closest("td.sv-grid-row-number-cell");if(th||gutter){event.preventDefault();if(!api)return;const rects2=selection;if(th){const col=lettersToCol(th.dataset.svgridHeaderCol??"");if(col<0)return;const inside3=rects2.some(([,c1,r2,c2])=>c1<=col&&col<=c2&&r2>=rowCount-1);if(!inside3)selectColumns(col,col,{active:"place"});api.openContextMenu(event,0,col);return}const row=rowOfGutter(gutter);if(row===null)return;const inside2=rects2.some(([r1,,r2,c2])=>r1<=row&&row<=r2&&c2>=colCount-1);if(!inside2)selectRows(row,row,{active:"place"});api.openContextMenu(event,row,0);return}const td=el.closest("td[data-svgrid-row][data-svgrid-col]");if(!td)return;const r=Number(td.dataset.svgridRow);const c=Number(td.dataset.svgridCol);const rects=selection.length?selection:[[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex]];const inside=rects.some(([r1,c1,r2,c2])=>r>=r1&&r<=r2&&c>=c1&&c<=c2);if(inside)return;const cmd=cmdOf();if(!cmd)return;cmd.setActiveCell(r,c);cmd.setSelection(r,c)}let headerDrag=null;function rowOfGutter(gutter){const rowAttr=gutter.parentElement?.querySelector("td[data-svgrid-row]")?.dataset.svgridRow;const row=rowAttr===void 0?Number(gutter.textContent)-1:Number(rowAttr);return Number.isInteger(row)&&row>=0?row:null}function headerHit(el,dragging2=null){if(!el)return null;if(el.closest(".sv-grid-resize-handle, .sv-grid-row-resize-handle"))return null;if(el.closest("th.sv-grid-row-number-column"))return{axis:"all"};const th=el.closest("th[data-svgrid-header-col]");if(th){const col=lettersToCol(th.dataset.svgridHeaderCol??"");return col<0?null:{axis:"col",index:col}}const gutter=el.closest("td.sv-grid-row-number-cell");if(gutter){const row=rowOfGutter(gutter);return row===null?null:{axis:"row",index:row}}if(dragging2){const td=el.closest("td[data-svgrid-row][data-svgrid-col]");if(td)return{axis:dragging2,index:Number(dragging2==="col"?td.dataset.svgridCol:td.dataset.svgridRow)}}return null}function firstVisible(axis2){const host=gridHost?.querySelector(".sv-grid-container");if(!host)return 0;const box=host.getBoundingClientRect();const headH=host.querySelector("thead")?.getBoundingClientRect().height??0;const gutterW=host.querySelector("td.sv-grid-row-number-cell")?.getBoundingClientRect().width??0;let best=null;for(const td of host.querySelectorAll("td[data-svgrid-row][data-svgrid-col]")){if(td.closest("tr")?.classList.contains("sv-grid-row-collapsed"))continue;const r=td.getBoundingClientRect();if(r.width===0||r.height===0)continue;const index=Number(axis2==="row"?td.dataset.svgridRow:td.dataset.svgridCol);const edge=axis2==="row"?r.top-(box.top+headH):r.left-(box.left+gutterW);if(edge<-1)continue;if(best===null||index<best)best=index}return best??0}function selectColumns(a,b,how){const cmd=cmdOf();if(!api||!cmd)return;const was=cmd.activeCell;api.selectCells([...how.keep??[],[0,Math.min(a,b),Number.POSITIVE_INFINITY,Math.max(a,b)]]);if(how.active==="place")cmd.setActiveCell(firstVisible("row"),a);else if(was)cmd.setActiveCell(was.rowIndex,was.colIndex)}function selectRows(a,b,how){const cmd=cmdOf();if(!api||!cmd)return;const was=cmd.activeCell;api.selectCells([...how.keep??[],[Math.min(a,b),0,Math.max(a,b),Number.POSITIVE_INFINITY]]);if(how.active==="place")cmd.setActiveCell(a,firstVisible("col"));else if(was)cmd.setActiveCell(was.rowIndex,was.colIndex)}function selectLine(hit,from,how){if(hit.axis==="col")selectColumns(from,hit.index,how);else selectRows(from,hit.index,how)}let resizeTip=$state(null);let resizeGuide=$state(null);let resizing=null;let cellDrag=$state(false);let fillDrag=null;const dragLabel=$derived.by(()=>{if(!cellDrag)return null;const rect=selection[selection.length-1];if(!rect)return null;const rows=Math.abs(rect[2]-rect[0])+1;const cols=Math.abs(rect[3]-rect[1])+1;return rows*cols>1?`${rows}R x ${cols}C`:null});function fillTipText(under){const src=fillDrag?.rect;if(!src)return null;const[r1,c1,r2,c2]=src;const{r,c}=under;const inside=r>=r1&&r<=r2&&c>=c1&&c<=c2;if(inside)return null;const vertical=r<r1||r>r2;if(vertical){if(c<c1||c>c2)return null;const down=r>r2;const sources2=Array.from({length:r2-r1+1},(_,i)=>raw(down?r1+i:r2-i,c));const count2=down?r-r2:r1-r;return fillTipValue(buildFillPattern(sources2,count2)[count2-1],down?r2:r1,c)}if(r<r1||r>r2)return null;const right=c>c2;const sources=Array.from({length:c2-c1+1},(_,i)=>raw(r,right?c1+i:c2-i));const count=right?c-c2:c1-c;return fillTipValue(buildFillPattern(sources,count)[count-1],r,right?c2:c1)}function fillTipValue(value,sr,sc){if(value===void 0||value===null||value==="")return null;const n=typeof value==="number"?value:Number(value);if(typeof value!=="boolean"&&Number.isFinite(n)&&String(value).trim()!==""){const fmt=storeFor().get(`r${sr}`,colToLetters(sc))?.numFmt;return fmt?compileNumberFormat(fmt,marks).format(n).text:String(Number(n.toPrecision(10)))}return String(value)}function placeFillTip(event){const host=gridHost;if(!host||!fillDrag)return;const td=document.elementFromPoint(event.clientX,event.clientY)?.closest("td[data-svgrid-row][data-svgrid-col]");const text=td?fillTipText({r:Number(td.dataset.svgridRow),c:Number(td.dataset.svgridCol)}):null;if(text===null||text===""){resizeTip=null;return}const box=host.getBoundingClientRect();resizeTip={x:event.clientX-box.left+14,y:event.clientY-box.top+18,text}}function resizeTipText(px){if(!resizing)return"";return resizing.axis==="col"?`Width: ${Math.max(0,(px-5)/7).toFixed(2)} (${px} pixels)`:`Height: ${(px*.75).toFixed(2)} (${px} pixels)`}function placeResizeTip(event){const host=gridHost;const drag=resizing;if(!host||!drag)return;const box=host.getBoundingClientRect();const travel=drag.axis==="col"?event.clientX-drag.startX:event.clientY-drag.startY;const px=Math.round(Math.max(drag.min,drag.startSize+travel));const x=Math.min(event.clientX-box.left+14,box.width-160);resizeTip={x:Math.max(0,x),y:event.clientY-box.top-30,text:resizeTipText(px)};resizeGuide={axis:drag.axis,at:drag.startEdge+(px-drag.startSize)}}function startResizeTip(handle,event){const host=gridHost;if(!host)return;const box=host.getBoundingClientRect();if(handle.classList.contains("sv-grid-row-resize-handle")){const tr=handle.closest("tr");const td=tr?.querySelector("td[data-svgrid-row]");const row=td?.dataset.svgridRow;if(!tr||!td||row===void 0)return;const r=td.getBoundingClientRect();resizing={axis:"row",key:row,startX:event.clientX,startY:event.clientY,startSize:Math.round(r.height),startEdge:r.bottom-box.top,min:20}}else{const th=handle.closest("[data-svgrid-header-col]");const col=th?.dataset.svgridHeaderCol;if(!th||!col)return;const r=th.getBoundingClientRect();resizing={axis:"col",key:col,startX:event.clientX,startY:event.clientY,startSize:Math.round(r.width),startEdge:r.right-box.left,min:40}}placeResizeTip(event)}function endResizeTip(){resizing=null;resizeTip=null;resizeGuide=null}let pointed=null;let pointDrag=null;let pointedPress=false;function formulaEditor(){const el=document.activeElement;if(!(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement))return null;if(!el.classList.contains("sv-grid-cell-editor")&&!(el.classList.contains("formula")&&el.closest(".sv-formula-bar")))return null;return el.value.startsWith("=")?el:null}function wantsReference(editor){const caret=editor.selectionStart??editor.value.length;if(pointed&&pointed.editor===editor&&pointed.end===caret)return true;if(editor.selectionEnd!==caret)return false;const before=editor.value.slice(0,caret).replace(/\s+$/,"");return/[=(,;+\-*/^&<>:]$/.test(before)}function insertPointedReference(editor,r1,c1,r2,c2){const top=Math.min(r1,r2),left=Math.min(c1,c2),bottom=Math.max(r1,r2),right=Math.max(c1,c2);const one=`${colToLetters(left)}${top+1}`;const text=top===bottom&&left===right?one:`${one}:${colToLetters(right)}${bottom+1}`;const caret=editor.selectionStart??editor.value.length;const replacing=pointed&&pointed.editor===editor&&pointed.end===caret;const start=replacing?pointed.start:caret;const end=replacing?pointed.end:caret;editor.value=editor.value.slice(0,start)+text+editor.value.slice(end);const after=start+text.length;editor.setSelectionRange(after,after);pointed={editor,start,end:after};editor.dispatchEvent(new Event("input",{bubbles:true}))}function pointAt(event,target){const editor=formulaEditor();if(!editor||editorOf(target))return false;const td=target?.closest("td[data-svgrid-row][data-svgrid-col]");if(!td||td.contains(editor)||!wantsReference(editor))return false;event.stopPropagation();const row=Number(td.dataset.svgridRow);const col=Number(td.dataset.svgridCol);insertPointedReference(editor,row,col,row,col);pointDrag={editor,row,col};pointedPress=true;return true}function onSheetMouseDown(event){if(!pointDrag)return;event.preventDefault();event.stopPropagation()}function onSheetClickCapture(event){if(!pointedPress)return;pointedPress=false;event.preventDefault();event.stopPropagation()}function pointDragTo(event){const drag=pointDrag;if(!drag||document.activeElement!==drag.editor)return;const td=document.elementFromPoint(event.clientX,event.clientY)?.closest("td[data-svgrid-row][data-svgrid-col]");if(!td)return;const row=Number(td.dataset.svgridRow);const col=Number(td.dataset.svgridCol);if(pointed&&pointed.editor===drag.editor)drag.editor.setSelectionRange(pointed.end,pointed.end);insertPointedReference(drag.editor,drag.row,drag.col,row,col)}let linkPress=null;function onSheetPointerDown(event){if(event.button!==0)return;const target=event.target;if(selectedObject&&!target?.closest(".sheet-object"))selectedObject=null;if(pointAt(event,target))return;const handle=target?.closest(".sv-grid-resize-handle, .sv-grid-row-resize-handle");if(handle){startResizeTip(handle,event);return}if(target?.closest(".sv-grid-fill-handle")){const rect=selection[selection.length-1]??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];fillDrag={rect:[Math.min(rect[0],rect[2]),Math.min(rect[1],rect[3]),Math.max(rect[0],rect[2]),Math.max(rect[1],rect[3])]};return}const hit=headerHit(target);if(!hit){const td=target?.closest("td[data-svgrid-row][data-svgrid-col]");if(td){cellDrag=true;const row=Number(td.dataset.svgridRow);const col=Number(td.dataset.svgridCol);const link=linkOf(row,col);linkPress=link&&editingText===null?{link,x:event.clientX,y:event.clientY}:null}return}const cmd=cmdOf();if(!api||!cmd)return;event.preventDefault();event.stopPropagation();if(hit.axis==="all"){const was=cmd.activeCell;api.selectCells([[0,0,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]]);if(was)cmd.setActiveCell(was.rowIndex,was.colIndex);headerDrag=null}else if(event.shiftKey){const anchor=cmd.activeCell;const from=anchor?hit.axis==="col"?anchor.colIndex:anchor.rowIndex:hit.index;selectLine(hit,from,{active:"keep"});headerDrag=null}else{const keep=event.ctrlKey||event.metaKey?cmd.ranges:[];selectLine(hit,hit.index,{active:"place",keep});headerDrag={axis:hit.axis,from:hit.index,keep}}cmd.focus()}function onSheetPointerMove(event){if(pointDrag){pointDragTo(event);return}if(fillDrag){placeFillTip(event);return}if(resizing){placeResizeTip(event);return}const drag=headerDrag;if(!drag)return;const hit=headerHit(document.elementFromPoint(event.clientX,event.clientY),drag.axis);if(!hit||hit.axis!==drag.axis)return;const cmd=cmdOf();if(!cmd)return;const was=cmd.activeCell;if(drag.axis==="col")api?.selectCells([...drag.keep,[0,Math.min(drag.from,hit.index),Number.POSITIVE_INFINITY,Math.max(drag.from,hit.index)]]);else api?.selectCells([...drag.keep,[Math.min(drag.from,hit.index),0,Math.max(drag.from,hit.index),Number.POSITIVE_INFINITY]]);if(was)cmd.setActiveCell(was.rowIndex,was.colIndex)}function endHeaderDrag(){headerDrag=null;cellDrag=false;fillDrag=null;endResizeTip()}$effect(()=>{window.addEventListener("pointerup",endHeaderDrag);window.addEventListener("pointercancel",endHeaderDrag);window.addEventListener("pointermove",onSheetPointerMove);return()=>{window.removeEventListener("pointerup",endHeaderDrag);window.removeEventListener("pointercancel",endHeaderDrag);window.removeEventListener("pointermove",onSheetPointerMove)}});function wouldEdit(event){if(event.ctrlKey||event.metaKey||event.altKey)return false;const el=event.target;if(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement||el instanceof HTMLSelectElement)return false;if(event.key==="F2"||event.key==="Delete"||event.key==="Backspace")return true;return event.key.length===1}function editorOf(target){const el=target;return(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement)&&el.classList.contains("sv-grid-cell-editor")?el:null}let measure=null;function growEditor(input){const td=input.closest("td");if(!td)return;measure??=document.createElement("canvas").getContext("2d");if(!measure)return;measure.font=getComputedStyle(input).font;const lines=input.value.split("\n");const widest=Math.max(...lines.map(line=>measure.measureText(line).width));const needed=Math.ceil(widest)+18;input.style.width=needed>td.clientWidth?`${needed}px`:"";if(input instanceof HTMLTextAreaElement){const lineHeight=parseFloat(getComputedStyle(input).lineHeight)||17;const tall=Math.ceil(lines.length*lineHeight)+4;input.style.height=tall>td.clientHeight?`${tall}px`:""}}let editingText=$state(null);let barDraft=$state(null);function onEditorFocusIn(event){const input=editorOf(event.target);if(!input)return;editingText=input.value;queueMicrotask(()=>{const end=input.value.length;try{input.setSelectionRange(end,end)}catch{}});growEditor(input);if(input.value.startsWith("="))formulaDraft=input.value}function onEditorInput(event){const input=editorOf(event.target);if(!input)return;if(event instanceof InputEvent&&event.inputType==="insertText")autoComplete(input);growEditor(input);editingText=input.value;formulaDraft=input.value.startsWith("=")?input.value:null;offerFunctions(input)}let suggested=null;function autoComplete(input){suggested=null;const typed=input.value;if(input.selectionStart!==typed.length||input.selectionEnd!==typed.length)return;const{rowIndex,colIndex}=active;const entry=completeEntry(typed,columnRunEntries(rowIndex,colIndex));if(entry===null||entry===typed)return;suggested=entry;input.value=typed+entry.slice(typed.length);input.setSelectionRange(typed.length,entry.length);input.dispatchEvent(new Event("input",{bubbles:true}))}function acceptSuggestion(event){if(suggested===null||event.key!=="Enter"&&event.key!=="Tab"||event.altKey)return;const input=editorOf(event.target);if(!input)return;const entry=suggested;suggested=null;const tail=input.selectionStart??input.value.length;if(input.selectionEnd!==input.value.length||tail>=input.value.length)return;if(input.value.toLowerCase()!==entry.toLowerCase())return;input.value=entry;input.dispatchEvent(new Event("input",{bubbles:true}))}function columnRunEntries(rowIndex,colIndex){const out=new Set;const textAt=r=>{const raw2=wb.getRaw(wb.active,r,colIndex);if(raw2==="")return null;if(raw2.startsWith("="))return"";return typeof wb.getValue(wb.active,r,colIndex)==="string"?raw2:""};for(let r=rowIndex-1;r>=0;r-=1){const t2=textAt(r);if(t2===null)break;if(t2)out.add(t2)}for(let r=rowIndex+1;r<rowCount;r+=1){const t2=textAt(r);if(t2===null)break;if(t2)out.add(t2)}return out}function onEditorFocusOut(event){if(!editorOf(event.target))return;pointed=null;fnSuggest=null;formulaDraft=null;editingText=null}let fnSuggest=$state(null);function offerFunctions(input){const host=gridHost;const td=input.closest("td");if(!host||!td||!input.value.startsWith("=")){fnSuggest=null;return}const items=suggestFunctions(input.value,input.selectionStart??input.value.length);if(!items.length){fnSuggest=null;return}const a=td.getBoundingClientRect();const b=host.getBoundingClientRect();fnSuggest={items,index:0,left:a.left-b.left,top:a.bottom-b.top}}function takeFunction(input,suggestion){const next=applySuggestion(input.value,suggestion);input.value=next.text;input.setSelectionRange(next.caret,next.caret);fnSuggest=null;input.dispatchEvent(new Event("input",{bubbles:true}))}function functionListKey(event){const list=fnSuggest;const input=editorOf(event.target);if(!list||!input)return false;if(event.key==="ArrowDown"||event.key==="ArrowUp"){const step=event.key==="ArrowDown"?1:-1;fnSuggest={...list,index:(list.index+step+list.items.length)%list.items.length}}else if(event.key==="Tab"||event.key==="Enter"){takeFunction(input,list.items[list.index])}else if(event.key==="Escape"){fnSuggest=null}else{return false}event.preventDefault();event.stopPropagation();return true}let formulaDraft=$state(null);function referencesIn(text){const seen=new Set;return referenceSpans(text).filter(span=>!seen.has(span.key)&&(seen.add(span.key),true))}let painted=[];function paintReferences(){for(const el of painted){delete el.dataset.sheetRef;el.style.removeProperty("--sheet-ref");el.style.removeProperty("--sheet-ref-edges")}painted=[];const host=root;if(!host||formulaDraft===null){clearEditorMirror();return}for(const{rect,colour}of referencesIn(formulaDraft)){const[r1,c1,r2,c2]=rect;for(const td of host.querySelectorAll("td[data-svgrid-row][data-col-id]")){const r=Number(td.dataset.svgridRow);const c=lettersToCol(td.dataset.colId??"");if(r<r1||r>r2||c<c1||c>c2)continue;const edges=[];if(r===r1)edges.push("inset 0 1.5px 0 var(--sheet-ref)");if(r===r2)edges.push("inset 0 -1.5px 0 var(--sheet-ref)");if(c===c1)edges.push("inset 1.5px 0 0 var(--sheet-ref)");if(c===c2)edges.push("inset -1.5px 0 0 var(--sheet-ref)");td.dataset.sheetRef="";td.style.setProperty("--sheet-ref",colour);td.style.setProperty("--sheet-ref-edges",edges.length?edges.join(", "):"none");painted.push(td)}}paintEditorText()}$effect(()=>{void formulaDraft;void version;const frame=requestAnimationFrame(paintReferences);return()=>cancelAnimationFrame(frame)});let mirror=null;function clearEditorMirror(){const input=mirror?.parentElement?.querySelector(".sv-grid-cell-editor");input?.classList.remove("sheet-ref-text");mirror?.remove();mirror=null}function paintEditorText(){const input=root?.querySelector("td.sv-grid-cell-editing .sv-grid-cell-editor")??null;const spans=formulaDraft!==null&&input?referenceSpans(input.value):[];if(!input||spans.length===0){clearEditorMirror();return}const td=input.closest("td");if(!td){clearEditorMirror();return}if(!mirror||mirror.parentElement!==td){clearEditorMirror();mirror=document.createElement("div");mirror.className="sheet-ref-mirror";mirror.setAttribute("aria-hidden","true");td.appendChild(mirror)}const cs=getComputedStyle(input);Object.assign(mirror.style,{left:`${input.offsetLeft}px`,top:`${input.offsetTop}px`,width:`${input.offsetWidth}px`,height:`${input.offsetHeight}px`,font:cs.font,lineHeight:cs.lineHeight,letterSpacing:cs.letterSpacing,padding:cs.padding,textAlign:cs.textAlign,boxSizing:cs.boxSizing,borderWidth:cs.borderWidth,borderStyle:"solid",borderColor:"transparent"});fillMirror(mirror,input.value,spans);mirror.scrollLeft=input.scrollLeft;mirror.scrollTop=input.scrollTop;input.classList.add("sheet-ref-text")}function fillMirror(host,text,spans){host.replaceChildren();let at=0;for(const span of spans){if(span.start>at)host.appendChild(document.createTextNode(text.slice(at,span.start)));const run=document.createElement("span");run.style.color=span.colour;run.textContent=text.slice(span.start,span.end);host.appendChild(run);at=span.end}if(at<text.length)host.appendChild(document.createTextNode(text.slice(at)))}
2
+ import{SvGrid,SvPopover,SvModal,tableFeatures,renderSnippet,buildFillPattern}from"@svgrid/grid";import{tick,untrack,mount,unmount,flushSync}from"svelte";import SvSheetRibbon from"./SvSheetRibbon.svelte";import SvFormulaBar from"./SvFormulaBar.svelte";import SvSheetTabs from"./SvSheetTabs.svelte";import SvSheetFindReplace from"./SvSheetFindReplace.svelte";import SvSheetPasteSpecial from"./SvSheetPasteSpecial.svelte";import SvSheetFormatCells from"./SvSheetFormatCells.svelte";import SvSheetInsertFunction from"./SvSheetInsertFunction.svelte";import SvSheetSizeDialog from"./SvSheetSizeDialog.svelte";import SvSheetNameManager from"./SvSheetNameManager.svelte";import SvSheetGoalSeek from"./SvSheetGoalSeek.svelte";import SvSheetIteration from"./SvSheetIteration.svelte";import SvSheetEvaluate from"./SvSheetEvaluate.svelte";import SvSheetErrors from"./SvSheetErrors.svelte";import SvSheetTextToColumns from"./SvSheetTextToColumns.svelte";import SvSheetRemoveDuplicates from"./SvSheetRemoveDuplicates.svelte";import SvSheetSort from"./SvSheetSort.svelte";import{downloadBlobFile}from"@svgrid/grid";import{documentToXlsx,documentFromXlsx}from"./sheet/xlsx-document";import{xlsxCanCarryPicture}from"./sheet/xlsx-drawing";import{csvText}from"./sheet/csv";import{documentFromFile}from"./sheet/open-file";import{documentToOds}from"./sheet/ods-document";import{documentToXls}from"./sheet/xls-document";import{sortOrder,guessHeaderRow}from"./sheet/sort";import{currentRegion,isBlankValue}from"./sheet/navigate";import{freezeAtActiveCell,freezeTopRow,freezeFirstColumn,applyFreeze}from"./sheet/freeze";import{gridOf}from"./sheet/shortcuts";import{enableSheet}from"./sheet-enable";import{createSheetDocument}from"./sheet/document";import{setWorkbook,setFormatTarget,setFindReplaceHandler,setFormatDialogHandler,setPasteSpecialHandler,setRibbonActionHandler,setShortcutOwner,getShortcutOwner,getFormatTarget,withFormatUndo,applyFormat,clearFormats}from"./sheet/shortcuts";import{applyBorders}from"./sheet/ribbon";import{RIBBON_ICONS}from"./sheet/ribbon-icons";import{planPaste,resolvePasteCell,buildClipboardPayload,parseClipboard,parseClipboardText,parseClipboardHtml,readClipboardOrigin,anchorForeignFormulas}from"./sheet/paste-special";import{setStructureTarget,insertRows,insertColumns,deleteRows,deleteColumns,axisForSelection}from"./sheet/structure";import{setFindTarget}from"./sheet/find-replace";import{setFillTranslator,setSheetValueProbe}from"./sheet/commands";import{translateFormula}from"./sheet/refs";import{entryToStyle}from"./sheet/format-store";import{compileNumberFormat,formatCategory}from"./sheet/number-format";import{colToLetters,lettersToCol,parseA1,quoteSheet}from"./sheet/address";import{isValidName}from"./sheet/names";import{referenceSpans}from"./sheet/refs";import{balanceParens,suggestFunctions,applySuggestion}from"./sheet/autocomplete";import{parseEntry,completeEntry}from"./sheet/entry";import{isError}from"./sheet/ast";import{parseFormula}from"./sheet/parse";import{isLocked,cellLocked,rectsHaveLocked,rectsMixLocked,rangeText}from"./sheet/protection";import SvSheetProtectSheet from"./SvSheetProtectSheet.svelte";import SvSheetEditRanges from"./SvSheetEditRanges.svelte";import SvSheetPageSetup from"./SvSheetPageSetup.svelte";import SvSheetChartSetup from"./SvSheetChartSetup.svelte";import SvSheetSparklines from"./SvSheetSparklines.svelte";import SvSheetPivot from"./SvSheetPivot.svelte";import SvSheetLink from"./SvSheetLink.svelte";import SvSheetTable from"./SvSheetTable.svelte";import{chartSpecOf,chartFromRange,copyObject,objectId,paneOf,paneClip}from"./sheet/objects";import{sparklinesFromRange,sparklineAt,sparklineSeries,sparklineScale,clearSparklines,copySparkline,sparklineSvg}from"./sheet/sparklines";import{pivotFields,pivotFieldValues,pivotBlock,pivotDrill,pivotFromRange,pivotWrittenRect,copyPivot,ALL_VALUES}from"./sheet/pivot-range";import{linkAt,setLink,removeLink,parseLinkTarget,isSafeLinkTarget,linkTitle,hyperlinkArgument}from"./sheet/links";import{imageCall,isDrawableImageSource}from"./sheet/cell-images";import{isValidTableName}from"./sheet/tables";import{tableStyleColours,tableStyleLabel,findTableStyle,DEFAULT_TABLE_STYLE}from"./sheet/table-styles";import{livePresence,presenceOnSheet,presenceAnchor,presenceColour,presenceInitials,presenceInk}from"./sheet/presence";import{SvChart,SvSparkline,chartToSvgString}from"@svgrid/grid";import{MARGIN_PRESETS,marginPresetOf,copyPageSetup}from"./sheet/page-setup";import{sheetPrintHtml}from"./sheet/print";import{resolveSheetMessages}from"./sheet/messages";import{INVARIANT_CULTURE,cultureFromLocale,isInvariant,formulaToCulture,formulaFromCulture}from"./sheet/culture";import{groupLines,ungroupLines,clearOutline,autoOutline,toggleCollapsed,hiddenByOutline,detailRange,outlineLevel,isOutlined,deepestLevel,showLevel}from"./sheet/outline";import{cellTypeAt,isChecked,toggledValue,radioIndex,applyCellType,removeCellTypes,newCellTypeId}from"./sheet/cell-types";import{projectGridSheet,coerceFieldValue}from"./sheet/sheet-kinds";import{provideSheetText,useSheetText}from"./sheet-text";import{commentAt,withComment,withThread,threadAt,threadText,notesOf,nextComment,listComments}from"./sheet/comments";import SvSheetComment from"./SvSheetComment.svelte";import SvSheetListPicker from"./SvSheetListPicker.svelte";import SvSheetDataValidation from"./SvSheetDataValidation.svelte";import SvSheetValidationAlert from"./SvSheetValidationAlert.svelte";import SvSheetConditionalFormat from"./SvSheetConditionalFormat.svelte";import SvSheetManageRules from"./SvSheetManageRules.svelte";import{ruleStats,evaluateCf,removeCf,cfId,COLOR_SCALES,DATA_BAR_COLOR}from"./sheet/conditional-formats";import{rectsIntersect}from"./sheet/rects";import{mergePlan,unmergePlan,toGridMerges,isCoveredCell,selectionMerged,mergesIn,sortBlockedByMerges,reorderMerges,mergeAt as sheetMergeAt,normalRect,expandToMerges}from"./sheet/merges";import{distinctValues,hiddenRowsFor,withColumnFilter,isFiltering,isDateColumn,distinctFills}from"./sheet/auto-filter";import SvSheetFilterMenu from"./SvSheetFilterMenu.svelte";import{ruleAt,checkEntry,listChoices,removeValidation,validationId,invalidCells}from"./sheet/validation";let{document:sheetDocument,workbook,data,rows:minRows=50,columns:minCols=12,height=420,columnWidth=96,rowHeight=22,look="theme",columnWidths,formats,extras=[],localization,commentAuthor,showRibbon=true,showFormulaBar=true,showTabs=true,showStatusBar=true,gridSheets,onAction,onCellAction,onReady,onChange,presence,onPresence}=$props();enableSheet();const messages=$derived(resolveSheetMessages(localization?.text));provideSheetText(()=>messages);const t=useSheetText();const gridLocalization=$derived(localization?.locale?{locale:localization.locale}:void 0);const culture=$derived.by(()=>{if(localization?.culture===false)return INVARIANT_CULTURE;const base=cultureFromLocale(localization?.locale??INVARIANT_CULTURE.locale);return localization?.culture?{...base,...localization.culture}:base});const toCulture=text=>text.startsWith("=")?formulaToCulture(text,culture):numberToCulture(text);const fromCulture=text=>text.startsWith("=")?formulaFromCulture(text,culture):text;const marks=$derived({decimal:culture.decimal,group:culture.group});function numberToCulture(text){if(isInvariant(culture)||text==="")return text;return/^[+-]?\d+\.\d+$/.test(text)?text.replace(".",culture.decimal):text}const doc=sheetDocument??createSheetDocument(workbook?{workbook}:{sheets:data?[...data]:gridSheets?Object.keys(gridSheets).map(name=>({name,cells:[]})):[{name:"Sheet1",cells:[]}]});const wb=doc.workbook;if(gridSheets){for(const[name,spec]of Object.entries(gridSheets)){const exists=wb.sheets.some(sheet=>sheet.toLowerCase()===name.toLowerCase());if(!exists)wb.addSheet(name);const state=doc.get(name);state.kind="grid";state.grid=spec}for(const[name,spec]of Object.entries(gridSheets))projectGridSheetInto(name,spec)}const selfReported=new Set;const changed=reason=>{selfReported.add(reason.kind);doc.changed(reason)};let restoringSelf=false;$effect(()=>doc.subscribe(reasons=>{const outside=reasons.filter(r=>!selfReported.has(r.kind));selfReported.clear();const restored=outside.some(r=>r.kind==="restore");if(restored&&!restoringSelf){afterRestore()}else if(outside.some(r=>r.kind==="sheets")){registerSheetTargets()}else if(outside.some(r=>r.kind==="sizes"||r.kind==="hidden"||r.kind==="freeze")){applyLive(wb.active);const cmd=cmdOf();if(cmd)applyFreeze(cmd,doc.get(wb.active).freeze)}if(restored)restoringSelf=false;bump();onChange?.(reasons)}));function afterRestore(){targetsBoundTo=wb.active;registerSheetTargets();applyLive(wb.active);const cmd=cmdOf();if(cmd)applyFreeze(cmd,doc.get(wb.active).freeze);api?.clearHistory();active={rowIndex:0,colIndex:0}}export function getState(){stashLive(wb.active);return doc.getState()}export function setState(state){restoringSelf=true;doc.setState(state);afterRestore();bump()}let fileName=$state("Workbook");export async function open(file){setState(await documentFromFile(file));const name=file.name??"";if(name)fileName=name.replace(/\.(xlsx|xls|ods|csv|tsv|txt)$/i,"")}export function toXlsx(){stashLive(wb.active);return documentToXlsx(doc)}export function toOds(){stashLive(wb.active);return documentToOds(doc)}export function toXls(){stashLive(wb.active);return new Blob([documentToXls(doc)],{type:"application/vnd.ms-excel"})}export function toCsv(){const rows=[];const lastRow=wb.rowCount(wb.active);const lastCol=wb.colCount(wb.active);for(let r=0;r<lastRow;r+=1){const line=[];for(let c=0;c<lastCol;c+=1)line.push(wb.getRaw(wb.active,r,c)===""?"":display(r,c).text);rows.push(line)}return csvText(rows)}function chartSvgFor(object){if(typeof document==="undefined")return null;const host=document.createElement("div");host.setAttribute("aria-hidden","true");host.style.cssText=`position:fixed;left:-10000px;top:0;width:${object.anchor.width}px;height:${object.anchor.height}px`;document.body.appendChild(host);let drawn=null;let chart=null;try{const spec=specOf(object);chart=mount(SvChart,{target:host,props:{spec,width:object.anchor.width,height:object.anchor.height,legend:spec.series.length>1,interactive:false}});flushSync();drawn=chartToSvgString(host)}catch{drawn=null}finally{if(chart)unmount(chart);host.remove()}return drawn}function printTableLook(row,col){const part=tablePartAt(row,col);if(!part)return null;const table=activeTables.find(t2=>col>=t2.firstCol&&col<=t2.lastCol&&row>=t2.headerRow&&row<=t2.lastRow+(t2.hasTotals?1:0));const colours=tableStyleColours(table?.style??DEFAULT_TABLE_STYLE);if(!colours)return null;if(part.part==="header"){return{fill:colours.header,...colours.headerText==="inherit"?{}:{color:colours.headerText},bold:true,borderBottom:colours.border}}if(part.part==="totals")return{fill:colours.totals,bold:true,borderTop:colours.border};if(part.part==="band")return{fill:colours.band};return null}function printObjects(name){const out=[];for(const object of doc.get(name).objects??[]){const html=object.kind==="chart"?chartSvgFor(object):`<img src="${escapeHtml(object.src)}" alt="${escapeHtml(object.alt??"")}">`;if(!html)continue;out.push({row:object.anchor.row,col:object.anchor.col,dx:object.anchor.dx,dy:object.anchor.dy,width:object.anchor.width,height:object.anchor.height,html})}return out}const HTML_ESCAPES={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};const escapeHtml=text=>text.replace(/[&<>"']/g,c=>HTML_ESCAPES[c]);export function printHtml(){const name=wb.active;const state=doc.get(name);return sheetPrintHtml({name,rowCount:wb.rowCount(name),colCount:wb.colCount(name),cellAt:(r,c)=>{const value=wb.getValue(name,r,c);const shown=wb.getRaw(name,r,c)===""?{text:""}:display(r,c);const entry=storeFor().get(`r${r}`,colToLetters(c));const cf=cfAt(r,c,value)?.style;const picture=imageAt(r,c);const image=picture?`<img src="${escapeHtml(picture.src)}" alt="${escapeHtml(picture.alt)}">`:"";const spark=sparkAt(r,c);const sparkline=spark?sparklineSvg(spark.values,{type:spark.group.type,width:Math.max(16,(state.widths[colToLetters(c)]??columnWidth)-8),height:Math.max(10,(state.heights.get(r)??rowHeight)-8),color:spark.group.color,negativeColor:spark.group.negativeColor,min:spark.min,max:spark.max,markers:spark.group.markers}):"";const table=printTableLook(r,c);return{text:shown.text,...shown.color?{color:shown.color}:{},align:typeof value==="number"?"right":typeof value==="boolean"||isError(value)?"center":"left",...entry?{entry}:{},...cf?{cf}:{},...sparkline?{sparkline}:{},...image?{image}:{},...table?{table}:{}}},widths:api?api.getColumnWidths():state.widths,defaultWidth:columnWidth,heights:state.heights,defaultHeight:rowHeight,hidden:{rows:new Set([...state.hidden.rows,...state.filterHidden]),cols:state.hidden.cols},merges:state.merges,setup:state.pageSetup,objects:printObjects(name)})}export function print(){const html=printHtml();const w=typeof window==="undefined"?null:window.open("","_blank","width=900,height=700");if(!w){say(t("couldNotPrint"));return}w.document.open();w.document.write(html);w.document.close();w.focus();w.addEventListener("load",()=>setTimeout(()=>w.print(),50));setTimeout(()=>{try{w.print()}catch{}},300)}export function newWorkbook(){setState({version:1,workbook:{sheets:[{name:"Sheet1",cells:[]}],active:"Sheet1",names:{}},sheets:{}});fileName="Workbook"}let newConfirm=$state(false);let fileInput=$state(null);function documentHasContent(){for(const name of wb.sheets){for(let r=0;r<wb.rowCount(name);r+=1){for(let c=0;c<wb.colCount(name);c+=1)if(wb.getRaw(name,r,c).trim()!=="")return true}}return false}async function openPicked(event){const input=event.currentTarget;const file=input.files?.[0];input.value="";if(!file)return;try{await open(file);say(t("openedFile",{name:file.name}))}catch(e){say(e instanceof Error?e.message:t("couldNotOpen",{name:file.name}))}}async function saveXlsx(){try{downloadBlobFile(await toXlsx(),`${fileName}.xlsx`);let left=0;for(const name of wb.sheets){for(const object of doc.get(name).objects??[]){if(object.kind==="image"&&!xlsxCanCarryPicture(object.src))left+=1}}if(left>0)say(t("picturesNotSaved",{count:left,unit:t(left===1?"unitPicture":"unitPictures")}))}catch(e){say(e instanceof Error?e.message:t("couldNotSave"))}}function saveXls(){try{downloadBlobFile(toXls(),`${fileName}.xls`)}catch(e){say(e instanceof Error?e.message:t("couldNotSave"))}}async function saveOds(){try{downloadBlobFile(await toOds(),`${fileName}.ods`)}catch(e){say(e instanceof Error?e.message:t("couldNotSave"))}}let version=$state(0);let sheetsSeen="";const bump=()=>{if(wb.active!==targetsBoundTo)registerSheetTargets();const signature=wb.sheets.join("\0")+"\0"+wb.active;if(sheetsSeen&&signature!==sheetsSeen)changed({kind:"sheets"});sheetsSeen=signature;cfStatsCache.clear();refreshAutoFilter();version+=1};let traces=$state([]);let traceSheet="";let traceFrontier=null;let traceLines=$state([]);function trace(kind){const here=`${active.rowIndex},${active.colIndex}`;if(traceSheet!==wb.active){traces=[];traceFrontier=null;traceSheet=wb.active}const fromFrontier=traceFrontier&&traceFrontier.kind===kind&&traceFrontier.at===here&&traceFrontier.cells.length>0;const starts=fromFrontier?traceFrontier.cells:[{row:active.rowIndex,col:active.colIndex}];const next=[];const seen=new Set(traces.map(t2=>`${t2.from.row},${t2.from.col}>${t2.to.row},${t2.to.col}`));const added=[];for(const start of starts){const linked=kind==="precedents"?wb.precedents(wb.active,start.row,start.col):wb.dependents(wb.active,start.row,start.col);for(const cell of linked){if(cell.sheet.toLowerCase()!==wb.active.toLowerCase())continue;const arrow=kind==="precedents"?{from:{row:cell.row,col:cell.col},to:start}:{from:start,to:{row:cell.row,col:cell.col}};const key=`${arrow.from.row},${arrow.from.col}>${arrow.to.row},${arrow.to.col}`;if(seen.has(key))continue;seen.add(key);added.push(arrow);next.push({row:cell.row,col:cell.col})}}if(!added.length&&!fromFrontier){say(t(kind==="precedents"?"noPrecedents":"noDependents"))}traces=[...traces,...added];traceFrontier={kind,at:here,cells:next};void tick().then(()=>requestAnimationFrame(measureTraces))}function removeArrows(){traces=[];traceFrontier=null;traceLines=[]}let outlineBrackets=$state([]);function measureOutline(){const host=gridHost;const state=doc.get(wb.active);if(!host||!isOutlined(state.outline.rows)){outlineBrackets=[];return}const b=host.getBoundingClientRect();const rowBox=r=>host.querySelector(`td[data-svgrid-row="${r}"]`)?.getBoundingClientRect()??null;const out=[];const rows=state.outline.rows;const folded=hiddenByOutline(rows,{summaryBelow:true});for(let line=0;line<rowCount;line+=1){const range=detailRange(rows,line,{summaryBelow:true});if(!range)continue;const summaryBox=rowBox(line);if(!summaryBox)continue;const collapsed=rows.collapsed.includes(line);const buttonY=summaryBox.top-b.top+summaryBox.height/2;let top=buttonY;let bottom=buttonY;if(!collapsed){for(let r=range.from;r<=range.to;r+=1){if(folded.has(r))continue;const box=rowBox(r);if(!box)continue;top=Math.min(top,box.top-b.top);bottom=Math.max(bottom,box.bottom-b.top)}}out.push({summary:line,top,bottom,buttonY,collapsed,level:outlineLevel(rows,line)+1})}outlineBrackets=out}const outlineLevels=$derived.by(()=>{void version;const rows=doc.get(wb.active).outline.rows;return isOutlined(rows)?deepestLevel(rows)+1:0});function measureTraces(){const host=gridHost;if(!host||!traces.length){traceLines=[];return}const b=host.getBoundingClientRect();const centre=cell=>{const td=host.querySelector(`td[data-svgrid-row="${cell.row}"][data-svgrid-col="${cell.col}"]`);if(!td)return null;const a=td.getBoundingClientRect();return{x:a.left-b.left+a.width/2,y:a.top-b.top+a.height/2}};const lines=[];for(const arrow of traces){const from=centre(arrow.from);const to=centre(arrow.to);if(from&&to)lines.push({x1:from.x,y1:from.y,x2:to.x,y2:to.y})}traceLines=lines}$effect(()=>{void version;void traces;if(!traces.length)return;if(traceSheet&&traceSheet.toLowerCase()!==wb.active.toLowerCase()){removeArrows();return}void tick().then(()=>requestAnimationFrame(measureTraces))});$effect(()=>{void version;void outlineLevels;void tick().then(()=>requestAnimationFrame(measureOutline))});const hiddenSheets=$derived.by(()=>{void version;return wb.sheets.filter(name=>doc.get(name).sheetHidden)});function hideSheet(name){const visible=wb.sheets.filter(n=>!doc.get(n).sheetHidden);if(visible.length<2||!wb.sheets.some(n=>n.toLowerCase()===name.toLowerCase()))return;doc.get(name).sheetHidden=true;if(wb.active.toLowerCase()===name.toLowerCase()){const at=visible.findIndex(n=>n.toLowerCase()===name.toLowerCase());const next=visible[at+1]??visible[at-1];if(next){wb.setActive(next);active={rowIndex:0,colIndex:0}}}changed({kind:"sheets"});bump()}function unhideSheet(name){if(!wb.sheets.some(n=>n.toLowerCase()===name.toLowerCase()))return;doc.get(name).sheetHidden=false;wb.setActive(name);active={rowIndex:0,colIndex:0};changed({kind:"sheets"});bump()}function duplicateSheet(name){const made=doc.duplicate(name);if(made===null){say(t("couldNotCopySheet",{name}));return}active={rowIndex:0,colIndex:0};bump()}export function refresh(){bump()}export function act(action){const context=cmdOf();if(!context)return;handleAction(action,context)}const definedNames=$derived.by(()=>{void version;return wb.names.list()});let active=$state({rowIndex:0,colIndex:0});let selection=$state([]);let api=$state(null);let showFormulas=$state(false);let gridlinesOn=$state(true);let formulaBarOn=$state(true);let headingsOn=$state(true);let ribbonCollapsed=$state(false);function storeFor(sheet=wb.active){return doc.get(sheet).formats}function splitSheet(address){const bang=address.lastIndexOf("!");if(bang<0)return{sheet:null,cell:address};const sheet=address.slice(0,bang).replace(/^'(.*)'$/,"$1");return{sheet,cell:address.slice(bang+1)}}for(const[address,entry]of Object.entries(formats??{})){const{sheet,cell}=splitSheet(address);const ref=parseA1(cell);if(!ref||ref.row===null)continue;storeFor(sheet??wb.active).set([[ref.row,ref.col,ref.row,ref.col]],entry,{rowIdAt:i=>`r${i}`,columnIdAt:i=>colToLetters(i)})}const rowCount=$derived.by(()=>{void version;return Math.max(minRows,wb.rowCount(wb.active)+1)});const colCount=$derived.by(()=>{void version;return Math.max(minCols,wb.colCount(wb.active)+1)});const gridRows=$derived.by(()=>{void version;return Array.from({length:rowCount},(_,index)=>{const row={id:`r${index}`,index};for(let c=0;c<colCount;c+=1){row[colToLetters(c)]=wb.getRaw(wb.active,index,c)}return row})});const lookup={rowIdAt:i=>i>=0&&i<rowCount?`r${i}`:null,columnIdAt:i=>i>=0&&i<colCount?colToLetters(i):null};const protectedNow=()=>doc.get(wb.active).protected;const isProtected=$derived.by(()=>{void version;return protectedNow()});const protectionNow=()=>doc.get(wb.active).protection;const allowNow=key=>!protectedNow()||Boolean(protectionNow().allow[key]);const lineKey=axis2=>axis2==="rows"?"formatRows":"formatColumns";const protectionState=$derived.by(()=>{void version;return protectionNow()});const canResizeRows=$derived.by(()=>{void version;return allowNow("formatRows")});const canResizeCols=$derived.by(()=>{void version;return allowNow("formatColumns")});function locked(r,c){return protectedNow()&&cellLocked(storeFor().get(`r${r}`,colToLetters(c)),protectionNow().ranges,r,c)}function refuse(){say(t("protectedCell"))}function selectedRects(cmd){if(cmd?.ranges.length)return cmd.ranges;if(selection.length)return selection;return[[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex]]}const notesNow=()=>doc.get(wb.active).notes;const activeNotes=$derived.by(()=>{void version;const out={};for(const[rowId,line]of Object.entries(notesOf(notesNow())))out[rowId.slice(1)]=line;return out});const popoverThread=$derived.by(()=>{void version;const pop=cellPopover;return pop?.kind==="comment"?threadAt(notesNow(),pop.r,pop.c)??null:null});let cellPopover=$state(null);let anchorRect=$state(null);let gridHost=$state(null);let tabs=$state(null);let showComments=$state(false);const allComments=$derived.by(()=>{void version;return listComments(notesNow())});function putComments(after){const sheet=wb.active;const before=doc.get(sheet).notes;const put=notes=>{doc.get(sheet).notes=notes;bump();changed({kind:"comments"})};put(after);cmdOf()?.recordUndo(()=>put(before),()=>put(after))}function setComment(r,c,text){const before=notesNow();const fresh=text.trim()&&commentAuthor&&!threadAt(before,r,c);putComments(fresh?withThread(before,r,c,{text,author:commentAuthor,at:new Date().toISOString()}):withComment(before,r,c,text))}function setThread(r,c,thread){putComments(withThread(notesNow(),r,c,thread))}function openCommentEditor(r,c){const cmd=cmdOf();if(!cmd)return;if(cellPopover)closeCellPopover();cmd.setActiveCell(r,c);cmd.setSelection(r,c);cmd.scrollIntoView(r,c);active={rowIndex:r,colIndex:c};const initial=commentAt(notesNow(),r,c)??"";cellPopover={kind:"comment",r,c,draft:initial,initial};void tick().then(()=>requestAnimationFrame(measureAnchor))}function measureAnchor(){const pop=cellPopover;const host=gridHost;if(!pop||!host){anchorRect=null;return}const td=host.querySelector(`td[data-svgrid-row="${pop.r}"][data-svgrid-col="${pop.c}"]`);if(!td){closeCellPopover();return}const a=td.getBoundingClientRect();const b=host.getBoundingClientRect();anchorRect={left:a.left-b.left,top:a.top-b.top,width:a.width,height:a.height}}function closeCellPopover(keep=true){const pop=cellPopover;if(!pop)return;cellPopover=null;anchorRect=null;if(pop.kind==="comment"&&keep&&pop.draft!==pop.initial)setComment(pop.r,pop.c,pop.draft);const cmd=cmdOf();if(cmd)focusSheet(cmd)}function walkComments(dir){const to=nextComment(notesNow(),{row:active.rowIndex,col:active.colIndex},dir);if(!to){say(t("noComments"));return}openCommentEditor(to.row,to.col)}const rulesNow=()=>doc.get(wb.active).validation;const validationCtx={evaluate:(text,entry)=>wb.evaluateText(wb.active,text,entry),range:text=>wb.evaluateRange(wb.active,text)};let pendingAlert=$state(null);let dataValidationOpen=$state(false);let circlesOn=$state(null);const circled=$derived.by(()=>{void version;const out=new Set;if(circlesOn===null||circlesOn.toLowerCase()!==wb.active.toLowerCase())return out;const hits=invalidCells(rulesNow(),validationCtx,(r,c)=>wb.getRaw(wb.active,r,c),wb.rowCount(wb.active),wb.colCount(wb.active));for(const hit of hits)out.add(`${hit.row},${hit.col}`);return out});const inputMessage=$derived.by(()=>{void version;if(cellPopover)return null;const rule=ruleAt(rulesNow(),active.rowIndex,active.colIndex);if(!rule?.input)return null;return{r:active.rowIndex,c:active.colIndex,title:rule.input.title,message:rule.input.message}});let messageRect=$state(null);function measureMessage(){const at=inputMessage;const host=gridHost;if(!at||!host){messageRect=null;return}const td=host.querySelector(`td[data-svgrid-row="${at.r}"][data-svgrid-col="${at.c}"]`);if(!td){messageRect=null;return}const a=td.getBoundingClientRect();const b=host.getBoundingClientRect();messageRect={left:a.left-b.left,top:a.top-b.top,height:a.height}}$effect(()=>{void inputMessage;void version;void tick().then(()=>requestAnimationFrame(measureMessage))});const cfNow=()=>doc.get(wb.active).conditionalFormats;const cfCtx={evaluate:(text,at)=>wb.evaluateText(wb.active,text,void 0,at)};const cfStatsCache=new Map;function cfStatsFor(rule){let stats=cfStatsCache.get(rule.id);if(!stats){stats=ruleStats(rule,(r,c)=>wb.getValue(wb.active,r,c),(r,c)=>display(r,c).text);cfStatsCache.set(rule.id,stats)}return stats}function cfAt(r,c,value){const rules=cfNow();if(!rules.length)return null;return evaluateCf(rules,r,c,value,display(r,c).text,cfStatsFor,cfCtx)}let cfDialog=$state(null);let manageRulesOpen=$state(false);const cfRules=$derived.by(()=>{void version;return cfNow()});const cfSelection=$derived.by(()=>{void version;void selection;void active;return cfRects()});const mergesNow=()=>doc.get(wb.active).merges;const activeMerges=$derived.by(()=>{void version;return toGridMerges(mergesNow())});let mergeConfirm=$state(null);function setMerges(next){const sheet=wb.active;const before=doc.get(sheet).merges;const put=merges=>{doc.get(sheet).merges=merges;bump();changed({kind:"merges"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}function covered(r,c){return isCoveredCell(mergesNow(),r,c)}const liveWidths=$state({});$effect(()=>{const next=api?.getColumnWidths()??{};for(const[letter,px]of Object.entries(next)){if(untrack(()=>liveWidths[letter])!==px)liveWidths[letter]=px}});const widthOf=col=>{const letter=colToLetters(col);return liveWidths[letter]??columnWidths?.[letter]??columnWidth};function cellWidth(r,c){const one=widthOf;const m=sheetMergeAt(mergesNow(),r,c);if(!m||m[0]!==r||m[1]!==c)return one(c);let total=0;for(let col=m[1];col<=m[3];col+=1)total+=one(col);return total}function runMerge(kind,cmd){const rects=selectedRects(cmd).map(normalRect);if(!allowNow("formatCells")&&rectsHaveLocked(storeFor(),lookup,rects,protectionNow().ranges)){refuse();return}if(kind==="center"&&rects.length===1&&mergesIn(mergesNow(),rects).some(m=>m.join()===rects[0].join())){runUnmerge(cmd);return}const plan=mergePlan(mergesNow(),rects,kind,(r,c)=>wb.getRaw(wb.active,r,c)==="");if(plan.merges.length===mergesNow().length&&plan.merges.every((m,i)=>m===mergesNow()[i]))return;if(plan.clear.length){mergeConfirm={plan,rects};return}applyMerge(plan,cmd)}function applyMerge(plan,cmd){const target=getFormatTarget();cmd.batch(()=>{for(const[r,c]of plan.clear)cmd.setCellValue(r,c,"");if(plan.center&&target&&plan.origins.length){const rects=plan.origins.map(([r,c])=>[r,c,r,c]);withFormatUndo(cmd,target,rects,()=>target.store.set(rects,{align:"center"},target.lookup))}setMerges(plan.merges)});if(plan.origins[0]){cmd.setActiveCell(plan.origins[0][0],plan.origins[0][1]);cmd.setSelection(plan.origins[0][0],plan.origins[0][1])}focusSheet(cmd)}function runUnmerge(cmd){const rects=selectedRects(cmd).map(normalRect);const next=unmergePlan(mergesNow(),rects);if(next.length===mergesNow().length)return;cmd.batch(()=>setMerges(next));focusSheet(cmd)}const selectionHasMerge=()=>selectionMerged(mergesNow(),selectedRects(cmdOf()).map(normalRect));const autoFilterNow=()=>doc.get(wb.active).autoFilter;const activeFilter=$derived.by(()=>{void version;return autoFilterNow()});const displayOnActive=(r,c)=>display(r,c).text;const valueOnActive=(r,c)=>wb.getValue(wb.active,r,c);const fillOnActive=(r,c)=>{const value=wb.getValue(wb.active,r,c);return cfAt(r,c,value)?.style?.fill??storeFor().get(`r${r}`,colToLetters(c))?.fill??null};const filterCtx=()=>({fillAt:fillOnActive});const colourOnActive=(r,c,on)=>{if(on==="fill")return fillOnActive(r,c);const value=wb.getValue(wb.active,r,c);return cfAt(r,c,value)?.style?.color??storeFor().get(`r${r}`,colToLetters(c))?.color??null};function displayOn(name,r,c){const value=wb.getValue(name,r,c);if(isError(value))return value.error;const entry=doc.get(name).formats.get(`r${r}`,colToLetters(c));if(entry?.numFmt)return compileNumberFormat(entry.numFmt,marks).format(value).text;if(value===""||value==null)return"";if(typeof value==="boolean")return value?"TRUE":"FALSE";return String(value)}function settleFilterRows(next){const state=doc.get(wb.active);const before=state.filterHidden;if(api){for(const r of before)if(!next.has(r)&&!state.hidden.rows.has(r))api.setRowCollapsed(r,false);for(const r of next)if(!before.has(r))api.setRowCollapsed(r,true)}state.filterHidden=new Set(next);tellWorkbookWhatIsHidden()}function tellWorkbookWhatIsHidden(){wb.setHiddenRows((sheet,row)=>{const state=doc.get(sheet);if(state.filterHidden.has(row))return"filter";return state.hidden.rows.has(row)?"hand":null})}function applyAutoFilter(next,cmd){const sheet=wb.active;const before=doc.get(sheet).autoFilter;const put=state=>{doc.get(sheet).autoFilter=state;settleFilterRows(hiddenRowsFor(state,valueOnActive,displayOnActive,filterCtx()));bump();changed({kind:"filter"})};put(next);cmd?.recordUndo(()=>put(before),()=>put(next))}function toggleAutoFilter(cmd){if(!allowNow("autoFilter")){refuse();return}if(autoFilterNow()){applyAutoFilter(null,cmd);return}const region=currentRegion(gridOf(cmd),{row:active.rowIndex,col:active.colIndex});const last=selection[selection.length-1];const isRange=last&&(last[0]!==last[2]||last[1]!==last[3]);const range=isRange?normalRect(last):region;applyAutoFilter({range,filters:{}},cmd)}function filterArrowAt(r,c){const af=activeFilter;if(!af||r!==af.range[0]||c<af.range[1]||c>af.range[3])return null;return af.filters[c]?"filtered":"plain"}function filterMenuFor(col){const af=autoFilterNow();const others=hiddenRowsFor(withColumnFilter(af,col,null),valueOnActive,displayOnActive,filterCtx());const values=distinctValues(af,col,valueOnActive,displayOnActive,r=>!others.has(r));const numeric=values.some(v=>v.numeric!==null)&&values.every(v=>v.numeric!==null||v.text==="");const dates=isDateColumn(values);const fills=distinctFills(af,col,fillOnActive);const header=display(af.range[0],col).text||colToLetters(col);return{values,numeric,dates,fills,header,filter:af.filters[col]??null}}function openFilterMenu(col){const af=autoFilterNow();const cmd=cmdOf();if(!af||!cmd)return;if(!allowNow("autoFilter")){refuse();return}if(cellPopover)closeCellPopover();cellPopover={kind:"filter",r:af.range[0],c:col,...filterMenuFor(col)};void tick().then(()=>requestAnimationFrame(measureAnchor))}function refreshAutoFilter(){const state=doc.get(wb.active);if(!state.autoFilter||!api)return;const next=hiddenRowsFor(state.autoFilter,valueOnActive,displayOnActive,filterCtx());if(next.size===state.filterHidden.size&&[...next].every(r=>state.filterHidden.has(r)))return;settleFilterRows(next)}const filterSummary=$derived.by(()=>{void version;const af=autoFilterNow();if(!isFiltering(af))return null;const total=af.range[2]-af.range[0];return t("statusRecordsFound",{shown:total-doc.get(wb.active).filterHidden.size,total})});function setCf(next){const sheet=wb.active;const before=doc.get(sheet).conditionalFormats;const put=rules=>{doc.get(sheet).conditionalFormats=rules;bump();changed({kind:"conditional-formats"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}function cfRects(){return selectedRects(cmdOf()).map(([r1,c1,r2,c2])=>[Math.min(r1,r2),Math.min(c1,c2),Math.max(r1,r2),Math.max(c1,c2)])}function addCf(body){const rule={id:cfId(),rects:cfRects(),...body};setCf([rule,...cfNow()])}function applyCfBody(body){const dialog=cfDialog;cfDialog=null;if(dialog?.rule&&dialog.replace){dialog.replace({...body,id:dialog.rule.id,rects:dialog.rule.rects,stopIfTrue:dialog.rule.stopIfTrue});return}addCf(body)}const CF_PRESETS={"cf-greater":"greater","cf-less":"less","cf-between":"between","cf-equal":"equal","cf-text":"text","cf-duplicates":"duplicates","cf-top10":"top10","cf-bottom10":"bottom10","cf-above-average":"aboveAverage","cf-below-average":"belowAverage","cf-formula":"formula"};function cfAction(action,context){const preset=CF_PRESETS[action];if(preset){cfDialog={preset,rule:null};return true}switch(action){case"cf-data-bar":addCf({kind:"dataBar",color:DATA_BAR_COLOR});break;case"cf-color-scale-3":addCf({kind:"colorScale",colors:COLOR_SCALES["green-yellow-red"]});break;case"cf-color-scale-2":addCf({kind:"colorScale",colors:COLOR_SCALES["green-white"]});break;case"cf-icon-set":addCf({kind:"iconSet",set:"arrows"});break;case"cf-clear-selection":{const next=removeCf(cfNow(),cfRects());if(next.length!==cfNow().length||next.some((rule,i)=>rule!==cfNow()[i]))setCf(next);break}case"cf-clear-sheet":if(cfNow().length)setCf([]);break;case"cf-manage":manageRulesOpen=true;return true;default:return false}focusSheet(context);return true}const PLAIN_NUMBER=/^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;function storedTextFor(r,c,text){const parsed=parseEntry(text,culture);if(parsed)return parsed.value;if(text.startsWith("="))return text;const entry=storeFor().get(`r${r}`,colToLetters(c));if(entry?.numFmt&&formatCategory(entry.numFmt).category==="percent"&&PLAIN_NUMBER.test(text.trim())){return String(Number(text.trim())/100)}return text}function admits(r,c,text){const rule=ruleAt(rulesNow(),r,c);if(!rule)return true;const judged=rule.allow==="list"?text:storedTextFor(r,c,text);const verdict=checkEntry(rule,judged,{row:r,col:c},validationCtx);if(verdict.ok)return true;pendingAlert={r,c,text,verdict};const cmd=cmdOf();if(cmd)void tick().then(()=>{cmd.setActiveCell(r,c);cmd.setSelection(r,c)});return false}function setValidation(next){const sheet=wb.active;const before=doc.get(sheet).validation;const put=rules=>{doc.get(sheet).validation=rules;bump();changed({kind:"validation"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}function applyValidation(spec){const rects=selectedRects(cmdOf()).map(([r1,c1,r2,c2])=>[Math.min(r1,r2),Math.min(c1,c2),Math.max(r1,r2),Math.max(c1,c2)]);const kept=removeValidation(rulesNow(),rects);setValidation([...kept,{id:validationId(),rects,...spec}])}function clearValidation(){const rects=selectedRects(cmdOf()).map(([r1,c1,r2,c2])=>[Math.min(r1,r2),Math.min(c1,c2),Math.max(r1,r2),Math.max(c1,c2)]);const next=removeValidation(rulesNow(),rects);if(next.length!==rulesNow().length||next.some((rule,i)=>rule!==rulesNow()[i]))setValidation(next)}function listRuleAt(r,c){const rule=ruleAt(rulesNow(),r,c);return rule&&rule.allow==="list"&&rule.inCellDropdown?rule:void 0}function openListPicker(r,c){const rule=listRuleAt(r,c);const cmd=cmdOf();if(!rule||!cmd)return;if(cellPopover)closeCellPopover();cellPopover={kind:"list",r,c,choices:listChoices(rule,validationCtx)};void tick().then(()=>requestAnimationFrame(measureAnchor))}function pickChoice(choice){const pop=cellPopover;closeCellPopover();const cmd=cmdOf();if(!pop||!cmd)return;if(locked(pop.r,pop.c)){refuse();return}cmd.batch(()=>cmd.setCellValue(pop.r,pop.c,choice))}function retryEntry(){const alert=pendingAlert;pendingAlert=null;const cmd=cmdOf();if(!alert||!cmd)return;void tick().then(()=>{cmd.startEditing(alert.r,alert.c,alert.text)})}function acceptEntry(){const alert=pendingAlert;pendingAlert=null;const cmd=cmdOf();if(!alert||!cmd)return;cmd.batch(()=>cmd.setCellValue(alert.r,alert.c,balanceParens(alert.text)));focusSheet(cmd)}function setProtected(on,cmd,allow){const sheet=wb.active;const state=doc.get(sheet);const before={on:state.protected,allow:{...state.protection.allow}};const after={on,allow:allow?{...allow}:before.allow};if(before.on===on&&!allow)return;const put=value=>{const target=doc.get(sheet);target.protected=value.on;target.protection={allow:{...value.allow},ranges:target.protection.ranges};bump();changed({kind:"protection"})};put(after);cmd?.recordUndo(()=>put(before),()=>put(after));say(t(on?"sheetProtected":"sheetUnprotected"))}function setEditRanges(ranges){const sheet=wb.active;const state=doc.get(sheet);const before=state.protection.ranges;const put=value=>{const target=doc.get(sheet);target.protection={allow:target.protection.allow,ranges:value};bump();changed({kind:"protection"})};put(ranges);cmdOf()?.recordUndo(()=>put(before),()=>put(ranges))}let protectSheetOpen=$state(false);let editRangesOpen=$state(false);const objectsNow=()=>doc.get(wb.active).objects;const activeObjects=$derived.by(()=>{void version;return objectsNow()});let selectedObject=$state(null);let chartSetup=$state(null);let objectBoxes=$state({});let draggingObject=$state(null);let dragging=null;let imageInput=$state(null);function putObjects(next){if(protectedNow()){refuse();return}const sheet=wb.active;const before=doc.get(sheet).objects;const put=value=>{doc.get(sheet).objects=value;bump();changed({kind:"objects"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}let objectSheet="";$effect(()=>{void version;if(wb.active===objectSheet)return;objectSheet=wb.active;untrack(()=>{selectedObject=null})});const addObject=object=>{putObjects([...objectsNow(),object]);selectedObject=object.id};const replaceObject=object=>putObjects(objectsNow().map(o=>o.id===object.id?object:o));function removeObject(id){if(!objectsNow().some(o=>o.id===id))return;putObjects(objectsNow().filter(o=>o.id!==id));if(selectedObject===id)selectedObject=null}const sparklinesNow=()=>doc.get(wb.active).sparklines;const activeSparklines=$derived.by(()=>{void version;return sparklinesNow()});let sparklineSetup=$state(null);function putSparklines(next){if(protectedNow()){refuse();return}const sheet=wb.active;const before=doc.get(sheet).sparklines;const put=value=>{doc.get(sheet).sparklines=value;bump();changed({kind:"sparklines"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}const addSparklines=group=>putSparklines([...sparklinesNow(),group]);const replaceSparklines=group=>putSparklines(sparklinesNow().map(g=>g.id===group.id?group:g));const sparklineHere=()=>sparklineAt(sparklinesNow(),active.rowIndex,active.colIndex);function startSparklines(type){if(protectedNow()){refuse();return}const here=sparklineHere();if(here){replaceSparklines({...copySparkline(here),type,markers:type==="line"?here.markers:void 0});return}const rects=selectedRects().map(normalRect);const rect=rects[rects.length-1];if(!rect||rect[0]===rect[2]&&rect[1]===rect[3]){say(t("selectRangeForSparklines"));return}sparklineSetup={group:sparklinesFromRange(rect,type),existing:false}}function setupSparklines(){if(protectedNow()){refuse();return}const here=sparklineHere();if(!here){say(t("noSparklinesHere"));return}sparklineSetup={group:here,existing:true}}function clearSparklinesHere(){if(protectedNow()){refuse();return}const rects=selectedRects().map(normalRect);const next=clearSparklines(sparklinesNow(),rects);if(next.length===sparklinesNow().length){say(t("noSparklinesHere"));return}putSparklines(next);say(t("sparklinesCleared"))}function imageAt(row,col){const call=imageCall(raw(row,col));if(!call)return null;const value=wb.getValue(wb.active,row,col);if(isError(value))return null;const src=String(value??"");if(!isDrawableImageSource(src))return null;let alt="";if(call.alt){const answered=wb.evaluateText(wb.active,`=${call.alt}`,void 0,{row,col});alt=isError(answered)?"":String(answered??"")}return{src,alt}}function sparkAt(row,col){const group=sparklineAt(activeSparklines,row,col);if(!group)return null;const read=(r,c)=>wb.getValue(wb.active,r,c);const values=sparklineSeries(group,row,col,read);if(!values)return null;const scale=sparklineScale(group,read);return{group,values,min:scale?.min,max:scale?.max}}const tablesNow=()=>wb.tables.list();const activeTables=$derived.by(()=>{void version;return tablesNow().filter(t2=>t2.sheet.toLowerCase()===wb.active.toLowerCase())});let tableSetup=$state(null);function putTables(next){if(protectedNow()){refuse();return}const before=tablesNow().map(t2=>({...t2}));const put=value=>{wb.tables.clear();for(const table of value)wb.tables.define({...table});wb.recalculate();bump();changed({kind:"tables"})};const after=next.map(t2=>({...t2}));put(after);cmdOf()?.recordUndo(()=>put(before),()=>put(after))}const tableHere=()=>wb.tables.at(wb.active,active.rowIndex,active.colIndex);function nextTableName(){const taken=new Set(tablesNow().map(t2=>t2.name.toLowerCase()));for(let i=1;;i+=1){const name=`Table${i}`;if(!taken.has(name.toLowerCase()))return name}}function insertTable(){if(protectedNow()){refuse();return}const here=tableHere();if(here){tableSetup={range:[here.headerRow,here.firstCol,here.lastRow+(here.hasTotals?1:0),here.lastCol],name:here.name,headers:true,totals:here.hasTotals,style:here.style??DEFAULT_TABLE_STYLE,existing:here.name};return}const block=blockAround(cmdOf());if(!block||block[0]===block[2]){say(t("selectBlockToTable"));return}tableSetup={range:block,name:nextTableName(),headers:true,totals:false,style:DEFAULT_TABLE_STYLE,existing:null}}function blockAround(cmd){const rects=selectedRects(cmd).map(normalRect);const last=rects[rects.length-1];if(last&&(last[0]!==last[2]||last[1]!==last[3]))return last;const region=cmd?currentRegion(gridOf(cmd),{row:active.rowIndex,col:active.colIndex}):null;return region??last??null}function applyTable(next){const cmd=cmdOf();const[r1,c1,r2,c2]=next.range;const existing=tableSetup?.existing;if(!isValidTableName(next.name)){say(t("table.badName"));return}const clash=tablesNow().find(t2=>t2.name.toLowerCase()===next.name.toLowerCase()&&t2.name!==existing);if(clash){say(t("tableNameTaken",{name:next.name}));return}const hadTotals=existing?tablesNow().find(t2=>t2.name===existing)?.hasTotals??false:false;const lastRow=hadTotals?r2-1:r2;const addingTotals=next.totals&&!hadTotals;const table={name:next.name,sheet:wb.active,headerRow:r1,firstCol:c1,lastCol:c2,lastRow,hasTotals:next.totals,style:next.style};const rest=tablesNow().filter(t2=>t2.name!==existing);cmd?.batch(()=>{putTables([...rest,table]);if(!next.headers){wb.applyStructuralEdit(wb.active,{kind:"insertRows",at:r1,count:1});doc.shift(wb.active,{kind:"insertRows",at:r1,count:1});for(let c=c1;c<=c2;c+=1)cmd.setCellValue(r1,c,`Column${c-c1+1}`)}if(addingTotals){const totalsRow=lastRow+1;let taken=false;for(let c=c1;c<=c2&&!taken;c+=1)taken=wb.getRaw(wb.active,totalsRow,c).trim()!=="";if(taken){wb.applyStructuralEdit(wb.active,{kind:"insertRows",at:totalsRow,count:1});doc.shift(wb.active,{kind:"insertRows",at:totalsRow,count:1})}cmd.setCellValue(totalsRow,c1,t("table.totalLabel"));if(c2>c1)cmd.setCellValue(totalsRow,c2,`=SUBTOTAL(109,[${wb.getRaw(wb.active,r1,c2).trim()||`Column${c2-c1+1}`}])`)}else if(!next.totals&&hadTotals){for(let c=c1;c<=c2;c+=1)if(wb.getRaw(wb.active,r2,c)!=="")cmd.setCellValue(r2,c,"")}applyAutoFilter({range:[r1,c1,lastRow,c2],filters:{}},cmd)});bump();const range=`${colToLetters(c1)}${r1+1}:${colToLetters(c2)}${(next.totals?lastRow+1:lastRow)+1}`;const look2=findTableStyle(next.style);say(existing?t("tableUpdated",{name:next.name,range,style:look2?tableStyleLabel(look2):t("table.styleNoneShort")}):t("tableMade",{name:next.name,range}))}function removeTableHere(){if(protectedNow()){refuse();return}const here=tableHere();if(!here){say(t("noTableHere"));return}putTables(tablesNow().filter(t2=>t2.name!==here.name));say(t("tableRemoved",{name:here.name}))}function fillTableFormulas(row,col){const table=wb.tables.at(wb.active,row,col);if(!table||row<=table.headerRow+1)return;for(let c=table.firstCol;c<=table.lastCol;c+=1){if(wb.getRaw(wb.active,row,c)!=="")continue;const above=wb.getRaw(wb.active,row-1,c);if(!above.startsWith("="))continue;const filled=translateFormula(above,1,0);if(typeof filled==="string")wb.setRaw(wb.active,row,c,filled)}}function tablePartAt(row,col){for(const table of activeTables){if(col<table.firstCol||col>table.lastCol)continue;const colours=tableStyleColours(table.style??DEFAULT_TABLE_STYLE);if(!colours)return null;const css=`--sheet-table-header:${colours.header};--sheet-table-header-text:${colours.headerText};--sheet-table-band:${colours.band};--sheet-table-totals:${colours.totals};--sheet-table-border:${colours.border}`;if(row===table.headerRow){return{part:"header",style:css,text:colours.headerText,fill:colours.headerText==="inherit"?"":colours.header}}const last=table.lastRow+(table.hasTotals?1:0);if(row<table.headerRow||row>last)continue;if(table.hasTotals&&row===last)return{part:"totals",style:css,text:"inherit",fill:""};return{part:(row-table.headerRow)%2===0?"band":"row",style:css,text:"inherit",fill:""}}return null}const linksNow=()=>doc.get(wb.active).links;const activeLinks=$derived.by(()=>{void version;return linksNow()});let linkSetup=$state(null);function putLinks(next){if(protectedNow()){refuse();return}const sheet=wb.active;const before=doc.get(sheet).links;const put=value=>{doc.get(sheet).links=value;bump();changed({kind:"links"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}function linkOf(row,col){const own=linkAt(linksNow(),row,col);if(own)return own;const argument=hyperlinkArgument(raw(row,col));if(!argument)return void 0;const value=wb.evaluateText(wb.active,`=${argument}`,void 0,{row,col});const target=typeof value==="string"?value:typeof value==="number"?String(value):"";return target.trim()?{target}:void 0}function insertLink(){if(protectedNow()){refuse();return}const{rowIndex,colIndex}=active;const here=linkAt(linksNow(),rowIndex,colIndex);linkSetup={link:here??{target:""},text:raw(rowIndex,colIndex),where:`${colToLetters(colIndex)}${rowIndex+1}`,row:rowIndex,col:colIndex,existing:Boolean(here)}}function applyLink(link,text){const setup=linkSetup;const cmd=cmdOf();if(!setup||!cmd)return;cmd.batch(()=>{if(text!==raw(setup.row,setup.col))cmd.setCellValue(setup.row,setup.col,text);putLinks(setLink(linksNow(),setup.row,setup.col,link))});bump()}function removeLinksIn(){if(protectedNow()){refuse();return}let next=linksNow();for(const[r1,c1,r2,c2]of selectedRects().map(normalRect)){for(let r=r1;r<=r2;r+=1)for(let c=c1;c<=c2;c+=1)next=removeLink(next,r,c)}if(next===linksNow()){say(t("noLinkHere"));return}putLinks(next);say(t("linkRemoved"))}async function followLink(link){const target=parseLinkTarget(link.target);if(!target){say(t(isSafeLinkTarget(link.target)?"cannotOpenLink":"linkNotFollowed"));return}if(target.kind==="external"){window.open(target.href,"_blank","noopener,noreferrer");return}if(target.kind==="name"){if(!wb.names.resolve(target.name)){say(t("cannotOpenLink"));return}await jumpToName(target.name);return}const sheet=target.sheet;if(sheet&&sheet.toLowerCase()!==wb.active.toLowerCase()){if(!wb.sheets.some(n=>n.toLowerCase()===sheet.toLowerCase())){say(t("cannotOpenLink"));return}wb.setActive(sheet);bump();await tick()}const cmd=cmdOf();if(!cmd)return;cmd.setActiveCell(target.row,target.col);cmd.setSelection(target.row,target.col);focusSheet(cmd);bump()}const pivotsNow=()=>doc.get(wb.active).pivots;let pivotSetup=$state(null);function putPivots(next){if(protectedNow()){refuse();return}const sheet=wb.active;const before=doc.get(sheet).pivots;const put=value=>{doc.get(sheet).pivots=value;bump();changed({kind:"pivots"})};put(next);cmdOf()?.recordUndo(()=>put(before),()=>put(next))}const cellValueAt=(r,c)=>wb.getValue(wb.active,r,c);const cellTextAt=(r,c)=>String(wb.getValue(wb.active,r,c)??"");function pivotAt(row,col){for(const pivot of pivotsNow()){const w=pivot.written;if(w&&row>=w[0]&&row<=w[2]&&col>=w[1]&&col<=w[3])return pivot;if(!w&&row===pivot.target.row&&col===pivot.target.col)return pivot}return null}let writingPivot=false;function writePivot(pivot,replacing){const cmd=cmdOf();if(!cmd)return;if(protectedNow()){refuse();return}const block=pivotBlock(pivot,cellValueAt,cellTextAt);if(!block.length){say(t("pivot.needValue"));return}const rect=pivotWrittenRect(pivot,block);const next={...copyPivot(pivot),written:rect};writingPivot=true;try{cmd.batch(()=>{const old=pivot.written;if(old){for(let r=old[0];r<=old[2];r+=1){for(let c=old[1];c<=old[3];c+=1)cmd.setCellValue(r,c,"")}}block.forEach((line,i)=>{line.forEach((text,j)=>cmd.setCellValue(pivot.target.row+i,pivot.target.col+j,text))});putPivots(replacing?pivotsNow().map(p=>p.id===next.id?next:p):[...pivotsNow(),next])})}finally{writingPivot=false}wb.recalculate();bump();say(t("pivotWritten",{range:`${colToLetters(rect[1])}${rect[0]+1}:${colToLetters(rect[3])}${rect[2]+1}`}))}function insertPivot(){if(protectedNow()){refuse();return}const here=pivotAt(active.rowIndex,active.colIndex);if(here){pivotSetup={pivot:here,fields:pivotFields(here.source,cellTextAt),existing:true};return}const rect=blockAround(cmdOf());if(!rect||rect[0]===rect[2]||rect[1]===rect[3]){say(t("selectBlockToPivot"));return}const fields=pivotFields(rect,cellTextAt);pivotSetup={pivot:pivotFromRange(rect,fields),fields,existing:false}}function refreshPivot(){const here=pivotAt(active.rowIndex,active.colIndex);if(!here){say(t("noPivotHere"));return}writePivot(here,true);say(t("pivotRefreshed"))}function showPivotDetails(){const here=pivotAt(active.rowIndex,active.colIndex);if(!here){say(t("noPivotHere"));return}const drill=pivotDrill(here,active.rowIndex,active.colIndex,cellValueAt,cellTextAt);if(!drill||!drill.records.length){say(t("noPivotDetails"));return}const name=wb.addSheet(nextDetailSheetName());drill.fields.forEach((field,c)=>wb.setRaw(name,0,c,field));drill.records.forEach((record,r)=>{drill.fields.forEach((field,c)=>{const value=record[field];wb.setRaw(name,r+1,c,value===null||value===void 0?"":String(value))})});doc.get(name).formats.set([[0,0,0,Math.max(0,drill.fields.length-1)]],{bold:true,fill:"#e2e8f0"},{rowIdAt:i=>`r${i}`,columnIdAt:i=>colToLetters(i)});doc.get(name).freeze={rows:1,cols:0};wb.setActive(name);changed({kind:"sheets"});bump();say(t("pivotDetails",{count:drill.records.length,name}))}function nextDetailSheetName(){const taken=new Set(wb.sheets.map(n=>n.toLowerCase()));const base=t("pivotDetailsSheet");if(!taken.has(base.toLowerCase()))return base;for(let i=2;;i+=1)if(!taken.has(`${base}${i}`.toLowerCase()))return`${base}${i}`}function specOf(object){void version;return chartSpecOf(object,(r,c)=>wb.getValue(wb.active,r,c),(r,c)=>display(r,c).text)}function sheetIsRtl(){return Boolean(gridHost)&&getComputedStyle(gridHost).direction==="rtl"}function startOf(a,b){return sheetIsRtl()?b.right-a.right:a.left-b.left}function xOfStart(start,b){return sheetIsRtl()?b.right-start:b.left+start}function paneEdges(host,b){const grid=host.querySelector(".sv-grid-container");if(!grid)return null;const g=grid.getBoundingClientRect();const rtl=sheetIsRtl();const endOf=r=>rtl?b.right-r.left:r.right-b.left;let start=startOf(g,b);const row=grid.querySelector("td[data-svgrid-row]")?.parentElement;for(const el of row?.querySelectorAll('td[data-pinned="left"], td.sv-grid-row-number-cell')??[]){const r=el.getBoundingClientRect();if(r.width)start=Math.max(start,endOf(r))}let top=g.top-b.top;const head=grid.querySelector(".sv-grid-head");if(head)top=Math.max(top,head.getBoundingClientRect().bottom-b.top);for(const tr of grid.querySelectorAll("tr.sv-grid-row-frozen"))top=Math.max(top,tr.getBoundingClientRect().bottom-b.top);return{start,top,end:endOf(g),bottom:g.bottom-b.top,rtl}}function measureObjects(){const host=gridHost;const objects=objectsNow();if(!host||!objects.length){objectBoxes={};return}const b=host.getBoundingClientRect();const edges=paneEdges(host,b);const freeze=doc.get(wb.active).freeze;const next={};for(const object of objects){const td=host.querySelector(`td[data-svgrid-row="${object.anchor.row}"][data-svgrid-col="${object.anchor.col}"]`);if(!td)continue;const a=td.getBoundingClientRect();const box={left:startOf(a,b)+object.anchor.dx,top:a.top-b.top+object.anchor.dy,width:object.anchor.width,height:object.anchor.height};const pane=paneOf(object.anchor,freeze);let clip=null;if(edges){const cut=paneClip(pane,box,edges);if(cut.start||cut.top||cut.end||cut.bottom){const side=n=>n>0?`${n}px`:"-12px";const[left,right]=edges.rtl?[cut.end,cut.start]:[cut.start,cut.end];clip=`inset(${side(cut.top)} ${side(right)} ${side(cut.bottom)} ${side(left)})`}}next[object.id]={...box,frozen:pane!=="body",clip}}objectBoxes=next}$effect(()=>{void version;void activeObjects;if(!activeObjects.length){objectBoxes={};return}void tick().then(()=>requestAnimationFrame(measureObjects))});$effect(()=>{const host=gridHost;if(!host||!activeObjects.length)return;let frame=0;const rows=new MutationObserver(()=>{if(frame||activeObjects.every(o=>objectBoxes[o.id]))return;frame=requestAnimationFrame(()=>{frame=0;measureObjects()})});rows.observe(host,{childList:true,subtree:true});return()=>{rows.disconnect();cancelAnimationFrame(frame)}});const peersHere=$derived.by(()=>presenceOnSheet(livePresence(presence??[]),wb.active));let peerBoxes=$state({});function measurePeers(){const host=gridHost;if(!host||!peersHere.length){peerBoxes={};return}const b=host.getBoundingClientRect();const cellBox=(row,col)=>host.querySelector(`td[data-svgrid-row="${row}"][data-svgrid-col="${col}"]`)?.getBoundingClientRect()??null;const headerBottom=host.querySelector("thead")?.getBoundingClientRect().bottom??b.top;const TAG_HEIGHT=20;const next={};for(const person of peersHere){const[r1,c1,r2,c2]=person.rect;const first=cellBox(r1,c1);const last=cellBox(r2,c2)??first;if(!first||!last)continue;const left=Math.min(startOf(first,b),startOf(last,b));const top=Math.min(first.top,last.top)-b.top;const width=Math.max(startOf(first,b)+first.width,startOf(last,b)+last.width)-left;const height2=Math.max(first.bottom,last.bottom)-b.top-top;const anchor=presenceAnchor(person);const tag=cellBox(anchor.row,anchor.col)??first;const tagBelow=tag.top-headerBottom<TAG_HEIGHT;next[person.id]={left,top,width,height:height2,tagLeft:startOf(tag,b),tagTop:(tagBelow?tag.bottom:tag.top)-b.top,tagBelow}}peerBoxes=next}$effect(()=>{void version;void peersHere;if(!peersHere.length){peerBoxes={};return}void tick().then(()=>requestAnimationFrame(measurePeers))});function reportPresence(){if(!onPresence)return;const rects=selection.length?selection.map(normalRect):[];const rect=rects[rects.length-1]??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];onPresence({sheet:wb.active,rect,active:{row:active.rowIndex,col:active.colIndex}})}function onObjectPointerDown(event,object,kind){if(event.button!==0)return;if(protectedNow()){refuse();return}event.preventDefault();event.stopPropagation();selectedObject=object.id;dragging={id:object.id,kind,x:event.clientX,y:event.clientY,anchor:{...object.anchor}};event.currentTarget.setPointerCapture(event.pointerId)}function onObjectPointerMove(event){const drag=dragging;if(!drag)return;const dx=event.clientX-drag.x;const dy=event.clientY-drag.y;const object=objectsNow().find(o=>o.id===drag.id);if(!object)return;const box=objectBoxes[drag.id];if(!box)return;if((dx||dy)&&draggingObject!==drag.id)draggingObject=drag.id;objectBoxes={...objectBoxes,[drag.id]:drag.kind==="move"?{...box,left:box.left+(sheetIsRtl()?-(event.movementX||0):event.movementX||0),top:box.top+(event.movementY||0)}:{...box,width:Math.max(80,drag.anchor.width+(sheetIsRtl()?-dx:dx)),height:Math.max(60,drag.anchor.height+dy)}}}function onObjectPointerCancel(){dragging=null;draggingObject=null;measureObjects()}function onObjectPointerUp(event){const drag=dragging;dragging=null;if(!drag)return;if(draggingObject){draggingObject=null;void tick().then(measureObjects)}const object=objectsNow().find(o2=>o2.id===drag.id);const box=objectBoxes[drag.id];if(!object||!box)return;if(event.clientX===drag.x&&event.clientY===drag.y)return;if(drag.kind==="resize"){const width=Math.round(box.width);const height2=Math.round(box.height);if(width===object.anchor.width&&height2===object.anchor.height)return;replaceObject({...copyObject(object),anchor:{...object.anchor,width,height:height2}});return}const host=gridHost;if(!host)return;const b=host.getBoundingClientRect();const rtl=sheetIsRtl();const corner=xOfStart(box.left,b)+(rtl?-1:1);const under=host.ownerDocument.elementsFromPoint(corner,b.top+box.top+1).find(el=>el instanceof HTMLElement&&el.matches("td[data-svgrid-row]"));const anchor={...object.anchor};if(under){const a=under.getBoundingClientRect();anchor.row=Number(under.dataset.svgridRow);anchor.col=Number(under.dataset.svgridCol);anchor.dx=Math.round(box.left-startOf(a,b));anchor.dy=Math.round(b.top+box.top-a.top)}else{anchor.dx=Math.round(anchor.dx+(box.left-(objectBoxes[drag.id]?.left??box.left)))}const o=object.anchor;if(anchor.row===o.row&&anchor.col===o.col&&anchor.dx===o.dx&&anchor.dy===o.dy)return;replaceObject({...copyObject(object),anchor})}function insertChart(cmd){if(protectedNow()){refuse();return}const rect=blockAround(cmd);if(!rect||rect[0]===rect[2]&&rect[1]===rect[3]){say(t("selectBlockToChart"));return}addObject(chartFromRange(rect,(r,c)=>wb.getValue(wb.active,r,c)))}async function pictureAsPng(src,width,height2){const image=new Image;await new Promise((resolve,reject)=>{image.onload=()=>resolve();image.onerror=()=>reject(new Error("decode failed"));image.src=src});const vector=/^data:image\/svg\+xml/i.test(src);const natural={w:image.naturalWidth||width,h:image.naturalHeight||height2};const scale=vector?Math.max(1,width*2/natural.w,height2*2/natural.h):1;const canvas=document.createElement("canvas");canvas.width=Math.max(1,Math.round(natural.w*scale));canvas.height=Math.max(1,Math.round(natural.h*scale));const context=canvas.getContext("2d");if(!context)throw new Error("no canvas");context.drawImage(image,0,0,canvas.width,canvas.height);return canvas.toDataURL("image/png")}async function insertPicture(file){if(protectedNow()){refuse();return}let src=await new Promise((resolve,reject)=>{const reader=new FileReader;reader.onload=()=>resolve(String(reader.result??""));reader.onerror=()=>reject(reader.error??new Error("read failed"));reader.readAsDataURL(file)});if(!xlsxCanCarryPicture(src)){try{src=await pictureAsPng(src,240,180)}catch{}}addObject({id:objectId(),kind:"image",anchor:{row:active.rowIndex,col:active.colIndex,dx:8,dy:8,width:240,height:180},src,alt:file.name??""})}async function pickedPicture(event){const input=event.currentTarget;const file=input.files?.[0];input.value="";if(!file)return;try{await insertPicture(file)}catch{say(t("couldNotReadPicture"))}}const pageSetupNow=()=>doc.get(wb.active).pageSetup;const pageSetupState=$derived.by(()=>{void version;return pageSetupNow()});let pageSetupOpen=$state(false);function setPageSetup(next){const sheet=wb.active;const before=copyPageSetup(doc.get(sheet).pageSetup);const after=copyPageSetup(next);const put=value=>{doc.get(sheet).pageSetup=copyPageSetup(value);bump();changed({kind:"page-setup"})};put(after);cmdOf()?.recordUndo(()=>put(before),()=>put(after))}const PAPER_ACTIONS={"paper-a4":"A4","paper-a3":"A3","paper-a5":"A5","paper-letter":"Letter","paper-legal":"Legal","paper-tabloid":"Tabloid"};const selectionText=$derived.by(()=>{void selection;void active;return rangeText(selectedRects().map(normalRect))});function stashWidths(name=wb.active){if(!api)return;doc.get(name).widths={...api.getColumnWidths()}}function applyWidths(name=wb.active){if(!api)return;const saved=doc.get(name).widths;for(let c=0;c<colCount;c+=1){const letter=colToLetters(c);api.setColumnWidth(letter,saved[letter]??columnWidths?.[letter]??columnWidth)}}function ownRowHeights(keep=new Map){const out=new Map;if(!api)return out;for(let r=0;r<rowCount;r+=1){if(api.isRowCollapsed(r)){const before=keep.get(r);if(before!==void 0)out.set(r,before);continue}const h=api.getRowHeight(r);if(h!==rowHeight)out.set(r,h)}return out}function stashHeights(name=wb.active){if(!api)return;doc.get(name).heights=ownRowHeights(doc.get(name).heights)}function applyHeights(name=wb.active){if(!api)return;const saved=doc.get(name).heights;for(let r=0;r<rowCount;r+=1)api.setRowHeight(r,saved.get(r)??null)}const activeGridSheet=$derived.by(()=>{void version;const state=doc.get(wb.active);return state.kind==="grid"?state.grid??null:null});const gridSheetColumns=$derived.by(()=>{const spec=activeGridSheet;if(!spec)return[];return spec.fields.map(field=>({id:field.field,field:field.field,header:field.label??field.field,...field.width!==void 0?{width:field.width}:{},editable:field.editable??spec.editable===true,...field.type==="number"?{align:"right"}:{}}))});function projectGridSheetInto(name,spec){const cells=projectGridSheet(spec);for(let r=0;r<cells.length;r+=1){const line=cells[r];for(let c=0;c<line.length;c+=1)wb.setRaw(name,r,c,line[c])}}function projectActiveGridSheet(){const spec=activeGridSheet;if(spec)projectGridSheetInto(wb.active,spec)}function onBoundGridReady(next){onReady?.(next,doc)}function onGridSheetEdit(change){const spec=activeGridSheet;if(!spec)return;const record=spec.rows[change.rowIndex];const field=spec.fields.find(f=>f.field===change.columnId);if(!record||!field)return;record[field.field]=coerceFieldValue(field,change.newValue);projectActiveGridSheet();changed({kind:"cells"});bump()}function cellTypeHere(r,c){void version;return cellTypeAt(doc.get(wb.active).cellTypes,r,c)}function setCellText(r,c,text){if(locked(r,c)){refuse();return}const cmd=cmdOf();if(cmd)cmd.batch(()=>cmd.setCellValue(r,c,text));else{wb.setRaw(wb.active,r,c,text);bump()}}function toggleCheckbox(r,c){const region=cellTypeHere(r,c);if(!region)return;setCellText(r,c,toggledValue(region,raw(r,c)))}function pressCellButton(r,c,region){onCellAction?.({row:r,col:c,action:region.action??region.id,sheet:wb.active})}const cellAddress=(r,c)=>`${colToLetters(c)}${r+1}`;function selectedLines(axis2,cmd){const rects=cmd.ranges.length?cmd.ranges:cmd.activeCell?[[cmd.activeCell.rowIndex,cmd.activeCell.colIndex,cmd.activeCell.rowIndex,cmd.activeCell.colIndex]]:[];if(!rects.length)return null;let from=Infinity;let to=-Infinity;for(const[r1,c1,r2,c2]of rects){from=Math.min(from,axis2==="rows"?r1:c1);to=Math.max(to,axis2==="rows"?r2:c2)}return Number.isFinite(from)&&to>=0?{from,to}:null}function summaryLineFor(state,line){const side={summaryBelow:true};if(detailRange(state,line,side))return line;const own=outlineLevel(state,line);if(own===0)return null;let at=line;while(outlineLevel(state,at+1)>=own)at+=1;return detailRange(state,at+1,side)?at+1:null}function afterOutlineChange(){const state=doc.get(wb.active);applyHidden(state.hidden,state.filterHidden);changed({kind:"hidden"});bump()}function outlineHidden(name=wb.active){const state=doc.get(name);return{rows:hiddenByOutline(state.outline.rows,{summaryBelow:true}),cols:hiddenByOutline(state.outline.cols,{summaryBelow:true})}}function ownHidden(){const out={rows:new Set,cols:new Set};if(!api)return out;const filtered=doc.get(wb.active).filterHidden;const outlined=outlineHidden();for(let r=0;r<rowCount;r+=1)if(api.isRowCollapsed(r)&&!filtered.has(r)&&!outlined.rows.has(r))out.rows.add(r);for(let c=0;c<colCount;c+=1)if(api.isColumnCollapsed(colToLetters(c))&&!outlined.cols.has(c))out.cols.add(c);return out}function applyHidden(hidden,filtered=new Set){if(!api)return;const outlined=outlineHidden();for(let r=0;r<rowCount;r+=1)api.setRowCollapsed(r,hidden.rows.has(r)||filtered.has(r)||outlined.rows.has(r));for(let c=0;c<colCount;c+=1)api.setColumnCollapsed(colToLetters(c),hidden.cols.has(c)||outlined.cols.has(c))}function stashHidden(name=wb.active){if(!api)return;doc.get(name).hidden=ownHidden()}function stashLive(name=wb.active){stashWidths(name);stashHeights(name);stashHidden(name)}function applyLive(name=wb.active){applyWidths(name);applyHeights(name);const state=doc.get(name);state.filterHidden=hiddenRowsFor(state.autoFilter,(r,c)=>wb.getValue(name,r,c),(r,c)=>displayOn(name,r,c));applyHidden(state.hidden,state.filterHidden)}function hideLines(axis2,hide,cmd){if(!api)return;if(!allowNow(lineKey(axis2))){refuse();return}const count=axis2==="rows"?rowCount:colCount;const isHidden=i=>axis2==="rows"?api.isRowCollapsed(i):api.isColumnCollapsed(colToLetters(i));const setHidden=(i,on)=>axis2==="rows"?api.setRowCollapsed(i,on):api.setColumnCollapsed(colToLetters(i),on);const rects=cmd.ranges.length?cmd.ranges:cmd.activeCell?[[cmd.activeCell.rowIndex,cmd.activeCell.colIndex,cmd.activeCell.rowIndex,cmd.activeCell.colIndex]]:[];const targets=new Set;let lo=count,hi=-1;for(const[r1,c1,r2,c2]of rects){const from=axis2==="rows"?r1:c1;const to=Math.min(axis2==="rows"?r2:c2,count-1);lo=Math.min(lo,from);hi=Math.max(hi,to);for(let i=from;i<=to;i+=1)if(isHidden(i)!==hide)targets.add(i)}if(!hide&&targets.size===0&&hi>=0){for(let i=lo-1;i>=0&&isHidden(i);i-=1)targets.add(i);for(let i=hi+1;i<count&&isHidden(i);i+=1)targets.add(i)}if(axis2==="rows"&&!hide)for(const r of doc.get(wb.active).filterHidden)targets.delete(r);if(targets.size===0){say(t(hide?"nothingToHide":"nothingHidden"));return}const apply=on=>{for(const i of targets)setHidden(i,on);stashHidden();tellWorkbookWhatIsHidden();bump();changed({kind:"hidden"})};apply(hide);cmd.recordUndo(()=>apply(!hide),()=>apply(hide));if(hide&&cmd.activeCell){const at=axis2==="rows"?cmd.activeCell.rowIndex:cmd.activeCell.colIndex;if(isHidden(at)){let next=hi+1;while(next<count&&isHidden(next))next+=1;if(next>=count){next=lo-1;while(next>=0&&isHidden(next))next-=1}if(next>=0){const r=axis2==="rows"?next:cmd.activeCell.rowIndex;const c=axis2==="rows"?cmd.activeCell.colIndex:next;cmd.setActiveCell(r,c);cmd.setSelection(r,c)}}}const unit=axis2==="rows"?targets.size===1?"unitRow":"unitRows":targets.size===1?"unitColumn":"unitColumns";say(t("linesToggled",{count:targets.size,unit:t(unit),state:t(hide?"stateHidden":"stateShown")}))}let targetsBoundTo="";function registerSheetTargets(){if(targetsBoundTo&&targetsBoundTo!==wb.active){if(doc.has(targetsBoundTo))stashLive(targetsBoundTo);applyLive(wb.active);const cmd=cmdOf();if(cmd)applyFreeze(cmd,doc.get(wb.active).freeze)}targetsBoundTo=wb.active;api?.setHistoryTag(doc.get(wb.active));const store=storeFor();setFormatTarget({store,lookup,onChange:()=>{bump();fitWrappedRows();changed({kind:"formats"})},guard:rects=>allowNow("formatCells")||!rectsHaveLocked(store,lookup,rects,protectionNow().ranges),refused:refuse});tellWorkbookWhatIsHidden();setStructureTarget({canApply:edit=>allowNow(edit.kind==="insertRows"?"insertRows":edit.kind==="insertCols"?"insertColumns":edit.kind==="deleteRows"?"deleteRows":"deleteColumns"),refused:refuse,getRaw:(r,c)=>wb.getRaw(wb.active,r,c),setRaw:(r,c,text)=>wb.setRaw(wb.active,r,c,text),apply:edit=>{const sheet=wb.active;stashLive(sheet);doc.shift(sheet,edit);wb.applyStructuralEdit(sheet,edit);applyLive(sheet);marquee=null;changed({kind:"structure",sheet,edit})},rewritesReferences:true,names:wb.names,format:{store,lookup},onChange:bump,snapshot:()=>getState(),restore:state=>{doc.setState(state);targetsBoundTo=wb.active;registerSheetTargets();applyLive(wb.active)}})}const me={};function ensureShortcuts(){if(getShortcutOwner()!==me)claimShortcuts()}function releaseShortcuts(){if(getShortcutOwner()!==me)return;setShortcutOwner(null);setWorkbook(null);setFormatTarget(null);setStructureTarget(null);setFindTarget(null);setFillTranslator(null);setSheetValueProbe(null);setFindReplaceHandler(null);setFormatDialogHandler(null);setPasteSpecialHandler(null);setRibbonActionHandler(null)}function claimShortcuts(){setShortcutOwner(me);setWorkbook(wb,()=>{active={rowIndex:0,colIndex:0};bump()},name=>doc.get(name).sheetHidden);registerSheetTargets();setFindTarget({getRaw:(r,c)=>wb.getRaw(wb.active,r,c),getDisplay:(r,c)=>display(r,c).text,setRaw:(r,c,text)=>{const cmd=cmdOf();if(cmd)cmd.setCellValue(r,c,text);else wb.setRaw(wb.active,r,c,text)},isEditable:(r,c)=>!locked(r,c),onChange:bump});setFillTranslator((value,delta)=>typeof value==="string"&&value.startsWith("=")?translateFormula(value,delta.rows,delta.cols):value);setFindReplaceHandler(context=>delegate("find-replace",context));setFormatDialogHandler(context=>delegate("format-cells",context));setPasteSpecialHandler(context=>delegate("paste-special",context));setRibbonActionHandler((action,context)=>{handleAction(action,context);return true});setSheetValueProbe((r,c)=>wb.getValue(wb.active,r,c))}$effect(()=>{void wb;claimShortcuts();return releaseShortcuts});function raw(r,c){void version;return wb.getRaw(wb.active,r,c)}function display(r,c,numFmt){void version;const text=raw(r,c);if(showFormulas)return{text};const value=wb.getValue(wb.active,r,c);if(isError(value))return{text:value.error,color:"var(--sg-danger, #dc2626)"};const entry=storeFor().get(`r${r}`,colToLetters(c));const fmt=numFmt??entry?.numFmt;if(fmt)return compileNumberFormat(fmt,marks).format(value);if(value===""||value==null)return{text:""};if(typeof value==="boolean")return{text:value?"TRUE":"FALSE"};if(typeof value==="number")return{text:numberToCulture(String(value))};return{text:String(value)}}let hashMeasure=null;function hashesFor(text,c,entry,r=-1,general){if(!text)return null;if(typeof document==="undefined")return null;hashMeasure??=document.createElement("canvas").getContext("2d");if(!hashMeasure)return null;const size=entry?.fontSize??13;const family=entry?.fontFamily||(root?getComputedStyle(root).fontFamily:"sans-serif");hashMeasure.font=`${entry?.bold?"bold ":""}${size}px ${family}`;const width=(r>=0?cellWidth(r,c):widthOf(c))-9;const fits=s=>hashMeasure.measureText(s).width<=width;if(fits(text))return null;if(general!==void 0&&Number.isFinite(general)){const decimals=(text.split(".")[1]??"").length;for(let d=decimals-1;d>=0;d-=1){const s=String(Number(general.toFixed(d)));if(fits(s))return s}for(let m=5;m>=0;m-=1){const[mantissa,exp]=general.toExponential(m).split("e");const e=Number(exp);const s=`${mantissa}E${e<0?"-":"+"}${String(Math.abs(e)).padStart(2,"0")}`;if(fits(s))return s}}const hash=hashMeasure.measureText("#").width||8;return"#".repeat(Math.max(1,Math.floor(width/hash)))}const activeRaw=$derived.by(()=>{void version;return raw(active.rowIndex,active.colIndex)});function spillWidth(r,c,value,entry){if(typeof value!=="string"||value===""||entry?.wrap)return 0;if(sheetMergeAt(mergesNow(),r,c))return 0;if(entry?.align==="right"||entry?.align==="center")return 0;const fill=entry?.fill??"";const store=storeFor();let extra=0;for(let next=c+1;next<colCount;next+=1){if(wb.getRaw(wb.active,r,next)!=="")break;if((store.get(`r${r}`,colToLetters(next))?.fill??"")!==fill)break;extra+=widthOf(next)}return extra}function commit(raw2,cell,via="enter"){const text=fromCulture(raw2);if(locked(cell.rowIndex,cell.colIndex)){refuse();return}if(!admits(cell.rowIndex,cell.colIndex,text))return;const cmd=cmdOf();if(cmd){cmd.batch(()=>cmd.setCellValue(cell.rowIndex,cell.colIndex,balanceParens(text)));if(via==="enter"){const next=Math.min(cell.rowIndex+1,rowCount-1);cmd.setActiveCell(next,cell.colIndex);cmd.setSelection(next,cell.colIndex);cmd.scrollIntoView(next,cell.colIndex);focusSheet(cmd)}return}wb.setRaw(wb.active,cell.rowIndex,cell.colIndex,balanceParens(text));bump()}function goTo(cell){const cmd=cmdOf();if(!cmd)return;cmd.setActiveCell(cell.rowIndex,cell.colIndex);cmd.setSelection(cell.rowIndex,cell.colIndex);cmd.scrollIntoView(cell.rowIndex,cell.colIndex);active=cell;cmd.focus()}function defineNameHere(name){if(!isValidName(name)){say(t("nameBoxBadName",{name}));cmdOf()?.focus();return}const rects=selectedRects().map(normalRect);const[r1,c1,r2,c2]=rects[rects.length-1]??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];const cellRef=(r,c)=>`${colToLetters(c)}${r+1}`;const refersTo=`${quoteSheet(wb.active)}!${cellRef(r1,c1)}${r1===r2&&c1===c2?"":`:${cellRef(r2,c2)}`}`;const put=value=>{if(value===null)wb.names.remove(name);else wb.names.define(name,value);wb.recalculate();doc.changed({kind:"workbook"});bump()};put(refersTo);const cmd=cmdOf();cmd?.recordUndo(()=>put(null),()=>put(refersTo));say(t("nameDefined",{name,refersTo:refersTo.replace(/^.*!/,"")}));cmd?.focus()}async function jumpToName(name){const node=wb.names.resolve(name);if(node)await selectNode(node)}function jumpToReference(text){let node;try{node=parseFormula(`=${text}`)}catch{return false}if(node.k!=="ref"&&node.k!=="range")return false;void selectNode(node);return true}async function selectNode(node){const from=node.k==="ref"?node.ref:node.k==="range"?node.from:null;const to=node.k==="range"?node.to:from;if(!from||from.row===null)return;const target=from.sheet??wb.active;if(target.toLowerCase()!==wb.active.toLowerCase()){if(!wb.sheets.some(s=>s.toLowerCase()===target.toLowerCase()))return;wb.setActive(target);bump();await tick()}const cmd=api?.getCommandContext();if(!cmd)return;cmd.setActiveCell(from.row,from.col);cmd.setSelection(from.row,from.col);if(to&&to.row!==null&&(to.row!==from.row||to.col!==from.col)){cmd.extendSelection(to.row,to.col)}cmd.scrollIntoView(from.row,from.col);active={rowIndex:from.row,colIndex:from.col};cmd.focus()}function lineHidden(r,c){const state=doc.get(wb.active);return state.hidden.rows.has(r)||state.filterHidden.has(r)||state.hidden.cols.has(c)}const aggregate=$derived.by(()=>{void version;const rects=selection.length?selection:[[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex]];let count=0;let numeric=0;let sum=0;for(const[minRow,minCol,maxRow,maxCol]of rects){for(let r=minRow;r<=maxRow;r+=1){for(let c=minCol;c<=maxCol;c+=1){if(lineHidden(r,c))continue;const value=wb.getValue(wb.active,r,c);if(value===""||value==null||isError(value))continue;count+=1;if(typeof value==="number"){numeric+=1;sum+=value}}}}return{count,numeric,sum,average:numeric?sum/numeric:null}});const money=n=>n.toLocaleString(localization?.locale??"en-US",{maximumFractionDigits:2});let root=$state(null);$effect(()=>{void version;const rects=selection.length?selection:[[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex]];const cols=new Set;for(const rect of rects){const[,minCol,,maxCol]=expandToMerges(mergesNow(),[rect[0],rect[1],rect[2],rect[3]]);for(let c=minCol;c<=maxCol;c+=1)cols.add(colToLetters(c))}const host=root;if(!host)return;const wholeCols=new Set;const wholeRows=new Set;for(const rect of rects){const[r1,c1,r2,c2]=expandToMerges(mergesNow(),[rect[0],rect[1],rect[2],rect[3]]);if(r1===0&&r2>=rowCount-1)for(let c=c1;c<=c2;c+=1)wholeCols.add(colToLetters(c));if(c1===0&&c2>=colCount-1)for(let r=r1;r<=r2;r+=1)wholeRows.add(r)}const paint=()=>{for(const th of host.querySelectorAll("th[data-svgrid-header-col]")){const letter=th.dataset.svgridHeaderCol??"";th.classList.toggle("sheet-col-selected",cols.has(letter));th.classList.toggle("sheet-col-whole",wholeCols.has(letter))}for(const td of host.querySelectorAll("td.sv-grid-row-number-cell")){const row=td.parentElement?.querySelector("td[data-svgrid-row]")?.dataset.svgridRow;td.classList.toggle("sheet-row-whole",row!==void 0&&wholeRows.has(Number(row)))}};const frame=requestAnimationFrame(paint);return()=>cancelAnimationFrame(frame)});const features=tableFeatures({});const columns=$derived.by(()=>Array.from({length:colCount},(_,c)=>({id:colToLetters(c),field:colToLetters(c),header:colToLetters(c),width:columnWidths?.[colToLetters(c)]??columnWidth,headerAlign:"center",editable:ctx=>!locked(ctx.row.original.index,c)&&!covered(ctx.row.original.index,c),tooltip:ctx=>{const thread=threadAt(notesNow(),ctx.row.original.index,c);return thread?threadText(thread):null},valueParser:params=>admits(params.data.index,c,params.rawInput)?params.newValue:params.oldValue,editorType:"text",editorMultiline:true,cell:ctx=>renderSnippet(Cell,{r:ctx.row.original.index,c})})));function cmdOf(){return api?api.getCommandContext():null}function sheetOfTag(tag){if(!tag)return null;return wb.sheets.find(name=>doc.get(name)===tag)??null}function historyIsElsewhere(direction){const next=direction==="undo"?api?.peekUndo():api?.peekRedo();if(!next)return false;const sheet=sheetOfTag(next.tag);return sheet!==null&&sheet.toLowerCase()!==wb.active.toLowerCase()}async function undoRedo(direction){const a=api;if(!a)return false;const next=direction==="undo"?a.peekUndo():a.peekRedo();if(!next)return false;const sheet=sheetOfTag(next.tag);if(sheet!==null&&sheet.toLowerCase()!==wb.active.toLowerCase()){wb.setActive(sheet);bump();await tick()}const done=direction==="undo"?a.undo():a.redo();cmdOf()?.focus();return done}function handleAction(action,context){switch(action){case"recalculate":wb.recalculate();bump();return;case"toggle-formulas":showFormulas=!showFormulas;bump();return;case"toggle-gridlines":if(onAction?.(action,context)===true)return;gridlinesOn=!gridlinesOn;focusSheet(context);return;case"toggle-formula-bar":if(onAction?.(action,context)===true)return;formulaBarOn=!formulaBarOn;focusSheet(context);return;case"toggle-headings":if(onAction?.(action,context)===true)return;headingsOn=!headingsOn;focusSheet(context);return;case"toggle-ribbon":if(onAction?.(action,context)===true)return;ribbonCollapsed=!ribbonCollapsed;focusSheet(context);return;case"toggle-filter":if(onAction?.(action,context)===true)return;toggleAutoFilter(context);focusSheet(context);return;case"sort-asc":case"sort-desc":if(onAction?.(action,context)===true)return;sortRegion(action==="sort-asc"?"asc":"desc");return;case"paste-values":case"paste-formulas":case"paste-formats":case"paste-transpose":if(onAction?.(action,context)===true)return;void pasteSpecial(action==="paste-transpose"?{transpose:true}:{what:action.slice("paste-".length)});return;case"format-painter":if(onAction?.(action,context)===true)return;if(painter)painter=null;else armPainter();focusSheet(context);return;case"row-height":case"column-width":if(onAction?.(action,context)===true)return;openSizeDialog(action==="row-height"?"rows":"cols");return;case"protect-sheet":if(onAction?.(action,context)===true)return;protectSheetOpen=true;return;case"unprotect-sheet":if(onAction?.(action,context)===true)return;setProtected(false,context);focusSheet(context);return;case"allow-edit-ranges":if(onAction?.(action,context)===true)return;editRangesOpen=true;return;case"new-comment":case"edit-comment":if(onAction?.(action,context)===true)return;openCommentEditor(active.rowIndex,active.colIndex);return;case"delete-comment":if(onAction?.(action,context)===true)return;if(cellPopover)closeCellPopover(false);if(commentAt(notesNow(),active.rowIndex,active.colIndex)!==void 0)setComment(active.rowIndex,active.colIndex,"");focusSheet(context);return;case"prev-comment":case"next-comment":if(onAction?.(action,context)===true)return;walkComments(action==="next-comment"?1:-1);return;case"toggle-comments":if(onAction?.(action,context)===true)return;showComments=!showComments;focusSheet(context);return;case"open-list":if(onAction?.(action,context)===true)return;if(filterArrowAt(active.rowIndex,active.colIndex)){openFilterMenu(active.colIndex);return}openListPicker(active.rowIndex,active.colIndex);return;case"cf-greater":case"cf-less":case"cf-between":case"cf-equal":case"cf-text":case"cf-duplicates":case"cf-top10":case"cf-bottom10":case"cf-above-average":case"cf-below-average":case"cf-data-bar":case"cf-color-scale-3":case"cf-color-scale-2":case"cf-icon-set":case"cf-formula":case"cf-clear-selection":case"cf-clear-sheet":case"cf-manage":if(onAction?.(action,context)===true)return;cfAction(action,context);return;case"merge-center":case"merge-across":case"merge-cells":if(onAction?.(action,context)===true)return;runMerge(action==="merge-center"?"center":action==="merge-across"?"across":"cells",context);return;case"unmerge-cells":if(onAction?.(action,context)===true)return;runUnmerge(context);return;case"toggle-lock":{if(onAction?.(action,context)===true)return;const wasLocked=isLocked(storeFor().get(`r${active.rowIndex}`,colToLetters(active.colIndex)));applyFormat(context,{locked:wasLocked?false:void 0});focusSheet(context);return}case"autofit-rows":case"autofit-columns":if(onAction?.(action,context)===true)return;autofitLines(action==="autofit-rows"?"rows":"cols",context);focusSheet(context);return;case"hide-rows":case"hide-columns":case"unhide-rows":case"unhide-columns":{if(onAction?.(action,context)===true)return;hideLines(action.endsWith("rows")?"rows":"cols",action.startsWith("hide"),context);focusSheet(context);return}case"group-rows":case"group-cols":case"ungroup-rows":case"ungroup-cols":{if(onAction?.(action,context)===true)return;const axis2=action.endsWith("rows")?"rows":"cols";const span=selectedLines(axis2,context);if(!span){say(t("selectLinesToGroup"));return}const state=doc.get(wb.active);const change=action.startsWith("group")?groupLines:ungroupLines;state.outline=axis2==="rows"?{rows:change(state.outline.rows,span.from,span.to),cols:state.outline.cols}:{rows:state.outline.rows,cols:change(state.outline.cols,span.from,span.to)};afterOutlineChange();focusSheet(context);return}case"insert-checkbox":case"insert-cell-button":case"clear-cell-type":{if(onAction?.(action,context)===true)return;const rects=context.ranges.length?context.ranges.map(r=>[...r]):context.activeCell?[[context.activeCell.rowIndex,context.activeCell.colIndex,context.activeCell.rowIndex,context.activeCell.colIndex]]:[];if(!rects.length){say(t("selectCellsForControl"));return}const state=doc.get(wb.active);if(action==="clear-cell-type"){state.cellTypes=removeCellTypes(state.cellTypes,rects)}else{const kind=action==="insert-checkbox"?"checkbox":"button";state.cellTypes=applyCellType(state.cellTypes,{id:newCellTypeId(),kind,rects})}changed({kind:"validation"});bump();focusSheet(context);return}case"clear-outline":{if(onAction?.(action,context)===true)return;const state=doc.get(wb.active);state.outline={rows:clearOutline(),cols:clearOutline()};afterOutlineChange();focusSheet(context);return}case"auto-outline":{if(onAction?.(action,context)===true)return;const state=doc.get(wb.active);const isSummary=r=>{for(let c=0;c<colCount;c+=1)if(raw(r,c).startsWith("="))return true;return false};state.outline={rows:autoOutline(0,rowCount-1,isSummary,{summaryBelow:true}),cols:state.outline.cols};afterOutlineChange();focusSheet(context);return}case"show-detail":case"hide-detail":{if(onAction?.(action,context)===true)return;const wanted=action==="hide-detail";const state=doc.get(wb.active);const row=context.activeCell?.rowIndex??0;const summary=summaryLineFor(state.outline.rows,row);if(summary===null){say(t("noGroupHere"));return}const already=state.outline.rows.collapsed.includes(summary);if(already!==wanted){state.outline={rows:toggleCollapsed(state.outline.rows,summary),cols:state.outline.cols};afterOutlineChange()}focusSheet(context);return}case"freeze-panes":case"freeze-top-row":case"freeze-first-column":case"unfreeze-panes":{if(onAction?.(action,context)===true)return;const before=doc.get(wb.active).freeze;const put=state2=>{applyFreeze(context,state2);doc.get(wb.active).freeze=state2;changed({kind:"freeze"})};const state=action==="freeze-panes"?freezeAtActiveCell(context):action==="freeze-top-row"?freezeTopRow(context):action==="freeze-first-column"?freezeFirstColumn(context):applyFreeze(context,{rows:0,cols:0});doc.get(wb.active).freeze=state;changed({kind:"freeze"});context.recordUndo(()=>put(before),()=>put(state));focusSheet(context);return}default:delegate(action,context)}}const without=$derived.by(()=>{const out=[];out.push(isProtected?"protect-sheet":"unprotect-sheet");return out});function sortBlock(over){const cmd=cmdOf();if(!cmd||!cmd.activeCell)return null;const last=selection[selection.length-1];const isRange=last&&(last[0]!==last[2]||last[1]!==last[3]);const chosen=over?over.rect:isRange?last:currentRegion(gridOf(cmd),{row:active.rowIndex,col:active.colIndex});const top=chosen[0];const left=chosen[1];const bottom=Math.min(chosen[2],Math.max(wb.rowCount(wb.active)-1,top));const right=Math.min(chosen[3],Math.max(wb.colCount(wb.active)-1,left));if(over)return{top,left,bottom,right};const rect=expandToMerges(mergesNow(),[top,left,bottom,right]);return{top:rect[0],left:rect[1],bottom:rect[2],right:rect[3]}}function sortRegion(direction,over){const block=sortBlock(over);if(!block)return;const keyCol=Math.min(Math.max(over?.keyCol??active.colIndex,block.left),block.right);const headerRow=over?true:guessHeaderRow((r,c)=>wb.getValue(wb.active,r,c),block.top,keyCol,block);sortBy(block,[{col:keyCol,direction}],headerRow)}function sortBy(block,keys,headerRow){const cmd=cmdOf();const target=getFormatTarget();if(!cmd||!cmd.activeCell||!target||!keys.length)return;const r1=block.top;const c1=block.left;const r2=block.bottom;const c2=block.right;if(r2<=r1)return;if(!allowNow("sort")||protectedNow()&&rectsHaveLocked(storeFor(),lookup,[[r1,c1,r2,c2]],protectionNow().ranges)){refuse();return}if(sortBlockedByMerges(mergesNow(),[r1,c1,r2,c2])){say(t("mergeSameSize"));return}const valueAt=(r,c)=>wb.getValue(wb.active,r,c);const start=headerRow?r1+1:r1;if(r2<=start)return;const span=Array.from({length:r2-start+1},(_,i)=>start+i);const rows=span.filter(r=>!lineHidden(r,c1));const skipped=span.length-rows.length;if(rows.length<2)return;const order=sortOrder(rows,keys,valueAt,colourOnActive);if(order.every((r,i)=>r===rows[i]))return;const store=target.store;const before=new Map(rows.map(r=>[r,{raw:Array.from({length:c2-c1+1},(_,i)=>wb.getRaw(wb.active,r,c1+i)),formats:Array.from({length:c2-c1+1},(_,i)=>store.get(`r${r}`,colToLetters(c1+i)))}]));const sheet=wb.active;const valueBefore=rows.map(row=>Array.from({length:c2-c1+1},(_,k)=>wb.getRaw(sheet,row,c1+k)));cmd.batch(()=>{withFormatUndo(cmd,target,[[start,c1,r2,c2]],()=>{order.forEach((source,i)=>{const row=rows[i];const from=before.get(source);for(let k=0;k<=c2-c1;k+=1){const c=c1+k;wb.setRaw(sheet,row,c,String(translateFormula(from.raw[k],row-source,0)??""));const one=[[row,c,row,c]];store.clear(one,target.lookup);if(from.formats[k])store.set(one,from.formats[k],target.lookup)}})});wb.recalculate();const valueAfter=rows.map(row=>Array.from({length:c2-c1+1},(_,k)=>wb.getRaw(sheet,row,c1+k)));const putValues=grid=>{rows.forEach((row,i)=>grid[i].forEach((text,k)=>wb.setRaw(sheet,row,c1+k,text)));wb.recalculate();bump();changed({kind:"cells"})};cmd.recordUndo(()=>putValues(valueBefore),()=>putValues(valueAfter));changed({kind:"cells"});if(mergesIn(mergesNow(),[[start,c1,r2,c2]]).length){const rowFor=oldRow=>{const i=order.indexOf(oldRow);return i<0?oldRow:rows[i]};setMerges(reorderMerges(mergesNow(),[start,c1,r2,c2],rowFor))}});if(skipped>0)say(t("sortKeptHidden",{count:skipped,unit:t(skipped===1?"unitRow":"unitRows")}));cmd.setSelection(r1,c1);cmd.extendSelection(r2,c2);bump();fitWrappedRows()}let statusMessage=$state(null);let statusTimer=null;function say(message){statusMessage=message;if(statusTimer)clearTimeout(statusTimer);statusTimer=setTimeout(()=>statusMessage=null,8e3)}let findOpen=$state(false);let pasteSpecialOpen=$state(false);let formatCellsOpen=$state(false);let insertFunctionOpen=$state(false);let nameManagerOpen=$state(false);let goalSeekOpen=$state(false);let iterationOpen=$state(false);let evaluateOpen=$state(false);let evaluateCell=$state({row:0,col:0});let errorsOpen=$state(false);let textToColumnsOpen=$state(false);let removeDuplicatesOpen=$state(false);let sortDialog=$state(null);function delegate(action,context){if(onAction?.(action,context)===true)return;switch(action){case"undo":void undoRedo("undo");return;case"delete-sheet":tabs?.deleteSheet(wb.active);return;case"redo":void undoRedo("redo");return;case"find-replace":findOpen=true;return;case"paste-special":void openPasteSpecial();return;case"format-cells":formatCellsOpen=true;return;case"insert-function":insertFunctionOpen=true;return;case"name-manager":nameManagerOpen=true;return;case"goal-seek":goalSeekOpen=true;return;case"calc-options":iterationOpen=true;return;case"evaluate-formula":evaluateCell={row:active.rowIndex,col:active.colIndex};evaluateOpen=true;return;case"cut":cutSelection(context);return;case"error-checking":errorsOpen=true;return;case"text-to-columns":textToColumnsOpen=true;return;case"remove-duplicates":removeDuplicatesOpen=true;return;case"sort-custom":{const block=sortBlock();if(!block||block.bottom<=block.top){say(t("selectBlockToSort"));return}const keyCol=Math.min(Math.max(active.colIndex,block.left),block.right);sortDialog={block,headerGuess:guessHeaderRow((r,c)=>wb.getValue(wb.active,r,c),block.top,keyCol,block)};return}case"data-validation":dataValidationOpen=true;return;case"file-new":if(documentHasContent())newConfirm=true;else newWorkbook();return;case"file-open":fileInput?.click();return;case"file-save-xlsx":void saveXlsx();return;case"file-save-ods":void saveOds();return;case"file-save-xls":saveXls();return;case"file-export-csv":{try{downloadBlobFile(new Blob([toCsv()],{type:"text/csv;charset=utf-8"}),`${wb.active}.csv`)}catch(e){say(e instanceof Error?e.message:t("couldNotExport"))}return}case"file-print":if(onAction?.(action,context)===true)return;print();return;case"page-portrait":case"page-landscape":if(onAction?.(action,context)===true)return;setPageSetup({...pageSetupNow(),orientation:action==="page-portrait"?"portrait":"landscape"});focusSheet(context);return;case"paper-a4":case"paper-a3":case"paper-a5":case"paper-letter":case"paper-legal":case"paper-tabloid":if(onAction?.(action,context)===true)return;setPageSetup({...pageSetupNow(),paper:PAPER_ACTIONS[action]});focusSheet(context);return;case"margins-normal":case"margins-narrow":case"margins-wide":if(onAction?.(action,context)===true)return;setPageSetup({...pageSetupNow(),margins:{...MARGIN_PRESETS[action.slice("margins-".length)]}});focusSheet(context);return;case"print-area-set":{if(onAction?.(action,context)===true)return;const rects=selectedRects(context).map(normalRect);setPageSetup({...pageSetupNow(),printArea:rects});say(t("printAreaSet",{range:rangeText(rects)}));focusSheet(context);return}case"print-area-clear":if(onAction?.(action,context)===true)return;setPageSetup({...pageSetupNow(),printArea:null});say(t("printAreaCleared"));focusSheet(context);return;case"print-gridlines":case"print-headings":if(onAction?.(action,context)===true)return;setPageSetup(action==="print-gridlines"?{...pageSetupNow(),gridlines:!pageSetupNow().gridlines}:{...pageSetupNow(),headings:!pageSetupNow().headings});focusSheet(context);return;case"print-titles":case"page-setup":if(onAction?.(action,context)===true)return;pageSetupOpen=true;return;case"insert-chart":if(onAction?.(action,context)===true)return;insertChart(context);return;case"insert-picture":if(onAction?.(action,context)===true)return;if(protectedNow()){refuse();return}imageInput?.click();return;case"chart-setup":{if(onAction?.(action,context)===true)return;if(protectedNow()){refuse();return}const object=objectsNow().find(o=>o.id===selectedObject);if(object?.kind==="chart")chartSetup=object;else say(t("selectChartFirst"));return}case"delete-object":{if(onAction?.(action,context)===true)return;if(protectedNow()){refuse();return}if(selectedObject)removeObject(selectedObject);return}case"sparkline-line":case"sparkline-column":case"sparkline-winloss":if(onAction?.(action,context)===true)return;startSparklines(action==="sparkline-line"?"line":action==="sparkline-column"?"column":"winloss");return;case"sparkline-setup":if(onAction?.(action,context)===true)return;setupSparklines();return;case"clear-sparklines":if(onAction?.(action,context)===true)return;clearSparklinesHere();return;case"insert-table":if(onAction?.(action,context)===true)return;insertTable();return;case"remove-table":if(onAction?.(action,context)===true)return;removeTableHere();return;case"table-style":if(onAction?.(action,context)===true)return;if(!tableHere()){say(t("noTableHere"));return}insertTable();return;case"insert-link":if(onAction?.(action,context)===true)return;insertLink();return;case"remove-link":if(onAction?.(action,context)===true)return;removeLinksIn();return;case"insert-pivot":if(onAction?.(action,context)===true)return;insertPivot();return;case"refresh-pivot":if(onAction?.(action,context)===true)return;refreshPivot();return;case"pivot-details":if(onAction?.(action,context)===true)return;showPivotDetails();return;case"trace-precedents":trace("precedents");return;case"trace-dependents":trace("dependents");return;case"remove-arrows":removeArrows();return;case"circle-invalid":{circlesOn=wb.active;bump();const count=circled.size;say(count===0?t("noInvalidData"):t(count===1?"invalidCellFound":"invalidCellsFound",{count}));return}case"clear-circles":circlesOn=null;bump();return}}function afterDialog(message){bump();if(message)say(message);const c=cmdOf();if(c)focusSheet(c)}const activeEntry=$derived.by(()=>{void version;return storeFor().get(`r${active.rowIndex}`,colToLetters(active.colIndex))});const activeValue=$derived.by(()=>{void version;return wb.getValue(wb.active,active.rowIndex,active.colIndex)});const activeRule=$derived.by(()=>{void version;return ruleAt(rulesNow(),active.rowIndex,active.colIndex)});const selectionAddress=$derived.by(()=>{void version;void selection;void active;const rects=selectedRects();return rects.map(([r1,c1,r2,c2])=>{const a=`${colToLetters(Math.min(c1,c2))}${Math.min(r1,r2)+1}`;const b=`${colToLetters(Math.max(c1,c2))}${Math.max(r1,r2)+1}`;return a===b?a:`${a}:${b}`}).join(", ")});const mixedLocked=$derived.by(()=>{void version;void selection;void active;return rectsMixLocked(storeFor(),lookup,selectedRects())});function applyFormatCells(patch,border){const cmd=cmdOf();if(!cmd)return;cmd.batch(()=>{if(Object.keys(patch).length)applyFormat(cmd,patch);if(border)applyBorders(cmd,border)});bump();focusSheet(cmd)}function insertFunction(name){const cmd=cmdOf();if(!cmd)return;const{rowIndex,colIndex}=active;void tick().then(()=>cmd.startEditing(rowIndex,colIndex,`=${name}(`))}function pasteBlock(grid,origin,opts,merges=[]){const cmd=cmdOf();const target=getFormatTarget();if(!cmd||!target)return false;const last=selection[selection.length-1];const dest={row:last?Math.min(last[0],last[2]):active.rowIndex,col:last?Math.min(last[1],last[3]):active.colIndex};const fill=last?{rows:Math.abs(last[2]-last[0])+1,cols:Math.abs(last[3]-last[1])+1}:void 0;const plan=planPaste(grid,dest,opts,origin,fill);if(!plan.length)return false;const beyond=entry=>entry.row>=rowCount||entry.col>=colCount;if(protectedNow()&&plan.some(entry=>locked(entry.row,entry.col))){refuse();return true}const laying=(opts.what==="all"||opts.what==="formats")&&merges.length>0?merges.map(m=>opts.transpose?[dest.row+m[1],dest.col+m[0],dest.row+m[3],dest.col+m[2]]:[dest.row+m[0],dest.col+m[1],dest.row+m[2],dest.col+m[3]]).filter(m=>m[2]<rowCount&&m[3]<colCount):[];const landingRect=plan.length?[Math.min(...plan.map(e=>e.row)),Math.min(...plan.map(e=>e.col)),Math.max(...plan.map(e=>e.row)),Math.max(...plan.map(e=>e.col))]:null;const replacing=laying.length&&landingRect?mergesNow().filter(m=>rectsIntersect(m,landingRect)):[];const landing=plan.filter(entry=>!covered(entry.row,entry.col)||replacing.some(m=>entry.row>=m[0]&&entry.row<=m[2]&&entry.col>=m[1]&&entry.col<=m[3]));const rects=[];for(const entry of landing)rects.push([entry.row,entry.col,entry.row,entry.col]);const moving=origin===null&&copied?.cut?copied:null;const before=moving?getState():null;pasting=true;try{cmd.batch(()=>{if(laying.length){const gone=new Set(replacing);if(moving)for(const m of moving.merges)gone.add(mergesNow().find(own=>own[0]===m[0]&&own[1]===m[1]&&own[2]===m[2]&&own[3]===m[3])??m);setMerges([...mergesNow().filter(m=>!gone.has(m)),...laying])}const sheet=wb.active;const bulk=landing.some(beyond);const direct=[];withFormatUndo(cmd,target,rects,()=>{for(const entry of landing){const at={row:entry.row,col:entry.col};const decision=resolvePasteCell(entry.source,wb.getValue(wb.active,entry.row,entry.col),opts,entry.offset,at,entry.turn);if(decision.kind==="skip")continue;const one=[[entry.row,entry.col,entry.row,entry.col]];if(decision.kind==="value"||decision.kind==="both"){if(bulk){const before2=wb.getRaw(sheet,entry.row,entry.col);const after=String(decision.value??"");if(before2!==after){wb.setRaw(sheet,entry.row,entry.col,after);direct.push({row:entry.row,col:entry.col,before:before2,after})}}else cmd.setCellValue(entry.row,entry.col,decision.value)}if(decision.kind==="format"||decision.kind==="both"){if(decision.format)target.store.set(one,decision.format,target.lookup);else target.store.clear(one,target.lookup)}}});if(direct.length){wb.recalculate();const put=which=>{for(const d of direct)wb.setRaw(sheet,d.row,d.col,d[which]);wb.recalculate();bump();changed({kind:"cells"})};cmd.recordUndo(()=>put("before"),()=>put("after"));changed({kind:"cells"})}})}finally{pasting=false}if(moving&&before)finishMove(cmd,moving,dest,landing,before);if(origin===null)marquee=null;bump();return true}function finishMove(cmd,block,dest,landing,before){const height2=block.cells.length;const width=block.cells.reduce((max,line)=>Math.max(max,line.length),0);if(height2===0||width===0)return;const move={sheet:block.sheet,toSheet:wb.active,top:block.origin.row,left:block.origin.col,bottom:block.origin.row+height2-1,right:block.origin.col+width-1,dRow:dest.row-block.origin.row,dCol:dest.col-block.origin.col};if(move.sheet===move.toSheet&&move.dRow===0&&move.dCol===0)return;const written=new Set(landing.map(at=>`${at.row}:${at.col}`));const sameSheet=move.sheet===move.toSheet;for(let r=move.top;r<=move.bottom;r+=1){for(let c=move.left;c<=move.right;c+=1){if(sameSheet&&written.has(`${r}:${c}`))continue;if(wb.getRaw(move.sheet,r,c)!=="")wb.setRaw(move.sheet,r,c,"")}}wb.repointAfterMove(move);if(!sameSheet&&block.merges.length){const source=doc.get(move.sheet);source.merges=source.merges.filter(m=>!block.merges.some(b=>b[0]===m[0]&&b[1]===m[1]&&b[2]===m[2]&&b[3]===m[3]))}const after=getState();cmd.recordUndo?.(()=>{doc.setState(before);registerSheetTargets();applyLive(wb.active);bump()},()=>{doc.setState(after);registerSheetTargets();applyLive(wb.active);bump()})}function cutSelection(cmd){const rects=selectedRects(cmd);if(protectedNow()&&rectsHaveLocked(storeFor(),lookup,rects,protectionNow().ranges)){refuse();return}cmd.copy();if(copied)copied.cut=true}async function readSystemClipboard(){if(typeof navigator==="undefined"||!navigator.clipboard)return null;try{let text="";let html=null;for(const item of await navigator.clipboard.read()){if(item.types.includes("text/html"))html=await(await item.getType("text/html")).text();if(item.types.includes("text/plain"))text=await(await item.getType("text/plain")).text()}return text||html?{text,html}:null}catch{try{const text=await navigator.clipboard.readText();return text?{text,html:null}:null}catch{return null}}}let pendingPaste=$state(null);async function openPasteSpecial(){pendingPaste=copied?null:await readSystemClipboard();pasteSpecialOpen=true}async function pasteSpecial(opts){const cmd=cmdOf();if(!cmd)return;const block=copied;if(block&&block.cells.length){if(pasteBlock(copiedGrid(block,"plain"),block.cut?null:block.origin,opts,blockMerges(block)))focusSheet(cmd);return}const payload=pendingPaste??await readSystemClipboard();pendingPaste=null;const grid=payload?parseClipboard({text:payload.text,html:payload.html??void 0}):null;if(!grid||!grid.length||grid.every(line=>line.every(c=>c.text===""&&!c.formula))){say(t("nothingToPaste"));return}const origin=payload?.html?readClipboardOrigin(payload.html):null;const placed=origin?{grid,origin}:anchorForeignFormulas(grid);if(pasteBlock(placed.grid,placed.origin,opts))focusSheet(cmd)}function focusSheet(cmd){void tick().then(()=>cmd.focus())}const activeActions=$derived.by(()=>{void version;void selection;const on=[];if(showFormulas)on.push("toggle-formulas");if(autoFilterNow())on.push("toggle-filter");if(painter)on.push("format-painter");if(isLocked(activeEntry))on.push("toggle-lock");if(showComments)on.push("toggle-comments");if(gridlinesOn)on.push("toggle-gridlines");if(formulaBarOn)on.push("toggle-formula-bar");if(headingsOn)on.push("toggle-headings");const ps=pageSetupNow();on.push(ps.orientation==="landscape"?"page-landscape":"page-portrait");on.push(`paper-${ps.paper.toLowerCase()}`);const preset=marginPresetOf(ps.margins);if(preset)on.push(`margins-${preset}`);if(ps.gridlines)on.push("print-gridlines");if(ps.headings)on.push("print-headings");if(sheetMergeAt(mergesNow(),active.rowIndex,active.colIndex))on.push("merge-center");return on});let painter=$state(null);function armPainter(){const target=getFormatTarget();if(!target)return;const last=selection[selection.length-1];const[r1,c1,r2,c2]=last??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];const entries=[];for(let r=r1;r<=r2;r+=1){const line=[];for(let c=c1;c<=c2;c+=1){const rowId=target.lookup.rowIdAt(r);const columnId=target.lookup.columnIdAt(c);line.push(rowId!=null&&columnId!=null?target.store.get(rowId,columnId):void 0)}entries.push(line)}painter={rows:r2-r1+1,cols:c2-c1+1,entries};say(t("formatPainterHint"))}function paintFormats(){const src=painter;const cmd=cmdOf();const target=getFormatTarget();painter=null;if(!src||!cmd||!target)return;const last=selection[selection.length-1];let[r1,c1,r2,c2]=last??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];if(r1===r2&&c1===c2){r2=Math.min(r1+src.rows-1,rowCount-1);c2=Math.min(c1+src.cols-1,colCount-1)}const rect=[r1,c1,r2,c2];withFormatUndo(cmd,target,[rect],()=>{target.store.clear([rect],target.lookup);for(let r=r1;r<=r2;r+=1){for(let c=c1;c<=c2;c+=1){const entry=src.entries[(r-r1)%src.rows]?.[(c-c1)%src.cols];if(entry)target.store.set([[r,c,r,c]],entry,target.lookup)}}});bump();fitWrappedRows();statusMessage=null}function onSheetPointerUp(event){pointDrag=null;const press=linkPress;linkPress=null;if(press&&event.button===0&&Math.abs(event.clientX-press.x)<=4&&Math.abs(event.clientY-press.y)<=4){void followLink(press.link)}if(!painter)return;const el=event.target;if(!el?.closest("td.sv-grid-cell"))return;setTimeout(paintFormats,0)}function onSheetKeyDownCapture(event){if(functionListKey(event))return;acceptSuggestion(event);if(selectedObject&&!editorOf(event.target)){if(event.key==="Delete"||event.key==="Backspace"){event.preventDefault();event.stopPropagation();if(protectedNow()){refuse();return}removeObject(selectedObject);return}if(event.key==="Escape")selectedObject=null}if((event.ctrlKey||event.metaKey)&&!event.altKey&&!event.shiftKey&&(event.key==="x"||event.key==="X")&&!editorOf(event.target)&&!painter){const cmd=cmdOf();if(cmd){event.preventDefault();event.stopPropagation();cutSelection(cmd);return}}if((event.ctrlKey||event.metaKey)&&!event.altKey&&!editorOf(event.target)){const key=event.key.toLowerCase();const direction=key==="z"?event.shiftKey?"redo":"undo":key==="y"&&!event.shiftKey?"redo":null;if(direction&&historyIsElsewhere(direction)){event.preventDefault();event.stopPropagation();void undoRedo(direction);return}}if(protectedNow()&&!editorOf(event.target)&&wouldEdit(event)&&locked(active.rowIndex,active.colIndex))refuse();if(event.key==="Backspace"&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!editorOf(event.target)&&!selectedObject&&!painter){const cmd=cmdOf();if(cmd&&!(protectedNow()&&locked(active.rowIndex,active.colIndex))){event.preventDefault();event.stopPropagation();cmd.startEditing(active.rowIndex,active.colIndex,"");return}}if(event.key==="Escape"&&marquee&&!editorOf(event.target))marquee=null;if(event.key==="Enter"&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!event.shiftKey&&marquee&&marquee.sheet===wb.active&&copied&&!editorOf(event.target)&&!painter){event.preventDefault();event.stopPropagation();const block=copied;pasteBlock(copiedGrid(block,"plain"),block.cut?null:block.origin,{what:"all"},blockMerges(block));marquee=null;return}if(!painter)return;if(event.key==="Escape"){painter=null;statusMessage=null;event.preventDefault();return}if(event.key==="Enter"&&!editorOf(event.target)){event.preventDefault();paintFormats()}}const PASS_THROUGH_FUNCTIONS=new Set(["SUM","AVERAGE","MIN","MAX","MEDIAN","ROUND","ROUNDUP","ROUNDDOWN","ABS","IF","IFERROR","IFNA","SUMIF","SUMIFS","AVERAGEIF","AVERAGEIFS","MINIFS","MAXIFS","SUMPRODUCT","PRODUCT","SUBTOTAL","INDEX","VLOOKUP","HLOOKUP","XLOOKUP","LOOKUP","CHOOSE","N","OFFSET","INDIRECT","LARGE","SMALL","MOD","INT","TRUNC","CEILING","FLOOR","MROUND"]);const DATE_FUNCTIONS=new Set(["TODAY","DATE","EOMONTH","EDATE","WORKDAY","DATEVALUE"]);const ISO_DATE_TEXT=/^\d{4}-\d{2}-\d{2}$/;function inheritedNumFmt(formula){const names=[...formula.matchAll(/([A-Za-z][A-Za-z0-9_.]*)\s*\(/g)].map(m=>m[1].toUpperCase());if(names.some(name=>!PASS_THROUGH_FUNCTIONS.has(name)&&!DATE_FUNCTIONS.has(name)))return void 0;if(names.some(name=>DATE_FUNCTIONS.has(name)))return"yyyy-mm-dd";const spans=referenceSpans(formula);const first=spans[0];if(!first)return void 0;const dateAt=span=>{const[r2,c2]=span.rect;const fmt2=storeFor().get(`r${r2}`,colToLetters(c2))?.numFmt;const category=fmt2?formatCategory(fmt2).category:void 0;return category==="date"||category==="time"||fmt2===void 0&&ISO_DATE_TEXT.test(wb.getRaw(wb.active,r2,c2).trim())};if(spans.length===2&&dateAt(first)&&dateAt(spans[1])&&/^=\s*\$?[A-Za-z]{1,3}\$?\d+\s*-\s*\$?[A-Za-z]{1,3}\$?\d+\s*$/.test(formula))return void 0;const[r,c]=first.rect;const fmt=storeFor().get(`r${r}`,colToLetters(c))?.numFmt;if(fmt)return fmt;return dateAt(first)?"yyyy-mm-dd":void 0}function onCellWritten(change){if(change.oldValue!==void 0&&change.oldValue===change.newValue)return;const ref=parseA1(`${change.columnId}1`);if(!ref)return;const text=balanceParens(fromCulture(change.newValue==null?"":String(change.newValue)));if(copied?.fresh&&text===""&&!copied.cut){const dr=change.rowIndex-copied.origin.row;const dc=ref.col-copied.origin.col;if(copied.cells[dr]?.[dc])copied.cut=true}else if(!pasting){marquee=null}formulaDraft=null;const r=change.rowIndex;const c=ref.col;let stored=text;const target=getFormatTarget();const cmd=cmdOf();const entry=storeFor().get(`r${r}`,colToLetters(c));const patch={};const parsed=parseEntry(text,culture);if(parsed){stored=parsed.value;if(parsed.numFmt&&(!entry?.numFmt||formatCategory(entry.numFmt).category!==formatCategory(parsed.numFmt).category))patch.numFmt=parsed.numFmt}if(!entry?.numFmt&&text.startsWith("=")){const inherited=inheritedNumFmt(text);if(inherited)patch.numFmt=inherited}if(!parsed&&!text.startsWith("=")&&entry?.numFmt&&formatCategory(entry.numFmt).category==="percent"){const plain=text.trim();if(PLAIN_NUMBER.test(plain))stored=String(Number(plain)/100)}if(text.includes("\n")&&!entry?.wrap)patch.wrap=true;if(Object.keys(patch).length&&target&&cmd){withFormatUndo(cmd,target,[[r,c,r,c]],()=>target.store.set([[r,c,r,c]],patch,target.lookup))}if(wb.getRaw(wb.active,r,c)===stored){if(patch.wrap){bump();fitWrappedRows()}return}wb.setRaw(wb.active,r,c,stored);if(stored!==""&&wb.tables.growToInclude(wb.active,r,c)){fillTableFormulas(r,c);wb.recalculate();changed({kind:"tables"})}bump();changed({kind:"cells"});refilterPivot(r,c,stored);if(patch.wrap||entry?.wrap)fitWrappedRows()}function refilterPivot(row,col,text){if(writingPivot)return;const pivot=pivotsNow().find(p=>{const filters=p.filters??[];if(!filters.length||col!==p.target.col+1)return false;return row>=p.target.row&&row<p.target.row+filters.length});if(!pivot)return;const index=row-pivot.target.row;const filter=(pivot.filters??[])[index];if(!filter)return;const wanted=text.trim()===ALL_VALUES?"":text.trim();if(wanted===filter.value)return;const next={...copyPivot(pivot),filters:(pivot.filters??[]).map((f,i)=>i===index?{...f,value:wanted}:{...f})};writePivot(next,true)}const autoFitRows=new Map;const autoFitOn=sheet=>{let set=autoFitRows.get(sheet);if(!set){set=new Set;autoFitRows.set(sheet,set)}return set};function fitWrappedRows(){void tick().then(()=>{if(!api||!root)return;const auto=autoFitOn(wb.active);const tallest=new Map;for(const span of root.querySelectorAll(".sheet-cell.wrap")){const td=span.closest("td");const r=Number(td?.dataset.svgridRow);if(!Number.isInteger(r))continue;const needed=span.scrollHeight+2;if(needed>(tallest.get(r)??0))tallest.set(r,needed)}for(const[r,needed]of tallest){const current=api.getRowHeight(r);if(needed>current){api.setRowHeight(r,needed);auto.add(r)}}for(const r of[...auto]){if(tallest.has(r)&&tallest.get(r)>=api.getRowHeight(r))continue;if(!root.querySelector(`td[data-svgrid-row="${r}"]`))continue;const needed=tallest.get(r);if(needed!==void 0&&needed>rowHeight)api.setRowHeight(r,needed);else{api.setRowHeight(r,null);auto.delete(r)}}})}let copied=$state(null);let marquee=$state(null);const activeSpill=$derived.by(()=>{void version;return wb.spillOf(wb.active,active.rowIndex,active.colIndex)?.rect??null});function spillEdges(r,c){const rect=activeSpill;if(!rect)return null;const[r1,c1,r2,c2]=rect;if(r<r1||r>r2||c<c1||c>c2)return null;const edges=[];if(r===r1)edges.push("top");if(r===r2)edges.push("bottom");if(c===c1)edges.push("left");if(c===c2)edges.push("right");return edges.length?edges.join(" "):null}function marqueeEdges(r,c){void version;const m=marquee;if(!m||m.sheet!==wb.active)return null;const[r1,c1,r2,c2]=m.rect;if(r<r1||r>r2||c<c1||c>c2)return null;const edges=[];if(r===r1)edges.push("top");if(r===r2)edges.push("bottom");if(c===c1)edges.push("left");if(c===c2)edges.push("right");return edges.length?edges.join(" "):null}let pasting=false;function toClipboard(params){const col=lettersToCol(params.columnId);const r=params.rowIndex;if(col<0)return"";const shown=display(r,col).text;const rects=selection.length?selection:[[r,col,r,col]];const first=rects[0];const whole=first[0]===first[2]&&first[1]===first[3]?sheetMergeAt(mergesNow(),r,col):null;const[minRow,minCol,maxRow,maxCol]=whole&&whole[0]===r&&whole[1]===col?whole:first;if(r===minRow&&col===minCol){copied={origin:{row:r,col},sheet:wb.active,cells:[],rowAt:new Map,colAt:new Map,fresh:true,cut:false,merges:mergesNow().filter(m=>m[0]>=minRow&&m[2]<=maxRow&&m[1]>=minCol&&m[3]<=maxCol).map(m=>[...m])};queueMicrotask(()=>{if(copied)copied.fresh=false});marquee={sheet:wb.active,rect:[minRow,minCol,Math.min(maxRow,rowCount-1),Math.min(maxCol,colCount-1)]};if(whole&&whole[0]===r&&whole[1]===col){for(let rr=minRow;rr<=maxRow;rr+=1){copied.rowAt.set(rr,rr-minRow);copied.cells[rr-minRow]=[];for(let cc=minCol;cc<=maxCol;cc+=1){copied.colAt.set(cc,cc-minCol);if(rr!==r||cc!==col)copied.cells[rr-minRow][cc-minCol]={shown:"",raw:"",value:"",format:storeFor().get(`r${rr}`,colToLetters(cc))}}}}}if(copied&&!copied.cut){let dr=copied.rowAt.get(r);if(dr===void 0){dr=copied.rowAt.size;copied.rowAt.set(r,dr)}let dc=copied.colAt.get(col);if(dc===void 0){dc=copied.colAt.size;copied.colAt.set(col,dc)}if(!copied.cells[dr])copied.cells[dr]=[];const line=copied.cells[dr];line[dc]={shown,raw:raw(r,col),value:plainValue(r,col),format:storeFor().get(`r${r}`,params.columnId)}}return shown}function plainValue(r,c){const value=wb.getValue(wb.active,r,c);if(isError(value))return value.error;if(value===""||value==null)return"";return String(value)}const EMPTY_COPIED={shown:"",raw:"",value:"",format:void 0};function blockMerges(block){const out=[];for(const[r1,c1,r2,c2]of block.merges){const dr1=block.rowAt.get(r1),dc1=block.colAt.get(c1),dr2=block.rowAt.get(r2),dc2=block.colAt.get(c2);if(dr1===void 0||dc1===void 0||dr2===void 0||dc2===void 0)continue;out.push([dr1,dc1,dr2,dc2])}return out}function copiedGrid(block,text){const width=block.cells.reduce((max,line)=>Math.max(max,line.length),0);return block.cells.map(line=>Array.from({length:width},(_,i)=>{const cell=line[i]??EMPTY_COPIED;const formula=cell.raw.startsWith("=");const numeric=cell.value!==""&&Number.isFinite(Number(cell.value));return{text:text==="shown"?cell.shown:formula?cell.value:cell.raw,...text==="shown"&&numeric?{value:cell.value}:{},...formula?{formula:cell.raw}:{},...cell.format?{format:cell.format}:{}}}))}function copiedText(block){return copiedGrid(block,"shown").map(line=>line.map(cell=>cell.text).join(" ")).join("\n")}function copiedHtml(){const block=copied;if(!block||!block.cells.length)return null;return buildClipboardPayload(copiedGrid(block,"shown"),block.origin).html}function pasteFromSystem(payload){const block=copied;const text=payload.text.replace(/\r\n/g,"\n").replace(/\n$/,"");if(block&&block.cells.length&&copiedText(block)===text){return pasteBlock(copiedGrid(block,"plain"),block.cut?null:block.origin,{what:"all"},blockMerges(block))}const grid=payload.html?parseClipboardHtml(payload.html):null;if(!grid){const lines=parseClipboardText(text);const width=lines.reduce((max,line)=>Math.max(max,line.length),0);const past=lines.length+active.rowIndex>rowCount||width+active.colIndex>colCount;return past?pasteBlock(lines,null,{what:"all"}):void 0}const origin=readClipboardOrigin(payload.html);if(origin)return pasteBlock(grid,origin,{what:"all"});const foreign=anchorForeignFormulas(grid);return pasteBlock(foreign.grid,foreign.origin,{what:"all"})}function withCmd(fn){const c=cmdOf();if(!c)return;fn(c);queueMicrotask(()=>c.focus())}const hasComment=()=>commentAt(notesNow(),active.rowIndex,active.colIndex)!==void 0;const hasLink=()=>linkOf(active.rowIndex,active.colIndex)!==void 0;const axis=()=>{const c=cmdOf();if(!c||!c.ranges.length)return"ambiguous";return axisForSelection(c)};const glyph=name=>({paths:RIBBON_ICONS[name]});const contextMenu=$derived.by(()=>[{key:"cut",icon:glyph("cut"),action:()=>withCmd(c=>cutSelection(c))},{key:"copy",icon:glyph("copy")},{key:"paste",icon:glyph("paste")},{key:"paste-special",label:t("menuPasteSpecial"),icon:glyph("paste-special"),action:()=>withCmd(c=>delegate("paste-special",c))},"separator",{key:"insert-rows",label:t("menuInsertRows"),icon:glyph("insert-cells"),hidden:()=>axis()==="cols",action:()=>withCmd(c=>insertRows(c))},{key:"insert-columns",label:t("menuInsertColumns"),icon:glyph("insert-cells"),hidden:()=>axis()==="rows",action:()=>withCmd(c=>insertColumns(c))},{key:"delete-rows",label:t("menuDeleteRows"),icon:glyph("delete-cells"),hidden:()=>axis()==="cols",action:()=>withCmd(c=>deleteRows(c))},{key:"delete-columns",label:t("menuDeleteColumns"),icon:glyph("delete-cells"),hidden:()=>axis()==="rows",action:()=>withCmd(c=>deleteColumns(c))},"separator",{key:"clear-contents",label:t("menuClearContents"),icon:glyph("clear"),action:()=>withCmd(c=>{const rects=c.ranges.length?c.ranges:c.activeCell?[[c.activeCell.rowIndex,c.activeCell.colIndex,c.activeCell.rowIndex,c.activeCell.colIndex]]:[];if(protectedNow()&&rectsHaveLocked(storeFor(),lookup,rects,protectionNow().ranges)){refuse();return}c.batch(()=>{for(const[r1,c1,r2,c2]of rects){for(let r=r1;r<=r2;r+=1){for(let col=c1;col<=c2;col+=1){if(lineHidden(r,col))continue;c.setCellValue(r,col,"")}}}})})},{key:"clear-formats",label:t("menuClearFormats"),icon:glyph("clear-formats"),action:()=>withCmd(c=>clearFormats(c))},"separator",{key:"merge-center",label:t("menuMergeCenter"),icon:glyph("merge"),hidden:()=>axis()!=="ambiguous"||selectionHasMerge(),action:()=>withCmd(c=>handleAction("merge-center",c))},{key:"unmerge-cells",label:t("menuUnmergeCells"),icon:glyph("unmerge"),hidden:()=>axis()!=="ambiguous"||!selectionHasMerge(),action:()=>withCmd(c=>handleAction("unmerge-cells",c))},"separator",{key:"new-comment",label:t("menuNewComment"),icon:glyph("comment"),hidden:()=>axis()!=="ambiguous"||hasComment(),action:()=>withCmd(c=>handleAction("new-comment",c))},{key:"edit-comment",label:t("menuEditComment"),icon:glyph("comment"),hidden:()=>axis()!=="ambiguous"||!hasComment(),action:()=>withCmd(c=>handleAction("edit-comment",c))},{key:"delete-comment",label:t("menuDeleteComment"),icon:glyph("comment-delete"),hidden:()=>axis()!=="ambiguous"||!hasComment(),action:()=>withCmd(c=>handleAction("delete-comment",c))},"separator",{key:"insert-link",label:t("menuLink"),icon:glyph("link"),hidden:()=>axis()!=="ambiguous"||hasLink(),action:()=>withCmd(c=>handleAction("insert-link",c))},{key:"edit-link",label:t("menuEditLink"),icon:glyph("link"),hidden:()=>axis()!=="ambiguous"||!hasLink(),action:()=>withCmd(c=>handleAction("insert-link",c))},{key:"open-link",label:t("menuOpenLink"),icon:glyph("link"),hidden:()=>axis()!=="ambiguous"||!hasLink(),action:()=>{const link=linkOf(active.rowIndex,active.colIndex);if(link)void followLink(link)}},{key:"remove-link",label:t("menuRemoveLink"),icon:glyph("unlink"),hidden:()=>axis()!=="ambiguous"||!hasLink(),action:()=>withCmd(c=>handleAction("remove-link",c))},"separator",{key:"format-cells",label:t("menuFormatCells"),icon:glyph("format-cells"),action:()=>withCmd(c=>delegate("format-cells",c))},{key:"column-width",label:t("menuColumnWidth"),icon:glyph("column-width"),hidden:()=>axis()!=="cols",action:()=>openSizeDialog("cols")},{key:"row-height",label:t("menuRowHeight"),icon:glyph("row-height"),hidden:()=>axis()!=="rows",action:()=>openSizeDialog("rows")},{key:"hide-columns",label:t("menuHide"),icon:glyph("hide"),hidden:()=>axis()!=="cols",action:()=>withCmd(c=>handleAction("hide-columns",c))},{key:"unhide-columns",label:t("menuUnhide"),icon:glyph("unhide"),hidden:()=>axis()!=="cols",action:()=>withCmd(c=>handleAction("unhide-columns",c))},{key:"hide-rows",label:t("menuHide"),icon:glyph("hide"),hidden:()=>axis()!=="rows",action:()=>withCmd(c=>handleAction("hide-rows",c))},{key:"unhide-rows",label:t("menuUnhide"),icon:glyph("unhide"),hidden:()=>axis()!=="rows",action:()=>withCmd(c=>handleAction("unhide-rows",c))}]);let sizeDialog=$state(null);const sizeDialogOpen=$derived(sizeDialog!==null);function sizeTargets(){return lineTargets(sizeDialog==="cols"?"cols":"rows")}function lineTargets(axis2){const last=selection[selection.length-1];if(!last)return[axis2==="cols"?active.colIndex:active.rowIndex];const[r1,c1,r2,c2]=last;const from=axis2==="cols"?c1:r1;const to=Math.min(axis2==="cols"?c2:r2,(axis2==="cols"?colCount:rowCount)-1);return Array.from({length:to-from+1},(_,i)=>from+i)}function autofitLines(axis2,cmd){if(!api)return;if(!allowNow(lineKey(axis2))){refuse();return}const targets=lineTargets(axis2);if(axis2==="cols"){const widths=()=>targets.map(c=>[c,api.getColumnWidths()[colToLetters(c)]??columnWidth]);const before=widths();for(const c of targets)api.autosizeColumn(colToLetters(c));const after=widths();const put=list=>{for(const[c,w]of list)api.setColumnWidth(colToLetters(c),w);stashWidths();changed({kind:"sizes"})};cmd.recordUndo(()=>put(before),()=>put(after))}else{const before=targets.map(r=>[r,api.getRowHeight(r)]);const fit=()=>{for(const r of targets)api.setRowHeight(r,null);fitWrappedRows();changed({kind:"sizes"})};fit();cmd.recordUndo(()=>{for(const[r,h]of before)api.setRowHeight(r,h===rowHeight?null:h);stashHeights();changed({kind:"sizes"})},fit)}stashLive();bump()}const sizeCurrent=$derived.by(()=>{void version;void selection;void active;if(!api||!sizeDialog)return 0;const first=sizeTargets()[0]??0;return sizeDialog==="cols"?api.getColumnWidths()[colToLetters(first)]??columnWidths?.[colToLetters(first)]??columnWidth:api.getRowHeight(first)});function openSizeDialog(kind){if(!allowNow(lineKey(kind))){refuse();return}sizeDialog=kind}function applySize(px){if(!api)return;if(!allowNow(lineKey(sizeDialog??"rows"))){refuse();return}const kind=sizeDialog;const targets=sizeTargets();const read=()=>targets.map(i=>[i,kind==="cols"?api.getColumnWidths()[colToLetters(i)]??columnWidth:api.getRowHeight(i)]);const put=list=>{for(const[i,size]of list){if(kind==="cols")api.setColumnWidth(colToLetters(i),size);else api.setRowHeight(i,size===rowHeight?null:size)}stashLive();bump();changed({kind:"sizes"})};const before=read();put(targets.map(i=>[i,px]));if(kind==="rows")for(const r of targets)autoFitOn(wb.active).delete(r);const after=read();const c=cmdOf();c?.recordUndo(()=>put(before),()=>put(after));if(c)focusSheet(c)}function onSheetContextMenu(event){const el=event.target;const th=el.closest("th[data-svgrid-header-col]");const gutter=el.closest("td.sv-grid-row-number-cell");if(th||gutter){event.preventDefault();if(!api)return;const rects2=selection;if(th){const col=lettersToCol(th.dataset.svgridHeaderCol??"");if(col<0)return;const inside3=rects2.some(([,c1,r2,c2])=>c1<=col&&col<=c2&&r2>=rowCount-1);if(!inside3)selectColumns(col,col,{active:"place"});api.openContextMenu(event,0,col);return}const row=rowOfGutter(gutter);if(row===null)return;const inside2=rects2.some(([r1,,r2,c2])=>r1<=row&&row<=r2&&c2>=colCount-1);if(!inside2)selectRows(row,row,{active:"place"});api.openContextMenu(event,row,0);return}const td=el.closest("td[data-svgrid-row][data-svgrid-col]");if(!td)return;const r=Number(td.dataset.svgridRow);const c=Number(td.dataset.svgridCol);const rects=selection.length?selection:[[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex]];const inside=rects.some(([r1,c1,r2,c2])=>r>=r1&&r<=r2&&c>=c1&&c<=c2);if(inside)return;const cmd=cmdOf();if(!cmd)return;cmd.setActiveCell(r,c);cmd.setSelection(r,c)}let headerDrag=null;function rowOfGutter(gutter){const rowAttr=gutter.parentElement?.querySelector("td[data-svgrid-row]")?.dataset.svgridRow;const row=rowAttr===void 0?Number(gutter.textContent)-1:Number(rowAttr);return Number.isInteger(row)&&row>=0?row:null}function headerHit(el,dragging2=null){if(!el)return null;if(el.closest(".sv-grid-resize-handle, .sv-grid-row-resize-handle"))return null;if(el.closest("th.sv-grid-row-number-column"))return{axis:"all"};const th=el.closest("th[data-svgrid-header-col]");if(th){const col=lettersToCol(th.dataset.svgridHeaderCol??"");return col<0?null:{axis:"col",index:col}}const gutter=el.closest("td.sv-grid-row-number-cell");if(gutter){const row=rowOfGutter(gutter);return row===null?null:{axis:"row",index:row}}if(dragging2){const td=el.closest("td[data-svgrid-row][data-svgrid-col]");if(td)return{axis:dragging2,index:Number(dragging2==="col"?td.dataset.svgridCol:td.dataset.svgridRow)}}return null}function firstVisible(axis2){const host=gridHost?.querySelector(".sv-grid-container");if(!host)return 0;const box=host.getBoundingClientRect();const headH=host.querySelector("thead")?.getBoundingClientRect().height??0;const gutterW=host.querySelector("td.sv-grid-row-number-cell")?.getBoundingClientRect().width??0;let best=null;for(const td of host.querySelectorAll("td[data-svgrid-row][data-svgrid-col]")){if(td.closest("tr")?.classList.contains("sv-grid-row-collapsed"))continue;const r=td.getBoundingClientRect();if(r.width===0||r.height===0)continue;const index=Number(axis2==="row"?td.dataset.svgridRow:td.dataset.svgridCol);const edge=axis2==="row"?r.top-(box.top+headH):r.left-(box.left+gutterW);if(edge<-1)continue;if(best===null||index<best)best=index}return best??0}function selectColumns(a,b,how){const cmd=cmdOf();if(!api||!cmd)return;const was=cmd.activeCell;api.selectCells([...how.keep??[],[0,Math.min(a,b),Number.POSITIVE_INFINITY,Math.max(a,b)]]);if(how.active==="place")cmd.setActiveCell(firstVisible("row"),a);else if(was)cmd.setActiveCell(was.rowIndex,was.colIndex)}function selectRows(a,b,how){const cmd=cmdOf();if(!api||!cmd)return;const was=cmd.activeCell;api.selectCells([...how.keep??[],[Math.min(a,b),0,Math.max(a,b),Number.POSITIVE_INFINITY]]);if(how.active==="place")cmd.setActiveCell(a,firstVisible("col"));else if(was)cmd.setActiveCell(was.rowIndex,was.colIndex)}function selectLine(hit,from,how){if(hit.axis==="col")selectColumns(from,hit.index,how);else selectRows(from,hit.index,how)}let resizeTip=$state(null);let resizeGuide=$state(null);let resizing=null;let cellDrag=$state(false);let fillDrag=null;const dragLabel=$derived.by(()=>{if(!cellDrag)return null;const rect=selection[selection.length-1];if(!rect)return null;const rows=Math.abs(rect[2]-rect[0])+1;const cols=Math.abs(rect[3]-rect[1])+1;return rows*cols>1?`${rows}R x ${cols}C`:null});function fillTipText(under){const src=fillDrag?.rect;if(!src)return null;const[r1,c1,r2,c2]=src;const{r,c}=under;const inside=r>=r1&&r<=r2&&c>=c1&&c<=c2;if(inside)return null;const vertical=r<r1||r>r2;if(vertical){if(c<c1||c>c2)return null;const down=r>r2;const sources2=Array.from({length:r2-r1+1},(_,i)=>raw(down?r1+i:r2-i,c));const count2=down?r-r2:r1-r;return fillTipValue(buildFillPattern(sources2,count2)[count2-1],down?r2:r1,c)}if(r<r1||r>r2)return null;const right=c>c2;const sources=Array.from({length:c2-c1+1},(_,i)=>raw(r,right?c1+i:c2-i));const count=right?c-c2:c1-c;return fillTipValue(buildFillPattern(sources,count)[count-1],r,right?c2:c1)}function fillTipValue(value,sr,sc){if(value===void 0||value===null||value==="")return null;const n=typeof value==="number"?value:Number(value);if(typeof value!=="boolean"&&Number.isFinite(n)&&String(value).trim()!==""){const fmt=storeFor().get(`r${sr}`,colToLetters(sc))?.numFmt;return fmt?compileNumberFormat(fmt,marks).format(n).text:String(Number(n.toPrecision(10)))}return String(value)}function placeFillTip(event){const host=gridHost;if(!host||!fillDrag)return;const td=document.elementFromPoint(event.clientX,event.clientY)?.closest("td[data-svgrid-row][data-svgrid-col]");const text=td?fillTipText({r:Number(td.dataset.svgridRow),c:Number(td.dataset.svgridCol)}):null;if(text===null||text===""){resizeTip=null;return}const box=host.getBoundingClientRect();resizeTip={x:event.clientX-box.left+14,y:event.clientY-box.top+18,text}}function resizeTipText(px){if(!resizing)return"";return resizing.axis==="col"?`Width: ${Math.max(0,(px-5)/7).toFixed(2)} (${px} pixels)`:`Height: ${(px*.75).toFixed(2)} (${px} pixels)`}function placeResizeTip(event){const host=gridHost;const drag=resizing;if(!host||!drag)return;const box=host.getBoundingClientRect();const travel=drag.axis==="col"?event.clientX-drag.startX:event.clientY-drag.startY;const px=Math.round(Math.max(drag.min,drag.startSize+travel));const x=Math.min(event.clientX-box.left+14,box.width-160);resizeTip={x:Math.max(0,x),y:event.clientY-box.top-30,text:resizeTipText(px)};resizeGuide={axis:drag.axis,at:drag.startEdge+(px-drag.startSize)}}function startResizeTip(handle,event){const host=gridHost;if(!host)return;const box=host.getBoundingClientRect();if(handle.classList.contains("sv-grid-row-resize-handle")){const tr=handle.closest("tr");const td=tr?.querySelector("td[data-svgrid-row]");const row=td?.dataset.svgridRow;if(!tr||!td||row===void 0)return;const r=td.getBoundingClientRect();resizing={axis:"row",key:row,startX:event.clientX,startY:event.clientY,startSize:Math.round(r.height),startEdge:r.bottom-box.top,min:20}}else{const th=handle.closest("[data-svgrid-header-col]");const col=th?.dataset.svgridHeaderCol;if(!th||!col)return;const r=th.getBoundingClientRect();resizing={axis:"col",key:col,startX:event.clientX,startY:event.clientY,startSize:Math.round(r.width),startEdge:r.right-box.left,min:40}}placeResizeTip(event)}function endResizeTip(){resizing=null;resizeTip=null;resizeGuide=null}let pointed=null;let pointDrag=null;let pointedPress=false;function formulaEditor(){const el=document.activeElement;if(!(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement))return null;if(!el.classList.contains("sv-grid-cell-editor")&&!(el.classList.contains("formula")&&el.closest(".sv-formula-bar")))return null;return el.value.startsWith("=")?el:null}function wantsReference(editor){const caret=editor.selectionStart??editor.value.length;if(pointed&&pointed.editor===editor&&pointed.end===caret)return true;if(editor.selectionEnd!==caret)return false;const before=editor.value.slice(0,caret).replace(/\s+$/,"");return/[=(,;+\-*/^&<>:]$/.test(before)}function insertPointedReference(editor,r1,c1,r2,c2){const top=Math.min(r1,r2),left=Math.min(c1,c2),bottom=Math.max(r1,r2),right=Math.max(c1,c2);const one=`${colToLetters(left)}${top+1}`;const text=top===bottom&&left===right?one:`${one}:${colToLetters(right)}${bottom+1}`;const caret=editor.selectionStart??editor.value.length;const replacing=pointed&&pointed.editor===editor&&pointed.end===caret;const start=replacing?pointed.start:caret;const end=replacing?pointed.end:caret;editor.value=editor.value.slice(0,start)+text+editor.value.slice(end);const after=start+text.length;editor.setSelectionRange(after,after);pointed={editor,start,end:after};editor.dispatchEvent(new Event("input",{bubbles:true}))}function pointAt(event,target){const editor=formulaEditor();if(!editor||editorOf(target))return false;const td=target?.closest("td[data-svgrid-row][data-svgrid-col]");if(!td||td.contains(editor)||!wantsReference(editor))return false;event.stopPropagation();const row=Number(td.dataset.svgridRow);const col=Number(td.dataset.svgridCol);insertPointedReference(editor,row,col,row,col);pointDrag={editor,row,col};pointedPress=true;return true}function onSheetMouseDown(event){if(!pointDrag)return;event.preventDefault();event.stopPropagation()}function onSheetClickCapture(event){if(!pointedPress)return;pointedPress=false;event.preventDefault();event.stopPropagation()}function pointDragTo(event){const drag=pointDrag;if(!drag||document.activeElement!==drag.editor)return;const td=document.elementFromPoint(event.clientX,event.clientY)?.closest("td[data-svgrid-row][data-svgrid-col]");if(!td)return;const row=Number(td.dataset.svgridRow);const col=Number(td.dataset.svgridCol);if(pointed&&pointed.editor===drag.editor)drag.editor.setSelectionRange(pointed.end,pointed.end);insertPointedReference(drag.editor,drag.row,drag.col,row,col)}let linkPress=null;function onSheetPointerDown(event){if(event.button!==0)return;const target=event.target;if(selectedObject&&!target?.closest(".sheet-object"))selectedObject=null;if(pointAt(event,target))return;const handle=target?.closest(".sv-grid-resize-handle, .sv-grid-row-resize-handle");if(handle){startResizeTip(handle,event);return}if(target?.closest(".sv-grid-fill-handle")){const rect=selection[selection.length-1]??[active.rowIndex,active.colIndex,active.rowIndex,active.colIndex];fillDrag={rect:[Math.min(rect[0],rect[2]),Math.min(rect[1],rect[3]),Math.max(rect[0],rect[2]),Math.max(rect[1],rect[3])]};return}const hit=headerHit(target);if(!hit){const td=target?.closest("td[data-svgrid-row][data-svgrid-col]");if(td){cellDrag=true;const row=Number(td.dataset.svgridRow);const col=Number(td.dataset.svgridCol);const link=linkOf(row,col);linkPress=link&&editingText===null?{link,x:event.clientX,y:event.clientY}:null}return}const cmd=cmdOf();if(!api||!cmd)return;event.preventDefault();event.stopPropagation();if(hit.axis==="all"){const was=cmd.activeCell;api.selectCells([[0,0,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]]);if(was)cmd.setActiveCell(was.rowIndex,was.colIndex);headerDrag=null}else if(event.shiftKey){const anchor=cmd.activeCell;const from=anchor?hit.axis==="col"?anchor.colIndex:anchor.rowIndex:hit.index;selectLine(hit,from,{active:"keep"});headerDrag=null}else{const keep=event.ctrlKey||event.metaKey?cmd.ranges:[];selectLine(hit,hit.index,{active:"place",keep});headerDrag={axis:hit.axis,from:hit.index,keep}}cmd.focus()}function onSheetPointerMove(event){if(pointDrag){pointDragTo(event);return}if(fillDrag){placeFillTip(event);return}if(resizing){placeResizeTip(event);return}const drag=headerDrag;if(!drag)return;const hit=headerHit(document.elementFromPoint(event.clientX,event.clientY),drag.axis);if(!hit||hit.axis!==drag.axis)return;const cmd=cmdOf();if(!cmd)return;const was=cmd.activeCell;if(drag.axis==="col")api?.selectCells([...drag.keep,[0,Math.min(drag.from,hit.index),Number.POSITIVE_INFINITY,Math.max(drag.from,hit.index)]]);else api?.selectCells([...drag.keep,[Math.min(drag.from,hit.index),0,Math.max(drag.from,hit.index),Number.POSITIVE_INFINITY]]);if(was)cmd.setActiveCell(was.rowIndex,was.colIndex)}function endHeaderDrag(){headerDrag=null;cellDrag=false;fillDrag=null;endResizeTip()}$effect(()=>{window.addEventListener("pointerup",endHeaderDrag);window.addEventListener("pointercancel",endHeaderDrag);window.addEventListener("pointermove",onSheetPointerMove);return()=>{window.removeEventListener("pointerup",endHeaderDrag);window.removeEventListener("pointercancel",endHeaderDrag);window.removeEventListener("pointermove",onSheetPointerMove)}});function wouldEdit(event){if(event.ctrlKey||event.metaKey||event.altKey)return false;const el=event.target;if(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement||el instanceof HTMLSelectElement)return false;if(event.key==="F2"||event.key==="Delete"||event.key==="Backspace")return true;return event.key.length===1}function editorOf(target){const el=target;return(el instanceof HTMLInputElement||el instanceof HTMLTextAreaElement)&&el.classList.contains("sv-grid-cell-editor")?el:null}let measure=null;function growEditor(input){const td=input.closest("td");if(!td)return;measure??=document.createElement("canvas").getContext("2d");if(!measure)return;measure.font=getComputedStyle(input).font;const lines=input.value.split("\n");const widest=Math.max(...lines.map(line=>measure.measureText(line).width));const needed=Math.ceil(widest)+18;input.style.width=needed>td.clientWidth?`${needed}px`:"";if(input instanceof HTMLTextAreaElement){const lineHeight=parseFloat(getComputedStyle(input).lineHeight)||17;const tall=Math.ceil(lines.length*lineHeight)+4;input.style.height=tall>td.clientHeight?`${tall}px`:""}}let editingText=$state(null);let barDraft=$state(null);function onEditorFocusIn(event){const input=editorOf(event.target);if(!input)return;editingText=input.value;queueMicrotask(()=>{const end=input.value.length;try{input.setSelectionRange(end,end)}catch{}});growEditor(input);if(input.value.startsWith("="))formulaDraft=input.value}function onEditorInput(event){const input=editorOf(event.target);if(!input)return;if(event instanceof InputEvent&&event.inputType==="insertText")autoComplete(input);growEditor(input);editingText=input.value;formulaDraft=input.value.startsWith("=")?input.value:null;offerFunctions(input)}let suggested=null;function autoComplete(input){suggested=null;const typed=input.value;if(input.selectionStart!==typed.length||input.selectionEnd!==typed.length)return;const{rowIndex,colIndex}=active;const entry=completeEntry(typed,columnRunEntries(rowIndex,colIndex));if(entry===null||entry===typed)return;suggested=entry;input.value=typed+entry.slice(typed.length);input.setSelectionRange(typed.length,entry.length);input.dispatchEvent(new Event("input",{bubbles:true}))}function acceptSuggestion(event){if(suggested===null||event.key!=="Enter"&&event.key!=="Tab"||event.altKey)return;const input=editorOf(event.target);if(!input)return;const entry=suggested;suggested=null;const tail=input.selectionStart??input.value.length;if(input.selectionEnd!==input.value.length||tail>=input.value.length)return;if(input.value.toLowerCase()!==entry.toLowerCase())return;input.value=entry;input.dispatchEvent(new Event("input",{bubbles:true}))}function columnRunEntries(rowIndex,colIndex){const out=new Set;const textAt=r=>{const raw2=wb.getRaw(wb.active,r,colIndex);if(raw2==="")return null;if(raw2.startsWith("="))return"";return typeof wb.getValue(wb.active,r,colIndex)==="string"?raw2:""};for(let r=rowIndex-1;r>=0;r-=1){const t2=textAt(r);if(t2===null)break;if(t2)out.add(t2)}for(let r=rowIndex+1;r<rowCount;r+=1){const t2=textAt(r);if(t2===null)break;if(t2)out.add(t2)}return out}function onEditorFocusOut(event){if(!editorOf(event.target))return;pointed=null;fnSuggest=null;formulaDraft=null;editingText=null}let fnSuggest=$state(null);function offerFunctions(input){const host=gridHost;const td=input.closest("td");if(!host||!td||!input.value.startsWith("=")){fnSuggest=null;return}const items=suggestFunctions(input.value,input.selectionStart??input.value.length);if(!items.length){fnSuggest=null;return}const a=td.getBoundingClientRect();const b=host.getBoundingClientRect();fnSuggest={items,index:0,left:a.left-b.left,top:a.bottom-b.top}}function takeFunction(input,suggestion){const next=applySuggestion(input.value,suggestion);input.value=next.text;input.setSelectionRange(next.caret,next.caret);fnSuggest=null;input.dispatchEvent(new Event("input",{bubbles:true}))}function functionListKey(event){const list=fnSuggest;const input=editorOf(event.target);if(!list||!input)return false;if(event.key==="ArrowDown"||event.key==="ArrowUp"){const step=event.key==="ArrowDown"?1:-1;fnSuggest={...list,index:(list.index+step+list.items.length)%list.items.length}}else if(event.key==="Tab"||event.key==="Enter"){takeFunction(input,list.items[list.index])}else if(event.key==="Escape"){fnSuggest=null}else{return false}event.preventDefault();event.stopPropagation();return true}let formulaDraft=$state(null);function referencesIn(text){const seen=new Set;return referenceSpans(text).filter(span=>!seen.has(span.key)&&(seen.add(span.key),true))}let painted=[];function paintReferences(){for(const el of painted){delete el.dataset.sheetRef;el.style.removeProperty("--sheet-ref");el.style.removeProperty("--sheet-ref-edges")}painted=[];const host=root;if(!host||formulaDraft===null){clearEditorMirror();return}for(const{rect,colour}of referencesIn(formulaDraft)){const[r1,c1,r2,c2]=rect;for(const td of host.querySelectorAll("td[data-svgrid-row][data-col-id]")){const r=Number(td.dataset.svgridRow);const c=lettersToCol(td.dataset.colId??"");if(r<r1||r>r2||c<c1||c>c2)continue;const edges=[];if(r===r1)edges.push("inset 0 1.5px 0 var(--sheet-ref)");if(r===r2)edges.push("inset 0 -1.5px 0 var(--sheet-ref)");if(c===c1)edges.push("inset 1.5px 0 0 var(--sheet-ref)");if(c===c2)edges.push("inset -1.5px 0 0 var(--sheet-ref)");td.dataset.sheetRef="";td.style.setProperty("--sheet-ref",colour);td.style.setProperty("--sheet-ref-edges",edges.length?edges.join(", "):"none");painted.push(td)}}paintEditorText()}$effect(()=>{void formulaDraft;void version;const frame=requestAnimationFrame(paintReferences);return()=>cancelAnimationFrame(frame)});let mirror=null;function clearEditorMirror(){const input=mirror?.parentElement?.querySelector(".sv-grid-cell-editor");input?.classList.remove("sheet-ref-text");mirror?.remove();mirror=null}function paintEditorText(){const input=root?.querySelector("td.sv-grid-cell-editing .sv-grid-cell-editor")??null;const spans=formulaDraft!==null&&input?referenceSpans(input.value):[];if(!input||spans.length===0){clearEditorMirror();return}const td=input.closest("td");if(!td){clearEditorMirror();return}if(!mirror||mirror.parentElement!==td){clearEditorMirror();mirror=document.createElement("div");mirror.className="sheet-ref-mirror";mirror.setAttribute("aria-hidden","true");td.appendChild(mirror)}const cs=getComputedStyle(input);Object.assign(mirror.style,{left:`${input.offsetLeft}px`,top:`${input.offsetTop}px`,width:`${input.offsetWidth}px`,height:`${input.offsetHeight}px`,font:cs.font,lineHeight:cs.lineHeight,letterSpacing:cs.letterSpacing,padding:cs.padding,textAlign:cs.textAlign,boxSizing:cs.boxSizing,borderWidth:cs.borderWidth,borderStyle:"solid",borderColor:"transparent"});fillMirror(mirror,input.value,spans);mirror.scrollLeft=input.scrollLeft;mirror.scrollTop=input.scrollTop;input.classList.add("sheet-ref-text")}function fillMirror(host,text,spans){host.replaceChildren();let at=0;for(const span of spans){if(span.start>at)host.appendChild(document.createTextNode(text.slice(at,span.start)));const run=document.createElement("span");run.style.color=span.colour;run.textContent=text.slice(span.start,span.end);host.appendChild(run);at=span.end}if(at<text.length)host.appendChild(document.createTextNode(text.slice(at)))}
3
3
  </script>
4
4
 
5
5