@gridsheet/react-core 3.4.1 → 3.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/GridSheet.d.ts.map +1 -1
- package/dist/{hooks-CCpInOc_.mjs → hooks-BhxFU0X7.mjs} +12 -10
- package/dist/hooks-BhxFU0X7.mjs.map +1 -0
- package/dist/index.js +169 -166
- package/dist/index.js.map +1 -1
- package/dist/spellbook.js +1 -1
- package/package.json +3 -3
- package/dist/hooks-CCpInOc_.mjs.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/store/index.ts","../src/components/ProgressOverlay.tsx","../src/components/AsyncProgressOverlay.tsx","../src/components/FunctionGuide.tsx","../src/components/EditorOptions.tsx","../src/lib/clipboard.ts","../src/components/useAutocomplete.ts","../src/components/Fixed.tsx","../src/lib/paste.ts","../src/components/Editor.tsx","../src/components/PluginBase.tsx","../src/components/StoreObserver.tsx","../src/components/Resizer.tsx","../src/components/Emitter.tsx","../src/store/applyers.ts","../src/lib/menu.ts","../src/components/MenuItem.tsx","../src/components/MenuNodes.tsx","../src/components/ContextMenu.tsx","../src/components/ColumnMenuFilterSection.tsx","../src/components/ColumnMenuSortSection.tsx","../src/components/ColumnMenuLabelSection.tsx","../src/components/ColumnMenu.tsx","../src/components/RowMenu.tsx","../src/lib/events.ts","../src/components/Cell.tsx","../src/components/ScrollHandle.tsx","../src/components/HeaderCellTop.tsx","../src/components/HeaderCellLeft.tsx","../src/components/CellStateOverlay.tsx","../src/components/Tabular.tsx","../src/components/FormulaBar.tsx","../src/components/svg/Base.tsx","../src/components/svg/SearchIcon.tsx","../src/components/svg/CloseIcon.tsx","../src/components/SearchBar.tsx","../src/components/GridSheet.tsx","../src/policy/checkbox.tsx","../src/lib/style.ts"],"sourcesContent":["import { createContext } from 'react';\nimport { StoreType } from '../types';\n\nexport type Dispatcher = React.Dispatch<{\n type: number;\n value: any;\n}>;\n\nexport const Context = createContext(\n {} as {\n store: StoreType;\n dispatch: Dispatcher;\n },\n);\n","import type { FC } from 'react';\n\nexport type ProgressOverlayProps = {\n /** 0..1 for a determinate bar; null/undefined for an indeterminate spinner. */\n progress?: number | null;\n /** Text shown before the percentage (e.g. \"Loading\", \"Saving\", \"Pasting\"). */\n label?: string;\n};\n\n/**\n * Shared progress overlay: a centered card with a spinner + label, plus a determinate bar\n * when `progress` is given. One component for initial loading, save, and chunked async\n * mutations so every progress indicator looks and behaves the same. It spans its (positioned)\n * container to capture pointer events — blocking interaction while work runs — but does NOT\n * dim, so the grid stays visible behind it. Drive it with a prop for cheap/occasional updates\n * (load/save); for a high-frequency mutation tick use AsyncProgressOverlay's imperative handle\n * so a tick re-renders only the overlay, not the grid.\n */\nexport const ProgressOverlay: FC<ProgressOverlayProps> = ({ progress, label = 'Loading' }) => {\n const determinate = progress != null;\n const pct = determinate ? Math.max(0, Math.min(100, Math.round(progress * 100))) : 0;\n return (\n <div className=\"gs-progress-overlay\">\n <div className=\"gs-progress-box\">\n <div className=\"gs-progress-head\">\n <span className=\"gs-loading-spinner\" />\n <span>{determinate ? `${label}… ${pct}%` : `${label}…`}</span>\n </div>\n {determinate && (\n <div className=\"gs-progress-track\">\n <div className=\"gs-progress-fill\" style={{ width: `${pct}%` }} />\n </div>\n )}\n </div>\n </div>\n );\n};\n","import { forwardRef, useImperativeHandle, useState } from 'react';\nimport { ProgressOverlay } from './ProgressOverlay';\n\nexport type AsyncProgressHandle = {\n setProgress: (ratio: number) => void;\n};\n\n/**\n * Determinate progress overlay for a chunked async mutation (large fill/paste). Its progress\n * is driven IMPERATIVELY (via the ref) so that a progress tick re-renders only this small\n * component — not the whole grid. Routing progress through the store instead made every tick\n * re-render the (expensive, at deep scroll) grid, so a million-cell fill spent most of its\n * time re-rendering. The visuals come from the shared ProgressOverlay.\n */\nexport const AsyncProgressOverlay = forwardRef<AsyncProgressHandle, { label: string }>(({ label }, ref) => {\n const [progress, setProgress] = useState(0);\n useImperativeHandle(ref, () => ({ setProgress }), []);\n return <ProgressOverlay progress={progress} label={label} />;\n});\n","import React, { useContext, useLayoutEffect, useRef } from 'react';\nimport type { FunctionHelp } from '@gridsheet/web';\nimport type { AutocompleteOption } from '@gridsheet/web';\nimport { Context } from '../store';\nimport { calcSideStyle, clampPopup } from '@gridsheet/web';\n\ntype OptionWithGuide = AutocompleteOption & {\n isFunction?: boolean;\n example?: string;\n category?: string;\n description?: string;\n defs?: any[];\n};\n\nexport interface FunctionGuideProps {\n // Option Help Mode (renders in EditorOptions)\n option?: OptionWithGuide;\n\n // Active Function Highlight Mode (renders floating near cursor)\n activeFunctionGuide?: FunctionHelp;\n activeArgIndex?: number;\n top?: number;\n left?: number;\n}\n\nexport const FunctionGuide: React.FC<FunctionGuideProps> = ({\n option,\n activeFunctionGuide,\n activeArgIndex = 0,\n top,\n left,\n}) => {\n const ref = useRef<HTMLDivElement>(null);\n const guide1Ref = useRef<HTMLDivElement>(null);\n const { store } = useContext(Context);\n // Hide the active help when not hovering over the editor, to prevent it from blocking clicks on other options.\n const isHidden = !store.editorHovering;\n\n useLayoutEffect(() => {\n const el = guide1Ref.current;\n if (!el) {\n return;\n }\n calcSideStyle(el);\n });\n\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el || left === undefined) {\n return;\n }\n clampPopup(el);\n });\n\n if (option) {\n return (\n <div\n ref={guide1Ref}\n className=\"gs-fn-guide1\"\n onMouseDown={(e) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n >\n {option.category && option.isFunction && (\n <span className={`gs-fn-guide-category gs-fn-guide-category-${option.category}`}>{option.category}</span>\n )}\n {option.tooltip && (\n <div className=\"gs-fn-guide1-tooltip\">\n {typeof option.tooltip === 'function'\n ? React.createElement(option.tooltip as any, { value: option.value })\n : option.tooltip}\n </div>\n )}\n {option.isFunction && (\n <>\n <div className=\"gs-fn-guide1-example\">{option.example}</div>\n {option.description && (\n <div className=\"gs-fn-guide1-desc\" style={{ whiteSpace: 'pre-line' }}>\n {option.description}\n </div>\n )}\n {option.defs && option.defs.length > 0 && (\n <div className=\"gs-fn-guide1-args\">\n {option.defs.map((arg: any, j: number) => (\n <div key={j} className=\"gs-fn-guide1-arg\">\n <span className=\"gs-fn-guide1-arg-name\">{arg.name}</span>\n {arg.optional && <span className=\"gs-fn-guide1-arg-opt\"> (optional)</span>}\n {arg.variadic && <span className=\"gs-fn-guide1-arg-iter\">...</span>}\n <code className=\"gs-fn-guide1-arg-type\">{arg.acceptedTypes?.join(' | ') || 'any'}</code>\n <span className=\"gs-fn-guide1-arg-desc\"> — {arg.description}</span>\n </div>\n ))}\n </div>\n )}\n </>\n )}\n </div>\n );\n }\n\n if (activeFunctionGuide) {\n return (\n <div\n ref={ref}\n className={`gs-fn-guide2 ${isHidden ? 'gs-fn-guide2-hidden' : ''}`}\n style={top !== undefined && left !== undefined ? { top: top + 4, left } : undefined}\n >\n {activeFunctionGuide.category && (\n <span className={`gs-fn-guide-category gs-fn-guide-category-${activeFunctionGuide.category}`}>\n {activeFunctionGuide.category}\n </span>\n )}\n <div className=\"gs-fn-guide2-name\">{activeFunctionGuide.example}</div>\n <div className=\"gs-fn-guide2-args-inline\">\n {(() => {\n const args = activeFunctionGuide.defs ?? [];\n const numIterable = args.filter((a: any) => a.variadic).length;\n const variadicStart = args.length - numIterable;\n\n return args.map((arg: any, j: number) => {\n let isActive: boolean;\n if (activeArgIndex < variadicStart) {\n // Cursor is on a fixed (non-variadic) argument\n isActive = activeArgIndex === j;\n } else if (numIterable > 0 && j >= variadicStart) {\n // Cursor is in the variadic zone; cycle through the variadic args\n const offset = (activeArgIndex - variadicStart) % numIterable;\n isActive = j === variadicStart + offset;\n } else {\n isActive = false;\n }\n return (\n <React.Fragment key={j}>\n {j > 0 ? ', ' : ''}\n <span className={isActive ? 'gs-active-arg' : ''}>\n {arg.optional ? '[' : ''}\n {arg.name}\n {arg.variadic ? ', ...' : ''}\n {arg.optional ? ']' : ''}\n </span>\n </React.Fragment>\n );\n });\n })()}\n </div>\n {(() => {\n const args = activeFunctionGuide.defs ?? [];\n const numIterable = args.filter((a: any) => a.variadic).length;\n const variadicStart = args.length - numIterable;\n\n let resolvedIndex: number;\n if (activeArgIndex < variadicStart || numIterable === 0) {\n resolvedIndex = Math.min(activeArgIndex, args.length - 1);\n } else {\n const offset = (activeArgIndex - variadicStart) % numIterable;\n resolvedIndex = variadicStart + offset;\n }\n const activeArg = args[resolvedIndex];\n if (!activeArg?.description) {\n return null;\n }\n return (\n <div className=\"gs-fn-guide2-desc\" style={{ marginTop: 8, fontSize: 12, color: '#888' }}>\n <p>\n <strong>{activeArg.name}:</strong>{' '}\n <code className=\"gs-fn-guide2-arg-type\">{activeArg.acceptedTypes?.join(' | ') || 'any'}</code>\n {activeArg.description}\n </p>\n </div>\n );\n })()}\n\n {activeFunctionGuide.description && (\n <div className=\"gs-fn-guide2-desc\" style={{ whiteSpace: 'pre-line' }}>\n {activeFunctionGuide.description}\n </div>\n )}\n </div>\n );\n }\n\n return null;\n};\n","import React, { useRef, useLayoutEffect, useState } from 'react';\nimport { FunctionGuide } from './FunctionGuide';\nimport { clampLeft } from '@gridsheet/web';\n\ninterface EditorOptionsProps {\n filteredOptions: any[];\n top: number;\n left: number;\n selected: number;\n onOptionMouseDown: (e: React.MouseEvent<HTMLLIElement>, i: number) => void;\n}\n\nexport const EditorOptions: React.FC<EditorOptionsProps> = ({\n filteredOptions,\n top,\n left,\n selected,\n onOptionMouseDown,\n}) => {\n const ulRef = useRef<HTMLUListElement>(null);\n const [adjustedLeft, setAdjustedLeft] = useState(left);\n\n useLayoutEffect(() => {\n if (!ulRef.current) {\n return;\n }\n const width = ulRef.current.getBoundingClientRect().width;\n setAdjustedLeft(clampLeft(left, width));\n }, [left, filteredOptions]);\n\n if (filteredOptions.length === 0) {\n return null;\n }\n\n return (\n <ul ref={ulRef} className=\"gs-editor-options\" style={{ top, left: adjustedLeft }}>\n {filteredOptions.map((option, i) => (\n <li\n key={i}\n className={`gs-editor-option ${selected === i ? ' gs-editor-option-selected' : ''}`}\n onMouseDown={(e) => onOptionMouseDown(e, i)}\n >\n <div className=\"gs-editor-option-content\">\n <span>{option.label ?? option.value}</span>\n {selected === i && <span className=\"gs-editor-option-tab\">⇥ Tab</span>}\n </div>\n {(option.isFunction || option.tooltip) && selected === i && <FunctionGuide option={option} />}\n </li>\n ))}\n </ul>\n );\n};\n","import type { StoreType, AreaType, PointType } from '../types';\n\nimport { zoneToArea } from '@gridsheet/web';\nimport type { Sheet, UserSheet } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\n\nexport const clip = (store: StoreType) => {\n const { selectingZone, choosing, editorRef, sheetReactive: sheetRef } = store;\n const sheet = sheetRef.current;\n\n if (!sheet) {\n return { top: 0, left: 0, bottom: 0, right: 0 };\n }\n\n const { y, x } = choosing;\n const selectingArea = zoneToArea(selectingZone);\n let area = selectingArea;\n if (area.left === -1) {\n area = { top: y, left: x, bottom: y, right: x };\n }\n const input = editorRef.current;\n const trimmed = sheet.trim(area);\n const tsv = sheet2csv(trimmed, {\n getter: (sheet, point) => {\n const policy = sheet.getPolicy(point);\n return policy.serializeForClipboard({ point, sheet });\n },\n });\n const html = sheet2html(trimmed, {\n getter: (sheet, point) => {\n const policy = sheet.getPolicy(point);\n return policy.serializeForClipboard({ point, sheet });\n },\n });\n\n if (navigator.clipboard) {\n const tsvBlob = new Blob([tsv], { type: 'text/plain' });\n const htmlBlob = new Blob([html], { type: 'text/html' });\n\n navigator.clipboard.write([\n new ClipboardItem({\n 'text/plain': tsvBlob,\n 'text/html': htmlBlob,\n }),\n ]);\n } else if (input != null) {\n input.value = tsv;\n focus(input);\n input.select();\n document.execCommand('copy');\n input.value = '';\n input.blur();\n }\n return area;\n};\n\nexport type SheetCSVProps = {\n getter?: (sheet: UserSheet, point: PointType) => string;\n filteredRowsIncluded?: boolean;\n trailingEmptyRowsOmitted?: boolean;\n separator?: string;\n newline?: string;\n};\n\nexport const sheet2csv = (\n sheet: UserSheet,\n {\n getter = (sheet, point) => {\n return String(sheet.getCell(point)?.value ?? '');\n },\n filteredRowsIncluded = false,\n trailingEmptyRowsOmitted = false,\n separator = '\\t',\n newline = '\\n',\n }: SheetCSVProps = {},\n): string => {\n const rows: { isEmpty: boolean; line: string }[] = [];\n for (let y = sheet.top; y <= sheet.bottom; y++) {\n if (sheet.isRowFiltered(y) && !filteredRowsIncluded) {\n continue;\n }\n const cols: string[] = [];\n let rowIsEmpty = true;\n for (let x = sheet.left; x <= sheet.right; x++) {\n const point: PointType = { y, x };\n const value = getter(sheet, point);\n if (value !== '') {\n rowIsEmpty = false;\n }\n if (value.indexOf('\\n') !== -1) {\n cols.push(`\"${value.replace(/\"/g, '\"\"')}\"`);\n } else {\n cols.push(value);\n }\n }\n rows.push({ isEmpty: rowIsEmpty, line: cols.join(separator) });\n }\n if (trailingEmptyRowsOmitted) {\n while (rows.length > 0 && rows[rows.length - 1].isEmpty) {\n rows.pop();\n }\n }\n return rows.map((r) => r.line).join(newline);\n};\n\nexport type SheetHTMLProps = {\n getter?: (sheet: UserSheet, point: PointType) => string;\n filteredRowsIncluded?: boolean;\n trailingEmptyRowsOmitted?: boolean;\n};\n\nexport const sheet2html = (\n sheet: UserSheet,\n {\n getter = (sheet, point) => {\n return String(sheet.getCell(point)?.value ?? '');\n },\n filteredRowsIncluded = false,\n trailingEmptyRowsOmitted = false,\n }: SheetHTMLProps = {},\n): string => {\n const rows: { isEmpty: boolean; html: string }[] = [];\n for (let y = sheet.top; y <= sheet.bottom; y++) {\n if (sheet.isRowFiltered(y) && !filteredRowsIncluded) {\n continue;\n }\n const cols: string[] = [];\n let rowIsEmpty = true;\n for (let x = sheet.left; x <= sheet.right; x++) {\n const point: PointType = { y, x };\n const value = getter(sheet, point);\n if (value !== '') {\n rowIsEmpty = false;\n }\n const valueEscaped = value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n cols.push(`<td>${valueEscaped}</td>`);\n }\n rows.push({ isEmpty: rowIsEmpty, html: `<tr>${cols.join('')}</tr>` });\n }\n if (trailingEmptyRowsOmitted) {\n while (rows.length > 0 && rows[rows.length - 1].isEmpty) {\n rows.pop();\n }\n }\n return `<table>${rows.map((r) => r.html).join('')}</table>`;\n};\n","import { useState, useMemo, useCallback } from 'react';\nimport { getFunctionHelps, type FunctionHelp } from '@gridsheet/web';\nimport type { FunctionMapping } from '@gridsheet/web';\nimport type { AutocompleteOption } from '@gridsheet/web';\nimport { Lexer } from '@gridsheet/web';\n\ntype UseAutocompleteProps = {\n inputting: string;\n selectionStart: number;\n optionsAll: AutocompleteOption[];\n functions?: FunctionMapping;\n};\n\nexport const useAutocomplete = ({ inputting, selectionStart, optionsAll, functions }: UseAutocompleteProps) => {\n const [selected, setSelected] = useState(0);\n\n const { filteredOptions, matchParams, activeFunctionHelp, activeArgIndex } = useMemo(() => {\n const isFormula = inputting.startsWith('=');\n\n let activeFunctionHelp: FunctionHelp | null = null;\n let activeArgIndex: number = 0;\n\n const textBeforeCursor = inputting.slice(0, selectionStart);\n const textAfterCursor = inputting.slice(selectionStart);\n\n // --- Active Argument Context Tracking ---\n if (isFormula && textBeforeCursor.length > 1) {\n try {\n const textToCursor = textBeforeCursor.slice(1); // skip '='\n const lexer = new Lexer(textToCursor);\n lexer.tokenize();\n\n const functionStack: { name: string; argIndex: number; hasWaitComma: boolean }[] = [];\n\n for (let i = 0; i < lexer.tokens.length; i++) {\n const token = lexer.tokens[i];\n if (token.type === 'FUNCTION') {\n const nextToken = lexer.tokens[i + 1];\n if (nextToken?.type === 'OPEN') {\n functionStack.push({ name: token.entity as string, argIndex: 0, hasWaitComma: false });\n i++; // skip OPEN\n } else if (i === lexer.tokens.length - 1) {\n // Function keyword right before cursor but without paren yet!\n // Do nothing special here, autocomplete dropdown will handle it.\n }\n } else if (token.type === 'COMMA') {\n if (functionStack.length > 0) {\n functionStack[functionStack.length - 1].argIndex++;\n functionStack[functionStack.length - 1].hasWaitComma = true;\n }\n } else if (token.type === 'CLOSE') {\n if (functionStack.length > 0) {\n functionStack.pop();\n }\n } else if (token.type !== 'SPACE' && functionStack.length > 0) {\n functionStack[functionStack.length - 1].hasWaitComma = false;\n }\n }\n\n if (functionStack.length > 0) {\n const activeItem = functionStack[functionStack.length - 1];\n const helps = getFunctionHelps(functions);\n activeArgIndex = activeItem.argIndex;\n activeFunctionHelp = helps.find((h: any) => h.name === activeItem.name.toUpperCase()) || null;\n }\n } catch (e) {\n /* ignore parse errors */\n }\n }\n\n const wordBefore = textBeforeCursor.match(/[a-zA-Z0-9_.]+$/)?.[0] || '';\n const wordAfter = textAfterCursor.match(/^[a-zA-Z0-9_.]+/)?.[0] || '';\n\n // For regular cells, we use the whole word as the search target.\n // For formulas, we extract the word under the cursor.\n const currentWord = isFormula ? (wordBefore + wordAfter).toLowerCase() : inputting.toLocaleLowerCase();\n const hasOpenParenAssigned = isFormula && textAfterCursor.slice(wordAfter.length).trimStart().startsWith('(');\n\n let filtered: any[] = [];\n\n let isOnAddress = false;\n if (isFormula) {\n try {\n const fullLexer = new Lexer(inputting.slice(1));\n fullLexer.tokenize();\n let currentIndex = 1; // start after '='\n for (const token of fullLexer.tokens) {\n const tLen = token.length();\n if (selectionStart > currentIndex && selectionStart < currentIndex + tLen) {\n if (['REF', 'RANGE', 'ID', 'ID_RANGE', 'UNREFERENCED'].includes(token.type)) {\n isOnAddress = true;\n }\n // Inside a string literal (VALUE token whose entity is a string)\n if (token.type === 'VALUE' && typeof token.entity === 'string') {\n isOnAddress = true;\n }\n break;\n }\n if (selectionStart === currentIndex || selectionStart === currentIndex + tLen) {\n if (['REF', 'RANGE', 'ID', 'ID_RANGE', 'UNREFERENCED'].includes(token.type)) {\n isOnAddress = true;\n }\n }\n currentIndex += tLen;\n }\n } catch (e) {\n /* ignore parse errors */\n }\n }\n\n if (isFormula && !isOnAddress) {\n // Suggest if we have at least 1 letter, and there isn't already an opening parenthesis attached\n if (currentWord.length > 0 && !hasOpenParenAssigned) {\n filtered = getFunctionHelps(functions)\n .map((help: any) => {\n const keywordLower = help.name.toLowerCase();\n const startsWith = keywordLower.startsWith(currentWord);\n const index = startsWith ? 0 : -1;\n const hasNoArgs = help.defs.length === 0;\n return {\n option: { ...help, value: help.name + (hasNoArgs ? '()' : '('), isFunction: true, label: help.name },\n index,\n startsWith,\n keywordCount: 1,\n keyword: keywordLower,\n };\n })\n .filter(({ startsWith }: { startsWith: boolean }) => startsWith)\n .sort((a: any, b: any) => {\n if (a.startsWith !== b.startsWith) {\n return b.startsWith ? 1 : -1;\n }\n if (a.index !== b.index) {\n return a.index - b.index;\n }\n return a.keyword.localeCompare(b.keyword);\n })\n .map(({ option }: { option: any }) => option);\n }\n } else {\n filtered = optionsAll\n .map((option) => {\n const keywords = option.keywords ?? [String(option.value)];\n let bestMatch = { index: -1, startsWith: false, keyword: '' };\n\n for (const keyword of keywords) {\n const keywordLower = keyword.toLowerCase();\n const index = keywordLower.indexOf(currentWord);\n if (index !== -1) {\n const startsWith = keywordLower.startsWith(currentWord);\n if (\n bestMatch.index === -1 ||\n index < bestMatch.index ||\n (index === bestMatch.index && startsWith && !bestMatch.startsWith)\n ) {\n bestMatch = { index, startsWith, keyword };\n }\n }\n }\n\n return {\n option,\n ...bestMatch,\n keywordCount: keywords.length,\n };\n })\n .filter(({ index }) => index !== -1)\n .sort((a, b) => {\n if (a.startsWith !== b.startsWith) {\n return b.startsWith ? 1 : -1;\n }\n if (a.index !== b.index) {\n return a.index - b.index;\n }\n if (a.keywordCount !== b.keywordCount) {\n return b.keywordCount - a.keywordCount;\n }\n return a.keyword.localeCompare(b.keyword);\n })\n .map(({ option }) => option);\n }\n\n return {\n filteredOptions: filtered,\n matchParams: {\n isFormula,\n currentWord,\n matchLengthBefore: wordBefore.length,\n matchLengthAfter: wordAfter.length,\n },\n activeFunctionHelp,\n activeArgIndex,\n };\n }, [inputting, selectionStart, optionsAll, functions]);\n\n useMemo(() => {\n if (selected >= filteredOptions.length) {\n setSelected(0);\n }\n }, [filteredOptions.length, selected]);\n\n const replaceWithOption = useCallback(\n (option: any) => {\n if (!option) {\n return { value: inputting, selectionStart };\n }\n\n if (matchParams.isFormula) {\n const beforeMatch = inputting.slice(0, selectionStart - matchParams.matchLengthBefore);\n const afterMatch = inputting.slice(selectionStart + matchParams.matchLengthAfter);\n const newValue = beforeMatch + option.value + afterMatch;\n return { value: newValue, selectionStart: beforeMatch.length + option.value.length };\n } else {\n return { value: String(option.value), selectionStart: String(option.value).length };\n }\n },\n [inputting, selectionStart, matchParams],\n );\n\n const handleArrowUp = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (filteredOptions.length > 1) {\n setSelected((s) => (s <= 0 ? filteredOptions.length - 1 : s - 1));\n e.preventDefault();\n return true;\n }\n return false;\n },\n [filteredOptions.length],\n );\n\n const handleArrowDown = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (filteredOptions.length > 1) {\n setSelected((s) => (s >= filteredOptions.length - 1 ? 0 : s + 1));\n e.preventDefault();\n return true;\n }\n return false;\n },\n [filteredOptions.length],\n );\n\n return {\n filteredOptions,\n selected,\n setSelected,\n replaceWithOption,\n handleArrowUp,\n handleArrowDown,\n isFormula: matchParams.isFormula,\n activeFunctionHelp,\n activeArgIndex,\n };\n};\n","import type { CSSProperties, FC, ReactNode } from 'react';\nimport { useBrowser } from '../lib/hooks';\nimport { createPortal } from 'react-dom';\n\ntype Props = {\n className?: string;\n style?: CSSProperties;\n children: ReactNode;\n [attr: string]: any;\n};\n\nexport const Fixed: FC<Props> = ({ children, style, className = '', ...attrs }) => {\n const { document } = useBrowser();\n if (document == null) {\n return null;\n }\n return createPortal(\n <div {...attrs} className={`gs-fixed ${className}`} style={style}>\n {children}\n </div>,\n document.body,\n );\n};\n","import React, { type CSSProperties } from 'react';\nimport type { RawCellType } from '../types';\nexport const parseHTML = (html: string, onlyValue = false): RawCellType[][] => {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n const results: RawCellType[][] = [];\n\n const processSheet = (sheet: HTMLTableElement) => {\n const spans = new Set<string>();\n const rows = sheet.querySelectorAll('tr,caption');\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n if (row.tagName === 'CAPTION') {\n const caption = row.textContent?.trim() ?? '';\n if (caption) {\n results.push([{ value: caption }]);\n }\n continue;\n }\n const cells = Array.from(row.querySelectorAll('td, th'));\n const result: RawCellType[] = [];\n let j = 0;\n for (const cell of cells) {\n const value = cell.textContent?.trim() ?? '';\n const style: CSSProperties | undefined = onlyValue\n ? undefined\n : (() => {\n const childStyle = parseStyleString(cell.firstElementChild);\n const parentStyle = parseStyleString(cell);\n return { ...parentStyle, ...childStyle };\n })();\n while (spans.has(`${i}-${++j}`)) {\n result.push({ value: '', style, skip: true });\n }\n result.push({ value, style });\n\n const rowSpan = parseInt(cell.getAttribute('rowspan') ?? '1', 10);\n const colSpan = parseInt(cell.getAttribute('colspan') ?? '1', 10);\n for (let r = 0; r < rowSpan; r++) {\n for (let c = 0; c < colSpan; c++) {\n spans.add(`${i + r}-${j + c}`);\n }\n }\n }\n results.push(result);\n }\n };\n\n const processNodeSequentially = (node: Node, currentLine: RawCellType[] = []) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as HTMLElement;\n const tagName = el.tagName;\n\n if (tagName === 'TABLE') {\n if (currentLine.length > 0) {\n results.push(currentLine.slice());\n currentLine.length = 0;\n }\n processSheet(el as HTMLTableElement);\n } else if (tagName === 'BR') {\n results.push(currentLine.slice());\n currentLine.length = 0;\n } else if (blockTags.has(tagName)) {\n if (currentLine.length > 0) {\n results.push(currentLine.slice());\n currentLine.length = 0;\n }\n el.childNodes.forEach((child) => processNodeSequentially(child, currentLine));\n if (currentLine.length > 0) {\n results.push(currentLine.slice());\n currentLine.length = 0;\n }\n } else {\n el.childNodes.forEach((child) => processNodeSequentially(child, currentLine));\n }\n } else if (node.nodeType === Node.TEXT_NODE) {\n const text = node.textContent ?? '';\n const lines = text.split(/\\r?\\n/);\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed) {\n currentLine.push({ value: trimmed });\n }\n }\n }\n };\n\n const currentLine: RawCellType[] = [];\n doc.body.childNodes.forEach((node) => processNodeSequentially(node, currentLine));\n if (currentLine.length > 0) {\n results.push(currentLine);\n }\n\n return results;\n};\n\nfunction parseStyleString(element: Element | null): React.CSSProperties | undefined {\n if (!element) {\n return undefined;\n }\n const styleString = element.getAttribute('style') ?? '';\n const styleObj: React.CSSProperties = {};\n\n styleString.split(';').forEach((d) => {\n let [rawKey, rawValue] = d.split(':');\n if (!rawKey || !rawValue) {\n return;\n }\n rawKey = rawKey.trim();\n if (rawKey === 'height' || rawKey === 'width') {\n return;\n }\n const key = rawKey.trim().replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n if (key === 'float' || key === 'display' || key.startsWith('padding')) {\n return;\n }\n if (key === 'border') {\n Object.assign(styleObj, {\n borderTop: rawValue,\n borderRight: rawValue,\n borderBottom: rawValue,\n borderLeft: rawValue,\n });\n return;\n }\n if (key === 'borderColor') {\n Object.assign(styleObj, {\n borderTopColor: rawValue,\n borderRightColor: rawValue,\n borderBottomColor: rawValue,\n borderLeftColor: rawValue,\n });\n return;\n }\n if (key === 'borderStyle') {\n Object.assign(styleObj, {\n borderTopStyle: rawValue,\n borderRightStyle: rawValue,\n borderBottomStyle: rawValue,\n borderLeftStyle: rawValue,\n });\n return;\n }\n if (key === 'borderWidth') {\n Object.assign(styleObj, {\n borderTopWidth: rawValue,\n borderRightWidth: rawValue,\n borderBottomWidth: rawValue,\n borderLeftWidth: rawValue,\n });\n return;\n }\n const value = rawValue.trim();\n (styleObj as any)[key] = value;\n });\n\n return styleObj;\n}\n\nexport const parseText = (tsv: string, sep = '\\t'): RawCellType[][] => {\n tsv = tsv.replace(/\"\"/g, '\\x00');\n const rows: RawCellType[][] = [[]];\n let row = rows[0];\n let entering = false;\n let word = '';\n for (let i = 0; i < tsv.length; i++) {\n const s = tsv[i];\n if (s === '\\n' && !entering) {\n row.push({ value: restoreDoubleQuote(word) });\n word = '';\n row = [];\n rows.push(row);\n continue;\n }\n if (s === sep) {\n row.push({ value: restoreDoubleQuote(word) });\n word = '';\n continue;\n }\n if (s === '\"' && !entering && word === '') {\n entering = true;\n continue;\n }\n if (s === '\"' && entering) {\n entering = false;\n continue;\n }\n word += s;\n }\n if (word) {\n row.push({ value: restoreDoubleQuote(word) });\n }\n return rows;\n};\n\nconst restoreDoubleQuote = (text: string) => text.replace(/\\x00/g, '\"');\n\nconst blockTags = new Set([\n 'ADDRESS',\n 'ARTICLE',\n 'ASIDE',\n 'BLOCKQUOTE',\n 'DETAILS',\n 'DIALOG',\n 'DD',\n 'DIV',\n 'DL',\n 'DT',\n 'FIELDSET',\n 'FIGCAPTION',\n 'FIGURE',\n 'FOOTER',\n 'FORM',\n 'H1',\n 'H2',\n 'H3',\n 'H4',\n 'H5',\n 'H6',\n 'HEADER',\n 'HR',\n 'LI',\n 'MAIN',\n 'NAV',\n 'OL',\n 'P',\n 'PRE',\n 'SECTION',\n 'TABLE',\n 'UL',\n]);\n","import type { FC } from 'react';\nimport { useContext, useEffect, useState, useCallback, useRef, memo } from 'react';\nimport { createPortal } from 'react-dom';\nimport { FunctionGuide } from './FunctionGuide';\nimport { EditorOptions } from './EditorOptions';\nimport { x2c, y2r } from '@gridsheet/web';\nimport { clip } from '../lib/clipboard';\nimport {\n clear,\n escape,\n select,\n selectToDataEdge,\n fillDown,\n fillRight,\n setEditingAddress,\n undo,\n redo,\n arrow,\n walk,\n write,\n copy,\n cut,\n paste,\n setSearchQuery,\n setEntering,\n setInputting,\n setEditorHovering,\n updateSheet,\n} from '../store/actions';\n\nimport { Context } from '../store';\nimport { areaToZone, zoneToArea } from '@gridsheet/web';\nimport { operations as prevention } from '@gridsheet/web';\nimport {\n expandInput,\n insertTextAtCursor,\n isFocus,\n isRefInsertable,\n resetInput,\n handleFormulaQuoteAutoClose,\n} from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { Lexer } from '@gridsheet/web';\nimport { COLOR_PALETTE } from '@gridsheet/web';\nimport { useAutocomplete } from './useAutocomplete';\nimport { EditorEventWithNativeEvent, FeedbackType, ModeType } from '../types';\nimport { Fixed } from './Fixed';\nimport { parseHTML, parseText } from '../lib/paste';\nimport React from 'react';\n\ntype Props = {\n mode: ModeType;\n};\n\nexport const Editor: FC<Props> = ({ mode }: Props) => {\n const { store, dispatch } = useContext(Context);\n const [shiftKey, setShiftKey] = useState(false);\n const [selectionStart, setSelectionStart] = useState(0);\n const [isFocused, setIsFocused] = useState(false);\n const composingRef = useRef(false);\n const {\n choosing,\n inputting,\n selectingZone,\n editorRect,\n editingAddress,\n entering,\n matchingCells,\n matchingCellIndex,\n searchQuery,\n editorRef,\n largeEditorRef,\n searchInputRef,\n editingOnEnter,\n sheetReactive: sheetRef,\n sheetId,\n dragging,\n } = store;\n const sheet = sheetRef.current;\n\n const renderOverlays = () => {\n if (!isFocused || !editing || typeof document === 'undefined') {\n return null;\n }\n if (editorRef.current !== document.activeElement) {\n return null;\n }\n\n const rect = editorRef.current?.getBoundingClientRect();\n if (!rect) {\n return null;\n }\n const { bottom: top, left } = rect;\n\n return createPortal(\n // Portaled to <body>, outside .gs-root1 / .gs-editor, so carry data-mode\n // here too — otherwise the theme-specific styles (e.g. the dark function\n // guide) never match and the help renders with the light palette.\n <div className=\"gs-editor-portal\" data-mode={mode}>\n {activeFunctionHelp &&\n filteredOptions.length === 0 &&\n (!selectingZone || (selectingZone.endY === -1 && selectingZone.endX === -1)) && (\n <FunctionGuide\n activeFunctionGuide={activeFunctionHelp}\n activeArgIndex={activeArgIndex}\n top={top}\n left={left}\n />\n )}\n {filteredOptions.length > 0 && (\n <EditorOptions\n filteredOptions={filteredOptions}\n top={top}\n left={left}\n selected={selected}\n onOptionMouseDown={handleOptionMouseDown}\n />\n )}\n </div>,\n document.body,\n );\n };\n\n const policy = sheet?.getPolicy(choosing);\n const optionsAll = policy?.getSelectOptions() ?? [];\n\n const handleSelect = useCallback((e: React.SyntheticEvent<HTMLTextAreaElement>) => {\n setSelectionStart(e.currentTarget.selectionStart);\n }, []);\n\n const {\n filteredOptions,\n selected,\n setSelected,\n replaceWithOption,\n handleArrowUp,\n handleArrowDown,\n isFormula,\n activeFunctionHelp,\n activeArgIndex,\n } = useAutocomplete({\n inputting,\n selectionStart,\n optionsAll,\n functions: sheet?.registry.functions,\n });\n\n useEffect(() => {\n focus(editorRef?.current);\n }, [editorRef]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n if (sheet.registry.lastFocused == null) {\n return;\n }\n if (sheet.registry.lastFocused !== editorRef.current) {\n return;\n }\n if (sheet.registry.lastFocused !== largeEditorRef.current) {\n return;\n }\n\n dispatch(setEditingAddress(''));\n }, [sheet?.registry.lastFocused, sheet, editorRef, largeEditorRef, dispatch]);\n useEffect(() => {\n if (!sheet) {\n return;\n }\n sheet.registry.editingSheetId = sheetId;\n sheet.registry.editingAddress = editingAddress;\n }, [editingAddress, sheet, sheetId]);\n\n useEffect(() => {\n //sheet.registry.transmit();\n expandInput(editorRef.current);\n }, [inputting, editingAddress, editorRef]);\n\n const { y, x } = choosing;\n const rowId = `${y2r(y)}`;\n const colId = x2c(x);\n const address = `${colId}${rowId}`;\n const editing = editingAddress === address;\n\n // Use 'RAW' so that spilled values (stored in solvedCaches) are already\n // reflected in cell.value without re-evaluating the formula.\n const cell = sheet?.getCell({ y, x }, { resolution: 'RAW' });\n const currentString = sheet ? sheet.getSerializedValue({ point: choosing, cell, resolution: 'RAW' }) : '';\n const [before, setBefore] = useState<string>(currentString);\n\n const writeCell = useCallback(\n (value: string) => {\n if (before !== value) {\n dispatch(write({ value }));\n }\n setBefore(value);\n },\n [before, dispatch],\n );\n\n const selectValue = useCallback(\n (selectedIndex: number) => {\n if (!sheet) {\n return;\n }\n const option = filteredOptions[selectedIndex];\n if (option) {\n if (option.isFunction) {\n const { value: newValue, selectionStart: newCursor } = replaceWithOption(option);\n dispatch(setInputting(newValue));\n\n setTimeout(() => {\n if (editorRef.current) {\n focus(editorRef.current);\n editorRef.current.setSelectionRange(newCursor, newCursor);\n }\n }, 0);\n } else {\n const t = sheet.update({\n diff: { [address]: { value: option.value } },\n partial: true,\n });\n dispatch(updateSheet(t.clone()));\n dispatch(setEditingAddress(''));\n dispatch(setInputting(''));\n }\n setSelected(0);\n }\n },\n [filteredOptions, sheet, address, inputting, writeCell, dispatch, editorRef],\n );\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n setBefore(currentString);\n dispatch(setInputting(currentString));\n resetInput(editorRef.current, sheet, choosing);\n }, [choosing, currentString, dispatch, editorRef, sheet]);\n\n const { y: top, x: left, height, width } = editorRect;\n\n const numLines = currentString.split('\\n').length;\n const [isKeyDown, setIsKeyDown] = useState(false);\n const handleKeyDown = useCallback(\n (e: EditorEventWithNativeEvent) => {\n if (!sheet) {\n return;\n }\n if (e.nativeEvent.isComposing || composingRef.current) {\n return;\n }\n if (isKeyDown) {\n return;\n }\n // do not debounce it if control key is down.\n if (!(e.key === 'Meta' || e.key === 'Control')) {\n setIsKeyDown(true);\n requestAnimationFrame(() => {\n setIsKeyDown(false);\n });\n }\n const input = e.currentTarget;\n\n // Auto-close double quotes in formula mode\n if (handleFormulaQuoteAutoClose(e, inputting)) {\n dispatch(setInputting(input.value));\n return false;\n }\n\n const shiftKey = e.shiftKey;\n switch (e.key) {\n case 'Tab': // TAB\n e.preventDefault();\n if (editing) {\n if (filteredOptions.length) {\n const isFunction = filteredOptions[selected]?.isFunction;\n selectValue(selected);\n if (isFunction) {\n return false;\n }\n } else {\n writeCell(input.value);\n dispatch(setEditingAddress(''));\n dispatch(setInputting(''));\n }\n }\n dispatch(\n walk({\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 0,\n deltaX: shiftKey ? -1 : 1,\n }),\n );\n dispatch(setEditingAddress(''));\n return false;\n\n case 'Enter': // ENTER\n if (editing) {\n if (filteredOptions.length) {\n const isFunction = filteredOptions[selected]?.isFunction;\n selectValue(selected);\n if (isFunction) {\n e.preventDefault();\n return false;\n }\n } else if (e.altKey) {\n insertTextAtCursor(input, '\\n');\n dispatch(setInputting(input.value));\n e.preventDefault();\n return false;\n } else {\n if (e.nativeEvent.isComposing) {\n return false;\n }\n writeCell(input.value);\n dispatch(setEditingAddress(''));\n dispatch(setInputting(''));\n }\n } else if (editingOnEnter && selectingZone.endY === -1) {\n const dblclick = document.createEvent('MouseEvents');\n dblclick.initEvent('dblclick', true, true);\n input.dispatchEvent(dblclick);\n e.preventDefault();\n return false;\n }\n dispatch(\n walk({\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: shiftKey ? -1 : 1,\n deltaX: 0,\n }),\n );\n e.preventDefault();\n return false;\n\n case 'Backspace': // BACKSPACE\n if (!editing) {\n // Spilled cells are read-only — clearing them would only erase the\n // cached spill value while the origin formula remains intact, causing\n // a confusing state where the FormulaBar goes blank but the cell\n // visually still shows the spilled value after re-evaluation.\n // e.preventDefault() is required here: without it the browser still\n // fires the default textarea behavior (deletes one char), which\n // triggers onInput → setInputting, making the value shrink character\n // by character on each Backspace press.\n if (sheet.getSystem({ y, x })?.spilledFrom != null) {\n e.preventDefault();\n return false;\n }\n dispatch(clear(null));\n dispatch(setInputting(''));\n return false;\n }\n break;\n case 'Delete': // DELETE\n if (!editing) {\n // Same guard as Backspace — spilled cells must not be cleared directly.\n if (sheet.getSystem({ y, x })?.spilledFrom != null) {\n e.preventDefault();\n return false;\n }\n dispatch(clear(null));\n dispatch(setInputting(''));\n return false;\n }\n break;\n case 'Shift': // SHIFT\n setShiftKey(true);\n return false;\n\n case 'Control': // CTRL\n return false;\n\n case 'Alt': // OPTION\n return false;\n\n case 'Meta': // COMMAND\n return false;\n\n case 'NumLock': // NUMLOCK\n return false;\n\n case 'Escape': // ESCAPE\n dispatch(escape(null));\n dispatch(setSearchQuery(undefined));\n dispatch(setInputting(before));\n // input.blur();\n return false;\n\n case 'ArrowLeft': // LEFT\n if (!editing) {\n if ((e.ctrlKey || e.metaKey) && shiftKey) {\n e.preventDefault();\n dispatch(selectToDataEdge({ deltaY: 0, deltaX: -1 }));\n return false;\n }\n dispatch(\n arrow({\n shiftKey,\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 0,\n deltaX: -1,\n }),\n );\n return false;\n }\n break;\n case 'ArrowUp': // UP\n if (!editing) {\n if ((e.ctrlKey || e.metaKey) && shiftKey) {\n e.preventDefault();\n dispatch(selectToDataEdge({ deltaY: -1, deltaX: 0 }));\n return false;\n }\n dispatch(\n arrow({\n shiftKey,\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: -1,\n deltaX: 0,\n }),\n );\n return false;\n }\n if (handleArrowUp(e as unknown as React.KeyboardEvent<HTMLTextAreaElement>)) {\n return true;\n }\n break;\n case 'ArrowRight': // RIGHT\n if (!editing) {\n if ((e.ctrlKey || e.metaKey) && shiftKey) {\n e.preventDefault();\n dispatch(selectToDataEdge({ deltaY: 0, deltaX: 1 }));\n return false;\n }\n dispatch(\n arrow({\n shiftKey,\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 0,\n deltaX: 1,\n }),\n );\n return false;\n }\n break;\n case 'ArrowDown': // DOWN\n if (!editing) {\n // Ctrl/Cmd+Shift+arrow: extend the selection to the data-block edge (no drag).\n if ((e.ctrlKey || e.metaKey) && shiftKey) {\n e.preventDefault();\n dispatch(selectToDataEdge({ deltaY: 1, deltaX: 0 }));\n return false;\n }\n dispatch(\n arrow({\n shiftKey,\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 1,\n deltaX: 0,\n }),\n );\n return false;\n }\n if (handleArrowDown(e as unknown as React.KeyboardEvent<HTMLTextAreaElement>)) {\n return true;\n }\n break;\n case 'a': // A\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n dispatch(\n select({\n startY: 1,\n startX: 1,\n endY: sheet.numRows,\n endX: sheet.numCols,\n }),\n );\n return false;\n }\n }\n break;\n case 'c': // C\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n const area = clip(store);\n dispatch(copy(areaToZone(area)));\n focus(input); // refocus\n return false;\n }\n return true;\n }\n break;\n case 'd': // D — fill down (Excel/Sheets Ctrl+D). Overrides the browser bookmark.\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n dispatch(fillDown(null));\n requestAnimationFrame(() => dispatch(setInputting(''))); // reset the textarea\n return false;\n }\n }\n break;\n case 'f': // F\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n if (typeof searchQuery === 'undefined') {\n dispatch(setSearchQuery(''));\n }\n dispatch(setEntering(false));\n requestAnimationFrame(() => focus(searchInputRef.current));\n return false;\n }\n }\n break;\n case 'r': // R — fill right (Excel/Sheets Ctrl+R). Overrides the browser reload.\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n dispatch(fillRight(null));\n requestAnimationFrame(() => dispatch(setInputting(''))); // reset the textarea\n return false;\n }\n }\n break;\n case 'y': // Y — redo (Ctrl+Shift+Z also redoes)\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n dispatch(redo(null));\n requestAnimationFrame(() => dispatch(setInputting(''))); // resetting textarea\n return false;\n }\n }\n break;\n case 's': // S\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n sheet.registry.onSave?.({\n sheet,\n points: {\n pointing: choosing,\n selectingFrom: {\n y: selectingZone.startY,\n x: selectingZone.startX,\n },\n selectingTo: {\n y: selectingZone.endY,\n x: selectingZone.endX,\n },\n },\n });\n return false;\n }\n }\n break;\n case 'v': // V\n if (e.ctrlKey || e.metaKey) {\n // moved to onPaste\n e.stopPropagation();\n return false;\n }\n break;\n case 'x': // X\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n const area = clip(store);\n dispatch(cut(areaToZone(area)));\n focus(input); // refocus\n return false;\n }\n }\n break;\n case 'z': // Z\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n if (e.shiftKey) {\n dispatch(redo(null));\n } else {\n dispatch(undo(null));\n }\n return false;\n }\n }\n break;\n case ';': // semicolon\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n // MAYBE: need to aware timezone.\n writeCell(new Date().toDateString());\n }\n }\n break;\n }\n if (e.ctrlKey || e.metaKey) {\n return false;\n }\n if (prevention.hasOperation(cell?.prevention, prevention.Write)) {\n console.warn('This cell is protected from writing.');\n return false;\n }\n dispatch(setEditingAddress(address));\n if (!editing) {\n dispatch(setInputting(''));\n }\n setSelected(0);\n return false;\n },\n [\n isKeyDown,\n editing,\n filteredOptions,\n selected,\n editingOnEnter,\n selectingZone,\n before,\n sheet,\n choosing,\n store,\n cell,\n address,\n writeCell,\n searchQuery,\n inputting,\n ],\n );\n\n const handleFocus = useCallback(\n (e: React.FocusEvent<HTMLTextAreaElement>) => {\n setIsFocused(true);\n if (!sheet) {\n return;\n }\n sheet.registry.lastFocused = e.currentTarget;\n },\n [sheet],\n );\n\n const handleDoubleClick = useCallback(\n (e: React.MouseEvent<HTMLTextAreaElement>) => {\n if (prevention.hasOperation(cell?.prevention, prevention.Write)) {\n console.warn('This cell is protected from writing.');\n return;\n }\n const input = e.currentTarget;\n if (!editing) {\n dispatch(setInputting(currentString));\n dispatch(setEditingAddress(address));\n requestAnimationFrame(() => {\n input.style.width = `${input.scrollWidth}px`;\n input.style.height = `${input.scrollHeight}px`;\n const length = new String(currentString).length;\n input.setSelectionRange(length, length);\n });\n }\n },\n [cell, editing, currentString, address],\n );\n\n const handleBlur = useCallback(\n (e: React.FocusEvent<HTMLTextAreaElement>) => {\n setIsFocused(false);\n if (isRefInsertable(e.currentTarget)) {\n return true;\n } else {\n if (editing) {\n writeCell(e.currentTarget.value);\n }\n }\n dispatch(setEditingAddress(''));\n },\n [editing, writeCell, dispatch],\n );\n\n const handleChange = useCallback(\n (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n if (prevention.hasOperation(cell?.prevention, prevention.Write)) {\n return;\n }\n dispatch(setInputting(e.currentTarget.value));\n setSelectionStart(e.currentTarget.selectionStart);\n setSelected(0);\n },\n [cell],\n );\n\n const handlePaste = useCallback(\n (e: React.ClipboardEvent<HTMLTextAreaElement>) => {\n if (editing) {\n return true;\n }\n\n const onlyValue = shiftKey;\n const html = e.clipboardData?.getData?.('text/html');\n if (html) {\n dispatch(paste({ matrix: parseHTML(html), onlyValue }));\n } else {\n const text = e.clipboardData?.getData?.('text/plain');\n if (text) {\n dispatch(paste({ matrix: parseText(text), onlyValue }));\n } else {\n console.warn('No clipboard data found.');\n }\n }\n e.preventDefault();\n e.stopPropagation();\n return false;\n },\n [editing, shiftKey],\n );\n\n const handleKeyUpInternal = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n setShiftKey(false);\n const selectingArea = zoneToArea(store.selectingZone);\n sheet?.registry.onKeyUp?.({\n e,\n points: {\n pointing: choosing,\n selectingFrom: { y: selectingArea.top, x: selectingArea.left },\n selectingTo: { y: selectingArea.bottom, x: selectingArea.right },\n },\n });\n },\n [store.selectingZone, choosing, sheet],\n );\n\n const handleOptionMouseDown = useCallback(\n (e: React.MouseEvent<HTMLLIElement>, index: number) => {\n selectValue(index);\n e.preventDefault();\n e.stopPropagation();\n return false;\n },\n [selectValue],\n );\n\n if (!sheet) {\n return null;\n }\n\n return (\n <Fixed\n className={`gs-editor ${editing ? 'gs-editing' : ''}`}\n style={editing ? { top, left, height } : {}}\n {...{\n 'data-mode': mode,\n 'data-sheet-id': sheetId,\n }}\n >\n <div className={`gs-cell-label ${editing ? ' gs-hidden' : ''}`}>{address}</div>\n <div className=\"gs-editor-inner\" style={{ width }}>\n <pre\n className=\"gs-editor-hl\"\n style={{\n //...cell?.style,\n height: editorRef.current?.scrollHeight,\n width: (editorRef.current?.scrollWidth ?? 0) - 4,\n }}\n >\n {(cell?.formulaEnabled ?? true) ? editorStyle(inputting) : inputting}\n </pre>\n <textarea\n data-sheet-id={sheetId}\n name=\"gs-editor-input\"\n data-size=\"small\"\n autoFocus={true}\n spellCheck={false}\n draggable={false}\n ref={editorRef}\n rows={numLines}\n onFocus={handleFocus}\n style={{ minWidth: width, minHeight: height }}\n onDoubleClick={handleDoubleClick}\n onBlur={handleBlur}\n value={inputting}\n onChange={handleChange}\n onSelect={handleSelect}\n onPaste={handlePaste}\n onKeyDown={handleKeyDown}\n onKeyUp={handleKeyUpInternal}\n onCompositionStart={() => {\n composingRef.current = true;\n if (!editing) {\n dispatch(setEditingAddress(address));\n dispatch(setInputting(''));\n }\n }}\n onCompositionEnd={(e) => {\n composingRef.current = false;\n dispatch(setInputting(e.currentTarget.value));\n }}\n onMouseEnter={() => {\n dispatch(setEditorHovering(true));\n }}\n onMouseLeave={() => {\n dispatch(setEditorHovering(false));\n }}\n />\n </div>\n {renderOverlays()}\n </Fixed>\n );\n};\n\n// Memoized token span component to prevent unnecessary re-renders\nconst TokenSpan = memo<{\n token: any;\n tokenKey: string;\n color?: string;\n className?: string;\n}>(\n ({ token, tokenKey, color, className }) => {\n return (\n <span key={tokenKey} style={color ? { color } : undefined} className={className}>\n {token.stringify()}\n </span>\n );\n },\n (prevProps, nextProps) => {\n // Custom comparison to prevent unnecessary re-renders\n return (\n prevProps.tokenKey === nextProps.tokenKey &&\n prevProps.color === nextProps.color &&\n prevProps.className === nextProps.className &&\n prevProps.token.stringify() === nextProps.token.stringify()\n );\n },\n);\n\nexport const editorStyle = (text: string) => {\n if (text[0] !== '=') {\n return <>{text}</>;\n }\n\n const lexer = new Lexer(text.substring(1));\n lexer.tokenize();\n let palletIndex = 0;\n const exists: { [ref: string]: number } = {};\n\n // Create a simple hash of the formula for stable keys\n const formulaHash = text.split('').reduce((hash, char) => {\n return ((hash << 5) - hash + char.charCodeAt(0)) & 0xffffffff;\n }, 0);\n\n return (\n <>\n =\n {lexer.tokens.map((token, i) => {\n // Handle SPACE tokens differently - render as plain text\n if (token.type === 'SPACE') {\n return <React.Fragment key={`${formulaHash}-SPACE-${i}`}>{token.stringify()}</React.Fragment>;\n }\n\n // Create a stable key based on formula hash, token content and index\n const tokenKey = `${formulaHash}-${token.type}-${token.stringify()}-${i}`;\n\n if (token.type === 'REF' || token.type === 'RANGE') {\n const normalizedToken = token.stringify();\n const existsIndex = exists[normalizedToken];\n if (existsIndex !== undefined) {\n return (\n <TokenSpan\n key={tokenKey}\n token={token}\n tokenKey={tokenKey}\n color={COLOR_PALETTE[existsIndex % COLOR_PALETTE.length]}\n />\n );\n }\n const color = COLOR_PALETTE[palletIndex % COLOR_PALETTE.length];\n exists[normalizedToken] = palletIndex++;\n return (\n <TokenSpan\n key={tokenKey}\n token={token}\n tokenKey={tokenKey}\n color={color}\n className={`gs-token-type-${token.type}`}\n />\n );\n }\n\n return (\n <TokenSpan\n key={tokenKey}\n token={token}\n tokenKey={tokenKey}\n className={`gs-token-type-${token.type} gs-token-entity-type-${typeof token.entity}`}\n />\n );\n })}\n </>\n );\n};\n","import type { ReactNode } from 'react';\nimport { createContext, useContext, useState } from 'react';\n\nimport type { StoreType } from '../types';\nimport type { Dispatcher } from '../store';\n\nexport type PluginContextType = {\n provided: boolean;\n store?: StoreType;\n apply?: Dispatcher;\n setStore: (store: StoreType) => void;\n setApply: (apply: Dispatcher) => void;\n};\n\nexport const PluginContext = createContext({} as PluginContextType);\n\nexport function useInitialPluginContext(): PluginContextType {\n const [store, setStore] = useState<StoreType | undefined>(undefined);\n const [apply, setApply] = useState<Dispatcher>();\n return {\n provided: true,\n store,\n apply,\n setStore,\n setApply,\n };\n}\n\nexport function usePluginContext(): [boolean, PluginContextType] {\n const ctx = useContext(PluginContext);\n if (ctx?.provided == null) {\n return [false, ctx];\n }\n return [true, ctx];\n}\n\nexport function usePluginDispatch() {\n const sync = useContext(PluginContext);\n if (!sync) {\n return undefined;\n }\n return sync;\n}\n\ntype Props = {\n children: ReactNode;\n context: PluginContextType;\n};\n\nexport function PluginBase({ children, context }: Props) {\n const [provided] = usePluginContext();\n if (provided) {\n return <>{children}</>;\n }\n return <PluginContext.Provider value={context}>{children}</PluginContext.Provider>;\n}\n","import type { FC, MutableRefObject } from 'react';\nimport { createRef, useContext, useEffect, useRef, useState } from 'react';\n\nimport type { OptionsType, Props, SheetHandle, StoreHandle } from '../types';\nimport { Context } from '../store';\n\nimport { setStore, updateSheet, submitAutofill, setDragging, setAutofillDraggingTo, drag } from '../store/actions';\n\nimport { usePluginContext } from './PluginBase';\nimport { Sheet } from '@gridsheet/web';\n\ntype StoreObserverProps = Omit<OptionsType, 'sheetHeight' | 'sheetWidth'> & {\n // GridSheet always passes the resolved pixel size here, even in string-based fill mode.\n sheetHeight?: number;\n sheetWidth?: number;\n fixedWidth?: boolean;\n fixedHeight?: boolean;\n sheetName?: string;\n sheetRef?: MutableRefObject<SheetHandle | null>;\n storeRef?: MutableRefObject<StoreHandle | null>;\n};\n\nexport const createSheetRef = () => createRef<SheetHandle | null>();\nexport const useSheetRef = () => useRef<SheetHandle | null>(null);\nexport const createStoreRef = () => createRef<StoreHandle | null>();\nexport const useStoreRef = () => useRef<StoreHandle | null>(null);\nexport const StoreObserver: FC<StoreObserverProps> = ({\n sheetName,\n sheetHeight,\n sheetWidth,\n fixedWidth,\n fixedHeight,\n sheetRef,\n storeRef,\n editingOnEnter,\n mode,\n}) => {\n const { store, dispatch } = useContext(Context);\n const { sheetReactive } = store;\n const sheet = sheetReactive.current;\n\n // Drag-during-scroll + robust drag-end. A capture-phase mousemove tracks the\n // cursor (Tabular stopPropagations mousemove, so bubble listeners never see it over\n // the grid). While a drag is active and the cursor is at/past a container edge (incl.\n // over the toolbar below the grid) an rAF loop scrolls and extends the selection to\n // the cell now under the cursor — but ONLY when that cell CHANGES, so holding at the\n // bottom dispatches nothing (no re-render/edit flood, no freeze). A capture mouseup\n // (and a button-up mousemove for releases we never got a mouseup for) ends it exactly\n // once and submits/clears, so autofillDraggingTo can never stay set and block clicks.\n const dragRef = useRef({ store, dispatch });\n dragRef.current = { store, dispatch };\n useEffect(() => {\n let raf = 0;\n let running = false;\n let dead = false;\n let cx = 0;\n let cy = 0;\n let lastCell = '';\n let lastExtend = 0;\n const EDGE = 0;\n const SPEED = 18;\n\n const stop = () => {\n running = false;\n cancelAnimationFrame(raf);\n };\n\n const finish = () => {\n if (dead) {\n return;\n }\n dead = true;\n stop();\n const { store: s, dispatch: d } = dragRef.current;\n if (s.autofillDraggingTo) {\n d(submitAutofill(s.autofillDraggingTo));\n }\n if (s.dragging) {\n d(setDragging(false));\n }\n };\n\n const tick = () => {\n if (dead || !running) {\n return;\n }\n const { store: s, dispatch: d } = dragRef.current;\n const el = s.tabularRef?.current;\n if (!el || !(s.dragging || s.autofillDraggingTo)) {\n running = false;\n return;\n }\n const r = el.getBoundingClientRect();\n const dy = cy > r.bottom - EDGE ? SPEED : cy < r.top + EDGE ? -SPEED : 0;\n const dx = cx > r.right - EDGE ? SPEED : cx < r.left + EDGE ? -SPEED : 0;\n if (dy || dx) {\n el.scrollTop += dy;\n el.scrollLeft += dx;\n const px = Math.min(Math.max(cx, r.left + 1), r.right - 1);\n const py = Math.min(Math.max(cy, r.top + 1), r.bottom - 1);\n const cell = (document.elementFromPoint(px, py) as HTMLElement | null)?.closest('.gs-cell') as HTMLElement | null;\n if (cell) {\n const y = Number(cell.dataset.y);\n const x = Number(cell.dataset.x);\n const key = y + ':' + x;\n const now = performance.now();\n // Dispatch only when the target cell CHANGES (holding still — e.g. at the\n // bottom over the toolbar — dispatches nothing → no freeze) AND at most every\n // 80ms (so a fast scroll doesn't re-render every frame and starve mousemove,\n // which would freeze `cy` and make the scroll unstoppable).\n if (!Number.isNaN(y) && !Number.isNaN(x) && key !== lastCell && now - lastExtend > 80) {\n lastCell = key;\n lastExtend = now;\n d(s.autofillDraggingTo ? setAutofillDraggingTo({ x, y }) : drag({ y, x }));\n }\n }\n }\n raf = requestAnimationFrame(tick);\n };\n\n const onMove = (e: MouseEvent) => {\n if (e.buttons === 0) {\n // Button up. End the drag once (covers a release we never got a mouseup for).\n const { store: s } = dragRef.current;\n if (!dead && (running || s.autofillDraggingTo != null || s.dragging)) {\n finish();\n }\n return;\n }\n cx = e.clientX;\n cy = e.clientY;\n const { store: s } = dragRef.current;\n if (!dead && !running && (s.dragging || s.autofillDraggingTo)) {\n running = true;\n lastCell = '';\n raf = requestAnimationFrame(tick);\n }\n };\n\n const onDown = () => {\n dead = false;\n };\n\n // onUp is the SOLE authority for ending a mouse drag. It is a capture-phase\n // WINDOW listener, so it fires on every mouseup before anything can stopPropagation\n // it — strictly more reliable than a cell's own onMouseUp, which in the VS Code\n // webview did NOT clear autofillDraggingTo when the release landed on a cell (it\n // stayed set and blocked every later click + froze scrolling). We submit/clear here\n // from the live store; the cell's handleDragEnd no longer submits, so there is no\n // double-fill despite this firing first (capture) then the cell's handler (bubble).\n const onUp = () => {\n dead = true;\n stop();\n const { store: s, dispatch: d } = dragRef.current;\n if (s.autofillDraggingTo) {\n d(submitAutofill(s.autofillDraggingTo));\n }\n if (s.dragging) {\n d(setDragging(false));\n }\n };\n\n // A drag can end WITHOUT a mouseup we ever see: the user drags the autofill\n // handle past the grid, out of the webview/window entirely, and releases there.\n // No mouseup → the old code left dragging/autofillDraggingTo stuck and the\n // rAF loop scrolling+extending forever. Ending the drag when the pointer leaves\n // the document (mouseleave) or the window loses focus (blur) closes that hole.\n // Scrolling OVER the in-grid toolbar still works: that stays inside the document,\n // so neither fires until the cursor exits the webview.\n const onLeaveWindow = () => finish();\n\n window.addEventListener('mousedown', onDown, true);\n window.addEventListener('mousemove', onMove, true);\n window.addEventListener('mouseup', onUp, true);\n window.addEventListener('blur', onLeaveWindow);\n document.addEventListener('mouseleave', onLeaveWindow);\n return () => {\n window.removeEventListener('mousedown', onDown, true);\n window.removeEventListener('mousemove', onMove, true);\n window.removeEventListener('mouseup', onUp, true);\n window.removeEventListener('blur', onLeaveWindow);\n document.removeEventListener('mouseleave', onLeaveWindow);\n cancelAnimationFrame(raf);\n };\n }, []);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n if (sheetName && sheetName !== sheet.name) {\n sheet.name = sheetName;\n sheet.registry.sheetIdsByName[sheetName] = sheet.id;\n delete sheet.registry.sheetIdsByName[sheet.prevName];\n sheet.prevName = sheetName;\n //book.transmit();\n }\n }, [sheetName]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n const { registry } = sheet;\n requestAnimationFrame(() => registry.boot());\n registry.contextsBySheetId[sheet.id] = { store, dispatch };\n registry.transmit();\n\n if (sheetRef) {\n sheetRef.current = {\n sheet,\n apply: (sheet) => {\n dispatch(updateSheet(sheet as Sheet));\n },\n };\n }\n if (storeRef) {\n storeRef.current = {\n store,\n apply: (store) => {\n dispatch(setStore(store));\n },\n dispatch,\n };\n }\n }, [store, sheet, sheetRef, storeRef]);\n\n useEffect(() => {\n if (sheetHeight) {\n dispatch(setStore({ sheetHeight }));\n }\n }, [sheetHeight, dispatch]);\n useEffect(() => {\n if (sheetWidth) {\n dispatch(setStore({ sheetWidth }));\n }\n }, [sheetWidth]);\n useEffect(() => {\n dispatch(setStore({ fixedWidth: !!fixedWidth, fixedHeight: !!fixedHeight }));\n }, [fixedWidth, fixedHeight]);\n useEffect(() => {\n if (typeof editingOnEnter !== 'undefined') {\n dispatch(setStore({ editingOnEnter }));\n }\n }, [editingOnEnter]);\n useEffect(() => {\n if (mode) {\n dispatch(setStore({ mode }));\n }\n }, [mode]);\n\n const [pluginProvided, pluginContext] = usePluginContext();\n useEffect(() => {\n if (!pluginProvided) {\n return;\n }\n pluginContext.setStore(store);\n pluginContext.setApply(() => dispatch);\n }, [store, pluginProvided, pluginContext]);\n\n return <></>;\n};\n","import { useContext } from 'react';\nimport type { MouseEvent } from 'react';\n\nimport { Context } from '../store';\nimport { setResizingPositionY, setResizingPositionX, updateSheet, setStore } from '../store/actions';\n\nimport { DEFAULT_HEIGHT, DEFAULT_WIDTH, MIN_WIDTH, MIN_HEIGHT } from '@gridsheet/web';\nimport { zoneToArea, makeSequence, between } from '@gridsheet/web';\nimport type { CellsByAddressType } from '../types';\nimport { p2a } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\n\nexport const Resizer = () => {\n const { store, dispatch } = useContext(Context);\n const {\n resizingPositionY: posY,\n resizingPositionX: posX,\n sheetReactive: sheetRef,\n leftHeaderSelecting,\n topHeaderSelecting,\n selectingZone,\n editorRef,\n mainRef,\n } = store;\n const sheet = sheetRef.current;\n\n const [y, startY, endY] = posY;\n const [x, startX, endX] = posX;\n\n if (mainRef.current == null || editorRef.current == null || !sheet) {\n return <div className=\"gs-resizing gs-hidden\" />;\n }\n\n const cell = sheet.getCell({ y: y === -1 ? 0 : y, x: x === -1 ? 0 : x }, { resolution: 'SYSTEM' });\n const { y: offsetY, x: offsetX } = mainRef.current.getBoundingClientRect();\n\n const baseWidth = cell?.width || DEFAULT_WIDTH;\n const baseHeight = cell?.height || DEFAULT_HEIGHT;\n\n const width = baseWidth + (endX - startX);\n const height = baseHeight + (endY - startY);\n\n const handleResizeEnd = () => {\n const selectingArea = zoneToArea(selectingZone);\n const { top, left, bottom, right } = selectingArea;\n const diff: CellsByAddressType = {};\n if (x !== -1) {\n let xs = [x];\n if (topHeaderSelecting && between({ start: left, end: right }, x)) {\n xs = makeSequence(left, right + 1);\n }\n xs.forEach((x) => {\n diff[p2a({ y: 0, x })] = { width };\n });\n }\n if (y !== -1) {\n let ys = [y];\n if (leftHeaderSelecting && between({ start: top, end: bottom }, y)) {\n ys = makeSequence(top, bottom + 1);\n }\n ys.forEach((y) => {\n diff[p2a({ y, x: 0 })] = { height };\n });\n }\n sheet.update({\n diff,\n partial: true,\n operator: 'USER',\n undoReflection: { selectingZone, sheetId: sheet.id },\n });\n dispatch(\n setStore({\n sheetReactive: { current: sheet },\n }),\n );\n dispatch(setResizingPositionY([-1, -1, -1]));\n dispatch(setResizingPositionX([-1, -1, -1]));\n focus(editorRef.current);\n };\n const handleResizeMove = (e: MouseEvent) => {\n if (y !== -1) {\n let endY = e.clientY;\n const height = baseHeight + (endY - startY);\n if (height < MIN_HEIGHT) {\n endY += MIN_HEIGHT - height;\n }\n dispatch(setResizingPositionY([y, startY, endY]));\n } else if (x !== -1) {\n let endX = e.clientX;\n const width = baseWidth + (endX - startX);\n if (width < MIN_WIDTH) {\n endX += MIN_WIDTH - width;\n }\n dispatch(setResizingPositionX([x, startX, endX]));\n }\n };\n\n return (\n <div\n className={`gs-resizing ${y === -1 && x === -1 ? 'gs-hidden' : ''}`}\n onMouseUp={handleResizeEnd}\n onMouseMove={handleResizeMove}\n >\n <div className={`gs-line-vertical ${x === -1 ? 'gs-hidden' : ''}`}>\n <div className={'gs-line'} style={{ width: 1, height: '100%', left: endX - offsetX }}>\n <span style={{ left: '-50%' }}>{width}px</span>\n </div>\n </div>\n <div className={`gs-line-horizontal ${y === -1 ? 'gs-hidden' : ''}`}>\n <div className={'gs-line'} style={{ width: '100%', height: 1, top: endY - offsetY }}>\n <span style={{ top: '-50%' }}>{height}px</span>\n </div>\n </div>\n </div>\n );\n};\n","import type { FC } from 'react';\nimport { useContext, useEffect, useRef } from 'react';\nimport { Context } from '../store';\n\nexport const Emitter: FC = () => {\n const { store } = useContext(Context);\n const { choosing: pointing, selectingZone: zone, sheetReactive } = store;\n const sheet = sheetReactive.current;\n\n useEffect(() => {\n if (sheet?.isInitialized && sheet.currentVersion > 0 && sheet.registry.onChange) {\n sheet.registry.onChange({\n sheet,\n points: {\n pointing,\n selectingFrom: { y: zone.startY, x: zone.startX },\n selectingTo: { y: zone.endY, x: zone.endX },\n },\n });\n }\n }, [sheetReactive]);\n\n useEffect(() => {\n if (sheet && sheet.registry.onSelect) {\n sheet.registry.onSelect({\n sheet,\n points: {\n pointing,\n selectingFrom: { y: zone.startY, x: zone.startX },\n selectingTo: { y: zone.endY, x: zone.endX },\n },\n });\n }\n }, [pointing, zone]);\n return null;\n};\n","import type { StoreDispatchType, FilterConfig, RawCellType } from '../types';\nimport { areaToZone, zoneShape, zoneToArea } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { p2a } from '@gridsheet/web';\nimport {\n copy,\n cut,\n paste,\n undo,\n redo,\n insertRowsAbove,\n insertRowsBelow,\n insertColsLeft,\n insertColsRight,\n removeRows,\n removeCols,\n sortRows,\n filterRows,\n setSearchQuery,\n setEntering,\n updateSheet,\n} from './actions';\nimport { clip } from '../lib/clipboard';\nimport { parseHTML, parseText } from '../lib/paste';\n\nexport const copier = async ({ store, dispatch }: StoreDispatchType) => {\n const { editorRef } = store;\n const area = clip(store);\n dispatch(copy(areaToZone(area)));\n focus(editorRef.current);\n};\n\nexport const cutter = async ({ store, dispatch }: StoreDispatchType) => {\n const { editorRef } = store;\n const area = clip(store);\n dispatch(cut(areaToZone(area)));\n focus(editorRef.current);\n};\n\nexport const paster = async ({ store, dispatch }: StoreDispatchType, onlyValue = false) => {\n const { editorRef } = store;\n const items = await navigator.clipboard.read();\n let cells: RawCellType[][] = [];\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n if (item.types.indexOf('text/html') !== -1) {\n const blob = await item.getType('text/html');\n const html = await blob.text();\n if (html) {\n cells = parseHTML(html, onlyValue);\n break;\n }\n } else if (item.types.indexOf('text/plain') !== -1) {\n const blob = await item.getType('text/plain');\n const text = await blob.text();\n if (text) {\n cells = parseText(text);\n break;\n }\n }\n }\n dispatch(paste({ matrix: cells, onlyValue }));\n focus(editorRef.current);\n};\n\nexport const undoer = async ({ store, dispatch }: StoreDispatchType) => {\n const { editorRef } = store;\n dispatch(undo(null));\n focus(editorRef.current);\n};\n\nexport const redoer = async ({ store, dispatch }: StoreDispatchType) => {\n const { editorRef } = store;\n dispatch(redo(null));\n focus(editorRef.current);\n};\n\nexport const rowsInserterAbove = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { top } = zoneToArea(selectingZone);\n const numRows = zoneShape(selectingZone).rows;\n dispatch(insertRowsAbove({ numRows, y: top, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const rowsInserterBelow = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { bottom } = zoneToArea(selectingZone);\n const numRows = zoneShape(selectingZone).rows;\n dispatch(insertRowsBelow({ numRows, y: bottom, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const colsInserterLeft = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { left } = zoneToArea(selectingZone);\n const numCols = zoneShape(selectingZone).cols;\n dispatch(insertColsLeft({ numCols, x: left, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const colsInserterRight = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { right } = zoneToArea(selectingZone);\n const numCols = zoneShape(selectingZone).cols;\n dispatch(insertColsRight({ numCols, x: right, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const rowsRemover = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { top } = zoneToArea(selectingZone);\n const numRows = zoneShape(selectingZone).rows;\n dispatch(removeRows({ numRows, y: top, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const colsRemover = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { left } = zoneToArea(selectingZone);\n const numCols = zoneShape(selectingZone).cols;\n dispatch(removeCols({ numCols, x: left, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const rowsSorterAsc = async ({ store, dispatch }: StoreDispatchType, x: number) => {\n const sheet = store.sheetReactive.current;\n if (sheet && (sheet.hasPendingCells() || sheet.registry.asyncPending.size > 0)) {\n await sheet.waitForPending();\n }\n dispatch(sortRows({ x, direction: 'asc' }));\n focus(store.editorRef.current);\n};\n\nexport const rowsSorterDesc = async ({ store, dispatch }: StoreDispatchType, x: number) => {\n const sheet = store.sheetReactive.current;\n if (sheet && (sheet.hasPendingCells() || sheet.registry.asyncPending.size > 0)) {\n await sheet.waitForPending();\n }\n dispatch(sortRows({ x, direction: 'desc' }));\n focus(store.editorRef.current);\n};\n\nexport const rowsFilterer = async ({ store, dispatch }: StoreDispatchType, x: number, filter: FilterConfig) => {\n const sheet = store.sheetReactive.current;\n if (sheet && (sheet.hasPendingCells() || sheet.registry.asyncPending.size > 0)) {\n await sheet.waitForPending();\n }\n dispatch(filterRows({ x, filter }));\n focus(store.editorRef.current);\n};\n\nexport const rowsFilterClearer = async ({ store, dispatch }: StoreDispatchType, x?: number) => {\n dispatch(filterRows({ x }));\n focus(store.editorRef.current);\n};\n\nexport const rowSortFixedToggler = ({ store, dispatch }: StoreDispatchType, y: number) => {\n const sheet = store.sheetReactive.current;\n if (!sheet) {\n return;\n }\n const addr = p2a({ y, x: 0 });\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n const next = !rowCell?.sortFixed || undefined;\n sheet.update({ diff: { [addr]: { sortFixed: next } }, partial: true });\n dispatch(updateSheet(sheet));\n focus(store.editorRef.current);\n};\n\nexport const rowFilterFixedToggler = ({ store, dispatch }: StoreDispatchType, y: number) => {\n const sheet = store.sheetReactive.current;\n if (!sheet) {\n return;\n }\n const addr = p2a({ y, x: 0 });\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n const next = !rowCell?.filterFixed || undefined;\n sheet.update({ diff: { [addr]: { filterFixed: next } }, partial: true });\n dispatch(updateSheet(sheet));\n focus(store.editorRef.current);\n};\n\nexport const searcher = async ({ store, dispatch }: StoreDispatchType) => {\n if (typeof store.searchQuery === 'undefined') {\n dispatch(setSearchQuery(''));\n }\n dispatch(setEntering(false));\n requestAnimationFrame(() => focus(store.searchInputRef.current));\n};\n\nexport const applyers = {\n copy: copier,\n cut: cutter,\n paste: paster,\n undo: undoer,\n redo: redoer,\n insertRowsAbove: rowsInserterAbove,\n insertRowsBelow: rowsInserterBelow,\n insertColsLeft: colsInserterLeft,\n insertColsRight: colsInserterRight,\n removeRows: rowsRemover,\n removeCols: colsRemover,\n sortRowsAsc: rowsSorterAsc,\n sortRowsDesc: rowsSorterDesc,\n filterRows: rowsFilterer,\n clearFilter: rowsFilterClearer,\n toggleSortFixed: rowSortFixedToggler,\n toggleFilterFixed: rowFilterFixedToggler,\n search: searcher,\n};\n","/**\n * Menu system — types, default descriptors, and MenuContext builder.\n */\n\n// ---- types ----------------------------------------------------------------\n\nimport type { PointType, ZoneType, FilterConfig } from '../types';\nimport type { UserSheet } from '@gridsheet/web';\nimport type { StoreType } from '../types';\nimport type { Dispatcher } from '../store';\nimport { operations as prevention } from '@gridsheet/web';\nimport { zoneShape } from '@gridsheet/web';\nimport { p2a } from '@gridsheet/web';\nimport {\n copier,\n cutter,\n paster,\n undoer,\n redoer,\n rowsSorterAsc,\n rowsSorterDesc,\n rowsFilterer,\n rowsFilterClearer,\n rowSortFixedToggler,\n rowFilterFixedToggler,\n searcher,\n} from '../store/applyers';\nimport {\n insertRowsAbove as _insertRowsAbove,\n insertRowsBelow as _insertRowsBelow,\n removeRows as _removeRows,\n insertColsLeft as _insertColsLeft,\n insertColsRight as _insertColsRight,\n removeCols as _removeCols,\n setStore as _setStore,\n} from '../store/actions';\n\nexport type MenuContext = {\n /** Current sheet instance */\n sheet: UserSheet;\n /** Currently focused cell */\n choosing: PointType;\n /** Currently selected zone */\n selectingZone: ZoneType;\n /** True when the left (row) header is being selected */\n leftHeaderSelecting: boolean;\n /** True when the top (column) header is being selected */\n topHeaderSelecting: boolean;\n\n // ---- actions ----\n cut(): Promise<void>;\n copy(): Promise<void>;\n paste(onlyValue?: boolean): Promise<void>;\n undo(): void;\n redo(): void;\n insertRowsAbove(y: number, numRows: number): void;\n insertRowsBelow(y: number, numRows: number): void;\n removeRows(y: number, numRows: number): void;\n insertColsLeft(x: number, numCols: number): void;\n insertColsRight(x: number, numCols: number): void;\n removeCols(x: number, numCols: number): void;\n sortRows(x: number, direction: 'asc' | 'desc'): Promise<void>;\n filterRows(x: number, filter?: FilterConfig): Promise<void>;\n clearFilter(x?: number): void;\n toggleSortFixed(y: number): void;\n toggleFilterFixed(y: number): void;\n search(): void;\n updateColLabel(x: number, label: string | undefined): void;\n /** Close the currently open menu */\n close(): void;\n};\n\nexport type MenuDividerItem = { type: 'divider'; visible?: (ctx: MenuContext) => boolean };\n\n/**\n * Base structure shared by all menu item descriptors.\n * `Args` is the tuple of coordinate arguments passed after `ctx`:\n * - `[]` → ContextMenu (no coordinate)\n * - `[y: number]` → RowMenu\n * - `[x: number]` → ColMenu\n */\nexport type MenuItemBase<Args extends unknown[] = []> = {\n type?: 'item';\n id?: string;\n label: string | ((ctx: MenuContext, ...args: Args) => string);\n shortcuts?: string[] | ((ctx: MenuContext, ...args: Args) => string[]);\n visible?: (ctx: MenuContext, ...args: Args) => boolean;\n disabled?: (ctx: MenuContext, ...args: Args) => boolean;\n /** Render a checkmark prefix when defined. */\n checked?: (ctx: MenuContext, ...args: Args) => boolean;\n onClick: (ctx: MenuContext, ...args: Args) => void | Promise<void>;\n};\n\n/**\n * A menu entry that renders a registered React component.\n * Use `registerMenuComponent(id, Component)` to associate an id with a component,\n * then reference it here as `{ type: 'component', componentId: id }`.\n */\nexport type MenuComponentItem<Args extends unknown[] = []> = {\n type: 'component';\n componentId: string;\n visible?: (ctx: MenuContext, ...args: Args) => boolean;\n};\n\n/**\n * A menu entry that opens a nested flyout of child items on hover. `children` uses the same\n * descriptor shape (items, dividers, or further submenus), so menus can nest arbitrarily —\n * useful when a category (e.g. cell \"Format\") has more options than fit in one flat list.\n */\nexport type MenuSubmenuItem<Args extends unknown[] = []> = {\n type: 'submenu';\n id?: string;\n label: string | ((ctx: MenuContext, ...args: Args) => string);\n visible?: (ctx: MenuContext, ...args: Args) => boolean;\n disabled?: (ctx: MenuContext, ...args: Args) => boolean;\n children: (MenuDividerItem | MenuItemBase<Args> | MenuSubmenuItem<Args>)[];\n};\n\nexport type ContextMenuItemDescriptor = MenuDividerItem | MenuItemBase | MenuComponentItem | MenuSubmenuItem;\nexport type RowMenuItemDescriptor =\n | MenuDividerItem\n | MenuItemBase<[y: number]>\n | MenuComponentItem<[y: number]>\n | MenuSubmenuItem<[y: number]>;\nexport type ColMenuItemDescriptor =\n | MenuDividerItem\n | MenuItemBase<[x: number]>\n | MenuComponentItem<[x: number]>\n | MenuSubmenuItem<[x: number]>;\n\n// ---- helpers ---------------------------------------------------------------\n\nconst rowInsertCount = (ctx: MenuContext, y: number): number => {\n const { selectingZone } = ctx;\n const selStart = Math.min(selectingZone.startY, selectingZone.endY);\n const selEnd = Math.max(selectingZone.startY, selectingZone.endY);\n const isFullRow = selectingZone.startX === 1 && selectingZone.endX === ctx.sheet.numCols;\n return isFullRow && y >= selStart && y <= selEnd ? selEnd - selStart + 1 : 1;\n};\n\nconst colInsertCount = (ctx: MenuContext, x: number): number => {\n const { selectingZone } = ctx;\n const selStart = Math.min(selectingZone.startX, selectingZone.endX);\n const selEnd = Math.max(selectingZone.startX, selectingZone.endX);\n const isFullCol = selectingZone.startY === 1 && selectingZone.endY === ctx.sheet.numRows;\n return isFullCol && x >= selStart && x <= selEnd ? selEnd - selStart + 1 : 1;\n};\n\n// ---- default descriptors ---------------------------------------------------\n\nexport const defaultContextMenuDescriptors: ContextMenuItemDescriptor[] = [\n {\n id: 'cut',\n label: 'Cut',\n shortcuts: ['X'],\n onClick: (ctx) => ctx.cut(),\n },\n {\n id: 'copy',\n label: 'Copy',\n shortcuts: ['C'],\n onClick: (ctx) => ctx.copy(),\n },\n {\n id: 'paste',\n label: 'Paste',\n shortcuts: ['V'],\n onClick: (ctx) => ctx.paste(false),\n },\n {\n id: 'paste-only-value',\n label: 'Paste only value',\n shortcuts: ['Shift+V'],\n onClick: (ctx) => ctx.paste(true),\n },\n { type: 'divider', visible: (ctx) => ctx.leftHeaderSelecting || ctx.topHeaderSelecting },\n {\n id: 'insert-rows-above',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n return `Insert ${n} row${n > 1 ? 's' : ''} above`;\n },\n visible: (ctx) => ctx.leftHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y: ctx.choosing.y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumRows !== -1 && sheet.numRows + n > sheet.maxNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.InsertRowsAbove)\n );\n },\n onClick: (ctx) => ctx.insertRowsAbove(ctx.choosing.y, zoneShape(ctx.selectingZone).rows),\n },\n {\n id: 'insert-rows-below',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n return `Insert ${n} row${n > 1 ? 's' : ''} below`;\n },\n visible: (ctx) => ctx.leftHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y: ctx.choosing.y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumRows !== -1 && sheet.numRows + n > sheet.maxNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.InsertRowsBelow)\n );\n },\n onClick: (ctx) => ctx.insertRowsBelow(ctx.choosing.y, zoneShape(ctx.selectingZone).rows),\n },\n {\n id: 'insert-cols-left',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n return `Insert ${n} column${n > 1 ? 's' : ''} left`;\n },\n visible: (ctx) => ctx.topHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x: ctx.choosing.x }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumCols !== -1 && sheet.numCols + n > sheet.maxNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.InsertColsLeft)\n );\n },\n onClick: (ctx) => ctx.insertColsLeft(ctx.choosing.x, zoneShape(ctx.selectingZone).cols),\n },\n {\n id: 'insert-cols-right',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n return `Insert ${n} column${n > 1 ? 's' : ''} right`;\n },\n visible: (ctx) => ctx.topHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x: ctx.choosing.x }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumCols !== -1 && sheet.numCols + n > sheet.maxNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.InsertColsRight)\n );\n },\n onClick: (ctx) => ctx.insertColsRight(ctx.choosing.x, zoneShape(ctx.selectingZone).cols),\n },\n {\n id: 'remove-rows',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n return `Remove ${n} row${n > 1 ? 's' : ''}`;\n },\n visible: (ctx) => ctx.leftHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y: ctx.choosing.y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.minNumRows !== -1 && sheet.numRows - n < sheet.minNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.RemoveRows)\n );\n },\n onClick: (ctx) => ctx.removeRows(ctx.choosing.y, zoneShape(ctx.selectingZone).rows),\n },\n {\n id: 'remove-cols',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n return `Remove ${n} column${n > 1 ? 's' : ''}`;\n },\n visible: (ctx) => ctx.topHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x: ctx.choosing.x }, { resolution: 'SYSTEM' });\n return (\n (sheet.minNumCols !== -1 && sheet.numCols - n < sheet.minNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.RemoveCols)\n );\n },\n onClick: (ctx) => ctx.removeCols(ctx.choosing.x, zoneShape(ctx.selectingZone).cols),\n },\n { type: 'divider' },\n {\n id: 'undo',\n label: 'Undo',\n shortcuts: ['Z'],\n disabled: (ctx) => ctx.sheet.historyIndex() <= -1,\n onClick: (ctx) => ctx.undo(),\n },\n {\n id: 'redo',\n label: 'Redo',\n shortcuts: ['R', 'Y', 'Shift+Z'],\n disabled: (ctx) => ctx.sheet.historyIndex() >= ctx.sheet.historySize() - 1,\n onClick: (ctx) => ctx.redo(),\n },\n { type: 'divider' },\n {\n id: 'search',\n label: 'Search',\n shortcuts: ['F'],\n onClick: (ctx) => ctx.search(),\n },\n];\n\nexport const defaultRowMenuDescriptors: RowMenuItemDescriptor[] = [\n {\n id: 'cut',\n label: 'Cut',\n shortcuts: ['X'],\n onClick: (ctx) => ctx.cut(),\n },\n {\n id: 'copy',\n label: 'Copy',\n shortcuts: ['C'],\n onClick: (ctx) => ctx.copy(),\n },\n {\n id: 'paste',\n label: 'Paste',\n shortcuts: ['V'],\n onClick: (ctx) => ctx.paste(false),\n },\n {\n id: 'paste-only-value',\n label: 'Paste only value',\n shortcuts: ['Shift+V'],\n onClick: (ctx) => ctx.paste(true),\n },\n { type: 'divider' },\n {\n id: 'insert-rows-above',\n label: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n return `Insert ${n} row${n > 1 ? 's' : ''} above`;\n },\n disabled: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumRows !== -1 && sheet.numRows + n > sheet.maxNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.InsertRowsAbove)\n );\n },\n onClick: (ctx, y) => ctx.insertRowsAbove(y, rowInsertCount(ctx, y)),\n },\n {\n id: 'insert-rows-below',\n label: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n return `Insert ${n} row${n > 1 ? 's' : ''} below`;\n },\n disabled: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumRows !== -1 && sheet.numRows + n > sheet.maxNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.InsertRowsBelow)\n );\n },\n onClick: (ctx, y) => ctx.insertRowsBelow(y, rowInsertCount(ctx, y)),\n },\n {\n id: 'remove-rows',\n label: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n return `Remove ${n} row${n > 1 ? 's' : ''}`;\n },\n disabled: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.minNumRows !== -1 && sheet.numRows - n < sheet.minNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.RemoveRows)\n );\n },\n onClick: (ctx, y) => ctx.removeRows(y, rowInsertCount(ctx, y)),\n },\n { type: 'divider' },\n {\n id: 'toggle-sort-fixed',\n label: 'Fix row for sorting',\n checked: (ctx, y) => !!ctx.sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' })?.sortFixed,\n onClick: (ctx, y) => ctx.toggleSortFixed(y),\n },\n {\n id: 'toggle-filter-fixed',\n label: 'Fix row for filtering',\n checked: (ctx, y) => !!ctx.sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' })?.filterFixed,\n onClick: (ctx, y) => ctx.toggleFilterFixed(y),\n },\n { type: 'divider' },\n {\n id: 'search',\n label: 'Search',\n shortcuts: ['F'],\n onClick: (ctx) => ctx.search(),\n },\n];\n\n// The col menu composes registered section components (filter, sort, label) and\n// simple menu items. Use `registerMenuComponent` to override built-in sections.\nexport const defaultColMenuDescriptors: ColMenuItemDescriptor[] = [\n { type: 'component', componentId: 'col-label' },\n { type: 'divider' },\n { type: 'component', componentId: 'col-filter' },\n { type: 'divider' },\n { type: 'component', componentId: 'col-sort' },\n { type: 'divider' },\n {\n id: 'cut',\n label: 'Cut',\n shortcuts: ['X'],\n onClick: (ctx) => ctx.cut(),\n },\n {\n id: 'copy',\n label: 'Copy',\n shortcuts: ['C'],\n onClick: (ctx) => ctx.copy(),\n },\n {\n id: 'paste',\n label: 'Paste',\n shortcuts: ['V'],\n onClick: (ctx) => ctx.paste(false),\n },\n {\n id: 'paste-only-value',\n label: 'Paste only value',\n shortcuts: ['Shift+V'],\n onClick: (ctx) => ctx.paste(true),\n },\n { type: 'divider' },\n {\n id: 'insert-cols-left',\n label: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n return `Insert ${n} column${n > 1 ? 's' : ''} left`;\n },\n disabled: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumCols !== -1 && sheet.numCols + n > sheet.maxNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.InsertColsLeft)\n );\n },\n onClick: (ctx, x) => ctx.insertColsLeft(x, colInsertCount(ctx, x)),\n },\n {\n id: 'insert-cols-right',\n label: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n return `Insert ${n} column${n > 1 ? 's' : ''} right`;\n },\n disabled: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumCols !== -1 && sheet.numCols + n > sheet.maxNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.InsertColsRight)\n );\n },\n onClick: (ctx, x) => ctx.insertColsRight(x, colInsertCount(ctx, x)),\n },\n {\n id: 'remove-cols',\n label: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n return `Remove ${n} column${n > 1 ? 's' : ''}`;\n },\n disabled: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n return (\n (sheet.minNumCols !== -1 && sheet.numCols - n < sheet.minNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.RemoveCols)\n );\n },\n onClick: (ctx, x) => ctx.removeCols(x, colInsertCount(ctx, x)),\n },\n { type: 'divider' },\n {\n id: 'search',\n label: 'Search',\n shortcuts: ['F'],\n onClick: (ctx) => ctx.search(),\n },\n];\n\n// ---- buildMenuContext -------------------------------------------------------\n\nexport function buildMenuContext(store: StoreType, dispatch: Dispatcher, close: () => void): MenuContext {\n const props = { store, dispatch };\n const sheet = store.sheetReactive.current!;\n\n return {\n sheet,\n choosing: store.choosing,\n selectingZone: store.selectingZone,\n leftHeaderSelecting: store.leftHeaderSelecting,\n topHeaderSelecting: store.topHeaderSelecting,\n\n cut: () => cutter(props),\n copy: () => copier(props),\n paste: (onlyValue = false) => paster(props, onlyValue),\n undo: () => undoer(props),\n redo: () => redoer(props),\n\n insertRowsAbove: (y, numRows) => {\n dispatch(_insertRowsAbove({ numRows, y, operator: 'USER' }));\n },\n insertRowsBelow: (y, numRows) => {\n dispatch(_insertRowsBelow({ numRows, y, operator: 'USER' }));\n },\n removeRows: (y, numRows) => {\n dispatch(_removeRows({ numRows, y, operator: 'USER' }));\n },\n insertColsLeft: (x, numCols) => {\n dispatch(_insertColsLeft({ numCols, x, operator: 'USER' }));\n },\n insertColsRight: (x, numCols) => {\n dispatch(_insertColsRight({ numCols, x, operator: 'USER' }));\n },\n removeCols: (x, numCols) => {\n dispatch(_removeCols({ numCols, x, operator: 'USER' }));\n },\n\n sortRows: async (x, direction) => {\n if (direction === 'asc') {\n await rowsSorterAsc(props, x);\n } else {\n await rowsSorterDesc(props, x);\n }\n },\n filterRows: async (x, filter) => {\n if (filter) {\n await rowsFilterer(props, x, filter);\n } else {\n rowsFilterClearer(props, x);\n }\n },\n clearFilter: (x) => rowsFilterClearer(props, x),\n\n toggleSortFixed: (y) => rowSortFixedToggler(props, y),\n toggleFilterFixed: (y) => rowFilterFixedToggler(props, y),\n\n search: () => searcher(props),\n\n updateColLabel: (x, label) => {\n if (!sheet) {\n return;\n }\n const addr = p2a({ y: 0, x });\n sheet.update({\n diff: { [addr]: { label: label || undefined } },\n partial: true,\n undoReflection: {\n sheetId: sheet.id,\n selectingZone: store.selectingZone,\n choosing: store.choosing,\n },\n redoReflection: {\n sheetId: sheet.id,\n selectingZone: store.selectingZone,\n choosing: store.choosing,\n },\n });\n dispatch(_setStore({ sheetReactive: { current: sheet } }));\n },\n\n close,\n };\n}\n\n// ---- menu component registry -----------------------------------------------\n\nimport type { FC } from 'react';\n\nexport type ContextMenuSectionProps = {\n close: () => void;\n};\n\nexport type RowMenuSectionProps = {\n y: number;\n close: () => void;\n};\n\nexport type ColMenuSectionProps = {\n x: number;\n close: () => void;\n /** Signal waiting state to parent menu. Pass null to clear. */\n onWaiting?: (message: string | null, cancel?: () => void) => void;\n};\n\nconst _menuComponentRegistry = new Map<string, FC<any>>();\n\n/**\n * Register a React component under a string id so it can be referenced in menu\n * descriptors via `{ type: 'component', componentId: '...' }`.\n *\n * Built-in ids: `'col-filter'`, `'col-sort'`, `'col-label'`.\n * You can override any built-in by registering your own component with the same id.\n */\n\nexport function registerMenuComponent(id: string, component: FC<any>): void {\n _menuComponentRegistry.set(id, component);\n}\n\n/** Look up a previously registered component by id. */\n\nexport function getMenuComponent(id: string): FC<any> | undefined {\n return _menuComponentRegistry.get(id);\n}\n","import type { FC } from 'react';\n\ntype MenuItemProps = {\n label: string;\n shortcuts?: string[];\n disabled?: boolean;\n /**\n * undefined → no check column\n * true/false → displayed as a toggle row with a checkmark\n */\n checked?: boolean;\n testId?: string;\n onClick?: () => void;\n className?: string;\n};\n\nexport const MenuItem: FC<MenuItemProps> = ({\n label,\n shortcuts,\n disabled = false,\n checked,\n testId,\n onClick,\n className,\n}) => {\n const hasCheck = checked !== undefined;\n return (\n <li\n className={`gs-menu-item ${disabled ? 'gs-disabled' : 'gs-enabled'}${className ? ` ${className}` : ''}`}\n data-testid={testId}\n onClick={disabled ? undefined : onClick}\n >\n <div className={`gs-menu-name${hasCheck ? ' gs-row-fixed-toggle' : ''}`}>\n {hasCheck && <span className={`gs-row-fixed-check${checked ? ' gs-row-fixed-active' : ''}`}>✓</span>}\n {label}\n </div>\n {shortcuts != null && shortcuts.length > 0 && (\n <div className=\"gs-menu-shortcut\">\n {shortcuts.map((shortcut, i) => (\n <span key={i}>\n {i > 0 && <span className=\"gs-menu-shortcut-sep\">, </span>}\n <span className=\"gs-menu-shortcut-badge\">\n {shortcut.split('+').map((part, j, arr) =>\n j < arr.length - 1 ? (\n <span key={j}>{part}+</span>\n ) : (\n <span key={j} className=\"gs-menu-underline\">\n {part}\n </span>\n ),\n )}\n </span>\n </span>\n ))}\n </div>\n )}\n </li>\n );\n};\n\nexport const MenuDivider: FC = () => <li className=\"gs-menu-divider\" />;\n","import { type FC, type ReactNode, useState, useRef, useLayoutEffect } from 'react';\nimport type { MenuContext } from '../lib/menu';\nimport { MenuItem, MenuDivider } from './MenuItem';\n\n// Loose structural view of a menu descriptor shared by all three menus (context/row/col).\n// The public descriptor unions in menu.ts stay type-safe per menu; this renderer takes the\n// trailing coordinate args generically (`[]` / `[x]` / `[y]`) so one implementation drives\n// items, dividers, registered components, and nested submenus for every menu.\nexport type MenuNode = {\n type?: 'item' | 'divider' | 'component' | 'submenu';\n id?: string;\n componentId?: string;\n label?: string | ((ctx: MenuContext, ...args: any[]) => string);\n shortcuts?: string[] | ((ctx: MenuContext, ...args: any[]) => string[]);\n visible?: (ctx: MenuContext, ...args: any[]) => boolean;\n disabled?: (ctx: MenuContext, ...args: any[]) => boolean;\n checked?: (ctx: MenuContext, ...args: any[]) => boolean;\n onClick?: (ctx: MenuContext, ...args: any[]) => void | Promise<void>;\n children?: MenuNode[];\n};\n\ntype MenuNodesProps = {\n items: MenuNode[];\n ctx: MenuContext;\n /** Trailing coordinate args passed after ctx to every callback: [] | [x] | [y]. */\n args: number[];\n /** Called after a leaf item is chosen, to close the whole menu. */\n onSelect: () => void;\n /** Renders a `type: 'component'` descriptor (e.g. the column menu's sort/filter sections). */\n renderComponent?: (componentId: string, key: number) => ReactNode;\n};\n\n/** Renders a list of menu descriptors (with nested submenu support) as `<li>` rows. */\nexport const MenuNodes: FC<MenuNodesProps> = ({ items, ctx, args, onSelect, renderComponent }) => {\n return (\n <>\n {items.map((d, i) => {\n if (d.type === 'divider') {\n if (d.visible && !d.visible(ctx, ...args)) {\n return null;\n }\n return <MenuDivider key={i} />;\n }\n if (d.type === 'component') {\n if (d.visible && !d.visible(ctx, ...args)) {\n return null;\n }\n return renderComponent && d.componentId ? renderComponent(d.componentId, i) : null;\n }\n if (d.visible && !d.visible(ctx, ...args)) {\n return null;\n }\n const label = typeof d.label === 'function' ? d.label(ctx, ...args) : (d.label ?? '');\n const disabled = d.disabled?.(ctx, ...args) ?? false;\n if (d.type === 'submenu') {\n return (\n <SubmenuNode\n key={i}\n label={label}\n disabled={disabled}\n testId={d.id}\n items={d.children ?? []}\n ctx={ctx}\n args={args}\n onSelect={onSelect}\n renderComponent={renderComponent}\n />\n );\n }\n const shortcuts = typeof d.shortcuts === 'function' ? d.shortcuts(ctx, ...args) : d.shortcuts;\n const checked = d.checked?.(ctx, ...args);\n return (\n <MenuItem\n key={i}\n label={label}\n shortcuts={shortcuts}\n disabled={disabled}\n checked={checked}\n testId={d.id ? `${d.id}-item` : undefined}\n onClick={() => {\n d.onClick?.(ctx, ...args);\n onSelect();\n }}\n />\n );\n })}\n </>\n );\n};\n\ntype SubmenuNodeProps = {\n label: string;\n disabled: boolean;\n testId?: string;\n items: MenuNode[];\n ctx: MenuContext;\n args: number[];\n onSelect: () => void;\n renderComponent?: (componentId: string, key: number) => ReactNode;\n};\n\nconst SubmenuNode: FC<SubmenuNodeProps> = ({ label, disabled, testId, items, ctx, args, onSelect, renderComponent }) => {\n const [open, setOpen] = useState(false);\n const liRef = useRef<HTMLLIElement>(null);\n const flyoutRef = useRef<HTMLUListElement>(null);\n // The flyout is position:fixed and placed in viewport coordinates so it can never be\n // clipped by an ancestor. Preferred side is to the right of the parent row; it flips left\n // and clamps vertically when it would spill off the viewport. `null` until measured.\n const [pos, setPos] = useState<{ left: number; top: number } | null>(null);\n\n useLayoutEffect(() => {\n if (!open || disabled) {\n setPos(null);\n return;\n }\n const li = liRef.current;\n const fly = flyoutRef.current;\n if (!li || !fly) {\n return;\n }\n const p = li.getBoundingClientRect();\n const f = fly.getBoundingClientRect();\n const margin = 6;\n let left = p.right;\n if (left + f.width > window.innerWidth - margin) {\n left = p.left - f.width; // flip to the left of the parent\n if (left < margin) {\n left = Math.max(margin, window.innerWidth - f.width - margin);\n }\n }\n let top = p.top;\n if (top + f.height > window.innerHeight - margin) {\n top = window.innerHeight - f.height - margin;\n }\n if (top < margin) {\n top = margin;\n }\n setPos({ left, top });\n }, [open, disabled]);\n\n return (\n <li\n ref={liRef}\n className={`gs-menu-item gs-submenu-parent ${disabled ? 'gs-disabled' : 'gs-enabled'}`}\n data-testid={testId ? `${testId}-item` : undefined}\n onMouseEnter={() => setOpen(true)}\n onMouseLeave={() => setOpen(false)}\n // Clicking the parent row opens the flyout (so it also works without hover, e.g. touch)\n // but must never bubble to the menu backdrop, which would close the whole menu.\n onClick={(e) => {\n e.stopPropagation();\n setOpen(true);\n }}\n >\n <div className=\"gs-menu-name\">{label}</div>\n <span className=\"gs-submenu-arrow\">▸</span>\n {open && !disabled && (\n <ul\n ref={flyoutRef}\n className=\"gs-menu-items gs-submenu-flyout\"\n style={{\n position: 'fixed',\n left: pos ? pos.left : -9999,\n top: pos ? pos.top : -9999,\n visibility: pos ? 'visible' : 'hidden',\n }}\n >\n <MenuNodes items={items} ctx={ctx} args={args} onSelect={onSelect} renderComponent={renderComponent} />\n </ul>\n )}\n </li>\n );\n};\n","import { useContext, useRef, useEffect } from 'react';\n\nimport { setContextMenuPosition } from '../store/actions';\n\nimport { Context } from '../store';\nimport { Fixed } from './Fixed';\nimport type { ContextMenuItemDescriptor } from '../lib/menu';\nimport { buildMenuContext } from '../lib/menu';\nimport { MenuNodes, type MenuNode } from './MenuNodes';\nimport { clampPopup } from '@gridsheet/web';\n\nexport const ContextMenu = () => {\n const { store, dispatch } = useContext(Context);\n const { contextMenuPosition, contextMenu } = store;\n const { y: top, x: left } = contextMenuPosition;\n const menuRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (menuRef.current) {\n clampPopup(menuRef.current);\n }\n });\n\n if (top === -1) {\n return null;\n }\n\n const close = () => dispatch(setContextMenuPosition({ y: -1, x: -1 }));\n const ctx = buildMenuContext(store, dispatch, close);\n\n return (\n <Fixed\n className=\"gs-menu-modal gs-context-menu-modal\"\n onClick={(e: MouseEvent) => {\n e.preventDefault();\n close();\n return false;\n }}\n >\n <div ref={menuRef} className={'gs-context-menu'} style={{ top: top, left: left }}>\n <ul className=\"gs-menu-items\">\n <MenuNodes items={contextMenu as MenuNode[]} ctx={ctx} args={[]} onSelect={close} />\n </ul>\n </div>\n </Fixed>\n );\n};\n","import { type FC, useContext, useState, useCallback, useEffect } from 'react';\nimport { Context } from '../store';\nimport { filterRows } from '../store/actions';\nimport type { FilterCondition, FilterConditionMethod } from '../types';\nimport { operations as prevention } from '@gridsheet/web';\nimport { registerMenuComponent, type ColMenuSectionProps } from '../lib/menu';\n\nconst METHOD_LABELS: Record<FilterConditionMethod, string> = {\n eq: '=',\n ne: '≠',\n gt: '>',\n gte: '≥',\n lt: '<',\n lte: '≤',\n blank: 'Blank',\n nonblank: 'Nonblank',\n includes: 'Includes',\n excludes: 'Excludes',\n};\n\nconst NO_VALUE_METHODS: FilterConditionMethod[] = ['blank', 'nonblank'];\nconst DEFAULT_CONDITION: FilterCondition = { method: 'eq', value: [''] };\n\ntype PendingFilter = {\n x: number;\n conditions: FilterCondition[];\n mode: 'and' | 'or';\n};\n\nconst FilterSection: FC<ColMenuSectionProps> = ({ x, close, onWaiting }) => {\n const { store, dispatch } = useContext(Context);\n const { sheetReactive: sheetRef } = store;\n const sheet = sheetRef.current;\n\n const [conditions, setConditions] = useState<FilterCondition[]>([{ ...DEFAULT_CONDITION }]);\n const [mode, setMode] = useState<'and' | 'or'>('or');\n const [pending, setPending] = useState<PendingFilter | null>(null);\n\n // Auto-focus first value input when x changes\n const firstValueRef = useCallback(\n (node: HTMLInputElement | null) => {\n if (node) {\n node.focus();\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [x],\n );\n\n // Restore conditions from existing filter on the column cell when x changes\n useEffect(() => {\n if (sheet) {\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const existing = colCell?.filter;\n if (existing && existing.conditions.length > 0) {\n setConditions(existing.conditions.map((c) => ({ ...c, value: [...c.value] })));\n setMode(existing.mode || 'or');\n } else {\n setConditions([{ ...DEFAULT_CONDITION, value: [''] }]);\n setMode('or');\n }\n }\n }, [x, sheet]);\n\n // Escape key cancels during waiting\n const handleCancel = useCallback(() => {\n setPending(null);\n onWaiting?.(null);\n close();\n }, [close, onWaiting]);\n\n // Notify parent about waiting state\n useEffect(() => {\n if (pending) {\n onWaiting?.('Filtering…', handleCancel);\n }\n // Do NOT include onWaiting/handleCancel in deps to avoid re-triggering execute\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pending]);\n\n // Execute pending filter after async formulas resolve\n useEffect(() => {\n if (!pending) {\n return;\n }\n let cancelled = false;\n const execute = () => {\n if (cancelled) {\n return;\n }\n const currentSheet = sheetRef.current;\n if (!currentSheet) {\n return;\n }\n const { x: actionX, conditions: validConditions, mode: filterMode } = pending;\n if (validConditions.length > 0) {\n dispatch(filterRows({ x: actionX, filter: { mode: filterMode, conditions: validConditions } }));\n } else {\n dispatch(filterRows({ x: actionX }));\n }\n onWaiting?.(null);\n setPending(null);\n close();\n };\n const currentSheet = sheetRef.current;\n if (currentSheet && (currentSheet.hasPendingCells() || currentSheet.registry.asyncPending.size > 0)) {\n currentSheet.waitForPending().then(execute);\n } else {\n execute();\n }\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pending]);\n\n const updateCondition = useCallback((index: number, patch: Partial<FilterCondition>) => {\n setConditions((prev) => {\n const next = [...prev];\n next[index] = { ...next[index], ...patch };\n return next;\n });\n }, []);\n\n const addCondition = useCallback(() => {\n setConditions((prev) => [...prev, { ...DEFAULT_CONDITION, value: [''] }]);\n }, []);\n\n const removeCondition = useCallback((index: number) => {\n setConditions((prev) => {\n if (prev.length <= 1) {\n return [{ ...DEFAULT_CONDITION, value: [''] }];\n }\n return prev.filter((_, i) => i !== index);\n });\n }, []);\n\n const handleApplyFilter = useCallback(() => {\n const valid = conditions.filter((c) => {\n if (NO_VALUE_METHODS.includes(c.method)) {\n return true;\n }\n return c.value.some((v) => v.trim() !== '');\n });\n setPending({ x, conditions: valid, mode });\n }, [x, conditions, mode]);\n\n const handleResetColumn = useCallback(() => {\n setPending(null);\n dispatch(filterRows({ x }));\n close();\n }, [dispatch, x, close]);\n\n const handleResetAll = useCallback(() => {\n setPending(null);\n dispatch(filterRows({}));\n close();\n }, [dispatch, close]);\n\n if (!sheet) {\n return null;\n }\n\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const filterDisabled = prevention.hasOperation(colCell?.prevention, prevention.Filter);\n const hasAnyFilter = sheet.hasActiveFilters();\n\n return (\n <li className={`gs-column-menu-filter${filterDisabled ? ' gs-disabled' : ''}`}>\n <>\n <div className=\"gs-filter-header\">\n <div className=\"gs-menu-name\">Filter:</div>\n <button className=\"gs-filter-add-btn\" onClick={addCondition} disabled={filterDisabled}>\n + ADD\n </button>\n <div className={`gs-filter-mode-toggle${conditions.length <= 1 ? ' gs-disabled' : ''}`}>\n <label className={mode === 'and' ? 'gs-active' : ''}>\n <input\n type=\"radio\"\n name=\"gs-filter-mode\"\n checked={mode === 'and'}\n onChange={() => setMode('and')}\n disabled={filterDisabled || conditions.length <= 1}\n />\n AND\n </label>\n <label className={mode === 'or' ? 'gs-active' : ''}>\n <input\n type=\"radio\"\n name=\"gs-filter-mode\"\n checked={mode === 'or'}\n onChange={() => setMode('or')}\n disabled={filterDisabled || conditions.length <= 1}\n />\n OR\n </label>\n </div>\n </div>\n <div className=\"gs-filter-conditions\">\n {conditions.map((cond, i) => (\n <div className=\"gs-filter-condition-row\" key={i}>\n <select\n className=\"gs-filter-method-select\"\n value={cond.method}\n disabled={filterDisabled}\n tabIndex={i * 2 + 1}\n onChange={(e) => updateCondition(i, { method: e.target.value as FilterConditionMethod })}\n >\n {(Object.keys(METHOD_LABELS) as FilterConditionMethod[]).map((m) => (\n <option key={m} value={m}>\n {METHOD_LABELS[m]}\n </option>\n ))}\n </select>\n {!NO_VALUE_METHODS.includes(cond.method) && (\n <input\n ref={i === 0 ? firstValueRef : undefined}\n className=\"gs-filter-value-input\"\n type=\"text\"\n placeholder=\"Value\"\n value={cond.value[0] || ''}\n disabled={filterDisabled}\n tabIndex={i * 2 + 2}\n onChange={(e) => updateCondition(i, { value: [e.target.value] })}\n onKeyDown={(e) => {\n if (e.nativeEvent.isComposing) {\n return;\n }\n if (e.key === 'Enter') {\n handleApplyFilter();\n }\n if (e.key === 'Escape') {\n close();\n }\n }}\n />\n )}\n <button\n className=\"gs-filter-remove-btn\"\n onClick={() => removeCondition(i)}\n disabled={filterDisabled}\n title=\"Remove condition\"\n >\n ✕\n </button>\n </div>\n ))}\n </div>\n <div className=\"gs-filter-actions\">\n {hasAnyFilter && (\n <button className=\"gs-filter-reset-all-btn\" onClick={handleResetAll}>\n RESET ALL\n </button>\n )}\n <div className=\"gs-filter-actions-right\">\n {colCell?.filter && (\n <button className=\"gs-filter-reset-btn\" onClick={handleResetColumn}>\n RESET\n </button>\n )}\n <button className=\"gs-filter-apply-btn\" onClick={handleApplyFilter} disabled={filterDisabled}>\n APPLY\n </button>\n </div>\n </div>\n </>\n </li>\n );\n};\n\nregisterMenuComponent('col-filter', FilterSection);\nexport { FilterSection };\n","import { type FC, useContext, useState, useCallback, useEffect } from 'react';\nimport { Context } from '../store';\nimport { sortRows } from '../store/actions';\nimport { operations as prevention } from '@gridsheet/web';\nimport { registerMenuComponent, type ColMenuSectionProps } from '../lib/menu';\n\ntype PendingSort = {\n x: number;\n direction: 'asc' | 'desc';\n};\n\nconst SortSection: FC<ColMenuSectionProps> = ({ x, close, onWaiting }) => {\n const { store, dispatch } = useContext(Context);\n const { sheetReactive: sheetRef } = store;\n const sheet = sheetRef.current;\n\n const [pending, setPending] = useState<PendingSort | null>(null);\n\n const handleCancel = useCallback(() => {\n setPending(null);\n onWaiting?.(null);\n close();\n }, [close, onWaiting]);\n\n // Notify parent about waiting state\n useEffect(() => {\n if (pending) {\n onWaiting?.('Sorting\\u2026', handleCancel);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pending]);\n\n // Execute pending sort after async formulas resolve\n useEffect(() => {\n if (!pending) {\n return;\n }\n let cancelled = false;\n const execute = () => {\n if (cancelled) {\n return;\n }\n const currentSheet = sheetRef.current;\n if (!currentSheet) {\n return;\n }\n dispatch(sortRows({ x: pending.x, direction: pending.direction }));\n onWaiting?.(null);\n setPending(null);\n close();\n };\n const currentSheet = sheetRef.current;\n if (currentSheet && (currentSheet.hasPendingCells() || currentSheet.registry.asyncPending.size > 0)) {\n currentSheet.waitForPending().then(execute);\n } else {\n execute();\n }\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pending]);\n\n if (!sheet) {\n return null;\n }\n\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const sortDisabled = prevention.hasOperation(colCell?.prevention, prevention.Sort);\n\n return (\n <li className={`gs-menu-item gs-column-menu-sort${sortDisabled ? ' gs-disabled' : ''}`}>\n <div className=\"gs-menu-name\">Sort:</div>\n <div className=\"gs-sort-buttons\">\n <button\n className=\"gs-sort-btn gs-sort-btn-asc\"\n onClick={(e) => {\n e.stopPropagation();\n if (!sortDisabled) {\n setPending({ x, direction: 'asc' });\n }\n }}\n disabled={sortDisabled}\n >\n ↓ A to Z\n </button>\n <button\n className=\"gs-sort-btn gs-sort-btn-desc\"\n onClick={(e) => {\n e.stopPropagation();\n if (!sortDisabled) {\n setPending({ x, direction: 'desc' });\n }\n }}\n disabled={sortDisabled}\n >\n ↑ Z to A\n </button>\n </div>\n </li>\n );\n};\n\nregisterMenuComponent('col-sort', SortSection);\nexport { SortSection };\n","import { type FC, useContext, useState, useCallback, useEffect, useRef } from 'react';\nimport { Context } from '../store';\nimport { setStore } from '../store/actions';\nimport { operations as prevention } from '@gridsheet/web';\nimport { x2c, p2a } from '@gridsheet/web';\nimport { getLabel } from '@gridsheet/web';\nimport { registerMenuComponent, type ColMenuSectionProps } from '../lib/menu';\n\nconst LabelSection: FC<ColMenuSectionProps> = ({ x, close }) => {\n const { store, dispatch } = useContext(Context);\n const { sheetReactive: sheetRef } = store;\n const sheet = sheetRef.current;\n const labelInputRef = useRef<HTMLInputElement>(null);\n const [label, setLabel] = useState('');\n\n // Restore label value when x changes\n useEffect(() => {\n if (sheet) {\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n setLabel(colCell?.label ?? '');\n }\n // When the menu was opened by double-clicking the header, jump straight into\n // renaming: focus the label input and select its text so a keystroke replaces\n // it. Double rAF so the controlled value has committed to the DOM before we\n // set the selection (otherwise React moves the caret to the end afterwards).\n if (store.columnMenuState?.focusLabel) {\n requestAnimationFrame(() =>\n requestAnimationFrame(() => {\n const input = labelInputRef.current;\n if (input) {\n input.focus();\n input.setSelectionRange(0, input.value.length);\n }\n }),\n );\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [x, sheet]);\n\n const handleApplyLabel = useCallback(() => {\n if (!sheet) {\n return;\n }\n const address = p2a({ y: 0, x });\n sheet.update({\n diff: { [address]: { label: label || undefined } },\n partial: true,\n ignoreFields: [],\n undoReflection: {\n sheetId: sheet.id,\n selectingZone: store.selectingZone,\n choosing: store.choosing,\n },\n redoReflection: {\n sheetId: sheet.id,\n selectingZone: store.selectingZone,\n choosing: store.choosing,\n },\n });\n dispatch(setStore({ sheetReactive: { current: sheet } }));\n close();\n }, [dispatch, x, label, close, sheet, store.selectingZone, store.choosing]);\n\n if (!sheet) {\n return null;\n }\n\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const labelDisabled = prevention.hasOperation(colCell?.prevention, prevention.SetLabel);\n const labelPlaceholder = getLabel(sheet, colCell?.label, { y: 0, x }, x) ?? x2c(x);\n\n return (\n <li className={`gs-menu-item gs-column-menu-label${labelDisabled ? ' gs-disabled' : ''}`}>\n <label className=\"gs-label-input-row\">\n <div className=\"gs-label-input-label\">Label:</div>\n <input\n ref={labelInputRef}\n className=\"gs-label-input\"\n type=\"text\"\n placeholder={labelPlaceholder}\n value={label}\n disabled={labelDisabled}\n onChange={(e) => setLabel(e.target.value)}\n onKeyDown={(e) => {\n if (e.nativeEvent.isComposing) {\n return;\n }\n if (e.key === 'Enter') {\n handleApplyLabel();\n }\n if (e.key === 'Escape') {\n close();\n }\n }}\n />\n <button className=\"gs-label-apply-btn\" onClick={handleApplyLabel} disabled={labelDisabled}>\n UPDATE\n </button>\n </label>\n </li>\n );\n};\n\nregisterMenuComponent('col-label', LabelSection);\nexport { LabelSection };\n","import { type FC, useContext, useCallback, useState } from 'react';\nimport { Context } from '../store';\nimport { setColumnMenu } from '../store/actions';\nimport { Fixed } from './Fixed';\nimport { focus } from '@gridsheet/web';\nimport { buildMenuContext } from '../lib/menu';\nimport { getMenuComponent } from '../lib/menu';\nimport { MenuNodes, type MenuNode } from './MenuNodes';\n\n// Import section modules so their registerMenuComponent() calls run at load time.\n// Users may override any of these ids via registerMenuComponent() after import.\nimport './ColumnMenuFilterSection';\nimport './ColumnMenuSortSection';\nimport './ColumnMenuLabelSection';\n\nexport const ColumnMenu: FC = () => {\n const { store, dispatch } = useContext(Context);\n const { columnMenuState, editorRef, colMenu } = store;\n const sheet = store.sheetReactive.current;\n\n const x = columnMenuState?.x;\n const position = columnMenuState?.position;\n\n const [waitingState, setWaitingState] = useState<{ message: string; cancel: () => void } | null>(null);\n\n const handleClose = useCallback(() => {\n dispatch(setColumnMenu(null));\n focus(editorRef.current);\n }, [dispatch, editorRef]);\n\n const handleWaiting = useCallback(\n (message: string | null, cancel?: () => void) => {\n if (message) {\n setWaitingState({ message, cancel: cancel ?? handleClose });\n } else {\n setWaitingState(null);\n }\n },\n [handleClose],\n );\n\n if (!columnMenuState || !sheet || x == null || !position) {\n return null;\n }\n\n const ctx = buildMenuContext(store, dispatch, handleClose);\n\n return (\n <Fixed\n className=\"gs-menu-modal gs-column-menu-modal\"\n onClick={(e: MouseEvent) => {\n e.preventDefault();\n if (!waitingState) {\n handleClose();\n }\n return false;\n }}\n >\n <div\n className=\"gs-column-menu\"\n style={{ top: position.y, left: position.x, display: waitingState ? 'none' : undefined }}\n onClick={(e) => e.stopPropagation()}\n >\n <ul className=\"gs-menu-items\">\n <MenuNodes\n items={colMenu as MenuNode[]}\n ctx={ctx}\n args={[x]}\n onSelect={() => dispatch(setColumnMenu(null))}\n renderComponent={(componentId, key) => {\n const Section = getMenuComponent(componentId);\n return Section ? <Section key={key} x={x} close={handleClose} onWaiting={handleWaiting} /> : null;\n }}\n />\n </ul>\n </div>\n {waitingState && (\n <div\n className=\"gs-column-menu gs-column-menu-waiting\"\n style={{ top: position.y, left: position.x }}\n onClick={(e) => e.stopPropagation()}\n >\n <div className=\"gs-waiting-message\">{waitingState.message}</div>\n <div className=\"gs-waiting-spinner\" />\n <button className=\"gs-waiting-cancel-btn\" onClick={waitingState.cancel}>\n CANCEL\n </button>\n </div>\n )}\n </Fixed>\n );\n};\n","import { type FC, useContext } from 'react';\nimport { Context } from '../store';\nimport { setRowMenu } from '../store/actions';\nimport { Fixed } from './Fixed';\nimport { focus } from '@gridsheet/web';\nimport { buildMenuContext } from '../lib/menu';\nimport { MenuNodes, type MenuNode } from './MenuNodes';\n\nexport const RowMenu: FC = () => {\n const { store, dispatch } = useContext(Context);\n const { rowMenuState, sheetReactive: sheetRef, editorRef, rowMenu } = store;\n const sheet = sheetRef.current;\n\n const y = rowMenuState?.y;\n const position = rowMenuState?.position;\n\n const handleClose = () => {\n dispatch(setRowMenu(null));\n focus(editorRef.current);\n };\n\n if (!rowMenuState || !sheet || y == null || !position) {\n return null;\n }\n\n const ctx = buildMenuContext(store, dispatch, handleClose);\n\n return (\n <Fixed\n className=\"gs-menu-modal gs-row-menu-modal\"\n onClick={(e: MouseEvent) => {\n e.preventDefault();\n handleClose();\n return false;\n }}\n >\n <div className=\"gs-row-menu\" style={{ top: position.y, left: position.x }} onClick={(e) => e.stopPropagation()}>\n <ul className=\"gs-menu-items\">\n <MenuNodes items={rowMenu as MenuNode[]} ctx={ctx} args={[y]} onSelect={handleClose} />\n </ul>\n </div>\n </Fixed>\n );\n};\n","export const isTouching = (e: React.TouchEvent | React.MouseEvent): boolean => {\n if (e.type.startsWith('touch')) {\n return (e as React.TouchEvent).touches.length > 0;\n }\n if (e.type.startsWith('mouse')) {\n const mouseEvent = e as React.MouseEvent;\n // left click only\n return !!(mouseEvent.buttons & 1) && mouseEvent.button === 0;\n }\n return false;\n};\n\n/**\n * Safely call preventDefault to avoid errors on touch events\n */\nexport const safePreventDefault = (e: React.MouseEvent | React.TouchEvent): void => {\n if (!e.type.startsWith('touch')) {\n e.preventDefault();\n }\n};\n","import { useContext, useRef, useCallback, useEffect, memo, useMemo, useState } from 'react';\nimport { x2c, y2r } from '@gridsheet/web';\nimport { zoneToArea, among, areaToRange } from '@gridsheet/web';\nimport {\n choose,\n select,\n drag,\n write,\n setEditorRect,\n setContextMenuPosition,\n setAutofillDraggingTo,\n setEditingAddress,\n setDragging,\n setStore,\n} from '../store/actions';\n\nimport { Context } from '../store';\nimport { FormulaError } from '@gridsheet/web';\nimport { Pending } from '@gridsheet/web';\nimport { insertRef, isRefInsertable } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { isXSheetFocused } from '../store/helpers';\nimport type { FC, RefObject } from 'react';\nimport { isTouching, safePreventDefault } from '../lib/events';\nimport type { UserSheet } from '@gridsheet/web';\nimport { calcBelowPosition, hAlignTransform, type PopupPosition } from '@gridsheet/web';\n\ntype Props = {\n y: number;\n x: number;\n};\n\nexport const Cell: FC<Props> = memo(({ y, x }) => {\n const rowId = y2r(y);\n const colId = x2c(x);\n const address = `${colId}${rowId}`;\n const { store, dispatch } = useContext(Context);\n const isFirstPointed = useRef(true);\n\n const cellRef = useRef<HTMLTableCellElement>(null);\n const [errorTooltipPos, setErrorTooltipPos] = useState<PopupPosition | null>(null);\n const {\n sheetReactive,\n editingAddress,\n choosing,\n selectingZone,\n leftHeaderSelecting,\n topHeaderSelecting,\n editorRef,\n autofillDraggingTo,\n contextMenu,\n } = store;\n const sheet = sheetReactive.current;\n\n // Whether the focus is on another sheet\n const xSheetFocused = isXSheetFocused(store);\n\n const lastFocused = sheet?.registry.lastFocused;\n\n const selectingArea = zoneToArea(selectingZone); // (top, left) -> (bottom, right)\n\n const editing = editingAddress === address;\n const pointed = choosing.y === y && choosing.x === x;\n const _setEditorRect = useCallback(() => {\n const rect = cellRef.current?.getBoundingClientRect();\n if (rect == null) {\n return null;\n }\n dispatch(\n setEditorRect({\n y: rect.y,\n x: rect.x,\n height: rect.height,\n width: rect.width,\n }),\n );\n }, [dispatch]);\n\n useEffect(() => {\n // Avoid setting coordinates on the initial render to account for shifts caused by redrawing due to virtualization.\n if (pointed && !isFirstPointed.current) {\n _setEditorRect();\n return;\n }\n isFirstPointed.current = false;\n }, [pointed, editing, _setEditorRect]);\n\n const cell = sheet?.getCell({ y, x }, { resolution: 'SYSTEM' });\n\n const writeCell = useCallback(\n (value: string) => {\n dispatch(write({ value }));\n },\n [dispatch],\n );\n\n const apply = useCallback(\n (sheet: UserSheet) => {\n dispatch(setStore({ sheetReactive: { current: sheet.__raw__ } }));\n },\n [dispatch],\n );\n\n let errorMessage = '';\n let rendered: any;\n try {\n if (sheet) {\n rendered = sheet.render({ sheet, point: { y, x }, apply, value: undefined });\n }\n } catch (e: any) {\n if (FormulaError.is(e)) {\n errorMessage = e.message;\n rendered = e.code;\n } else {\n errorMessage = e.message;\n rendered = '#UNKNOWN';\n }\n }\n const [, v] = sheet?.getSolvedCache({ y, x }) ?? [undefined, undefined];\n const isPendingCell = Pending.is(v);\n const input = editorRef.current;\n\n const editingAnywhere = !!(sheet?.registry.editingAddress || editingAddress);\n\n const handleDragStart = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n safePreventDefault(e);\n\n if (!sheet) {\n return false;\n }\n if (!isTouching(e)) {\n return false;\n }\n if (!input) {\n return false;\n }\n\n // Single cell selection only for touch events\n if (e.type.startsWith('touch')) {\n // Blur the input field to commit current value when selecting via touch\n if (editingAnywhere && input) {\n input.blur();\n }\n dispatch(choose({ y, x }));\n dispatch(select({ startY: y, startX: x, endY: y, endX: x }));\n return true;\n }\n\n // Normal drag operation for mouse events\n if (e.shiftKey) {\n dispatch(drag({ y, x }));\n } else {\n dispatch(select({ startY: y, startX: x, endY: -1, endX: -1 }));\n }\n\n dispatch(setDragging(true));\n const fullAddress = `${sheet.sheetPrefix(!xSheetFocused)}${address}`;\n if (editingAnywhere) {\n const inserted = insertRef({ input: lastFocused || null, ref: fullAddress });\n if (inserted) {\n return false;\n }\n }\n\n sheet.registry.lastFocused = input;\n focus(input);\n dispatch(setEditingAddress(''));\n\n if (autofillDraggingTo) {\n return false;\n }\n\n if (editingAnywhere) {\n writeCell(input.value);\n }\n if (!e.shiftKey) {\n dispatch(choose({ y, x }));\n }\n return true;\n },\n [editingAnywhere, input, address, xSheetFocused, lastFocused, autofillDraggingTo, writeCell, sheet],\n );\n\n const handleDragEnd = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n if (e.type.startsWith('touch')) {\n return;\n }\n\n safePreventDefault(e);\n dispatch(setDragging(false));\n // Autofill submit/clear is owned by StoreObserver's capture-phase window mouseup\n // (onUp) — the reliable place that always fires. Doing it here too would double-fill\n // (this bubble handler runs after onUp already cleared the store, with a stale\n // autofillDraggingTo closure). We only handle the formula-range-drag end.\n if (editingAnywhere) {\n dispatch(drag({ y: -1, x: -1 }));\n }\n },\n [editingAnywhere],\n );\n\n const handleDragging = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n if (!isTouching(e)) {\n return false;\n }\n\n // Do nothing for touch events\n if (e.type.startsWith('touch')) {\n return false;\n }\n\n if (!sheet) {\n return false;\n }\n\n safePreventDefault(e);\n e.stopPropagation();\n\n if (autofillDraggingTo) {\n dispatch(setAutofillDraggingTo({ x, y }));\n return false;\n }\n if (leftHeaderSelecting) {\n dispatch(drag({ y, x: sheet.numCols }));\n return false;\n }\n if (topHeaderSelecting) {\n dispatch(drag({ y: sheet.numRows, x }));\n return false;\n }\n if (editingAnywhere && !isRefInsertable(lastFocused || null)) {\n return false;\n }\n dispatch(drag({ y, x }));\n\n if (editingAnywhere) {\n const newArea = zoneToArea({ ...selectingZone, endY: y, endX: x });\n const fullRange = `${sheet.sheetPrefix(!xSheetFocused)}${areaToRange(newArea)}`;\n insertRef({ input: lastFocused || null, ref: fullRange });\n }\n //sheet.registry.transmit(); // Force drawing because the formula is not reflected in largeInput\n return true;\n },\n [\n autofillDraggingTo,\n leftHeaderSelecting,\n topHeaderSelecting,\n sheet,\n editingAnywhere,\n lastFocused,\n selectingZone,\n xSheetFocused,\n ],\n );\n\n const handleAutofillMouseDown = useCallback(\n (e: React.MouseEvent) => {\n dispatch(setAutofillDraggingTo({ x, y }));\n dispatch(setDragging(true));\n e.stopPropagation();\n },\n [dispatch, x, y],\n );\n\n const handleErrorTriangleEnter = useCallback(() => {\n const rect = cellRef.current?.getBoundingClientRect();\n if (!rect) {\n return;\n }\n setErrorTooltipPos(calcBelowPosition(rect));\n }, []);\n\n const handleErrorTriangleLeave = useCallback(() => {\n setErrorTooltipPos(null);\n }, []);\n\n // --- Memoize event handlers with useCallback ---\n const onContextMenu = useCallback(\n (e: React.MouseEvent<HTMLTableCellElement>) => {\n if (contextMenu.length > 0) {\n e.stopPropagation();\n safePreventDefault(e);\n dispatch(setContextMenuPosition({ y: e.clientY, x: e.clientX }));\n return false;\n }\n return true;\n },\n [contextMenu.length],\n );\n\n const onDoubleClick = useCallback(\n (e: React.MouseEvent<HTMLTableCellElement>) => {\n e.stopPropagation();\n safePreventDefault(e);\n setEditingAddress(address);\n const dblclick = document.createEvent('MouseEvents');\n dblclick.initEvent('dblclick', true, true);\n input?.dispatchEvent(dblclick);\n return false;\n },\n [address, input],\n );\n\n const autofillDragClass = useMemo(() => {\n if (!editing && pointed && selectingArea.bottom === -1) {\n return 'gs-autofill-drag';\n }\n\n if (selectingArea.bottom === y && selectingArea.right === x) {\n return 'gs-autofill-drag';\n }\n return 'gs-autofill-drag gs-hidden';\n }, [editing, pointed, selectingArea]);\n\n if (!sheet) {\n return null;\n }\n\n if (!input) {\n return (\n <td key={x} data-x={x} data-y={y} data-address={address} className=\"gs-cell gs-hidden\">\n <div className=\"gs-cell-inner-wrap\">\n <div className=\"gs-cell-inner\">\n <div className=\"gs-cell-rendered\"></div>\n </div>\n <div className=\"gs-autofill-drag\"></div>\n </div>\n </td>\n );\n }\n\n return (\n <td\n key={x}\n ref={cellRef}\n data-x={x}\n data-y={y}\n data-address={address}\n className={`gs-cell ${among(selectingArea, { y, x }) ? 'gs-selecting' : ''} ${pointed ? 'gs-choosing' : ''} ${\n editing ? 'gs-editing' : ''\n } ${isPendingCell ? 'gs-pending' : ''}`}\n style={{\n ...cell?.style,\n }}\n onContextMenu={onContextMenu}\n onDoubleClick={onDoubleClick}\n >\n <div\n className={`gs-cell-inner-wrap`}\n onMouseDown={handleDragStart}\n onTouchStart={handleDragStart}\n onMouseEnter={handleDragging}\n onMouseUp={handleDragEnd}\n >\n <div\n className={'gs-cell-inner'}\n style={{\n ...cell?.style,\n textAlign: cell?.style?.textAlign || cell?.justifyContent || 'left',\n alignItems: cell?.alignItems || 'start',\n }}\n >\n {errorMessage && (\n <div\n className=\"gs-formula-error-triangle\"\n onMouseEnter={handleErrorTriangleEnter}\n onMouseLeave={handleErrorTriangleLeave}\n />\n )}\n <div\n className=\"gs-cell-rendered\"\n style={\n cell?.alignItems\n ? {\n display: 'flex',\n flexDirection: 'column',\n justifyContent:\n cell.alignItems === 'center' ? 'center' : cell.alignItems === 'end' ? 'flex-end' : undefined,\n }\n : undefined\n }\n >\n {rendered}\n </div>\n </div>\n {errorMessage && errorTooltipPos && (\n <div\n className=\"gs-formula-error-tooltip\"\n style={{\n top: errorTooltipPos.y + 4,\n left: errorTooltipPos.x,\n transform: hAlignTransform(errorTooltipPos.hAlign),\n }}\n >\n {errorMessage}\n </div>\n )}\n <div className={autofillDragClass} onMouseDown={handleAutofillMouseDown}></div>\n </div>\n </td>\n );\n});\n","import type { CSSProperties } from 'react';\nimport { useEffect, useRef, useContext, useCallback } from 'react';\nimport { Context } from '../store';\nimport { drag, setAutofillDraggingTo, setDragging, submitAutofill } from '../store/actions';\nimport { getAreaInTabular } from '@gridsheet/web';\nimport { insertRef, isFocus } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { areaToRange, zoneToArea } from '@gridsheet/web';\nimport { isXSheetFocused } from '../store/helpers';\n\ntype Props = {\n className?: string;\n style: CSSProperties;\n horizontal?: number;\n vertical?: number;\n};\n\nconst acceleration = 0.4;\nconst maxSpeed = 200;\n\nlet lastScrollTime = new Date().getTime();\nlet currentSpeed = 0;\n\nexport function ScrollHandle({ style, horizontal = 0, vertical = 0, className = '' }: Props) {\n const scrollRef = useRef<number | null>(null);\n const { store, dispatch } = useContext(Context);\n const {\n tabularRef,\n autofillDraggingTo,\n dragging,\n selectingZone,\n editorRef,\n sheetReactive: sheetRef,\n searchInputRef,\n editingAddress,\n } = store;\n const sheet = sheetRef.current;\n\n // The rAF scroll loop below closes over one render's props. When it dispatches\n // (re-render), the running loop keeps the OLD closure — including a stale, still-truthy\n // autofillDraggingTo — so it re-arms the autofill every frame. Read the LIVE store\n // through a ref instead, so the loop sees the drag end and stops.\n const storeRef = useRef(store);\n storeRef.current = store;\n\n let isScrolling = false;\n const xSheetFocused = isXSheetFocused(store);\n const editingAnywhere = !!(sheet?.registry.editingAddress || editingAddress);\n\n const getDestEdge = useCallback(\n (e: React.MouseEvent) => {\n if (!sheet) {\n return { x: -1, y: -1 };\n }\n if (horizontal == 0 && vertical == 0) {\n const tabularRect = tabularRef.current!.getBoundingClientRect();\n const { left, top, right, bottom } = tabularRect;\n horizontal = e.pageX > right ? 1 : e.pageX < left ? -1 : 0;\n if (horizontal === 0) {\n vertical = e.pageY > bottom ? 1 : e.pageY < top ? -1 : 0;\n }\n }\n const area = getAreaInTabular(tabularRef.current!);\n let { endX: x, endY: y } = selectingZone;\n if (horizontal) {\n x = horizontal > 0 ? area.right : area.left;\n } else if (vertical) {\n y = vertical > 0 ? area.bottom : area.top;\n }\n return { x, y };\n },\n [sheet, horizontal, vertical, selectingZone],\n );\n\n const scrollStep = useCallback(\n (e: React.MouseEvent) => {\n if (!isScrolling || tabularRef.current === null || !sheet) {\n return;\n }\n // The drag has ended (the mouseup landed off this strip, e.g. on a cell, or the\n // strip hid at the edge so its onMouseUp/onMouseLeave never fired). Stop now —\n // otherwise this loop keeps scrolling and re-dispatching setAutofillDraggingTo\n // forever, so the autofill can never be cleared and the grid can't be scrolled.\n const live = storeRef.current;\n if (!live.dragging && !live.autofillDraggingTo) {\n if (scrollRef.current !== null) {\n cancelAnimationFrame(scrollRef.current);\n scrollRef.current = null;\n }\n isScrolling = false;\n return;\n }\n const now = new Date().getTime();\n if (now - lastScrollTime > 1000) {\n currentSpeed = 0;\n }\n lastScrollTime = now;\n\n tabularRef.current.scrollBy({\n left: currentSpeed * horizontal!,\n top: currentSpeed * vertical!,\n });\n focus(editorRef.current);\n\n const { x, y } = getDestEdge(e);\n if (live.autofillDraggingTo) {\n const { y: curY, x: curX } = live.autofillDraggingTo;\n dispatch(setAutofillDraggingTo({ y: y === -1 ? curY : y, x: x === -1 ? curX : x }));\n } else {\n if (editingAnywhere) {\n const newArea = zoneToArea({ ...selectingZone, endY: y, endX: x });\n const sheetPrefix = sheet.sheetPrefix(!xSheetFocused);\n const sheetRange = areaToRange(newArea);\n const fullRange = `${sheetPrefix}${sheetRange}`;\n insertRef({ input: editorRef.current, ref: fullRange });\n }\n dispatch(drag({ y, x }));\n }\n currentSpeed = Math.min(currentSpeed + acceleration, maxSpeed);\n scrollRef.current = requestAnimationFrame(() => scrollStep(e));\n },\n [\n isScrolling,\n sheet,\n horizontal,\n vertical,\n autofillDraggingTo,\n editingAnywhere,\n selectingZone,\n xSheetFocused,\n getDestEdge,\n ],\n );\n\n const handleMouseEnter = useCallback(\n (e: React.MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n if (isScrolling) {\n return;\n }\n isScrolling = true;\n\n if (horizontal === 0 || vertical === 0) {\n const tabularRect = tabularRef.current!.getBoundingClientRect();\n const { left, top, right, bottom } = tabularRect;\n\n horizontal ||= e.pageX > right ? 1 : e.pageX < left ? -1 : 0;\n if (horizontal === 0) {\n vertical ||= e.pageY > bottom ? 1 : e.pageY < top ? -1 : 0;\n }\n }\n scrollRef.current = requestAnimationFrame(() => scrollStep(e));\n },\n [isScrolling, horizontal, vertical, scrollStep],\n );\n\n const stopScroll = useCallback(() => {\n if (scrollRef.current !== null) {\n cancelAnimationFrame(scrollRef.current);\n scrollRef.current = null;\n }\n isScrolling = false;\n if (!isFocus(searchInputRef.current)) {\n // Pressing Enter on a search result will not focus the editor.\n focus(editorRef.current);\n }\n }, []);\n\n const handleMouseUp = useCallback(\n (e: React.MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n const area = getAreaInTabular(tabularRef.current!);\n if (area.bottom === -1 || area.right === -1) {\n return;\n }\n\n const { x, y } = getDestEdge(e);\n if (autofillDraggingTo) {\n const { y: curY, x: curX } = autofillDraggingTo;\n dispatch(submitAutofill({ y: y === -1 ? curY : y, x: x === -1 ? curX : x }));\n focus(editorRef.current);\n } else {\n if (editingAnywhere) {\n // inserting a range\n dispatch(drag({ y: -1, x: -1 })); // Reset dragging\n }\n }\n },\n [autofillDraggingTo, editingAnywhere, getDestEdge],\n );\n\n const handleMouseUpWrapper = useCallback(\n (e: React.MouseEvent) => {\n stopScroll();\n dispatch(setDragging(false));\n requestAnimationFrame(() => handleMouseUp(e));\n },\n [stopScroll, handleMouseUp],\n );\n\n const handleMouseLeave = useCallback(() => {\n stopScroll();\n }, [stopScroll]);\n\n useEffect(() => {\n return stopScroll;\n }, [stopScroll]);\n\n // The directional auto-scroll strips (right/bottom/left/top edges) sit on top of the\n // grid (zIndex). At an edge where there is nothing left to scroll to, such a strip only\n // gets in the way — e.g. it covers the rightmost column's cells, so dragging the\n // autofill handle straight down stays over the strip and never reaches the cells below.\n // Only render a directional strip while it can actually scroll in that direction; the\n // beyond-edge catch-all handle (horizontal === 0 && vertical === 0) always renders.\n const t = tabularRef.current;\n const cannotScrollHere =\n !!t &&\n ((horizontal > 0 && t.scrollLeft + t.clientWidth >= t.scrollWidth - 1) ||\n (horizontal < 0 && t.scrollLeft <= 0) ||\n (vertical > 0 && t.scrollTop + t.clientHeight >= t.scrollHeight - 1) ||\n (vertical < 0 && t.scrollTop <= 0));\n\n if (!editorRef.current || (!dragging && !autofillDraggingTo) || cannotScrollHere) {\n return <div className={`gs-scroll-handle gs-hidden ${className}`} />;\n }\n\n return (\n <div\n style={style}\n className={`gs-scroll-handle ${className}`}\n onMouseUp={(e) => {\n handleMouseUpWrapper(e);\n }}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n />\n );\n}\n","import type { FC } from 'react';\nimport { useContext, useCallback, memo, useRef } from 'react';\nimport { x2c } from '@gridsheet/web';\nimport { getLabel } from '@gridsheet/web';\nimport { between, zoneToArea } from '@gridsheet/web';\nimport { Context } from '../store';\nimport {\n choose,\n drag,\n select,\n selectCols,\n setAutofillDraggingTo,\n setColumnMenu,\n setContextMenuPosition,\n setDragging,\n setEditingAddress,\n setResizingPositionX,\n submitAutofill,\n write,\n} from '../store/actions';\nimport { DEFAULT_WIDTH } from '@gridsheet/web';\nimport { operations as prevention } from '@gridsheet/web';\nimport { insertRef } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { isXSheetFocused } from '../store/helpers';\nimport { ScrollHandle } from './ScrollHandle';\nimport { isTouching, safePreventDefault } from '../lib/events';\nimport { useDebounceCallback } from '../lib/hooks';\n\ntype Props = {\n x: number;\n};\n\nexport const HeaderCellTop: FC<Props> = memo(({ x }) => {\n const colId = x2c(x);\n const { store, dispatch } = useContext(Context);\n\n const {\n sheetReactive: sheetRef,\n editingAddress,\n choosing,\n selectingZone,\n topHeaderSelecting,\n editorRef,\n autofillDraggingTo,\n dragging,\n contextMenu,\n columnMenuState,\n } = store;\n const sheet = sheetRef.current;\n\n const col = sheet?.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const width = col?.width || DEFAULT_WIDTH;\n const hasFilter = !!(col?.filter && col.filter.conditions.length > 0);\n\n const xSheetFocused = isXSheetFocused(store);\n const lastFocused = sheet?.registry.lastFocused;\n\n const editingAnywhere = !!(sheet?.registry.editingAddress || editingAddress);\n\n const writeCell = useCallback(\n (value: string) => {\n dispatch(write({ value, point: choosing }));\n },\n [choosing],\n );\n\n const handleResizeMouseDown = useCallback((e: React.MouseEvent) => {\n dispatch(setResizingPositionX([x, e.clientX, e.clientX]));\n e.stopPropagation();\n safePreventDefault(e);\n }, []);\n\n const handleDragStart = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n safePreventDefault(e);\n\n if (!isTouching(e) || !sheet) {\n return false;\n }\n\n if (dragging) {\n return false;\n }\n\n // Single column selection only for touch events\n if (e.type.startsWith('touch')) {\n // Blur the input field to commit current value when selecting via touch\n if (editingAnywhere && editorRef.current) {\n editorRef.current.blur();\n }\n dispatch(choose({ y: 1, x }));\n dispatch(select({ startY: 1, startX: x, endY: sheet.numRows, endX: x }));\n return true;\n }\n\n dispatch(select({ startY: 1, startX: x, endY: -1, endX: x }));\n const fullAddress = `${sheet.sheetPrefix(!xSheetFocused)}${colId}:${colId}`;\n if (editingAnywhere) {\n const inserted = insertRef({ input: lastFocused || null, ref: fullAddress });\n if (inserted) {\n dispatch(select({ startY: sheet.numRows, startX: x, endY: 0, endX: x }));\n return false;\n }\n }\n\n let startX = e.shiftKey ? selectingZone.startX : x;\n if (startX === -1) {\n startX = choosing.x;\n }\n\n dispatch(\n selectCols({\n range: { start: startX, end: x },\n numRows: sheet.numRows,\n }),\n );\n\n if (editingAnywhere) {\n writeCell(lastFocused?.value ?? '');\n }\n dispatch(setEditingAddress(''));\n dispatch(setDragging(true));\n focus(editorRef.current);\n\n if (autofillDraggingTo) {\n return false;\n }\n return true;\n },\n [\n dragging,\n editingAnywhere,\n xSheetFocused,\n colId,\n lastFocused,\n selectingZone,\n choosing,\n autofillDraggingTo,\n editorRef,\n ],\n );\n\n const handleDragEnd = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n if (e.type.startsWith('touch')) {\n return;\n }\n\n safePreventDefault(e);\n dispatch(setDragging(false));\n if (autofillDraggingTo) {\n focus(editorRef.current);\n return false;\n }\n },\n [autofillDraggingTo],\n );\n\n const handleDragging = useDebounceCallback((e: React.MouseEvent | React.TouchEvent) => {\n if (!isTouching(e) || !sheet) {\n return false;\n }\n\n if (e.type.startsWith('touch')) {\n return false;\n }\n\n safePreventDefault(e);\n e.stopPropagation();\n\n if (autofillDraggingTo) {\n dispatch(setAutofillDraggingTo({ y: 1, x }));\n return false;\n }\n\n if (editingAnywhere) {\n const newArea = zoneToArea({ ...selectingZone, endY: 1, endX: x });\n const [left, right] = [x2c(newArea.left), x2c(newArea.right)];\n const fullRange = `${sheet.sheetPrefix(!xSheetFocused)}${left}:${right}`;\n insertRef({ input: lastFocused || null, ref: fullRange });\n }\n\n if (autofillDraggingTo == null) {\n const { startY } = selectingZone;\n if (startY === 1) {\n dispatch(drag({ y: sheet.numRows, x }));\n } else {\n dispatch(drag({ y: 1, x }));\n }\n }\n return false;\n }, 100);\n\n if (!sheet) {\n return (\n <th data-x={x} className=\"gs-th gs-th-top gs-hidden\">\n <div className=\"gs-th-inner-wrap\">\n <div className=\"gs-th-inner\">\n <ScrollHandle style={{ position: 'absolute' }} vertical={-1} />\n <div className=\"gs-resizer\"></div>\n </div>\n </div>\n </th>\n );\n }\n\n return (\n <th\n data-x={x}\n className={`gs-th gs-th-top ${choosing.x === x ? 'gs-choosing' : ''} ${\n between({ start: selectingZone.startX, end: selectingZone.endX }, x)\n ? topHeaderSelecting\n ? 'gs-th-selecting'\n : 'gs-selecting'\n : ''\n }`}\n style={{ ...col?.style, width, minWidth: width, maxWidth: width }}\n onDoubleClick={(e) => {\n // Double-clicking the header opens the column menu straight into label\n // editing (label section is first, its input focused + all-selected).\n // Ignore double-clicks on the resizer or the ⋮ menu button.\n const target = e.target as HTMLElement;\n if (target.closest('.gs-resizer, .gs-menu-btn')) {\n return;\n }\n if (prevention.hasOperation(col?.prevention, prevention.ColumnMenu)) {\n return;\n }\n e.stopPropagation();\n const inner = (e.currentTarget as HTMLElement).querySelector('.gs-th-inner') as HTMLElement | null;\n const rect = (inner ?? (e.currentTarget as HTMLElement)).getBoundingClientRect();\n const alreadySelected =\n between({ start: selectingZone.startX, end: selectingZone.endX }, x) &&\n selectingZone.startY === 1 &&\n selectingZone.endY === sheet.numRows;\n if (!alreadySelected) {\n dispatch(selectCols({ range: { start: x, end: x }, numRows: sheet.numRows }));\n }\n dispatch(setColumnMenu({ x, position: { y: rect.bottom, x: rect.left }, focusLabel: true }));\n }}\n onContextMenu={(e) => {\n if (contextMenu.length > 0) {\n e.stopPropagation();\n safePreventDefault(e);\n dispatch(setContextMenuPosition({ y: e.clientY, x: e.clientX }));\n return false;\n }\n return true;\n }}\n >\n <div\n className=\"gs-th-inner-wrap\"\n onMouseDown={handleDragStart}\n onTouchStart={handleDragStart}\n onMouseEnter={handleDragging}\n onMouseUp={handleDragEnd}\n >\n <div className=\"gs-th-inner\" style={{ height: sheet.headerHeight, position: 'relative' }}>\n <ScrollHandle\n style={{\n position: 'absolute',\n zIndex: topHeaderSelecting ? -1 : 1,\n }}\n vertical={-1}\n />\n {(() => {\n const displayedLabel = getLabel(sheet, col?.label, { y: 0, x }, x) ?? colId;\n if (displayedLabel !== colId) {\n return (\n <>\n <span className=\"gs-col-addr\">{colId}</span>\n {displayedLabel}\n </>\n );\n }\n return displayedLabel;\n })()}\n {!prevention.hasOperation(col?.prevention, prevention.ColumnMenu) && (\n <button\n className={`gs-menu-btn gs-column-menu-btn ${hasFilter ? 'gs-filtered' : ''} ${columnMenuState?.x === x ? 'gs-active' : ''}`}\n onMouseDown={(e) => {\n e.stopPropagation();\n e.preventDefault();\n (e.currentTarget as HTMLElement).dataset.pressX = String(e.clientX);\n (e.currentTarget as HTMLElement).dataset.pressY = String(e.clientY);\n }}\n onMouseUp={(e) => {\n e.stopPropagation();\n const btn = e.currentTarget as HTMLElement;\n const pressX = Number(btn.dataset.pressX ?? e.clientX);\n const pressY = Number(btn.dataset.pressY ?? e.clientY);\n const moved = Math.abs(e.clientX - pressX) > 4 || Math.abs(e.clientY - pressY) > 4;\n if (moved) {\n return; // was a drag, ignore\n }\n const rect = btn.getBoundingClientRect();\n if (columnMenuState?.x === x) {\n dispatch(setColumnMenu(null));\n } else {\n const alreadySelected =\n between({ start: selectingZone.startX, end: selectingZone.endX }, x) &&\n selectingZone.startY === 1 &&\n selectingZone.endY === sheet.numRows;\n if (!alreadySelected) {\n dispatch(selectCols({ range: { start: x, end: x }, numRows: sheet.numRows }));\n }\n dispatch(setColumnMenu({ x, position: { y: rect.bottom, x: rect.left } }));\n }\n }}\n >\n ⋮\n </button>\n )}\n <div\n className={`\n gs-resizer \n ${prevention.hasOperation(col?.prevention, prevention.Resize) ? 'gs-protected' : ''}\n ${dragging ? 'gs-hidden' : ''}`}\n style={{ height: sheet.headerHeight }}\n onMouseDown={handleResizeMouseDown}\n >\n <i />\n </div>\n </div>\n </div>\n </th>\n );\n});\n","import type { FC } from 'react';\nimport { useContext, useCallback, memo, useRef } from 'react';\nimport { y2r } from '@gridsheet/web';\nimport { getLabel } from '@gridsheet/web';\nimport { between, zoneToArea } from '@gridsheet/web';\nimport { Context } from '../store';\nimport {\n choose,\n drag,\n select,\n selectRows,\n setAutofillDraggingTo,\n setContextMenuPosition,\n setDragging,\n setEditingAddress,\n setResizingPositionY,\n setRowMenu,\n submitAutofill,\n write,\n} from '../store/actions';\nimport { DEFAULT_HEIGHT } from '@gridsheet/web';\nimport { operations as prevention } from '@gridsheet/web';\nimport { insertRef } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { isXSheetFocused } from '../store/helpers';\nimport { ScrollHandle } from './ScrollHandle';\nimport { isTouching, safePreventDefault } from '../lib/events';\nimport { useDebounceCallback } from '../lib/hooks';\n\ntype Props = {\n y: number;\n};\n\nexport const HeaderCellLeft: FC<Props> = memo(({ y }) => {\n const rowId = `${y2r(y)}`;\n const { store, dispatch } = useContext(Context);\n\n const {\n choosing,\n editingAddress,\n selectingZone,\n leftHeaderSelecting,\n editorRef,\n sheetReactive: sheetRef,\n autofillDraggingTo,\n dragging,\n contextMenu,\n rowMenuState,\n } = store;\n const sheet = sheetRef.current;\n\n const row = sheet?.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n const height = row?.height || DEFAULT_HEIGHT;\n\n const xSheetFocused = isXSheetFocused(store);\n const lastFocused = sheet?.registry.lastFocused;\n\n const editingAnywhere = !!(sheet?.registry.editingAddress || editingAddress);\n\n const writeCell = useCallback(\n (value: string) => {\n dispatch(write({ value, point: choosing }));\n },\n [choosing],\n );\n\n const handleResizeMouseDown = useCallback((e: React.MouseEvent) => {\n dispatch(setResizingPositionY([y, e.clientY, e.clientY]));\n e.stopPropagation();\n safePreventDefault(e);\n }, []);\n\n const handleDragStart = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n safePreventDefault(e);\n\n if (!isTouching(e) || !sheet) {\n return false;\n }\n if (dragging) {\n return false;\n }\n\n // Single row selection only for touch events\n if (e.type.startsWith('touch')) {\n // Blur the input field to commit current value when selecting via touch\n if (editingAnywhere && editorRef.current) {\n editorRef.current.blur();\n }\n dispatch(choose({ y, x: 1 }));\n dispatch(select({ startY: y, startX: 1, endY: y, endX: sheet.numCols }));\n return true;\n }\n\n // Normal drag operation for mouse events\n dispatch(select({ startY: y, startX: 1, endY: y, endX: -1 }));\n const fullAddress = `${sheet.sheetPrefix(!xSheetFocused)}${rowId}:${rowId}`;\n if (editingAnywhere) {\n const inserted = insertRef({ input: lastFocused || null, ref: fullAddress });\n if (inserted) {\n dispatch(select({ startY: y, startX: sheet.numCols, endY: y, endX: 0 }));\n return false;\n }\n }\n\n let startY = e.shiftKey ? selectingZone.startY : y;\n if (startY === -1) {\n startY = choosing.y;\n }\n\n dispatch(\n selectRows({\n range: { start: startY, end: y },\n numCols: sheet.numCols,\n }),\n );\n\n if (editingAnywhere) {\n writeCell(lastFocused?.value ?? '');\n }\n dispatch(setEditingAddress(''));\n dispatch(setDragging(true));\n focus(editorRef.current);\n\n if (autofillDraggingTo) {\n return false;\n }\n return true;\n },\n [\n dragging,\n editingAnywhere,\n xSheetFocused,\n rowId,\n lastFocused,\n selectingZone,\n choosing,\n autofillDraggingTo,\n editorRef,\n ],\n );\n\n const handleDragEnd = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n if (e.type.startsWith('touch')) {\n return;\n }\n\n safePreventDefault(e);\n dispatch(setDragging(false));\n if (autofillDraggingTo) {\n focus(editorRef.current);\n return false;\n }\n },\n [autofillDraggingTo],\n );\n\n const handleDragging = useDebounceCallback((e: React.MouseEvent | React.TouchEvent) => {\n if (!isTouching(e) || !sheet) {\n return false;\n }\n\n // Do nothing for touch events\n if (e.type.startsWith('touch')) {\n return false;\n }\n\n safePreventDefault(e);\n e.stopPropagation();\n\n if (autofillDraggingTo) {\n dispatch(setAutofillDraggingTo({ y, x: 1 }));\n return false;\n }\n\n if (editingAnywhere) {\n const newArea = zoneToArea({ ...selectingZone, endY: y, endX: 1 });\n const [top, bottom] = [y2r(newArea.top), y2r(newArea.bottom)];\n const fullRange = `${sheet.sheetPrefix(!xSheetFocused)}${top}:${bottom}`;\n insertRef({ input: lastFocused || null, ref: fullRange });\n }\n\n if (autofillDraggingTo == null) {\n const { startX } = selectingZone;\n if (startX === 1) {\n dispatch(drag({ y, x: sheet.numCols }));\n } else {\n dispatch(drag({ y, x: 1 }));\n }\n }\n return false;\n }, 100);\n\n const handleContextMenu = useCallback(\n (e: React.MouseEvent<HTMLTableCellElement>) => {\n if (contextMenu.length > 0) {\n e.stopPropagation();\n safePreventDefault(e);\n dispatch(setContextMenuPosition({ y: e.clientY, x: e.clientX }));\n return false;\n }\n return true;\n },\n [contextMenu.length],\n );\n\n if (!sheet) {\n return null;\n }\n\n return (\n <th\n data-y={y}\n className={`gs-th gs-th-left ${choosing.y === y ? 'gs-choosing' : ''} ${\n between({ start: selectingZone.startY, end: selectingZone.endY }, y)\n ? leftHeaderSelecting\n ? 'gs-th-selecting'\n : 'gs-selecting'\n : ''\n } ${row?.filterFixed ? 'gs-filter-fixed' : ''} ${row?.sortFixed ? 'gs-sort-fixed' : ''}`}\n style={{ ...row?.style, height }}\n onContextMenu={handleContextMenu}\n >\n <div\n className=\"gs-th-inner-wrap\"\n onMouseDown={handleDragStart}\n onTouchStart={handleDragStart}\n onMouseEnter={handleDragging}\n onMouseUp={handleDragEnd}\n >\n <div className=\"gs-th-inner\" style={{ width: sheet.headerWidth, position: 'relative' }}>\n <ScrollHandle\n style={{\n position: 'absolute',\n zIndex: leftHeaderSelecting ? -1 : 1,\n }}\n horizontal={-1}\n />\n {getLabel(sheet, row?.label, { y, x: 0 }, y) ?? rowId}\n {!prevention.hasOperation(row?.prevention, prevention.RowMenu) && (\n <button\n className={`gs-menu-btn gs-row-menu-btn ${rowMenuState?.y === y ? 'gs-active' : ''}`}\n onMouseDown={(e) => {\n e.stopPropagation();\n e.preventDefault();\n (e.currentTarget as HTMLElement).dataset.pressX = String(e.clientX);\n (e.currentTarget as HTMLElement).dataset.pressY = String(e.clientY);\n }}\n onMouseUp={(e) => {\n e.stopPropagation();\n const btn = e.currentTarget as HTMLElement;\n const pressX = Number(btn.dataset.pressX ?? e.clientX);\n const pressY = Number(btn.dataset.pressY ?? e.clientY);\n const moved = Math.abs(e.clientX - pressX) > 4 || Math.abs(e.clientY - pressY) > 4;\n if (moved) {\n return; // was a drag, ignore\n }\n const rect = btn.getBoundingClientRect();\n if (rowMenuState?.y === y) {\n dispatch(setRowMenu(null));\n } else {\n const alreadySelected =\n between({ start: selectingZone.startY, end: selectingZone.endY }, y) &&\n selectingZone.startX === 1 &&\n selectingZone.endX === sheet.numCols;\n if (!alreadySelected) {\n dispatch(selectRows({ range: { start: y, end: y }, numCols: sheet.numCols }));\n }\n dispatch(setRowMenu({ y, position: { y: rect.bottom, x: rect.right } }));\n }\n }}\n >\n ⋮\n </button>\n )}\n <div\n className={`\n gs-resizer\n ${prevention.hasOperation(row?.prevention, prevention.Resize) ? 'gs-protected' : ''}\n ${dragging ? 'gs-hidden' : ''}`}\n style={{ width: sheet.headerWidth }}\n onMouseDown={handleResizeMouseDown}\n ></div>\n </div>\n </div>\n </th>\n );\n});\n","import { useContext, useEffect, useRef, useCallback } from 'react';\nimport { Context } from '../store';\nimport { zoneToArea } from '@gridsheet/web';\nimport { between } from '@gridsheet/web';\nimport { a2p } from '@gridsheet/web';\nimport { COLOR_PALETTE } from '@gridsheet/web';\nimport { Autofill } from '@gridsheet/web';\nimport { getCellRectPositions, getVisibleRowRange, getVisibleColRange, toVirtualScrollTop } from '@gridsheet/web';\nimport type { Sheet } from '@gridsheet/web';\nimport type { FC } from 'react';\nimport type { RefPaletteType, AreaType, ModeType } from '../types';\n\nconst COLOR_POINTED = 'rgba(0, 119, 255, 1)';\nconst COLOR_SELECTED = 'rgba(0, 119, 255, 0.6)';\nconst SELECTING_FILL = 'rgba(0, 128, 255, 0.2)';\nconst COLOR_COPYING = '#0077ff';\nconst COLOR_CUTTING = '#0077ff';\nconst SEARCH_MATCHING_BACKGROUND = 'rgba(0, 200, 100, 0.2)';\nconst COLOR_SEARCH_MATCHING = '#00aa78';\nconst COLOR_AUTOFILL = '#0077aa';\n\nconst HEADER_COLORS = {\n light: {\n selecting: 'rgba(0, 0, 0, 0.1)',\n choosing: 'rgba(0, 0, 0, 0.2)',\n thSelecting: 'rgba(0, 0, 0, 0.55)',\n },\n dark: {\n selecting: 'rgba(255, 255, 255, 0.08)',\n choosing: 'rgba(255, 255, 255, 0.18)',\n thSelecting: 'rgba(255, 255, 255, 0.4)',\n },\n} as const;\n\ntype Props = {\n refs?: RefPaletteType;\n};\n\ntype Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n\nconst fillRect = (ctx: Ctx2D, x: number, y: number, width: number, height: number, color: string) => {\n ctx.fillStyle = color;\n ctx.fillRect(x, y, width, height);\n};\n\nconst drawRect = (\n ctx: Ctx2D,\n x: number,\n y: number,\n width: number,\n height: number,\n color: string,\n lineWidth: number = 2,\n dashPattern: number[] = [],\n fillColor?: string,\n) => {\n if (fillColor) {\n ctx.fillStyle = fillColor;\n ctx.fillRect(x, y, width, height);\n }\n\n ctx.strokeStyle = color;\n ctx.lineWidth = lineWidth;\n ctx.setLineDash(dashPattern);\n ctx.strokeRect(x + lineWidth / 2, y + lineWidth / 2, width - lineWidth, height - lineWidth);\n ctx.setLineDash([]);\n};\n\n// Draw an area rect in viewport coordinates (absolute coords - scroll offset, clamped to viewport)\nconst drawAreaRectViewport = (\n ctx: Ctx2D,\n sheet: Sheet,\n scrollTop: number,\n scrollLeft: number,\n viewW: number,\n viewH: number,\n area: AreaType,\n color: string,\n lineWidth: number = 2,\n dashPattern: number[] = [],\n fillColor?: string,\n) => {\n const { top, left, bottom, right } = area;\n if (top === -1 || left === -1 || bottom === -1 || right === -1) {\n return;\n }\n\n const topLeft = getCellRectPositions(sheet, { y: top, x: left });\n const bottomRight = getCellRectPositions(sheet, { y: bottom, x: right });\n\n const x1 = topLeft.left - scrollLeft;\n const y1 = topLeft.top - scrollTop;\n const x2 = bottomRight.right - scrollLeft;\n const y2 = bottomRight.bottom - scrollTop;\n\n // Quick reject if entirely off-screen\n if (x2 < 0 || x1 > viewW || y2 < 0 || y1 > viewH) {\n return;\n }\n\n drawRect(ctx, x1, y1, x2 - x1, y2 - y1, color, lineWidth, dashPattern, fillColor);\n};\n\nexport const CellStateOverlay: FC<Props> = ({ refs = {} }) => {\n const { store } = useContext(Context);\n const {\n sheetReactive,\n tabularRef,\n choosing,\n selectingZone,\n matchingCells,\n matchingCellIndex,\n autofillDraggingTo,\n topHeaderSelecting,\n leftHeaderSelecting,\n mode,\n dragging,\n } = store;\n const sheet = sheetReactive.current;\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const rafIdRef = useRef<number>(0);\n const storeRef = useRef(store);\n storeRef.current = store;\n\n const drawCanvas = useCallback(() => {\n if (!sheet || !tabularRef.current || !canvasRef.current) {\n return;\n }\n\n const canvas = canvasRef.current;\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n return;\n }\n\n const container = tabularRef.current;\n const dpr = window.devicePixelRatio || 1;\n const w = container.clientWidth;\n const h = container.clientHeight;\n\n // Resize canvas to viewport\n if (canvas.width !== w * dpr || canvas.height !== h * dpr) {\n canvas.style.width = `${w}px`;\n canvas.style.height = `${h}px`;\n canvas.width = w * dpr;\n canvas.height = h * dpr;\n }\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n ctx.clearRect(0, 0, w, h);\n\n const { registry } = sheet;\n // Vertical overlay math is all in virtual space (getCellRectPositions.top is virtual),\n // so map the DOM's capped physical scrollTop into virtual space. Horizontal columns\n // aren't remapped, so scrollLeft stays physical.\n const scrollTop = toVirtualScrollTop(sheet, container.scrollTop, container.clientHeight);\n const scrollLeft = container.scrollLeft;\n const headerW = sheet.headerWidth;\n const headerH = sheet.headerHeight;\n\n // Clip cell-area drawing to exclude header region\n ctx.save();\n ctx.beginPath();\n ctx.rect(headerW, headerH, w - headerW, h - headerH);\n ctx.clip();\n\n // 1. Selecting zone (border + fill)\n const selectingArea = zoneToArea(selectingZone);\n drawAreaRectViewport(ctx, sheet, scrollTop, scrollLeft, w, h, selectingArea, COLOR_SELECTED, 1, [], SELECTING_FILL);\n\n // 2. Autofill dragging\n if (autofillDraggingTo) {\n const autofill = new Autofill(storeRef.current, autofillDraggingTo);\n drawAreaRectViewport(ctx, sheet, scrollTop, scrollLeft, w, h, autofill.wholeArea, COLOR_AUTOFILL, 1, [5, 5]);\n }\n\n // 3. Choosing (pointed cell)\n {\n const { y, x } = choosing;\n if (y !== -1 && x !== -1) {\n const pos = getCellRectPositions(sheet, { y, x });\n const vx = pos.left - scrollLeft;\n const vy = pos.top - scrollTop;\n drawRect(ctx, vx, vy, pos.width, pos.height, COLOR_POINTED, 2, []);\n }\n }\n\n // 4. Copying/Cutting zone\n const { copyingSheetId, copyingZone, cutting } = registry;\n if (sheet.id === copyingSheetId) {\n const copyingArea = zoneToArea(copyingZone);\n const color = cutting ? COLOR_CUTTING : COLOR_COPYING;\n const dashPattern = cutting ? [4, 4] : [6, 4];\n drawAreaRectViewport(ctx, sheet, scrollTop, scrollLeft, w, h, copyingArea, color, 2.5, dashPattern);\n }\n\n // 5. Formula references (from palette)\n Object.entries(refs).forEach(([ref, i]) => {\n const palette = COLOR_PALETTE[i % COLOR_PALETTE.length];\n try {\n const refArea = sheet.rangeToArea(ref);\n drawAreaRectViewport(ctx, sheet, scrollTop, scrollLeft, w, h, refArea, palette, 2, [5, 5]);\n } catch (e) {\n // Invalid reference, skip\n }\n });\n\n // 6. Search matching cells\n matchingCells.forEach((address, index) => {\n const { y, x } = a2p(address);\n const pos = getCellRectPositions(sheet, { y, x });\n const vx = pos.left - scrollLeft;\n const vy = pos.top - scrollTop;\n\n // Skip if off-screen\n if (vx + pos.width < 0 || vx > w || vy + pos.height < 0 || vy > h) {\n return;\n }\n\n const isCurrentMatch = index === matchingCellIndex;\n drawRect(\n ctx,\n vx,\n vy,\n pos.width,\n pos.height,\n isCurrentMatch ? COLOR_SEARCH_MATCHING : 'transparent',\n isCurrentMatch ? 2 : 0,\n [],\n SEARCH_MATCHING_BACKGROUND,\n );\n });\n\n // Restore full canvas for header drawing\n ctx.restore();\n\n // 7. Header highlights (top and left) — draw bottom border for top headers, right border for left headers.\n // Only visible rows/cols can produce an on-screen highlight, so bound the scans to the viewport range.\n // Iterating 1..numRows here made every overlay redraw (e.g. after inserting rows, which bumps the sheet\n // version) O(numRows) AND materialized every row-header cell via isRowFiltered — ~150ms at a million rows.\n const [firstCol, lastCol] = getVisibleColRange(sheet, scrollLeft, w);\n const [firstRow, lastRow] = getVisibleRowRange(sheet, scrollTop, h);\n\n // Top headers - draw bottom border and background\n for (let x = firstCol; x <= lastCol; x++) {\n let color: string | null = null;\n let backgroundColor: string | null = null;\n if (between({ start: selectingZone.startX, end: selectingZone.endX }, x)) {\n color = 'rgba(80, 180, 255, 1)';\n backgroundColor = topHeaderSelecting ? 'rgba(128, 128, 128, 0.25)' : 'rgba(0, 119, 255, 0.05)';\n }\n if (choosing.x === x) {\n color = COLOR_POINTED;\n backgroundColor = topHeaderSelecting ? 'rgba(128, 128, 128, 0.45)' : 'rgba(0, 119, 255, 0.15)';\n }\n if (!color) {\n continue;\n }\n\n const pos = getCellRectPositions(sheet, { y: 1, x });\n const left = pos.left - scrollLeft;\n if (left + pos.width < headerW || left > w) {\n continue;\n }\n const drawLeft = Math.max(left, headerW);\n const drawWidth = Math.min(left + pos.width, w) - drawLeft;\n if (drawWidth > 0) {\n if (backgroundColor) {\n fillRect(ctx, drawLeft, 0, drawWidth, headerH, backgroundColor);\n }\n // Draw bottom border of the header\n ctx.strokeStyle = color;\n ctx.lineWidth = 2;\n ctx.beginPath();\n ctx.moveTo(drawLeft, headerH + 1);\n ctx.lineTo(drawLeft + drawWidth, headerH + 1);\n ctx.stroke();\n }\n }\n\n // Left headers - draw right border and background\n for (let y = firstRow; y <= lastRow; y++) {\n if (sheet.isRowFiltered(y)) {\n continue;\n }\n let color: string | null = null;\n let backgroundColor: string | null = null;\n if (between({ start: selectingZone.startY, end: selectingZone.endY }, y)) {\n color = 'rgba(80, 180, 255, 1)';\n backgroundColor = leftHeaderSelecting ? 'rgba(128, 128, 128, 0.25)' : 'rgba(0, 119, 255, 0.05)';\n }\n if (choosing.y === y) {\n color = COLOR_POINTED;\n backgroundColor = leftHeaderSelecting ? 'rgba(128, 128, 128, 0.45)' : 'rgba(0, 119, 255, 0.15)';\n }\n if (!color) {\n continue;\n }\n\n const pos = getCellRectPositions(sheet, { y, x: 1 });\n const top = pos.top - scrollTop;\n if (top + pos.height < headerH || top > h) {\n continue;\n }\n const drawTop = Math.max(top, headerH);\n const drawHeight = Math.min(top + pos.height, h) - drawTop;\n if (drawHeight > 0) {\n if (backgroundColor) {\n fillRect(ctx, 0, drawTop, headerW, drawHeight, backgroundColor);\n }\n // Draw right border of the header\n ctx.strokeStyle = color;\n ctx.lineWidth = 2;\n ctx.beginPath();\n ctx.moveTo(headerW + 1, drawTop);\n ctx.lineTo(headerW + 1, drawTop + drawHeight);\n ctx.stroke();\n }\n }\n }, [\n sheet,\n // The Sheet instance is mutated in place, so its identity stays stable across structural\n // changes (insert/remove rows & cols, resize, sort, filter). Depend on its monotonic version\n // so the overlay redraws when the grid layout shifts; otherwise the old box stays misaligned.\n sheet?.currentVersion,\n tabularRef,\n choosing,\n selectingZone,\n matchingCells,\n matchingCellIndex,\n autofillDraggingTo,\n topHeaderSelecting,\n leftHeaderSelecting,\n mode,\n dragging,\n refs,\n ]);\n\n // Schedule a draw on the next animation frame (for state changes)\n const scheduleDrawCanvas = useCallback(() => {\n cancelAnimationFrame(rafIdRef.current);\n rafIdRef.current = requestAnimationFrame(drawCanvas);\n }, [drawCanvas]);\n\n // Draw synchronously on scroll to avoid 1-frame lag\n const handleScroll = useCallback(() => {\n drawCanvas();\n }, [drawCanvas]);\n\n useEffect(() => {\n scheduleDrawCanvas();\n return () => cancelAnimationFrame(rafIdRef.current);\n }, [scheduleDrawCanvas]);\n\n useEffect(() => {\n const container = tabularRef.current;\n if (!container) {\n return;\n }\n container.addEventListener('scroll', handleScroll);\n const ro = new ResizeObserver(() => drawCanvas());\n ro.observe(container);\n return () => {\n container.removeEventListener('scroll', handleScroll);\n ro.disconnect();\n };\n }, [tabularRef, handleScroll, drawCanvas]);\n\n return (\n <div\n style={{\n position: 'sticky',\n top: 0,\n left: 0,\n width: 0,\n height: 0,\n overflow: 'visible',\n pointerEvents: 'none',\n zIndex: 10,\n }}\n >\n <canvas\n ref={canvasRef}\n className=\"gs-cell-state-overlay\"\n style={{\n pointerEvents: 'none',\n display: 'block',\n }}\n />\n </div>\n );\n};\n","import { useEffect, useContext, useState, useCallback } from 'react';\n\nimport { Cell } from './Cell';\nimport { HeaderCellTop } from './HeaderCellTop';\nimport { HeaderCellLeft } from './HeaderCellLeft';\nimport { CellStateOverlay } from './CellStateOverlay';\n\nimport { Context } from '../store';\nimport { choose, select, setContextMenuPosition } from '../store/actions';\n\nimport type { RefPaletteType, Virtualization } from '../types';\nimport { virtualize, physicalScrollHeight } from '@gridsheet/web';\nimport { p2a, stripAddressAbsolute } from '@gridsheet/web';\nimport { Lexer, stripSheetName } from '@gridsheet/web';\nimport { ScrollHandle } from './ScrollHandle';\nimport { preventSafariBounce } from '@gridsheet/web';\n\nexport const Tabular = () => {\n const [palette, setPalette] = useState<RefPaletteType>({});\n const { store, dispatch } = useContext(Context);\n const {\n sheetReactive,\n choosing,\n editingAddress,\n tabularRef,\n mainRef,\n sheetWidth,\n sheetHeight,\n fixedWidth,\n fixedHeight,\n inputting,\n leftHeaderSelecting,\n topHeaderSelecting,\n contextMenu,\n } = store;\n const sheet = sheetReactive.current;\n\n const [virtualized, setVirtualized] = useState<Virtualization | null>(null);\n\n // Mark on .gs-main whether the grid overflows the viewport per axis, so the matrix outer\n // border hugs the content when it fits (border on the inner) and switches to a fixed\n // viewport overlay when it scrolls. Runs after every render (so it always catches the\n // ready flip, content growth and size changes) but reads layout inside rAF — after paint\n // — so it never blocks the render/paint the way a synchronous reflow would, and only\n // writes the attribute when the value actually changes.\n useEffect(() => {\n const t = tabularRef.current;\n const m = mainRef.current;\n if (!t || !m) {\n return;\n }\n const raf = requestAnimationFrame(() => {\n const ox = String(t.scrollWidth > t.clientWidth + 1);\n const oy = String(t.scrollHeight > t.clientHeight + 1);\n if (m.getAttribute('data-overflow-x') !== ox) {\n m.setAttribute('data-overflow-x', ox);\n }\n if (m.getAttribute('data-overflow-y') !== oy) {\n m.setAttribute('data-overflow-y', oy);\n }\n });\n return () => cancelAnimationFrame(raf);\n });\n\n const handleMouseMove = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n }, []);\n\n const handleScroll = useCallback(\n (e: React.UIEvent<HTMLDivElement>) => {\n if (sheet) {\n setVirtualized(virtualize(sheet, e.currentTarget));\n }\n },\n [sheetReactive],\n );\n\n const handleSelectAllClick = useCallback(() => {\n if (!sheet) {\n return;\n }\n dispatch(choose({ y: -1, x: -1 }));\n requestAnimationFrame(() => {\n dispatch(choose({ y: 1, x: 1 }));\n dispatch(\n select({\n startY: 1,\n startX: 1,\n endY: sheet.numRows,\n endX: sheet.numCols,\n }),\n );\n });\n }, [sheetReactive]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n const formulaEditing = editingAddress && inputting.startsWith('=');\n if (!formulaEditing) {\n setPalette({});\n sheet.registry.paletteBySheetName = {};\n return;\n }\n const palette: RefPaletteType = {};\n const paletteBySheetName: { [sheetName: string]: RefPaletteType } = {};\n const lexer = new Lexer(inputting.substring(1));\n lexer.tokenize();\n\n let i = 0;\n for (const token of lexer.tokens) {\n if (token.type === 'REF' || token.type === 'RANGE') {\n const normalizedRef = stripAddressAbsolute(token.stringify());\n const splitterIndex = normalizedRef.indexOf('!');\n if (splitterIndex !== -1) {\n const sheetName = normalizedRef.substring(0, splitterIndex);\n const ref = normalizedRef.substring(splitterIndex + 1);\n const stripped = stripSheetName(sheetName);\n const upperRef = ref.toUpperCase();\n if (paletteBySheetName[stripped] == null) {\n paletteBySheetName[stripped] = {};\n }\n if (paletteBySheetName[stripped][upperRef] == null) {\n paletteBySheetName[stripped][upperRef] = i++;\n }\n } else {\n const upperRef = normalizedRef.toUpperCase();\n if (palette[upperRef] == null) {\n palette[upperRef] = i++;\n }\n }\n }\n }\n setPalette(palette);\n sheet.registry.paletteBySheetName = paletteBySheetName;\n }, [store.inputting, store.editingAddress, sheetReactive]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n sheet.registry.choosingAddress = p2a(choosing);\n sheet.registry.choosingSheetId = sheet.id;\n }, [choosing]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n setVirtualized(virtualize(sheet, tabularRef.current));\n }, [\n tabularRef.current,\n sheetReactive,\n mainRef.current?.clientHeight,\n mainRef.current?.clientWidth,\n sheetHeight,\n sheetWidth,\n ]);\n\n useEffect(() => {\n const el = tabularRef.current;\n if (!el) {\n return;\n }\n return preventSafariBounce(el);\n }, [sheetReactive]);\n\n // Eager resolution: virtualization only renders/solves visible cells, so\n // off-screen async formulas would never fire. When the sheet opts in via\n // `eager`, fire every off-screen async cell after each update. resolveAll()\n // is idempotent — resolved/pending cells are cache hits — so it converges\n // once all async formulas have settled.\n useEffect(() => {\n if (!sheet || !sheet.eager || !sheet.registry.ready) {\n return;\n }\n sheet.resolveAll();\n }, [sheet, sheetReactive]);\n\n const mergedRefs: RefPaletteType = {\n ...palette,\n ...(sheet ? sheet.registry.paletteBySheetName[sheet.name] : {}),\n };\n\n if (!sheet || !sheet.registry.ready) {\n return null;\n }\n\n return (\n <>\n <div\n className=\"gs-tabular\"\n style={{\n // When a size is explicitly configured, keep that box so a smaller grid can be\n // centered within it (see .gs-tabular in tabular.less); otherwise shrink to fit.\n width:\n sheetWidth === -1 ? undefined : fixedWidth ? sheetWidth : Math.min(sheetWidth, sheet.totalWidth),\n height:\n sheetHeight === -1 ? undefined : fixedHeight ? sheetHeight : Math.min(sheetHeight, sheet.totalHeight),\n }}\n ref={tabularRef}\n onMouseMove={handleMouseMove}\n onScroll={handleScroll}\n >\n <div\n className={'gs-tabular-inner'}\n style={{\n width: sheet.totalWidth,\n // Physical scroll height is capped below the browser's ~2^24px precision limit;\n // virtualize() maps this back to the sheet's full virtual height (see SCROLL_CAP).\n height: physicalScrollHeight(sheet),\n overflow: 'clip',\n }}\n >\n <CellStateOverlay refs={mergedRefs} />\n <table className={`gs-table`}>\n <thead className=\"gs-thead\" style={{ height: sheet.headerHeight }}>\n <tr className=\"gs-row\">\n <th\n className=\"gs-th gs-th-left gs-th-top\"\n style={{ position: 'sticky', width: sheet.headerWidth, height: sheet.headerHeight }}\n onClick={handleSelectAllClick}\n >\n <div className=\"gs-th-inner\">\n <ScrollHandle\n className={leftHeaderSelecting || topHeaderSelecting ? 'gs-hidden' : ''}\n style={{ position: 'absolute' }}\n horizontal={leftHeaderSelecting ? 0 : -1}\n vertical={topHeaderSelecting ? 0 : -1}\n />\n {contextMenu.length > 0 && (\n <button\n className=\"gs-menu-btn gs-corner-menu-btn\"\n onClick={(e) => e.stopPropagation()}\n onMouseDown={(e) => {\n e.preventDefault();\n (e.currentTarget as HTMLElement).dataset.pressX = String(e.clientX);\n (e.currentTarget as HTMLElement).dataset.pressY = String(e.clientY);\n }}\n onMouseUp={(e) => {\n e.stopPropagation();\n const btn = e.currentTarget as HTMLElement;\n const pressX = Number(btn.dataset.pressX ?? e.clientX);\n const pressY = Number(btn.dataset.pressY ?? e.clientY);\n const moved = Math.abs(e.clientX - pressX) > 4 || Math.abs(e.clientY - pressY) > 4;\n if (moved) {\n return;\n }\n const rect = btn.getBoundingClientRect();\n dispatch(setContextMenuPosition({ y: rect.bottom, x: rect.left }));\n }}\n >\n ⋮\n </button>\n )}\n </div>\n </th>\n <th\n className=\"gs-adjuster gs-adjuster-horizontal gs-adjuster-horizontal-left\"\n style={{ width: virtualized?.adjuster?.left ?? 1 }}\n ></th>\n {virtualized?.xs?.map?.((x) => <HeaderCellTop x={x} key={x} />)}\n <th\n className=\"gs-adjuster gs-adjuster-horizontal gs-adjuster-horizontal-right\"\n style={{ width: virtualized?.adjuster?.right }}\n ></th>\n </tr>\n </thead>\n\n <tbody className=\"gs-sheet-body-adjuster\">\n <tr className=\"gs-row\">\n <th\n className={`gs-adjuster gs-adjuster-horizontal gs-adjuster-vertical`}\n style={{ height: virtualized?.adjuster?.top ?? 1 }}\n ></th>\n <td className=\"gs-adjuster gs-adjuster-vertical\"></td>\n {virtualized?.xs?.map((x) => <td className=\"gs-adjuster gs-adjuster-vertical\" key={x}></td>)}\n <th className={`gs-adjuster gs-adjuster-horizontal gs-adjuster-vertical`}></th>\n </tr>\n </tbody>\n\n <tbody className=\"gs-sheet-body-data\">\n {virtualized?.ys?.map((y) => {\n return (\n <tr key={y} className={`gs-row ${y % 2 === 0 ? 'gs-row-even' : 'gs-row-odd'}`}>\n <HeaderCellLeft y={y} />\n <td className=\"gs-adjuster gs-adjuster-horizontal gs-adjuster-horizontal-left\" />\n {virtualized?.xs?.map((x) => <Cell key={x} y={y} x={x} />)}\n <td className=\"gs-adjuster gs-adjuster-horizontal gs-adjuster-horizontal-right\" />\n </tr>\n );\n })}\n </tbody>\n </table>\n </div>\n </div>\n </>\n );\n};\n","import type { KeyboardEvent } from 'react';\nimport React, { useCallback, useEffect, useRef, useState, useContext } from 'react';\nimport { createPortal } from 'react-dom';\nimport { FunctionGuide } from './FunctionGuide';\nimport { EditorOptions } from './EditorOptions';\nimport { Context } from '../store';\nimport { p2a, a2p } from '@gridsheet/web';\nimport { setEditingAddress, setInputting, setEditorHovering, walk, write, updateSheet } from '../store/actions';\nimport { operations as prevention } from '@gridsheet/web';\nimport { insertTextAtCursor, isFocus } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { editorStyle } from './Editor';\nimport { ScrollHandle } from './ScrollHandle';\nimport { useAutocomplete } from './useAutocomplete';\n\ntype FormulaBarProps = {\n ready: boolean;\n};\n\nexport const FormulaBar = ({ ready }: FormulaBarProps) => {\n const { store, dispatch } = useContext(Context);\n const [before, setBefore] = useState('');\n const [selectionStart, setSelectionStart] = useState(0);\n const [isFocused, setIsFocused] = useState(false);\n const {\n choosing,\n selectingZone,\n editorRef,\n largeEditorRef,\n sheetReactive: sheetRef,\n inputting,\n editingAddress: editingCell,\n dragging,\n } = store;\n const sheet = sheetRef.current;\n const hlRef = useRef<HTMLDivElement | null>(null);\n\n const address = choosing.x === -1 ? '' : p2a(choosing);\n const cell = sheet?.getCell(choosing, { resolution: 'SYSTEM' });\n const spilledFromAddress = sheet?.getSystem(choosing)?.spilledFrom;\n const originPoint = spilledFromAddress ? a2p(spilledFromAddress) : undefined;\n const originAddress = originPoint != null ? p2a(originPoint) : undefined;\n useEffect(() => {\n if (!sheet) {\n return;\n }\n let value = sheet.getCell(choosing, { resolution: 'SYSTEM' })?.value ?? '';\n // debug to remove this line\n value = sheet.getSerializedValue({ point: choosing, cell: { ...cell, value }, resolution: 'RAW' });\n largeEditorRef.current!.value = value;\n setBefore(value as string);\n }, [address, sheet]);\n\n const writeCell = useCallback(\n (value: string) => {\n if (before !== value) {\n dispatch(write({ value }));\n }\n dispatch(setEditingAddress(''));\n focus(editorRef.current);\n },\n [before],\n );\n\n useEffect(() => {\n const observer = new ResizeObserver((entries) => {\n entries.forEach(updateScroll);\n });\n if (largeEditorRef.current) {\n observer.observe(largeEditorRef.current);\n }\n return () => {\n observer.disconnect();\n };\n }, []);\n\n const policy = sheet?.getPolicy(choosing);\n const optionsAll = policy?.getSelectOptions() || [];\n\n const {\n filteredOptions,\n selected,\n setSelected,\n replaceWithOption,\n handleArrowUp,\n handleArrowDown,\n isFormula,\n activeFunctionHelp,\n activeArgIndex,\n } = useAutocomplete({\n inputting,\n selectionStart,\n optionsAll,\n functions: sheet?.registry.functions,\n });\n\n const composingRef = useRef(false);\n const largeInput = largeEditorRef.current;\n\n const handleInput = useCallback((e: React.SyntheticEvent<HTMLTextAreaElement>) => {\n dispatch(setInputting(e.currentTarget.value));\n setSelectionStart(e.currentTarget.selectionStart);\n }, []);\n\n const handleSelect = useCallback((e: React.SyntheticEvent<HTMLTextAreaElement>) => {\n setSelectionStart(e.currentTarget.selectionStart);\n }, []);\n\n const updateScroll = useCallback(() => {\n if (!hlRef.current || !largeEditorRef.current) {\n return;\n }\n hlRef.current.style.height = `${largeEditorRef.current.clientHeight}px`;\n hlRef.current.scrollLeft = largeEditorRef.current.scrollLeft;\n hlRef.current.scrollTop = largeEditorRef.current.scrollTop;\n }, []);\n\n const handleFocus = useCallback(\n (e: React.FocusEvent<HTMLTextAreaElement>) => {\n if (!largeInput || !sheet) {\n return;\n }\n setIsFocused(true);\n dispatch(setEditingAddress(address));\n sheet.registry.lastFocused = e.currentTarget;\n },\n [largeInput, address, sheet],\n );\n\n const handleBlur = useCallback(\n (e: React.FocusEvent<HTMLTextAreaElement>) => {\n setIsFocused(false);\n if (e.currentTarget.value!.startsWith('=')) {\n return true;\n } else {\n if (editingCell) {\n writeCell(e.currentTarget.value);\n }\n }\n },\n [editingCell, writeCell],\n );\n\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if ((e.nativeEvent as any).isComposing || composingRef.current) {\n return;\n }\n if (e.ctrlKey || !sheet) {\n return true;\n }\n const input = e.currentTarget;\n\n switch (e.key) {\n case 'Tab': // TAB\n e.preventDefault();\n if (filteredOptions.length) {\n const option = filteredOptions[selected];\n const isFunc = option?.isFunction;\n\n if (isFunc) {\n const { value: newValue, selectionStart: newCursor } = replaceWithOption(option);\n dispatch(setInputting(newValue));\n setTimeout(() => {\n if (largeEditorRef.current) {\n focus(largeEditorRef.current);\n largeEditorRef.current.setSelectionRange(newCursor, newCursor);\n }\n }, 0);\n return false;\n } else {\n // ... regular completion ...\n const t = sheet.update({ diff: { [address]: { value: option.value } }, partial: true });\n dispatch(updateSheet(t.clone()));\n dispatch(setEditingAddress(''));\n dispatch(setInputting(''));\n }\n }\n break;\n case 'ArrowUp':\n if (handleArrowUp(e as unknown as React.KeyboardEvent<HTMLTextAreaElement>)) {\n return true;\n }\n break;\n case 'ArrowDown':\n if (handleArrowDown(e as unknown as React.KeyboardEvent<HTMLTextAreaElement>)) {\n return true;\n }\n break;\n case 'Enter': {\n if (filteredOptions.length) {\n const option = filteredOptions[selected];\n if (option?.isFunction) {\n const { value: newValue, selectionStart: newCursor } = replaceWithOption(option);\n dispatch(setInputting(newValue));\n setTimeout(() => {\n if (largeEditorRef.current) {\n focus(largeEditorRef.current);\n largeEditorRef.current.setSelectionRange(newCursor, newCursor);\n }\n }, 0);\n e.preventDefault();\n return false;\n }\n }\n\n if (e.altKey) {\n insertTextAtCursor(input, '\\n');\n } else {\n writeCell(input.value);\n dispatch(setInputting(''));\n dispatch(\n walk({\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 1,\n deltaX: 0,\n }),\n );\n e.preventDefault();\n return false;\n }\n break;\n }\n case 'Escape': {\n input.value = before;\n dispatch(setInputting(before));\n dispatch(setEditingAddress(''));\n e.preventDefault();\n focus(editorRef.current);\n\n break;\n }\n case 'a': // A\n if (e.ctrlKey || e.metaKey) {\n return true;\n }\n case 'c': // C\n if (e.ctrlKey || e.metaKey) {\n return true;\n }\n break;\n case 'v': // V\n if (e.ctrlKey || e.metaKey) {\n return true;\n }\n break;\n }\n\n const cell = sheet.getCell(choosing, { resolution: 'SYSTEM' });\n if (prevention.hasOperation(cell?.prevention, prevention.Write)) {\n console.warn('This cell is protected from writing.');\n e.preventDefault();\n }\n updateScroll();\n return false;\n },\n [\n sheet,\n choosing,\n address,\n before,\n writeCell,\n updateScroll,\n filteredOptions,\n selected,\n replaceWithOption,\n handleArrowUp,\n handleArrowDown,\n inputting,\n ],\n );\n\n const handleOptionMouseDown = useCallback(\n (e: React.MouseEvent, i: number) => {\n e.preventDefault();\n e.stopPropagation();\n const option = filteredOptions[i];\n if (option.isFunction) {\n const { value: newValue, selectionStart: newCursor } = replaceWithOption(option);\n writeCell(newValue);\n dispatch(setInputting(newValue));\n setTimeout(() => {\n if (largeEditorRef.current) {\n focus(largeEditorRef.current);\n largeEditorRef.current.setSelectionRange(newCursor, newCursor);\n }\n }, 0);\n }\n },\n [filteredOptions, replaceWithOption, writeCell, dispatch],\n );\n\n const style: React.CSSProperties = ready ? {} : { visibility: 'hidden' };\n if (!sheet) {\n return (\n <label className=\"gs-formula-bar gs-hidden\" style={style}>\n <div className=\"gs-selecting-address\"></div>\n <div className=\"gs-fx\">fx</div>\n <div className=\"gs-formula-bar-editor-inner\">\n <textarea />\n </div>\n </label>\n );\n }\n const renderOverlays = () => {\n if (!isFocused || typeof document === 'undefined') {\n return null;\n }\n if (largeEditorRef.current !== document.activeElement) {\n return null;\n }\n\n const rect = largeEditorRef.current?.getBoundingClientRect();\n if (!rect) {\n return null;\n }\n\n const top = rect.bottom;\n const left = rect.left;\n\n return createPortal(\n <>\n {activeFunctionHelp &&\n filteredOptions.length === 0 &&\n (!selectingZone || (selectingZone.endY === -1 && selectingZone.endX === -1)) && (\n <FunctionGuide\n activeFunctionGuide={activeFunctionHelp}\n activeArgIndex={activeArgIndex}\n top={top}\n left={left}\n />\n )}\n {filteredOptions.length > 0 && choosing.x !== -1 && (\n <EditorOptions\n filteredOptions={filteredOptions}\n top={top}\n left={left}\n selected={selected}\n onOptionMouseDown={handleOptionMouseDown}\n />\n )}\n </>,\n document.body,\n );\n };\n\n return (\n <div\n className=\"gs-formula-bar\"\n data-sheet-id={store.sheetId}\n data-spill={originAddress != null ? 'true' : undefined}\n style={style}\n >\n <ScrollHandle style={{ position: 'absolute', left: 0, top: 0, zIndex: 2 }} vertical={-1} />\n <div className=\"gs-selecting-address\">{originAddress != null ? originAddress : address}</div>\n <div className=\"gs-fx\">fx</div>\n <div className=\"gs-formula-bar-editor-inner\">\n <div\n className=\"gs-editor-hl\"\n ref={hlRef}\n style={{\n height: largeEditorRef.current?.clientHeight,\n width: '100%',\n }}\n >\n {(cell?.formulaEnabled ?? true) ? editorStyle(inputting) : inputting}\n </div>\n <textarea\n name=\"gs-formula-bar-editor\"\n data-sheet-id={store.sheetId}\n data-size=\"large\"\n rows={1}\n spellCheck={false}\n ref={largeEditorRef}\n value={inputting}\n // Spilled cells must not be edited from the FormulaBar — input here\n // would modify `inputting` one character at a time (via onInput) even\n // though the underlying cell cannot be written to.\n readOnly={originAddress != null}\n onInput={handleInput}\n onFocus={handleFocus}\n onSelect={handleSelect}\n onPaste={(e) => {\n e.stopPropagation();\n }}\n onKeyDown={handleKeyDown}\n onKeyUp={updateScroll}\n onCompositionStart={() => {\n composingRef.current = true;\n }}\n onCompositionEnd={(e) => {\n composingRef.current = false;\n dispatch(setInputting(e.currentTarget.value));\n }}\n onScroll={updateScroll}\n onMouseEnter={(e) => {\n dispatch(setEditorHovering(true));\n }}\n onMouseLeave={(e) => {\n dispatch(setEditorHovering(false));\n }}\n ></textarea>\n {renderOverlays()}\n </div>\n </div>\n );\n};\n","import type { ReactNode, CSSProperties } from 'react';\n\nexport interface IconProps {\n style?: CSSProperties;\n color?: string;\n size?: number;\n}\n\ninterface BaseProps extends IconProps {\n children?: ReactNode;\n}\n\n// https://tabler.io/icons\n\nexport const Base = ({ style, size = 24, children }: BaseProps) => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox={`0 0 24 24`}\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={style}\n className=\"icon-tabler\"\n >\n {children}\n </svg>\n );\n};\n","import { type IconProps, Base } from './Base';\n\n// https://tabler.io/icons\n\nexport const SearchIcon = ({ style, color = 'none', size = 24 }: IconProps) => {\n return (\n <Base style={style} size={size}>\n <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill={color} />\n <path d=\"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0\" fill={color} />\n <path d=\"M21 21l-6 -6\" fill={color} />\n </Base>\n );\n};\n","import { type IconProps, Base } from './Base';\n\n// https://tabler.io/icons\n\nexport const CloseIcon = ({ style, color = 'none', size = 24 }: IconProps) => {\n return (\n <Base style={style} size={size}>\n <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill={color} />\n <path d=\"M18 6l-12 12\" fill={color} />\n <path d=\"M6 6l12 12\" fill={color} />\n </Base>\n );\n};\n","import { useContext, useEffect, useRef, useCallback, useMemo } from 'react';\n\nimport { a2p, x2c, y2r } from '@gridsheet/web';\nimport { isZoneNotSelected } from '@gridsheet/web';\n\nimport { Context } from '../store';\nimport { setSearchQuery, search, setSearchCaseSensitive, setSearchRegex, setSearchRange } from '../store/actions';\nimport { smartScroll } from '@gridsheet/web';\nimport { SearchIcon } from './svg/SearchIcon';\nimport { CloseIcon } from './svg/CloseIcon';\nimport { focus } from '@gridsheet/web';\n\nexport const SearchBar = () => {\n const { store, dispatch } = useContext(Context);\n const {\n rootRef,\n editorRef,\n searchInputRef,\n tabularRef,\n searchQuery,\n searchCaseSensitive,\n searchRegex,\n searchRange,\n selectingZone,\n matchingCellIndex,\n matchingCells,\n sheetReactive: sheetRef,\n } = store;\n const sheet = sheetRef.current;\n\n const matchingCell = matchingCells[matchingCellIndex];\n useEffect(() => {\n if (!matchingCell || !sheet) {\n return;\n }\n const point = a2p(matchingCell);\n if (typeof point === 'undefined') {\n return;\n }\n smartScroll(sheet, tabularRef.current, point);\n }, [searchQuery, matchingCellIndex, searchCaseSensitive, searchRegex, sheet, tabularRef]);\n\n const handleProgressClick = useCallback((e: React.MouseEvent) => {\n const input = e.currentTarget.previousSibling as HTMLInputElement;\n input?.nodeName === 'INPUT' && focus(input);\n }, []);\n\n const handleSearchClick = useCallback(() => {\n dispatch(search(1));\n }, []);\n\n const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {\n dispatch(setSearchQuery(e.currentTarget.value));\n }, []);\n\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Escape') {\n const el = editorRef?.current;\n if (el) {\n focus(el);\n }\n dispatch(setSearchQuery(undefined));\n }\n if (e.key === 'f' && (e.ctrlKey || e.metaKey)) {\n e.preventDefault();\n return false;\n }\n if (e.key === 'Enter') {\n dispatch(search(e.shiftKey ? -1 : 1));\n e.preventDefault();\n return false;\n }\n return true;\n },\n [editorRef],\n );\n\n const handleCaseSensitiveClick = useCallback(() => {\n dispatch(setSearchCaseSensitive(!searchCaseSensitive));\n }, [searchCaseSensitive]);\n\n const handleRegexClick = useCallback(() => {\n dispatch(setSearchRegex(!searchRegex));\n }, [searchRegex]);\n\n const hasSelection = useMemo(() => {\n if (!selectingZone) {\n return false;\n }\n if (isZoneNotSelected(selectingZone)) {\n return false;\n }\n const { startY, startX, endY, endX } = selectingZone;\n return !(startY === endY && startX === endX);\n }, [selectingZone]);\n\n const selectionLabel = useMemo(() => {\n if (!selectingZone || !hasSelection) {\n return '';\n }\n const { startY, startX, endY, endX } = selectingZone;\n const topLeft = `${x2c(Math.min(startX, endX))}${y2r(Math.min(startY, endY))}`;\n const bottomRight = `${x2c(Math.max(startX, endX))}${y2r(Math.max(startY, endY))}`;\n return `${topLeft}:${bottomRight}`;\n }, [selectingZone, hasSelection]);\n\n const handleRangeClick = useCallback(() => {\n if (searchRange) {\n // Clear search range\n dispatch(setSearchRange(undefined));\n } else if (selectingZone && hasSelection) {\n // Set search range to current selection\n const { startY, startX, endY, endX } = selectingZone;\n dispatch(\n setSearchRange({\n startY: Math.min(startY, endY),\n startX: Math.min(startX, endX),\n endY: Math.max(startY, endY),\n endX: Math.max(startX, endX),\n }),\n );\n }\n }, [searchRange, selectingZone, hasSelection]);\n\n const searchRangeLabel = useMemo(() => {\n if (!searchRange) {\n return '';\n }\n const { startY, startX, endY, endX } = searchRange;\n const topLeft = `${x2c(startX)}${y2r(startY)}`;\n const bottomRight = `${x2c(endX)}${y2r(endY)}`;\n return `${topLeft}:${bottomRight}`;\n }, [searchRange]);\n\n const handleCloseClick = useCallback(() => {\n dispatch(setSearchQuery(undefined));\n focus(editorRef.current);\n }, [editorRef]);\n\n if (typeof searchQuery === 'undefined') {\n return null;\n }\n if (rootRef.current === null) {\n return null;\n }\n return (\n <label className={`gs-search-bar ${matchingCells.length > 0 ? 'gs-search-found' : ''}`}>\n <div className=\"gs-search-progress\" onClick={handleProgressClick}>\n {matchingCells.length === 0 ? 0 : matchingCellIndex + 1} / {matchingCells.length}\n </div>\n <div className=\"gs-search-bar-icon\" onClick={handleSearchClick}>\n <SearchIcon style={{ verticalAlign: 'middle', marginLeft: '5px' }} />\n </div>\n <div className=\"gs-search-input-wrapper\">\n <div className=\"gs-search-input-ghost\">\n <span className=\"gs-search-ghost-text\">{searchQuery}</span>\n {searchQuery && <span className=\"gs-search-ghost-hint\"> ↵ Next</span>}\n </div>\n <textarea\n ref={searchInputRef}\n value={searchQuery}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n placeholder=\"Search\"\n title=\"Press Enter to next, Shift+Enter to previous\"\n ></textarea>\n </div>\n <div className=\"gs-search-buttons\">\n {searchRange && (\n <div className=\"gs-search-button gs-search-range\">\n <span\n className=\"gs-search-button-on\"\n onClick={handleRangeClick}\n title={`Search range: ${searchRangeLabel}`}\n >\n in {searchRangeLabel}\n </span>\n </div>\n )}\n {!searchRange && hasSelection && (\n <div className=\"gs-search-button gs-search-range\">\n <span onClick={handleRangeClick} title={`Limit to range: ${selectionLabel}`}>\n in {selectionLabel}\n </span>\n </div>\n )}\n <div className=\"gs-search-button gs-search-casesensitive\">\n <span\n className={`${searchCaseSensitive ? 'gs-search-button-on' : ''}`}\n onClick={handleCaseSensitiveClick}\n title={`Case sensitive`}\n >\n Aa\n </span>\n </div>\n <div className=\"gs-search-button gs-search-regex\">\n <span\n className={`${searchRegex ? 'gs-search-button-on' : ''}`}\n onClick={handleRegexClick}\n title={`Regular expression`}\n >\n .*\n </span>\n </div>\n </div>\n <a className=\"gs-search-close\" onClick={handleCloseClick}>\n <CloseIcon style={{ verticalAlign: 'middle' }} />\n </a>\n </label>\n );\n};\n","import { useEffect, useState, useRef, useReducer, createRef, useCallback } from 'react';\nimport type { CSSProperties } from 'react';\nimport type { BorderSides, CellsByAddressType, SheetHandle, StoreHandle, OptionsType, Props, StoreType } from '../types';\nimport {\n DEFAULT_HEIGHT,\n DEFAULT_WIDTH,\n HEADER_HEIGHT,\n HEADER_WIDTH,\n SHEET_HEIGHT,\n SHEET_WIDTH,\n DEFAULT_COL_KEY,\n DEFAULT_ROW_KEY,\n} from '@gridsheet/web';\nimport { Context } from '../store';\nimport { reducer as defaultReducer, isMutationAction, isAsyncMutationAction, commitAsyncOp } from '../store/actions';\nimport { AsyncProgressOverlay, type AsyncProgressHandle } from './AsyncProgressOverlay';\nimport { ProgressOverlay } from './ProgressOverlay';\nimport { Editor } from './Editor';\nimport { StoreObserver } from './StoreObserver';\nimport { Resizer } from './Resizer';\nimport { Emitter } from './Emitter';\nimport { ContextMenu } from './ContextMenu';\nimport { ColumnMenu } from './ColumnMenu';\nimport { RowMenu } from './RowMenu';\nimport { Sheet } from '@gridsheet/web';\nimport { Tabular } from './Tabular';\nimport { getMaxSizesFromCells } from '@gridsheet/web';\nimport { x2c, y2r } from '@gridsheet/web';\nimport { embedStyle } from '@gridsheet/web';\nimport { FormulaBar } from './FormulaBar';\nimport { SearchBar } from './SearchBar';\nimport { useBook } from '../lib/hooks';\nimport { ScrollHandle } from './ScrollHandle';\nimport { defaultContextMenuDescriptors, defaultRowMenuDescriptors, defaultColMenuDescriptors } from '../lib/menu';\n\nexport const createSheetRef = () => createRef<SheetHandle | null>();\nexport const useSheetRef = () => useRef<SheetHandle | null>(null);\nexport const createStoreRef = () => createRef<StoreHandle | null>();\nexport const useStoreRef = () => useRef<StoreHandle | null>(null);\n\nexport function GridSheet({\n initialCells,\n sheetName = '',\n sheetRef: initialSheetRef,\n storeRef: initialStoreRef,\n options = {},\n className,\n style,\n book: initialBook,\n loading: loadingProp,\n}: Props) {\n const {\n sheetResize,\n showFormulaBar = true,\n mode = 'light',\n density = 'compact',\n gridLines = 'all',\n formulaBarBorders = { all: true },\n matrixBorders = { all: true },\n } = options;\n // Translate the border config objects into CSS custom properties consumed by the\n // stylesheet (--gs-fb-* for the formula bar, --gs-mx-* for the matrix). A specific side\n // overrides `all`.\n const bw = (b: BorderSides, side: 'left' | 'top' | 'right' | 'bottom') =>\n (b[side] ?? b.all ?? false) ? '1px' : '0';\n const borderVars = {\n '--gs-fb-bl': bw(formulaBarBorders, 'left'),\n '--gs-fb-bt': bw(formulaBarBorders, 'top'),\n '--gs-fb-br': bw(formulaBarBorders, 'right'),\n '--gs-fb-bb': bw(formulaBarBorders, 'bottom'),\n '--gs-mx-bl': bw(matrixBorders, 'left'),\n '--gs-mx-bt': bw(matrixBorders, 'top'),\n '--gs-mx-br': bw(matrixBorders, 'right'),\n '--gs-mx-bb': bw(matrixBorders, 'bottom'),\n } as CSSProperties;\n const rootRef = useRef<HTMLDivElement>(null);\n const flashRef = useRef<HTMLDivElement>(null);\n const mainRef = useRef<HTMLDivElement>(null);\n const searchInputRef = useRef<HTMLTextAreaElement>(null);\n const editorRef = useRef<HTMLTextAreaElement>(null);\n const largeEditorRef = useRef<HTMLTextAreaElement>(null);\n const tabularRef = useRef<HTMLDivElement>(null);\n\n const internalSheetRef = useSheetRef();\n const sheetRef = initialSheetRef ?? internalSheetRef;\n const internalStoreRef = useStoreRef();\n const storeRef = initialStoreRef ?? internalStoreRef;\n\n const internalBook = useBook({});\n const book = initialBook ?? internalBook;\n const { registry } = book;\n\n const [sheetId] = useState<number>(() => {\n if (sheetName) {\n // Named sheets: use sheetName as stable dedup key to prevent double-increment in Strict Mode.\n if (!registry._componentSheetIds.has(sheetName)) {\n registry._componentSheetIds.set(sheetName, ++registry.sheetHead);\n }\n return registry._componentSheetIds.get(sheetName)!;\n }\n // Unnamed sheets: accept double-increment in Strict Mode (IDs may skip, but remain unique).\n return ++registry.sheetHead;\n });\n\n // Initialize sheetReactive\n const sheetReactive = useRef<Sheet | null>(null);\n\n const [initialState] = useState<StoreType>(() => {\n if (!sheetName) {\n sheetName = `Sheet${sheetId}`;\n console.debug('GridSheet: sheetName is not provided, using default name:', sheetName);\n }\n const { limits, contextMenu, rowMenu, colMenu, eager } = options;\n const sheet = new Sheet({\n limits,\n name: sheetName,\n registry,\n eager,\n });\n sheet.id = sheetId;\n registry.sheetIdsByName[sheetName] = sheetId;\n\n sheet.initialize(initialCells);\n registry.onInit?.({ sheet });\n\n sheet.setTotalSize();\n sheetReactive.current = sheet;\n\n const store: StoreType = {\n sheetId,\n sheetReactive,\n rootRef,\n flashRef,\n mainRef,\n searchInputRef,\n editorRef,\n largeEditorRef,\n tabularRef,\n choosing: { y: 1, x: 1 },\n inputting: '',\n selectingZone: { startY: 1, startX: 1, endY: -1, endX: -1 },\n autofillDraggingTo: null,\n leftHeaderSelecting: false,\n topHeaderSelecting: false,\n editingAddress: '',\n editorRect: { y: 0, x: 0, height: 0, width: 0 },\n dragging: false,\n sheetHeight: 0,\n sheetWidth: 0,\n fixedWidth: false,\n fixedHeight: false,\n entering: false,\n matchingCells: [],\n matchingCellIndex: 0,\n searchCaseSensitive: false,\n searchRegex: false,\n editingOnEnter: true,\n contextMenuPosition: { y: -1, x: -1 },\n contextMenu: contextMenu ?? defaultContextMenuDescriptors,\n rowMenu: rowMenu ?? defaultRowMenuDescriptors,\n colMenu: colMenu ?? defaultColMenuDescriptors,\n resizingPositionY: [-1, -1, -1],\n resizingPositionX: [-1, -1, -1],\n columnMenuState: null,\n rowMenuState: null,\n editorHovering: true,\n mode: 'light',\n pendingAsyncOp: null,\n };\n return store;\n });\n\n type ReducerWithoutAction<S> = (prevState: S) => S;\n\n const [store, dispatch] = useReducer(\n defaultReducer as unknown as ReducerWithoutAction<StoreType>,\n initialState,\n () => initialState,\n );\n\n useEffect(() => {\n embedStyle();\n }, []);\n\n // When sheetWidth/sheetHeight is a string, the sheet stretches to its parent (fill mode)\n // and the rendered pixel size is measured via ResizeObserver instead of being fixed.\n const fillWidth = typeof options.sheetWidth === 'string';\n const fillHeight = typeof options.sheetHeight === 'string';\n // matrixAlignment picks which axes may center. A fixed box (that a smaller grid centers\n // within) only exists when the size is *intentionally* larger than the content — an\n // explicit sheetWidth/sheetHeight, or a manual resize — never from the content estimate\n // or the formula-bar width, so nothing but those produces an empty gap. 'none' keeps the\n // old shrink-to-content behavior.\n const matrixAlignment = options.matrixAlignment ?? 'none';\n const centersWidth = matrixAlignment === 'horizontal' || matrixAlignment === 'both';\n const centersHeight = matrixAlignment === 'vertical' || matrixAlignment === 'both';\n const [resizedWidth, setResizedWidth] = useState(false);\n const [resizedHeight, setResizedHeight] = useState(false);\n const fixedWidth = centersWidth && (options.sheetWidth != null || resizedWidth);\n const fixedHeight = centersHeight && (options.sheetHeight != null || resizedHeight);\n const [sheetHeight, setSheetHeight] = useState(\n typeof options?.sheetHeight === 'number' ? options.sheetHeight : estimateSheetHeight(initialCells),\n );\n const [sheetWidth, setSheetWidth] = useState(\n typeof options?.sheetWidth === 'number' ? options.sheetWidth : estimateSheetWidth(initialCells),\n );\n useEffect(() => {\n const el = mainRef.current;\n if (!el) {\n return;\n }\n let first = true;\n const ro = new ResizeObserver(() => {\n // CSS `resize` writes an inline width/height when the user drags the handle; that is\n // the signal that the box was intentionally sized, so a smaller grid may now center.\n if (el.style.width) {\n setResizedWidth(true);\n }\n if (el.style.height) {\n setResizedHeight(true);\n }\n if (first) {\n first = false;\n // In fill mode we want the initial measurement; otherwise keep the provided/estimated size.\n if (!fillWidth && !fillHeight) {\n return;\n }\n }\n const root = rootRef.current;\n setSheetHeight(root ? Math.min(el.clientHeight, root.clientHeight) : el.clientHeight);\n setSheetWidth(root ? Math.min(el.clientWidth, root.clientWidth) : el.clientWidth);\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, [fillWidth, fillHeight]);\n useEffect(() => {\n if (typeof options.sheetHeight === 'number') {\n setSheetHeight(options.sheetHeight);\n }\n }, [options.sheetHeight]);\n useEffect(() => {\n if (typeof options.sheetWidth === 'number') {\n setSheetWidth(options.sheetWidth);\n }\n }, [options.sheetWidth]);\n\n const [loading, setLoading] = useState(false);\n\n // Latest store, so wrappedDispatch (memoized) can read pendingAsyncOp for the lock.\n const latestStoreRef = useRef(store);\n latestStoreRef.current = store;\n\n const wrappedDispatch = useCallback(\n ((action: { type: number; value: any }) => {\n const async = isAsyncMutationAction(action.type);\n const mutating = isMutationAction(action.type);\n // Lock: while a chunked async op is in flight the sheet is mid-mutation, so\n // reject any other mutation (edit/undo/paste/fill) until it commits. Read-only\n // actions (selection, scroll) still pass through.\n if (latestStoreRef.current.pendingAsyncOp != null && (async || mutating)) {\n return;\n }\n if (async) {\n // Its reduce just sets pendingAsyncOp (cheap); the runner effect drives it.\n (dispatch as any)(action);\n return;\n }\n if (!mutating) {\n (dispatch as any)(action);\n return;\n }\n setLoading(true);\n // TWO rAFs before running the (synchronous, possibly multi-second) mutation:\n // a single rAF fires BEFORE the overlay's first paint, so the overlay never\n // actually showed during the block. The second rAF runs after that paint, so\n // the spinner is on screen (and its compositor-driven animation keeps moving)\n // while the main thread is blocked. Clear right after dispatch — React batches\n // loading:false with the mutation's own re-render, so the overlay lifts exactly\n // when the result appears.\n requestAnimationFrame(() =>\n requestAnimationFrame(() => {\n (dispatch as any)(action);\n setLoading(false);\n }),\n );\n }) as typeof dispatch,\n [dispatch],\n );\n\n // Runner for chunked async mutations (large fill/paste): when an action sets\n // store.pendingAsyncOp, run it off the reducer — reporting progress into the store\n // and committing the mutated sheet when done. Two rAFs first so the progress\n // overlay paints before the (still-synchronous) diff-build inside run() starts.\n const overlayRef = useRef<AsyncProgressHandle>(null);\n const pendingAsyncOp = store.pendingAsyncOp;\n useEffect(() => {\n if (pendingAsyncOp == null) {\n return;\n }\n let cancelled = false;\n const raf = requestAnimationFrame(() =>\n requestAnimationFrame(async () => {\n if (cancelled) {\n return;\n }\n try {\n const nextSheet = await pendingAsyncOp.run((ratio) => {\n // Imperative — updates only the overlay, never the grid.\n overlayRef.current?.setProgress(ratio);\n });\n if (!cancelled) {\n (dispatch as any)(\n commitAsyncOp({\n sheet: nextSheet,\n selectingZone: pendingAsyncOp.selectingZone,\n finalize: pendingAsyncOp.finalize,\n }),\n );\n pendingAsyncOp.postCommit?.();\n }\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error('[gridsheet] async op failed:', e);\n if (!cancelled) {\n (dispatch as any)(commitAsyncOp({ sheet: latestStoreRef.current.sheetReactive.current!, selectingZone: pendingAsyncOp.selectingZone }));\n }\n }\n }),\n );\n return () => {\n cancelled = true;\n cancelAnimationFrame(raf);\n };\n }, [pendingAsyncOp, dispatch]);\n\n return (\n <Context.Provider value={{ store, dispatch: wrappedDispatch }}>\n <div\n className={`gs-root1 ${registry.ready ? 'gs-initialized' : ''}`}\n ref={rootRef}\n data-sheet-name={sheetName}\n data-mode={mode}\n data-density={density}\n data-gridlines={gridLines}\n data-matrix-align={matrixAlignment}\n data-rows={store.sheetReactive.current?.numRows ?? 0}\n data-cols={store.sheetReactive.current?.numCols ?? 0}\n style={\n fillWidth || fillHeight\n ? {\n ...borderVars,\n // inline-flex (when width isn't filled) keeps the prior shrink-to-content width.\n display: fillWidth ? 'flex' : 'inline-flex',\n flexDirection: 'column',\n ...(fillWidth ? { width: options.sheetWidth as string } : null),\n ...(fillHeight ? { height: options.sheetHeight as string } : null),\n }\n : borderVars\n }\n >\n <div className=\"gs-flash-overlay\" ref={flashRef} />\n <ScrollHandle style={{ position: 'fixed', top: 0, left: 0 }} />\n <ScrollHandle style={{ position: 'absolute', zIndex: 4, right: 0, top: 0, width: 5 }} horizontal={1} />\n <ScrollHandle style={{ position: 'absolute', zIndex: 4, left: 0, bottom: 0, height: 5 }} vertical={1} />\n\n {typeof store.searchQuery === 'undefined' ? (\n showFormulaBar && <FormulaBar ready={registry.ready} />\n ) : (\n <SearchBar />\n )}\n <div\n className={`gs-main ${className || ''}`}\n ref={mainRef}\n style={{\n ...(fillWidth ? { width: '100%' } : null),\n maxWidth: '100%',\n // In fill-height mode the parent's height is the limit (flex:1 fills the remaining\n // space below the formula bar); otherwise cap at the viewport bottom as before.\n ...(fillHeight\n ? { flex: 1, minHeight: 0, maxHeight: '100%' }\n : {\n maxHeight: mainRef.current\n ? window.innerHeight - mainRef.current.getBoundingClientRect().top\n : (store.sheetReactive.current?.fullHeight || 0) + 2,\n }),\n resize: sheetResize,\n ...style,\n }}\n >\n <Editor mode={mode} />\n <Tabular />\n <StoreObserver\n {...{ ...options, sheetHeight, sheetWidth, fixedWidth, fixedHeight, sheetName, sheetRef, storeRef }}\n />\n <ContextMenu />\n <ColumnMenu />\n <RowMenu />\n <Resizer />\n <Emitter />\n {store.pendingAsyncOp != null ? (\n // Chunked async mutation (large fill/paste): imperative progress, grid not re-rendered.\n <AsyncProgressOverlay ref={overlayRef} label={store.pendingAsyncOp.label} />\n ) : loading ? (\n // Internal sync mutation in flight: brief indeterminate spinner.\n <div className=\"gs-loading-overlay\">\n <div className=\"gs-loading-spinner\" />\n </div>\n ) : loadingProp ? (\n // Consumer-driven initial loading (data not ready yet).\n <ProgressOverlay\n progress={typeof loadingProp === 'object' ? (loadingProp.progress ?? null) : null}\n label={typeof loadingProp === 'object' ? loadingProp.label : undefined}\n />\n ) : null}\n </div>\n </div>\n </Context.Provider>\n );\n}\n\nconst estimateSheetHeight = (initialCells: CellsByAddressType) => {\n const auto = getMaxSizesFromCells(initialCells);\n let estimatedHeight = initialCells[0]?.height ?? HEADER_HEIGHT;\n for (let y = 1; y <= auto.numRows; y++) {\n const row = y2r(y);\n const height =\n initialCells?.[row]?.height ||\n initialCells?.['0' + row]?.height ||\n initialCells?.[DEFAULT_ROW_KEY]?.height ||\n initialCells?.default?.height ||\n DEFAULT_HEIGHT;\n if (estimatedHeight + height > SHEET_HEIGHT) {\n return SHEET_HEIGHT;\n }\n estimatedHeight += height;\n }\n return estimatedHeight + 3;\n};\n\nconst estimateSheetWidth = (initialCells: CellsByAddressType) => {\n const auto = getMaxSizesFromCells(initialCells);\n let estimatedWidth = initialCells[0]?.width ?? HEADER_WIDTH;\n for (let x = 1; x <= auto.numCols; x++) {\n const col = x2c(x);\n const width =\n initialCells?.[col]?.width ||\n initialCells?.[col + '0']?.width ||\n initialCells?.[DEFAULT_COL_KEY]?.width ||\n initialCells?.default?.width ||\n DEFAULT_WIDTH;\n if (estimatedWidth + width > SHEET_WIDTH) {\n return SHEET_WIDTH;\n }\n estimatedWidth += width;\n }\n return estimatedWidth + 3;\n};\n","import type { PolicyMixinType, RenderProps } from '@gridsheet/web';\n\nexport const CheckboxPolicyMixin: PolicyMixinType = {\n renderBool({ value, apply, sheet, point }: RenderProps<boolean>): any {\n return (\n <input\n type=\"checkbox\"\n checked={value}\n onChange={(e) => {\n if (apply) {\n apply(sheet.write({ point, value: e.currentTarget.checked.toString() }));\n }\n e.currentTarget.blur();\n }}\n />\n );\n },\n};\n","import type { CSSProperties } from 'react';\n\ntype BorderStyleValue = string;\n\ninterface BorderOptions {\n all?: BorderStyleValue;\n top?: BorderStyleValue;\n right?: BorderStyleValue;\n bottom?: BorderStyleValue;\n left?: BorderStyleValue;\n}\n\nexport function makeBorder(options: BorderOptions): CSSProperties {\n const result: CSSProperties = {};\n const all = options.all;\n if (options.top ?? all) {\n result.borderTop = options.top ?? all;\n }\n if (options.right ?? all) {\n result.borderRight = options.right ?? all;\n }\n if (options.bottom ?? all) {\n result.borderBottom = options.bottom ?? all;\n }\n if (options.left ?? all) {\n result.borderLeft = options.left ?? all;\n }\n return result;\n}\n"],"names":["Context","createContext","ProgressOverlay","progress","label","determinate","pct","jsxs","jsx","AsyncProgressOverlay","forwardRef","ref","setProgress","useState","useImperativeHandle","FunctionGuide","option","activeFunctionGuide","activeArgIndex","top","left","useRef","guide1Ref","store","useContext","isHidden","useLayoutEffect","el","calcSideStyle","clampPopup","e","React","Fragment","arg","j","args","numIterable","a","variadicStart","isActive","offset","resolvedIndex","activeArg","EditorOptions","filteredOptions","selected","onOptionMouseDown","ulRef","adjustedLeft","setAdjustedLeft","width","clampLeft","i","clip","selectingZone","choosing","editorRef","sheetRef","sheet","y","x","area","zoneToArea","input","trimmed","tsv","sheet2csv","point","html","sheet2html","tsvBlob","htmlBlob","focus","getter","filteredRowsIncluded","trailingEmptyRowsOmitted","separator","newline","rows","cols","rowIsEmpty","value","r","valueEscaped","useAutocomplete","inputting","selectionStart","optionsAll","functions","setSelected","matchParams","activeFunctionHelp","useMemo","isFormula","textBeforeCursor","textAfterCursor","textToCursor","lexer","Lexer","functionStack","token","nextToken","activeItem","helps","getFunctionHelps","h","wordBefore","_a","wordAfter","_b","currentWord","hasOpenParenAssigned","filtered","isOnAddress","fullLexer","currentIndex","tLen","help","keywordLower","startsWith","index","hasNoArgs","b","keywords","bestMatch","keyword","replaceWithOption","useCallback","beforeMatch","afterMatch","handleArrowUp","s","handleArrowDown","Fixed","children","style","className","attrs","document","useBrowser","createPortal","parseHTML","onlyValue","doc","results","processSheet","spans","row","caption","cells","result","cell","childStyle","parseStyleString","rowSpan","colSpan","c","processNodeSequentially","node","currentLine","tagName","blockTags","child","lines","line","element","styleString","styleObj","d","rawKey","rawValue","key","_","letter","parseText","sep","entering","word","restoreDoubleQuote","text","Editor","mode","dispatch","shiftKey","setShiftKey","setSelectionStart","isFocused","setIsFocused","composingRef","editorRect","editingAddress","matchingCells","matchingCellIndex","searchQuery","largeEditorRef","searchInputRef","editingOnEnter","sheetId","dragging","renderOverlays","editing","rect","handleOptionMouseDown","policy","handleSelect","useEffect","setEditingAddress","expandInput","rowId","y2r","address","x2c","currentString","before","setBefore","writeCell","write","selectValue","selectedIndex","newValue","newCursor","setInputting","t","updateSheet","resetInput","height","numLines","isKeyDown","setIsKeyDown","handleKeyDown","handleFormulaQuoteAutoClose","isFunction","walk","insertTextAtCursor","dblclick","_c","clear","_d","escape","setSearchQuery","selectToDataEdge","arrow","select","copy","areaToZone","fillDown","setEntering","fillRight","redo","_f","_e","cut","undo","prevention","handleFocus","handleDoubleClick","length","handleBlur","isRefInsertable","handleChange","handlePaste","paste","handleKeyUpInternal","selectingArea","editorStyle","setEditorHovering","TokenSpan","memo","tokenKey","color","prevProps","nextProps","palletIndex","exists","formulaHash","hash","char","normalizedToken","existsIndex","COLOR_PALETTE","PluginContext","useInitialPluginContext","setStore","apply","setApply","usePluginContext","ctx","PluginBase","context","provided","StoreObserver","sheetName","sheetHeight","sheetWidth","fixedWidth","fixedHeight","storeRef","sheetReactive","dragRef","raf","running","dead","cx","cy","lastCell","lastExtend","EDGE","SPEED","stop","finish","submitAutofill","setDragging","tick","dy","dx","px","py","now","setAutofillDraggingTo","drag","onMove","onDown","onUp","onLeaveWindow","registry","pluginProvided","pluginContext","Resizer","posY","posX","leftHeaderSelecting","topHeaderSelecting","mainRef","startY","endY","startX","endX","offsetY","offsetX","baseWidth","DEFAULT_WIDTH","baseHeight","DEFAULT_HEIGHT","bottom","right","diff","xs","between","makeSequence","p2a","ys","setResizingPositionY","setResizingPositionX","MIN_HEIGHT","MIN_WIDTH","Emitter","pointing","zone","copier","cutter","paster","items","item","undoer","redoer","rowsInserterAbove","numRows","zoneShape","insertRowsAbove","rowsInserterBelow","insertRowsBelow","colsInserterLeft","numCols","insertColsLeft","colsInserterRight","insertColsRight","rowsRemover","removeRows","colsRemover","removeCols","rowsSorterAsc","sortRows","rowsSorterDesc","rowsFilterer","filter","filterRows","rowsFilterClearer","rowSortFixedToggler","addr","rowCell","next","rowFilterFixedToggler","searcher","applyers","rowInsertCount","selStart","selEnd","colInsertCount","defaultContextMenuDescriptors","colCell","defaultRowMenuDescriptors","n","defaultColMenuDescriptors","buildMenuContext","close","props","_insertRowsAbove","_insertRowsBelow","_removeRows","_insertColsLeft","_insertColsRight","_removeCols","direction","_setStore","_menuComponentRegistry","registerMenuComponent","id","component","getMenuComponent","MenuItem","shortcuts","disabled","checked","testId","onClick","hasCheck","shortcut","part","arr","MenuDivider","MenuNodes","onSelect","renderComponent","SubmenuNode","open","setOpen","liRef","flyoutRef","pos","setPos","li","fly","p","f","margin","ContextMenu","contextMenuPosition","contextMenu","menuRef","setContextMenuPosition","METHOD_LABELS","NO_VALUE_METHODS","DEFAULT_CONDITION","FilterSection","onWaiting","conditions","setConditions","setMode","pending","setPending","firstValueRef","existing","handleCancel","cancelled","execute","actionX","validConditions","filterMode","currentSheet","updateCondition","patch","prev","addCondition","removeCondition","handleApplyFilter","valid","v","handleResetColumn","handleResetAll","filterDisabled","hasAnyFilter","cond","m","SortSection","sortDisabled","LabelSection","labelInputRef","setLabel","handleApplyLabel","labelDisabled","labelPlaceholder","getLabel","ColumnMenu","columnMenuState","colMenu","position","waitingState","setWaitingState","handleClose","setColumnMenu","handleWaiting","message","cancel","componentId","Section","RowMenu","rowMenuState","rowMenu","setRowMenu","isTouching","mouseEvent","safePreventDefault","Cell","isFirstPointed","cellRef","errorTooltipPos","setErrorTooltipPos","autofillDraggingTo","xSheetFocused","isXSheetFocused","lastFocused","pointed","_setEditorRect","setEditorRect","errorMessage","rendered","FormulaError","isPendingCell","Pending","editingAnywhere","handleDragStart","choose","fullAddress","insertRef","handleDragEnd","handleDragging","newArea","fullRange","areaToRange","handleAutofillMouseDown","handleErrorTriangleEnter","calcBelowPosition","handleErrorTriangleLeave","onContextMenu","onDoubleClick","autofillDragClass","among","hAlignTransform","acceleration","maxSpeed","lastScrollTime","currentSpeed","ScrollHandle","horizontal","vertical","scrollRef","tabularRef","isScrolling","getDestEdge","tabularRect","getAreaInTabular","scrollStep","live","curY","curX","sheetPrefix","sheetRange","handleMouseEnter","stopScroll","isFocus","handleMouseUp","handleMouseUpWrapper","handleMouseLeave","cannotScrollHere","HeaderCellTop","colId","col","hasFilter","handleResizeMouseDown","selectCols","useDebounceCallback","displayedLabel","btn","pressX","pressY","HeaderCellLeft","selectRows","handleContextMenu","COLOR_POINTED","COLOR_SELECTED","SELECTING_FILL","COLOR_COPYING","COLOR_CUTTING","SEARCH_MATCHING_BACKGROUND","COLOR_SEARCH_MATCHING","COLOR_AUTOFILL","fillRect","drawRect","lineWidth","dashPattern","fillColor","drawAreaRectViewport","scrollTop","scrollLeft","viewW","viewH","topLeft","getCellRectPositions","bottomRight","x1","y1","x2","y2","CellStateOverlay","refs","canvasRef","rafIdRef","drawCanvas","canvas","container","dpr","w","toVirtualScrollTop","headerW","headerH","autofill","Autofill","vx","vy","copyingSheetId","copyingZone","cutting","copyingArea","palette","refArea","a2p","isCurrentMatch","firstCol","lastCol","getVisibleColRange","firstRow","lastRow","getVisibleRowRange","backgroundColor","drawLeft","drawWidth","drawTop","drawHeight","scheduleDrawCanvas","handleScroll","ro","Tabular","setPalette","virtualized","setVirtualized","ox","oy","handleMouseMove","virtualize","handleSelectAllClick","paletteBySheetName","normalizedRef","stripAddressAbsolute","splitterIndex","stripped","stripSheetName","upperRef","preventSafariBounce","mergedRefs","physicalScrollHeight","_g","_h","FormulaBar","ready","editingCell","hlRef","spilledFromAddress","originPoint","originAddress","observer","entries","updateScroll","largeInput","handleInput","Base","size","SearchIcon","CloseIcon","SearchBar","rootRef","searchCaseSensitive","searchRegex","searchRange","matchingCell","smartScroll","handleProgressClick","handleSearchClick","search","handleCaseSensitiveClick","setSearchCaseSensitive","handleRegexClick","setSearchRegex","hasSelection","isZoneNotSelected","selectionLabel","handleRangeClick","setSearchRange","searchRangeLabel","handleCloseClick","createSheetRef","createRef","useSheetRef","createStoreRef","useStoreRef","GridSheet","initialCells","initialSheetRef","initialStoreRef","options","initialBook","loadingProp","sheetResize","showFormulaBar","density","gridLines","formulaBarBorders","matrixBorders","bw","side","borderVars","flashRef","internalSheetRef","internalStoreRef","internalBook","useBook","book","initialState","limits","eager","Sheet","useReducer","defaultReducer","embedStyle","fillWidth","fillHeight","matrixAlignment","centersWidth","centersHeight","resizedWidth","setResizedWidth","resizedHeight","setResizedHeight","setSheetHeight","estimateSheetHeight","setSheetWidth","estimateSheetWidth","first","root","loading","setLoading","latestStoreRef","wrappedDispatch","action","async","isAsyncMutationAction","mutating","isMutationAction","overlayRef","pendingAsyncOp","nextSheet","ratio","commitAsyncOp","auto","getMaxSizesFromCells","estimatedHeight","HEADER_HEIGHT","DEFAULT_ROW_KEY","SHEET_HEIGHT","estimatedWidth","HEADER_WIDTH","DEFAUL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AA,aAAawjB,EAAQ,QAAQkE,IAE/B1nB;AACT;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/store/index.ts","../src/components/ProgressOverlay.tsx","../src/components/AsyncProgressOverlay.tsx","../src/components/FunctionGuide.tsx","../src/components/EditorOptions.tsx","../src/lib/clipboard.ts","../src/components/useAutocomplete.ts","../src/components/Fixed.tsx","../src/lib/paste.ts","../src/components/Editor.tsx","../src/components/PluginBase.tsx","../src/components/StoreObserver.tsx","../src/components/Resizer.tsx","../src/components/Emitter.tsx","../src/store/applyers.ts","../src/lib/menu.ts","../src/components/MenuItem.tsx","../src/components/MenuNodes.tsx","../src/components/ContextMenu.tsx","../src/components/ColumnMenuFilterSection.tsx","../src/components/ColumnMenuSortSection.tsx","../src/components/ColumnMenuLabelSection.tsx","../src/components/ColumnMenu.tsx","../src/components/RowMenu.tsx","../src/lib/events.ts","../src/components/Cell.tsx","../src/components/ScrollHandle.tsx","../src/components/HeaderCellTop.tsx","../src/components/HeaderCellLeft.tsx","../src/components/CellStateOverlay.tsx","../src/components/Tabular.tsx","../src/components/FormulaBar.tsx","../src/components/svg/Base.tsx","../src/components/svg/SearchIcon.tsx","../src/components/svg/CloseIcon.tsx","../src/components/SearchBar.tsx","../src/components/GridSheet.tsx","../src/policy/checkbox.tsx","../src/lib/style.ts"],"sourcesContent":["import { createContext } from 'react';\nimport { StoreType } from '../types';\n\nexport type Dispatcher = React.Dispatch<{\n type: number;\n value: any;\n}>;\n\nexport const Context = createContext(\n {} as {\n store: StoreType;\n dispatch: Dispatcher;\n },\n);\n","import type { FC } from 'react';\n\nexport type ProgressOverlayProps = {\n /** 0..1 for a determinate bar; null/undefined for an indeterminate spinner. */\n progress?: number | null;\n /** Text shown before the percentage (e.g. \"Loading\", \"Saving\", \"Pasting\"). */\n label?: string;\n};\n\n/**\n * Shared progress overlay: a centered card with a spinner + label, plus a determinate bar\n * when `progress` is given. One component for initial loading, save, and chunked async\n * mutations so every progress indicator looks and behaves the same. It spans its (positioned)\n * container to capture pointer events — blocking interaction while work runs — but does NOT\n * dim, so the grid stays visible behind it. Drive it with a prop for cheap/occasional updates\n * (load/save); for a high-frequency mutation tick use AsyncProgressOverlay's imperative handle\n * so a tick re-renders only the overlay, not the grid.\n */\nexport const ProgressOverlay: FC<ProgressOverlayProps> = ({ progress, label = 'Loading' }) => {\n const determinate = progress != null;\n const pct = determinate ? Math.max(0, Math.min(100, Math.round(progress * 100))) : 0;\n return (\n <div className=\"gs-progress-overlay\">\n <div className=\"gs-progress-box\">\n <div className=\"gs-progress-head\">\n <span className=\"gs-loading-spinner\" />\n <span>{determinate ? `${label}… ${pct}%` : `${label}…`}</span>\n </div>\n {determinate && (\n <div className=\"gs-progress-track\">\n <div className=\"gs-progress-fill\" style={{ width: `${pct}%` }} />\n </div>\n )}\n </div>\n </div>\n );\n};\n","import { forwardRef, useImperativeHandle, useState } from 'react';\nimport { ProgressOverlay } from './ProgressOverlay';\n\nexport type AsyncProgressHandle = {\n setProgress: (ratio: number) => void;\n};\n\n/**\n * Determinate progress overlay for a chunked async mutation (large fill/paste). Its progress\n * is driven IMPERATIVELY (via the ref) so that a progress tick re-renders only this small\n * component — not the whole grid. Routing progress through the store instead made every tick\n * re-render the (expensive, at deep scroll) grid, so a million-cell fill spent most of its\n * time re-rendering. The visuals come from the shared ProgressOverlay.\n */\nexport const AsyncProgressOverlay = forwardRef<AsyncProgressHandle, { label: string }>(({ label }, ref) => {\n const [progress, setProgress] = useState(0);\n useImperativeHandle(ref, () => ({ setProgress }), []);\n return <ProgressOverlay progress={progress} label={label} />;\n});\n","import React, { useContext, useLayoutEffect, useRef } from 'react';\nimport type { FunctionHelp } from '@gridsheet/web';\nimport type { AutocompleteOption } from '@gridsheet/web';\nimport { Context } from '../store';\nimport { calcSideStyle, clampPopup } from '@gridsheet/web';\n\ntype OptionWithGuide = AutocompleteOption & {\n isFunction?: boolean;\n example?: string;\n category?: string;\n description?: string;\n defs?: any[];\n};\n\nexport interface FunctionGuideProps {\n // Option Help Mode (renders in EditorOptions)\n option?: OptionWithGuide;\n\n // Active Function Highlight Mode (renders floating near cursor)\n activeFunctionGuide?: FunctionHelp;\n activeArgIndex?: number;\n top?: number;\n left?: number;\n}\n\nexport const FunctionGuide: React.FC<FunctionGuideProps> = ({\n option,\n activeFunctionGuide,\n activeArgIndex = 0,\n top,\n left,\n}) => {\n const ref = useRef<HTMLDivElement>(null);\n const guide1Ref = useRef<HTMLDivElement>(null);\n const { store } = useContext(Context);\n // Hide the active help when not hovering over the editor, to prevent it from blocking clicks on other options.\n const isHidden = !store.editorHovering;\n\n useLayoutEffect(() => {\n const el = guide1Ref.current;\n if (!el) {\n return;\n }\n calcSideStyle(el);\n });\n\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el || left === undefined) {\n return;\n }\n clampPopup(el);\n });\n\n if (option) {\n return (\n <div\n ref={guide1Ref}\n className=\"gs-fn-guide1\"\n onMouseDown={(e) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n >\n {option.category && option.isFunction && (\n <span className={`gs-fn-guide-category gs-fn-guide-category-${option.category}`}>{option.category}</span>\n )}\n {option.tooltip && (\n <div className=\"gs-fn-guide1-tooltip\">\n {typeof option.tooltip === 'function'\n ? React.createElement(option.tooltip as any, { value: option.value })\n : option.tooltip}\n </div>\n )}\n {option.isFunction && (\n <>\n <div className=\"gs-fn-guide1-example\">{option.example}</div>\n {option.description && (\n <div className=\"gs-fn-guide1-desc\" style={{ whiteSpace: 'pre-line' }}>\n {option.description}\n </div>\n )}\n {option.defs && option.defs.length > 0 && (\n <div className=\"gs-fn-guide1-args\">\n {option.defs.map((arg: any, j: number) => (\n <div key={j} className=\"gs-fn-guide1-arg\">\n <span className=\"gs-fn-guide1-arg-name\">{arg.name}</span>\n {arg.optional && <span className=\"gs-fn-guide1-arg-opt\"> (optional)</span>}\n {arg.variadic && <span className=\"gs-fn-guide1-arg-iter\">...</span>}\n <code className=\"gs-fn-guide1-arg-type\">{arg.acceptedTypes?.join(' | ') || 'any'}</code>\n <span className=\"gs-fn-guide1-arg-desc\"> — {arg.description}</span>\n </div>\n ))}\n </div>\n )}\n </>\n )}\n </div>\n );\n }\n\n if (activeFunctionGuide) {\n return (\n <div\n ref={ref}\n className={`gs-fn-guide2 ${isHidden ? 'gs-fn-guide2-hidden' : ''}`}\n style={top !== undefined && left !== undefined ? { top: top + 4, left } : undefined}\n >\n {activeFunctionGuide.category && (\n <span className={`gs-fn-guide-category gs-fn-guide-category-${activeFunctionGuide.category}`}>\n {activeFunctionGuide.category}\n </span>\n )}\n <div className=\"gs-fn-guide2-name\">{activeFunctionGuide.example}</div>\n <div className=\"gs-fn-guide2-args-inline\">\n {(() => {\n const args = activeFunctionGuide.defs ?? [];\n const numIterable = args.filter((a: any) => a.variadic).length;\n const variadicStart = args.length - numIterable;\n\n return args.map((arg: any, j: number) => {\n let isActive: boolean;\n if (activeArgIndex < variadicStart) {\n // Cursor is on a fixed (non-variadic) argument\n isActive = activeArgIndex === j;\n } else if (numIterable > 0 && j >= variadicStart) {\n // Cursor is in the variadic zone; cycle through the variadic args\n const offset = (activeArgIndex - variadicStart) % numIterable;\n isActive = j === variadicStart + offset;\n } else {\n isActive = false;\n }\n return (\n <React.Fragment key={j}>\n {j > 0 ? ', ' : ''}\n <span className={isActive ? 'gs-active-arg' : ''}>\n {arg.optional ? '[' : ''}\n {arg.name}\n {arg.variadic ? ', ...' : ''}\n {arg.optional ? ']' : ''}\n </span>\n </React.Fragment>\n );\n });\n })()}\n </div>\n {(() => {\n const args = activeFunctionGuide.defs ?? [];\n const numIterable = args.filter((a: any) => a.variadic).length;\n const variadicStart = args.length - numIterable;\n\n let resolvedIndex: number;\n if (activeArgIndex < variadicStart || numIterable === 0) {\n resolvedIndex = Math.min(activeArgIndex, args.length - 1);\n } else {\n const offset = (activeArgIndex - variadicStart) % numIterable;\n resolvedIndex = variadicStart + offset;\n }\n const activeArg = args[resolvedIndex];\n if (!activeArg?.description) {\n return null;\n }\n return (\n <div className=\"gs-fn-guide2-desc\" style={{ marginTop: 8, fontSize: 12, color: '#888' }}>\n <p>\n <strong>{activeArg.name}:</strong>{' '}\n <code className=\"gs-fn-guide2-arg-type\">{activeArg.acceptedTypes?.join(' | ') || 'any'}</code>\n {activeArg.description}\n </p>\n </div>\n );\n })()}\n\n {activeFunctionGuide.description && (\n <div className=\"gs-fn-guide2-desc\" style={{ whiteSpace: 'pre-line' }}>\n {activeFunctionGuide.description}\n </div>\n )}\n </div>\n );\n }\n\n return null;\n};\n","import React, { useRef, useLayoutEffect, useState } from 'react';\nimport { FunctionGuide } from './FunctionGuide';\nimport { clampLeft } from '@gridsheet/web';\n\ninterface EditorOptionsProps {\n filteredOptions: any[];\n top: number;\n left: number;\n selected: number;\n onOptionMouseDown: (e: React.MouseEvent<HTMLLIElement>, i: number) => void;\n}\n\nexport const EditorOptions: React.FC<EditorOptionsProps> = ({\n filteredOptions,\n top,\n left,\n selected,\n onOptionMouseDown,\n}) => {\n const ulRef = useRef<HTMLUListElement>(null);\n const [adjustedLeft, setAdjustedLeft] = useState(left);\n\n useLayoutEffect(() => {\n if (!ulRef.current) {\n return;\n }\n const width = ulRef.current.getBoundingClientRect().width;\n setAdjustedLeft(clampLeft(left, width));\n }, [left, filteredOptions]);\n\n if (filteredOptions.length === 0) {\n return null;\n }\n\n return (\n <ul ref={ulRef} className=\"gs-editor-options\" style={{ top, left: adjustedLeft }}>\n {filteredOptions.map((option, i) => (\n <li\n key={i}\n className={`gs-editor-option ${selected === i ? ' gs-editor-option-selected' : ''}`}\n onMouseDown={(e) => onOptionMouseDown(e, i)}\n >\n <div className=\"gs-editor-option-content\">\n <span>{option.label ?? option.value}</span>\n {selected === i && <span className=\"gs-editor-option-tab\">⇥ Tab</span>}\n </div>\n {(option.isFunction || option.tooltip) && selected === i && <FunctionGuide option={option} />}\n </li>\n ))}\n </ul>\n );\n};\n","import type { StoreType, AreaType, PointType } from '../types';\n\nimport { zoneToArea } from '@gridsheet/web';\nimport type { Sheet, UserSheet } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\n\nexport const clip = (store: StoreType) => {\n const { selectingZone, choosing, editorRef, sheetReactive: sheetRef } = store;\n const sheet = sheetRef.current;\n\n if (!sheet) {\n return { top: 0, left: 0, bottom: 0, right: 0 };\n }\n\n const { y, x } = choosing;\n const selectingArea = zoneToArea(selectingZone);\n let area = selectingArea;\n if (area.left === -1) {\n area = { top: y, left: x, bottom: y, right: x };\n }\n const input = editorRef.current;\n const trimmed = sheet.trim(area);\n const tsv = sheet2csv(trimmed, {\n getter: (sheet, point) => {\n const policy = sheet.getPolicy(point);\n return policy.serializeForClipboard({ point, sheet });\n },\n });\n const html = sheet2html(trimmed, {\n getter: (sheet, point) => {\n const policy = sheet.getPolicy(point);\n return policy.serializeForClipboard({ point, sheet });\n },\n });\n\n if (navigator.clipboard) {\n const tsvBlob = new Blob([tsv], { type: 'text/plain' });\n const htmlBlob = new Blob([html], { type: 'text/html' });\n\n navigator.clipboard.write([\n new ClipboardItem({\n 'text/plain': tsvBlob,\n 'text/html': htmlBlob,\n }),\n ]);\n } else if (input != null) {\n input.value = tsv;\n focus(input);\n input.select();\n document.execCommand('copy');\n input.value = '';\n input.blur();\n }\n return area;\n};\n\nexport type SheetCSVProps = {\n getter?: (sheet: UserSheet, point: PointType) => string;\n filteredRowsIncluded?: boolean;\n trailingEmptyRowsOmitted?: boolean;\n separator?: string;\n newline?: string;\n};\n\nexport const sheet2csv = (\n sheet: UserSheet,\n {\n getter = (sheet, point) => {\n return String(sheet.getCell(point)?.value ?? '');\n },\n filteredRowsIncluded = false,\n trailingEmptyRowsOmitted = false,\n separator = '\\t',\n newline = '\\n',\n }: SheetCSVProps = {},\n): string => {\n const rows: { isEmpty: boolean; line: string }[] = [];\n for (let y = sheet.top; y <= sheet.bottom; y++) {\n if (sheet.isRowFiltered(y) && !filteredRowsIncluded) {\n continue;\n }\n const cols: string[] = [];\n let rowIsEmpty = true;\n for (let x = sheet.left; x <= sheet.right; x++) {\n const point: PointType = { y, x };\n const value = getter(sheet, point);\n if (value !== '') {\n rowIsEmpty = false;\n }\n if (value.indexOf('\\n') !== -1) {\n cols.push(`\"${value.replace(/\"/g, '\"\"')}\"`);\n } else {\n cols.push(value);\n }\n }\n rows.push({ isEmpty: rowIsEmpty, line: cols.join(separator) });\n }\n if (trailingEmptyRowsOmitted) {\n while (rows.length > 0 && rows[rows.length - 1].isEmpty) {\n rows.pop();\n }\n }\n return rows.map((r) => r.line).join(newline);\n};\n\nexport type SheetHTMLProps = {\n getter?: (sheet: UserSheet, point: PointType) => string;\n filteredRowsIncluded?: boolean;\n trailingEmptyRowsOmitted?: boolean;\n};\n\nexport const sheet2html = (\n sheet: UserSheet,\n {\n getter = (sheet, point) => {\n return String(sheet.getCell(point)?.value ?? '');\n },\n filteredRowsIncluded = false,\n trailingEmptyRowsOmitted = false,\n }: SheetHTMLProps = {},\n): string => {\n const rows: { isEmpty: boolean; html: string }[] = [];\n for (let y = sheet.top; y <= sheet.bottom; y++) {\n if (sheet.isRowFiltered(y) && !filteredRowsIncluded) {\n continue;\n }\n const cols: string[] = [];\n let rowIsEmpty = true;\n for (let x = sheet.left; x <= sheet.right; x++) {\n const point: PointType = { y, x };\n const value = getter(sheet, point);\n if (value !== '') {\n rowIsEmpty = false;\n }\n const valueEscaped = value\n .replace(/&/g, '&')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n .replace(/</g, '<')\n .replace(/>/g, '>');\n cols.push(`<td>${valueEscaped}</td>`);\n }\n rows.push({ isEmpty: rowIsEmpty, html: `<tr>${cols.join('')}</tr>` });\n }\n if (trailingEmptyRowsOmitted) {\n while (rows.length > 0 && rows[rows.length - 1].isEmpty) {\n rows.pop();\n }\n }\n return `<table>${rows.map((r) => r.html).join('')}</table>`;\n};\n","import { useState, useMemo, useCallback } from 'react';\nimport { getFunctionHelps, type FunctionHelp } from '@gridsheet/web';\nimport type { FunctionMapping } from '@gridsheet/web';\nimport type { AutocompleteOption } from '@gridsheet/web';\nimport { Lexer } from '@gridsheet/web';\n\ntype UseAutocompleteProps = {\n inputting: string;\n selectionStart: number;\n optionsAll: AutocompleteOption[];\n functions?: FunctionMapping;\n};\n\nexport const useAutocomplete = ({ inputting, selectionStart, optionsAll, functions }: UseAutocompleteProps) => {\n const [selected, setSelected] = useState(0);\n\n const { filteredOptions, matchParams, activeFunctionHelp, activeArgIndex } = useMemo(() => {\n const isFormula = inputting.startsWith('=');\n\n let activeFunctionHelp: FunctionHelp | null = null;\n let activeArgIndex: number = 0;\n\n const textBeforeCursor = inputting.slice(0, selectionStart);\n const textAfterCursor = inputting.slice(selectionStart);\n\n // --- Active Argument Context Tracking ---\n if (isFormula && textBeforeCursor.length > 1) {\n try {\n const textToCursor = textBeforeCursor.slice(1); // skip '='\n const lexer = new Lexer(textToCursor);\n lexer.tokenize();\n\n const functionStack: { name: string; argIndex: number; hasWaitComma: boolean }[] = [];\n\n for (let i = 0; i < lexer.tokens.length; i++) {\n const token = lexer.tokens[i];\n if (token.type === 'FUNCTION') {\n const nextToken = lexer.tokens[i + 1];\n if (nextToken?.type === 'OPEN') {\n functionStack.push({ name: token.entity as string, argIndex: 0, hasWaitComma: false });\n i++; // skip OPEN\n } else if (i === lexer.tokens.length - 1) {\n // Function keyword right before cursor but without paren yet!\n // Do nothing special here, autocomplete dropdown will handle it.\n }\n } else if (token.type === 'COMMA') {\n if (functionStack.length > 0) {\n functionStack[functionStack.length - 1].argIndex++;\n functionStack[functionStack.length - 1].hasWaitComma = true;\n }\n } else if (token.type === 'CLOSE') {\n if (functionStack.length > 0) {\n functionStack.pop();\n }\n } else if (token.type !== 'SPACE' && functionStack.length > 0) {\n functionStack[functionStack.length - 1].hasWaitComma = false;\n }\n }\n\n if (functionStack.length > 0) {\n const activeItem = functionStack[functionStack.length - 1];\n const helps = getFunctionHelps(functions);\n activeArgIndex = activeItem.argIndex;\n activeFunctionHelp = helps.find((h: any) => h.name === activeItem.name.toUpperCase()) || null;\n }\n } catch (e) {\n /* ignore parse errors */\n }\n }\n\n const wordBefore = textBeforeCursor.match(/[a-zA-Z0-9_.]+$/)?.[0] || '';\n const wordAfter = textAfterCursor.match(/^[a-zA-Z0-9_.]+/)?.[0] || '';\n\n // For regular cells, we use the whole word as the search target.\n // For formulas, we extract the word under the cursor.\n const currentWord = isFormula ? (wordBefore + wordAfter).toLowerCase() : inputting.toLocaleLowerCase();\n const hasOpenParenAssigned = isFormula && textAfterCursor.slice(wordAfter.length).trimStart().startsWith('(');\n\n let filtered: any[] = [];\n\n let isOnAddress = false;\n if (isFormula) {\n try {\n const fullLexer = new Lexer(inputting.slice(1));\n fullLexer.tokenize();\n let currentIndex = 1; // start after '='\n for (const token of fullLexer.tokens) {\n const tLen = token.length();\n if (selectionStart > currentIndex && selectionStart < currentIndex + tLen) {\n if (['REF', 'RANGE', 'ID', 'ID_RANGE', 'UNREFERENCED'].includes(token.type)) {\n isOnAddress = true;\n }\n // Inside a string literal (VALUE token whose entity is a string)\n if (token.type === 'VALUE' && typeof token.entity === 'string') {\n isOnAddress = true;\n }\n break;\n }\n if (selectionStart === currentIndex || selectionStart === currentIndex + tLen) {\n if (['REF', 'RANGE', 'ID', 'ID_RANGE', 'UNREFERENCED'].includes(token.type)) {\n isOnAddress = true;\n }\n }\n currentIndex += tLen;\n }\n } catch (e) {\n /* ignore parse errors */\n }\n }\n\n if (isFormula && !isOnAddress) {\n // Suggest if we have at least 1 letter, and there isn't already an opening parenthesis attached\n if (currentWord.length > 0 && !hasOpenParenAssigned) {\n filtered = getFunctionHelps(functions)\n .map((help: any) => {\n const keywordLower = help.name.toLowerCase();\n const startsWith = keywordLower.startsWith(currentWord);\n const index = startsWith ? 0 : -1;\n const hasNoArgs = help.defs.length === 0;\n return {\n option: { ...help, value: help.name + (hasNoArgs ? '()' : '('), isFunction: true, label: help.name },\n index,\n startsWith,\n keywordCount: 1,\n keyword: keywordLower,\n };\n })\n .filter(({ startsWith }: { startsWith: boolean }) => startsWith)\n .sort((a: any, b: any) => {\n if (a.startsWith !== b.startsWith) {\n return b.startsWith ? 1 : -1;\n }\n if (a.index !== b.index) {\n return a.index - b.index;\n }\n return a.keyword.localeCompare(b.keyword);\n })\n .map(({ option }: { option: any }) => option);\n }\n } else {\n filtered = optionsAll\n .map((option) => {\n const keywords = option.keywords ?? [String(option.value)];\n let bestMatch = { index: -1, startsWith: false, keyword: '' };\n\n for (const keyword of keywords) {\n const keywordLower = keyword.toLowerCase();\n const index = keywordLower.indexOf(currentWord);\n if (index !== -1) {\n const startsWith = keywordLower.startsWith(currentWord);\n if (\n bestMatch.index === -1 ||\n index < bestMatch.index ||\n (index === bestMatch.index && startsWith && !bestMatch.startsWith)\n ) {\n bestMatch = { index, startsWith, keyword };\n }\n }\n }\n\n return {\n option,\n ...bestMatch,\n keywordCount: keywords.length,\n };\n })\n .filter(({ index }) => index !== -1)\n .sort((a, b) => {\n if (a.startsWith !== b.startsWith) {\n return b.startsWith ? 1 : -1;\n }\n if (a.index !== b.index) {\n return a.index - b.index;\n }\n if (a.keywordCount !== b.keywordCount) {\n return b.keywordCount - a.keywordCount;\n }\n return a.keyword.localeCompare(b.keyword);\n })\n .map(({ option }) => option);\n }\n\n return {\n filteredOptions: filtered,\n matchParams: {\n isFormula,\n currentWord,\n matchLengthBefore: wordBefore.length,\n matchLengthAfter: wordAfter.length,\n },\n activeFunctionHelp,\n activeArgIndex,\n };\n }, [inputting, selectionStart, optionsAll, functions]);\n\n useMemo(() => {\n if (selected >= filteredOptions.length) {\n setSelected(0);\n }\n }, [filteredOptions.length, selected]);\n\n const replaceWithOption = useCallback(\n (option: any) => {\n if (!option) {\n return { value: inputting, selectionStart };\n }\n\n if (matchParams.isFormula) {\n const beforeMatch = inputting.slice(0, selectionStart - matchParams.matchLengthBefore);\n const afterMatch = inputting.slice(selectionStart + matchParams.matchLengthAfter);\n const newValue = beforeMatch + option.value + afterMatch;\n return { value: newValue, selectionStart: beforeMatch.length + option.value.length };\n } else {\n return { value: String(option.value), selectionStart: String(option.value).length };\n }\n },\n [inputting, selectionStart, matchParams],\n );\n\n const handleArrowUp = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (filteredOptions.length > 1) {\n setSelected((s) => (s <= 0 ? filteredOptions.length - 1 : s - 1));\n e.preventDefault();\n return true;\n }\n return false;\n },\n [filteredOptions.length],\n );\n\n const handleArrowDown = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (filteredOptions.length > 1) {\n setSelected((s) => (s >= filteredOptions.length - 1 ? 0 : s + 1));\n e.preventDefault();\n return true;\n }\n return false;\n },\n [filteredOptions.length],\n );\n\n return {\n filteredOptions,\n selected,\n setSelected,\n replaceWithOption,\n handleArrowUp,\n handleArrowDown,\n isFormula: matchParams.isFormula,\n activeFunctionHelp,\n activeArgIndex,\n };\n};\n","import type { CSSProperties, FC, ReactNode } from 'react';\nimport { useBrowser } from '../lib/hooks';\nimport { createPortal } from 'react-dom';\n\ntype Props = {\n className?: string;\n style?: CSSProperties;\n children: ReactNode;\n [attr: string]: any;\n};\n\nexport const Fixed: FC<Props> = ({ children, style, className = '', ...attrs }) => {\n const { document } = useBrowser();\n if (document == null) {\n return null;\n }\n return createPortal(\n <div {...attrs} className={`gs-fixed ${className}`} style={style}>\n {children}\n </div>,\n document.body,\n );\n};\n","import React, { type CSSProperties } from 'react';\nimport type { RawCellType } from '../types';\nexport const parseHTML = (html: string, onlyValue = false): RawCellType[][] => {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n const results: RawCellType[][] = [];\n\n const processSheet = (sheet: HTMLTableElement) => {\n const spans = new Set<string>();\n const rows = sheet.querySelectorAll('tr,caption');\n for (let i = 0; i < rows.length; i++) {\n const row = rows[i];\n if (row.tagName === 'CAPTION') {\n const caption = row.textContent?.trim() ?? '';\n if (caption) {\n results.push([{ value: caption }]);\n }\n continue;\n }\n const cells = Array.from(row.querySelectorAll('td, th'));\n const result: RawCellType[] = [];\n let j = 0;\n for (const cell of cells) {\n const value = cell.textContent?.trim() ?? '';\n const style: CSSProperties | undefined = onlyValue\n ? undefined\n : (() => {\n const childStyle = parseStyleString(cell.firstElementChild);\n const parentStyle = parseStyleString(cell);\n return { ...parentStyle, ...childStyle };\n })();\n while (spans.has(`${i}-${++j}`)) {\n result.push({ value: '', style, skip: true });\n }\n result.push({ value, style });\n\n const rowSpan = parseInt(cell.getAttribute('rowspan') ?? '1', 10);\n const colSpan = parseInt(cell.getAttribute('colspan') ?? '1', 10);\n for (let r = 0; r < rowSpan; r++) {\n for (let c = 0; c < colSpan; c++) {\n spans.add(`${i + r}-${j + c}`);\n }\n }\n }\n results.push(result);\n }\n };\n\n const processNodeSequentially = (node: Node, currentLine: RawCellType[] = []) => {\n if (node.nodeType === Node.ELEMENT_NODE) {\n const el = node as HTMLElement;\n const tagName = el.tagName;\n\n if (tagName === 'TABLE') {\n if (currentLine.length > 0) {\n results.push(currentLine.slice());\n currentLine.length = 0;\n }\n processSheet(el as HTMLTableElement);\n } else if (tagName === 'BR') {\n results.push(currentLine.slice());\n currentLine.length = 0;\n } else if (blockTags.has(tagName)) {\n if (currentLine.length > 0) {\n results.push(currentLine.slice());\n currentLine.length = 0;\n }\n el.childNodes.forEach((child) => processNodeSequentially(child, currentLine));\n if (currentLine.length > 0) {\n results.push(currentLine.slice());\n currentLine.length = 0;\n }\n } else {\n el.childNodes.forEach((child) => processNodeSequentially(child, currentLine));\n }\n } else if (node.nodeType === Node.TEXT_NODE) {\n const text = node.textContent ?? '';\n const lines = text.split(/\\r?\\n/);\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed) {\n currentLine.push({ value: trimmed });\n }\n }\n }\n };\n\n const currentLine: RawCellType[] = [];\n doc.body.childNodes.forEach((node) => processNodeSequentially(node, currentLine));\n if (currentLine.length > 0) {\n results.push(currentLine);\n }\n\n return results;\n};\n\nfunction parseStyleString(element: Element | null): React.CSSProperties | undefined {\n if (!element) {\n return undefined;\n }\n const styleString = element.getAttribute('style') ?? '';\n const styleObj: React.CSSProperties = {};\n\n styleString.split(';').forEach((d) => {\n let [rawKey, rawValue] = d.split(':');\n if (!rawKey || !rawValue) {\n return;\n }\n rawKey = rawKey.trim();\n if (rawKey === 'height' || rawKey === 'width') {\n return;\n }\n const key = rawKey.trim().replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());\n if (key === 'float' || key === 'display' || key.startsWith('padding')) {\n return;\n }\n if (key === 'border') {\n Object.assign(styleObj, {\n borderTop: rawValue,\n borderRight: rawValue,\n borderBottom: rawValue,\n borderLeft: rawValue,\n });\n return;\n }\n if (key === 'borderColor') {\n Object.assign(styleObj, {\n borderTopColor: rawValue,\n borderRightColor: rawValue,\n borderBottomColor: rawValue,\n borderLeftColor: rawValue,\n });\n return;\n }\n if (key === 'borderStyle') {\n Object.assign(styleObj, {\n borderTopStyle: rawValue,\n borderRightStyle: rawValue,\n borderBottomStyle: rawValue,\n borderLeftStyle: rawValue,\n });\n return;\n }\n if (key === 'borderWidth') {\n Object.assign(styleObj, {\n borderTopWidth: rawValue,\n borderRightWidth: rawValue,\n borderBottomWidth: rawValue,\n borderLeftWidth: rawValue,\n });\n return;\n }\n const value = rawValue.trim();\n (styleObj as any)[key] = value;\n });\n\n return styleObj;\n}\n\nexport const parseText = (tsv: string, sep = '\\t'): RawCellType[][] => {\n tsv = tsv.replace(/\"\"/g, '\\x00');\n const rows: RawCellType[][] = [[]];\n let row = rows[0];\n let entering = false;\n let word = '';\n for (let i = 0; i < tsv.length; i++) {\n const s = tsv[i];\n if (s === '\\n' && !entering) {\n row.push({ value: restoreDoubleQuote(word) });\n word = '';\n row = [];\n rows.push(row);\n continue;\n }\n if (s === sep) {\n row.push({ value: restoreDoubleQuote(word) });\n word = '';\n continue;\n }\n if (s === '\"' && !entering && word === '') {\n entering = true;\n continue;\n }\n if (s === '\"' && entering) {\n entering = false;\n continue;\n }\n word += s;\n }\n if (word) {\n row.push({ value: restoreDoubleQuote(word) });\n }\n return rows;\n};\n\nconst restoreDoubleQuote = (text: string) => text.replace(/\\x00/g, '\"');\n\nconst blockTags = new Set([\n 'ADDRESS',\n 'ARTICLE',\n 'ASIDE',\n 'BLOCKQUOTE',\n 'DETAILS',\n 'DIALOG',\n 'DD',\n 'DIV',\n 'DL',\n 'DT',\n 'FIELDSET',\n 'FIGCAPTION',\n 'FIGURE',\n 'FOOTER',\n 'FORM',\n 'H1',\n 'H2',\n 'H3',\n 'H4',\n 'H5',\n 'H6',\n 'HEADER',\n 'HR',\n 'LI',\n 'MAIN',\n 'NAV',\n 'OL',\n 'P',\n 'PRE',\n 'SECTION',\n 'TABLE',\n 'UL',\n]);\n","import type { FC } from 'react';\nimport { useContext, useEffect, useState, useCallback, useRef, memo } from 'react';\nimport { createPortal } from 'react-dom';\nimport { FunctionGuide } from './FunctionGuide';\nimport { EditorOptions } from './EditorOptions';\nimport { x2c, y2r } from '@gridsheet/web';\nimport { clip } from '../lib/clipboard';\nimport {\n clear,\n escape,\n select,\n selectToDataEdge,\n fillDown,\n fillRight,\n setEditingAddress,\n undo,\n redo,\n arrow,\n walk,\n write,\n copy,\n cut,\n paste,\n setSearchQuery,\n setEntering,\n setInputting,\n setEditorHovering,\n updateSheet,\n} from '../store/actions';\n\nimport { Context } from '../store';\nimport { areaToZone, zoneToArea } from '@gridsheet/web';\nimport { operations as prevention } from '@gridsheet/web';\nimport {\n expandInput,\n insertTextAtCursor,\n isFocus,\n isRefInsertable,\n resetInput,\n handleFormulaQuoteAutoClose,\n} from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { Lexer } from '@gridsheet/web';\nimport { COLOR_PALETTE } from '@gridsheet/web';\nimport { useAutocomplete } from './useAutocomplete';\nimport { EditorEventWithNativeEvent, FeedbackType, ModeType } from '../types';\nimport { Fixed } from './Fixed';\nimport { parseHTML, parseText } from '../lib/paste';\nimport React from 'react';\n\ntype Props = {\n mode: ModeType;\n};\n\nexport const Editor: FC<Props> = ({ mode }: Props) => {\n const { store, dispatch } = useContext(Context);\n const [shiftKey, setShiftKey] = useState(false);\n const [selectionStart, setSelectionStart] = useState(0);\n const [isFocused, setIsFocused] = useState(false);\n const composingRef = useRef(false);\n const {\n choosing,\n inputting,\n selectingZone,\n editorRect,\n editingAddress,\n entering,\n matchingCells,\n matchingCellIndex,\n searchQuery,\n editorRef,\n largeEditorRef,\n searchInputRef,\n editingOnEnter,\n sheetReactive: sheetRef,\n sheetId,\n dragging,\n } = store;\n const sheet = sheetRef.current;\n\n const renderOverlays = () => {\n if (!isFocused || !editing || typeof document === 'undefined') {\n return null;\n }\n if (editorRef.current !== document.activeElement) {\n return null;\n }\n\n const rect = editorRef.current?.getBoundingClientRect();\n if (!rect) {\n return null;\n }\n const { bottom: top, left } = rect;\n\n return createPortal(\n // Portaled to <body>, outside .gs-root1 / .gs-editor, so carry data-mode\n // here too — otherwise the theme-specific styles (e.g. the dark function\n // guide) never match and the help renders with the light palette.\n <div className=\"gs-editor-portal\" data-mode={mode}>\n {activeFunctionHelp &&\n filteredOptions.length === 0 &&\n (!selectingZone || (selectingZone.endY === -1 && selectingZone.endX === -1)) && (\n <FunctionGuide\n activeFunctionGuide={activeFunctionHelp}\n activeArgIndex={activeArgIndex}\n top={top}\n left={left}\n />\n )}\n {filteredOptions.length > 0 && (\n <EditorOptions\n filteredOptions={filteredOptions}\n top={top}\n left={left}\n selected={selected}\n onOptionMouseDown={handleOptionMouseDown}\n />\n )}\n </div>,\n document.body,\n );\n };\n\n const policy = sheet?.getPolicy(choosing);\n const optionsAll = policy?.getSelectOptions() ?? [];\n\n const handleSelect = useCallback((e: React.SyntheticEvent<HTMLTextAreaElement>) => {\n setSelectionStart(e.currentTarget.selectionStart);\n }, []);\n\n const {\n filteredOptions,\n selected,\n setSelected,\n replaceWithOption,\n handleArrowUp,\n handleArrowDown,\n isFormula,\n activeFunctionHelp,\n activeArgIndex,\n } = useAutocomplete({\n inputting,\n selectionStart,\n optionsAll,\n functions: sheet?.registry.functions,\n });\n\n useEffect(() => {\n focus(editorRef?.current);\n }, [editorRef]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n if (sheet.registry.lastFocused == null) {\n return;\n }\n if (sheet.registry.lastFocused !== editorRef.current) {\n return;\n }\n if (sheet.registry.lastFocused !== largeEditorRef.current) {\n return;\n }\n\n dispatch(setEditingAddress(''));\n }, [sheet?.registry.lastFocused, sheet, editorRef, largeEditorRef, dispatch]);\n useEffect(() => {\n if (!sheet) {\n return;\n }\n sheet.registry.editingSheetId = sheetId;\n sheet.registry.editingAddress = editingAddress;\n }, [editingAddress, sheet, sheetId]);\n\n useEffect(() => {\n //sheet.registry.transmit();\n expandInput(editorRef.current);\n }, [inputting, editingAddress, editorRef]);\n\n const { y, x } = choosing;\n const rowId = `${y2r(y)}`;\n const colId = x2c(x);\n const address = `${colId}${rowId}`;\n const editing = editingAddress === address;\n\n // Use 'RAW' so that spilled values (stored in solvedCaches) are already\n // reflected in cell.value without re-evaluating the formula.\n const cell = sheet?.getCell({ y, x }, { resolution: 'RAW' });\n const currentString = sheet ? sheet.getSerializedValue({ point: choosing, cell, resolution: 'RAW' }) : '';\n const [before, setBefore] = useState<string>(currentString);\n\n const writeCell = useCallback(\n (value: string) => {\n if (before !== value) {\n dispatch(write({ value }));\n }\n setBefore(value);\n },\n [before, dispatch],\n );\n\n const selectValue = useCallback(\n (selectedIndex: number) => {\n if (!sheet) {\n return;\n }\n const option = filteredOptions[selectedIndex];\n if (option) {\n if (option.isFunction) {\n const { value: newValue, selectionStart: newCursor } = replaceWithOption(option);\n dispatch(setInputting(newValue));\n\n setTimeout(() => {\n if (editorRef.current) {\n focus(editorRef.current);\n editorRef.current.setSelectionRange(newCursor, newCursor);\n }\n }, 0);\n } else {\n const t = sheet.update({\n diff: { [address]: { value: option.value } },\n partial: true,\n });\n dispatch(updateSheet(t.clone()));\n dispatch(setEditingAddress(''));\n dispatch(setInputting(''));\n }\n setSelected(0);\n }\n },\n [filteredOptions, sheet, address, inputting, writeCell, dispatch, editorRef],\n );\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n setBefore(currentString);\n dispatch(setInputting(currentString));\n resetInput(editorRef.current, sheet, choosing);\n }, [choosing, currentString, dispatch, editorRef, sheet]);\n\n const { y: top, x: left, height, width } = editorRect;\n\n const numLines = currentString.split('\\n').length;\n const [isKeyDown, setIsKeyDown] = useState(false);\n const handleKeyDown = useCallback(\n (e: EditorEventWithNativeEvent) => {\n if (!sheet) {\n return;\n }\n if (e.nativeEvent.isComposing || composingRef.current) {\n return;\n }\n if (isKeyDown) {\n return;\n }\n // do not debounce it if control key is down.\n if (!(e.key === 'Meta' || e.key === 'Control')) {\n setIsKeyDown(true);\n requestAnimationFrame(() => {\n setIsKeyDown(false);\n });\n }\n const input = e.currentTarget;\n\n // Auto-close double quotes in formula mode\n if (handleFormulaQuoteAutoClose(e, inputting)) {\n dispatch(setInputting(input.value));\n return false;\n }\n\n const shiftKey = e.shiftKey;\n switch (e.key) {\n case 'Tab': // TAB\n e.preventDefault();\n if (editing) {\n if (filteredOptions.length) {\n const isFunction = filteredOptions[selected]?.isFunction;\n selectValue(selected);\n if (isFunction) {\n return false;\n }\n } else {\n writeCell(input.value);\n dispatch(setEditingAddress(''));\n dispatch(setInputting(''));\n }\n }\n dispatch(\n walk({\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 0,\n deltaX: shiftKey ? -1 : 1,\n }),\n );\n dispatch(setEditingAddress(''));\n return false;\n\n case 'Enter': // ENTER\n if (editing) {\n if (filteredOptions.length) {\n const isFunction = filteredOptions[selected]?.isFunction;\n selectValue(selected);\n if (isFunction) {\n e.preventDefault();\n return false;\n }\n } else if (e.altKey) {\n insertTextAtCursor(input, '\\n');\n dispatch(setInputting(input.value));\n e.preventDefault();\n return false;\n } else {\n if (e.nativeEvent.isComposing) {\n return false;\n }\n writeCell(input.value);\n dispatch(setEditingAddress(''));\n dispatch(setInputting(''));\n }\n } else if (editingOnEnter && selectingZone.endY === -1) {\n const dblclick = document.createEvent('MouseEvents');\n dblclick.initEvent('dblclick', true, true);\n input.dispatchEvent(dblclick);\n e.preventDefault();\n return false;\n }\n dispatch(\n walk({\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: shiftKey ? -1 : 1,\n deltaX: 0,\n }),\n );\n e.preventDefault();\n return false;\n\n case 'Backspace': // BACKSPACE\n if (!editing) {\n // Spilled cells are read-only — clearing them would only erase the\n // cached spill value while the origin formula remains intact, causing\n // a confusing state where the FormulaBar goes blank but the cell\n // visually still shows the spilled value after re-evaluation.\n // e.preventDefault() is required here: without it the browser still\n // fires the default textarea behavior (deletes one char), which\n // triggers onInput → setInputting, making the value shrink character\n // by character on each Backspace press.\n if (sheet.getSystem({ y, x })?.spilledFrom != null) {\n e.preventDefault();\n return false;\n }\n dispatch(clear(null));\n dispatch(setInputting(''));\n return false;\n }\n break;\n case 'Delete': // DELETE\n if (!editing) {\n // Same guard as Backspace — spilled cells must not be cleared directly.\n if (sheet.getSystem({ y, x })?.spilledFrom != null) {\n e.preventDefault();\n return false;\n }\n dispatch(clear(null));\n dispatch(setInputting(''));\n return false;\n }\n break;\n case 'Shift': // SHIFT\n setShiftKey(true);\n return false;\n\n case 'Control': // CTRL\n return false;\n\n case 'Alt': // OPTION\n return false;\n\n case 'Meta': // COMMAND\n return false;\n\n case 'NumLock': // NUMLOCK\n return false;\n\n case 'Escape': // ESCAPE\n dispatch(escape(null));\n dispatch(setSearchQuery(undefined));\n dispatch(setInputting(before));\n // input.blur();\n return false;\n\n case 'ArrowLeft': // LEFT\n if (!editing) {\n if ((e.ctrlKey || e.metaKey) && shiftKey) {\n e.preventDefault();\n dispatch(selectToDataEdge({ deltaY: 0, deltaX: -1 }));\n return false;\n }\n dispatch(\n arrow({\n shiftKey,\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 0,\n deltaX: -1,\n }),\n );\n return false;\n }\n break;\n case 'ArrowUp': // UP\n if (!editing) {\n if ((e.ctrlKey || e.metaKey) && shiftKey) {\n e.preventDefault();\n dispatch(selectToDataEdge({ deltaY: -1, deltaX: 0 }));\n return false;\n }\n dispatch(\n arrow({\n shiftKey,\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: -1,\n deltaX: 0,\n }),\n );\n return false;\n }\n if (handleArrowUp(e as unknown as React.KeyboardEvent<HTMLTextAreaElement>)) {\n return true;\n }\n break;\n case 'ArrowRight': // RIGHT\n if (!editing) {\n if ((e.ctrlKey || e.metaKey) && shiftKey) {\n e.preventDefault();\n dispatch(selectToDataEdge({ deltaY: 0, deltaX: 1 }));\n return false;\n }\n dispatch(\n arrow({\n shiftKey,\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 0,\n deltaX: 1,\n }),\n );\n return false;\n }\n break;\n case 'ArrowDown': // DOWN\n if (!editing) {\n // Ctrl/Cmd+Shift+arrow: extend the selection to the data-block edge (no drag).\n if ((e.ctrlKey || e.metaKey) && shiftKey) {\n e.preventDefault();\n dispatch(selectToDataEdge({ deltaY: 1, deltaX: 0 }));\n return false;\n }\n dispatch(\n arrow({\n shiftKey,\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 1,\n deltaX: 0,\n }),\n );\n return false;\n }\n if (handleArrowDown(e as unknown as React.KeyboardEvent<HTMLTextAreaElement>)) {\n return true;\n }\n break;\n case 'a': // A\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n dispatch(\n select({\n startY: 1,\n startX: 1,\n endY: sheet.numRows,\n endX: sheet.numCols,\n }),\n );\n return false;\n }\n }\n break;\n case 'c': // C\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n const area = clip(store);\n dispatch(copy(areaToZone(area)));\n focus(input); // refocus\n return false;\n }\n return true;\n }\n break;\n case 'd': // D — fill down (Excel/Sheets Ctrl+D). Overrides the browser bookmark.\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n dispatch(fillDown(null));\n requestAnimationFrame(() => dispatch(setInputting(''))); // reset the textarea\n return false;\n }\n }\n break;\n case 'f': // F\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n if (typeof searchQuery === 'undefined') {\n dispatch(setSearchQuery(''));\n }\n dispatch(setEntering(false));\n requestAnimationFrame(() => focus(searchInputRef.current));\n return false;\n }\n }\n break;\n case 'r': // R — fill right (Excel/Sheets Ctrl+R). Overrides the browser reload.\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n dispatch(fillRight(null));\n requestAnimationFrame(() => dispatch(setInputting(''))); // reset the textarea\n return false;\n }\n }\n break;\n case 'y': // Y — redo (Ctrl+Shift+Z also redoes)\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n dispatch(redo(null));\n requestAnimationFrame(() => dispatch(setInputting(''))); // resetting textarea\n return false;\n }\n }\n break;\n case 's': // S\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n sheet.registry.onSave?.({\n sheet,\n points: {\n pointing: choosing,\n selectingFrom: {\n y: selectingZone.startY,\n x: selectingZone.startX,\n },\n selectingTo: {\n y: selectingZone.endY,\n x: selectingZone.endX,\n },\n },\n });\n return false;\n }\n }\n break;\n case 'v': // V\n if (e.ctrlKey || e.metaKey) {\n // moved to onPaste\n e.stopPropagation();\n return false;\n }\n break;\n case 'x': // X\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n const area = clip(store);\n dispatch(cut(areaToZone(area)));\n focus(input); // refocus\n return false;\n }\n }\n break;\n case 'z': // Z\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n if (e.shiftKey) {\n dispatch(redo(null));\n } else {\n dispatch(undo(null));\n }\n return false;\n }\n }\n break;\n case ';': // semicolon\n if (e.ctrlKey || e.metaKey) {\n if (!editing) {\n e.preventDefault();\n // MAYBE: need to aware timezone.\n writeCell(new Date().toDateString());\n }\n }\n break;\n }\n if (e.ctrlKey || e.metaKey) {\n return false;\n }\n if (prevention.hasOperation(cell?.prevention, prevention.Write)) {\n console.warn('This cell is protected from writing.');\n return false;\n }\n dispatch(setEditingAddress(address));\n if (!editing) {\n dispatch(setInputting(''));\n }\n setSelected(0);\n return false;\n },\n [\n isKeyDown,\n editing,\n filteredOptions,\n selected,\n editingOnEnter,\n selectingZone,\n before,\n sheet,\n choosing,\n store,\n cell,\n address,\n writeCell,\n searchQuery,\n inputting,\n ],\n );\n\n const handleFocus = useCallback(\n (e: React.FocusEvent<HTMLTextAreaElement>) => {\n setIsFocused(true);\n if (!sheet) {\n return;\n }\n sheet.registry.lastFocused = e.currentTarget;\n },\n [sheet],\n );\n\n const handleDoubleClick = useCallback(\n (e: React.MouseEvent<HTMLTextAreaElement>) => {\n if (prevention.hasOperation(cell?.prevention, prevention.Write)) {\n console.warn('This cell is protected from writing.');\n return;\n }\n const input = e.currentTarget;\n if (!editing) {\n dispatch(setInputting(currentString));\n dispatch(setEditingAddress(address));\n requestAnimationFrame(() => {\n input.style.width = `${input.scrollWidth}px`;\n input.style.height = `${input.scrollHeight}px`;\n const length = new String(currentString).length;\n input.setSelectionRange(length, length);\n });\n }\n },\n [cell, editing, currentString, address],\n );\n\n const handleBlur = useCallback(\n (e: React.FocusEvent<HTMLTextAreaElement>) => {\n setIsFocused(false);\n if (isRefInsertable(e.currentTarget)) {\n return true;\n } else {\n if (editing) {\n writeCell(e.currentTarget.value);\n }\n }\n dispatch(setEditingAddress(''));\n },\n [editing, writeCell, dispatch],\n );\n\n const handleChange = useCallback(\n (e: React.ChangeEvent<HTMLTextAreaElement>) => {\n if (prevention.hasOperation(cell?.prevention, prevention.Write)) {\n return;\n }\n dispatch(setInputting(e.currentTarget.value));\n setSelectionStart(e.currentTarget.selectionStart);\n setSelected(0);\n },\n [cell],\n );\n\n const handlePaste = useCallback(\n (e: React.ClipboardEvent<HTMLTextAreaElement>) => {\n if (editing) {\n return true;\n }\n\n const onlyValue = shiftKey;\n const html = e.clipboardData?.getData?.('text/html');\n if (html) {\n dispatch(paste({ matrix: parseHTML(html), onlyValue }));\n } else {\n const text = e.clipboardData?.getData?.('text/plain');\n if (text) {\n dispatch(paste({ matrix: parseText(text), onlyValue }));\n } else {\n console.warn('No clipboard data found.');\n }\n }\n e.preventDefault();\n e.stopPropagation();\n return false;\n },\n [editing, shiftKey],\n );\n\n const handleKeyUpInternal = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n setShiftKey(false);\n const selectingArea = zoneToArea(store.selectingZone);\n sheet?.registry.onKeyUp?.({\n e,\n points: {\n pointing: choosing,\n selectingFrom: { y: selectingArea.top, x: selectingArea.left },\n selectingTo: { y: selectingArea.bottom, x: selectingArea.right },\n },\n });\n },\n [store.selectingZone, choosing, sheet],\n );\n\n const handleOptionMouseDown = useCallback(\n (e: React.MouseEvent<HTMLLIElement>, index: number) => {\n selectValue(index);\n e.preventDefault();\n e.stopPropagation();\n return false;\n },\n [selectValue],\n );\n\n if (!sheet) {\n return null;\n }\n\n return (\n <Fixed\n className={`gs-editor ${editing ? 'gs-editing' : ''}`}\n style={editing ? { top, left, height } : {}}\n {...{\n 'data-mode': mode,\n 'data-sheet-id': sheetId,\n }}\n >\n <div className={`gs-cell-label ${editing ? ' gs-hidden' : ''}`}>{address}</div>\n <div className=\"gs-editor-inner\" style={{ width }}>\n <pre\n className=\"gs-editor-hl\"\n style={{\n //...cell?.style,\n height: editorRef.current?.scrollHeight,\n width: (editorRef.current?.scrollWidth ?? 0) - 4,\n }}\n >\n {(cell?.formulaEnabled ?? true) ? editorStyle(inputting) : inputting}\n </pre>\n <textarea\n data-sheet-id={sheetId}\n name=\"gs-editor-input\"\n data-size=\"small\"\n autoFocus={true}\n spellCheck={false}\n draggable={false}\n ref={editorRef}\n rows={numLines}\n onFocus={handleFocus}\n style={{ minWidth: width, minHeight: height }}\n onDoubleClick={handleDoubleClick}\n onBlur={handleBlur}\n value={inputting}\n onChange={handleChange}\n onSelect={handleSelect}\n onPaste={handlePaste}\n onKeyDown={handleKeyDown}\n onKeyUp={handleKeyUpInternal}\n onCompositionStart={() => {\n composingRef.current = true;\n if (!editing) {\n dispatch(setEditingAddress(address));\n dispatch(setInputting(''));\n }\n }}\n onCompositionEnd={(e) => {\n composingRef.current = false;\n dispatch(setInputting(e.currentTarget.value));\n }}\n onMouseEnter={() => {\n dispatch(setEditorHovering(true));\n }}\n onMouseLeave={() => {\n dispatch(setEditorHovering(false));\n }}\n />\n </div>\n {renderOverlays()}\n </Fixed>\n );\n};\n\n// Memoized token span component to prevent unnecessary re-renders\nconst TokenSpan = memo<{\n token: any;\n tokenKey: string;\n color?: string;\n className?: string;\n}>(\n ({ token, tokenKey, color, className }) => {\n return (\n <span key={tokenKey} style={color ? { color } : undefined} className={className}>\n {token.stringify()}\n </span>\n );\n },\n (prevProps, nextProps) => {\n // Custom comparison to prevent unnecessary re-renders\n return (\n prevProps.tokenKey === nextProps.tokenKey &&\n prevProps.color === nextProps.color &&\n prevProps.className === nextProps.className &&\n prevProps.token.stringify() === nextProps.token.stringify()\n );\n },\n);\n\nexport const editorStyle = (text: string) => {\n if (text[0] !== '=') {\n return <>{text}</>;\n }\n\n const lexer = new Lexer(text.substring(1));\n lexer.tokenize();\n let palletIndex = 0;\n const exists: { [ref: string]: number } = {};\n\n // Create a simple hash of the formula for stable keys\n const formulaHash = text.split('').reduce((hash, char) => {\n return ((hash << 5) - hash + char.charCodeAt(0)) & 0xffffffff;\n }, 0);\n\n return (\n <>\n =\n {lexer.tokens.map((token, i) => {\n // Handle SPACE tokens differently - render as plain text\n if (token.type === 'SPACE') {\n return <React.Fragment key={`${formulaHash}-SPACE-${i}`}>{token.stringify()}</React.Fragment>;\n }\n\n // Create a stable key based on formula hash, token content and index\n const tokenKey = `${formulaHash}-${token.type}-${token.stringify()}-${i}`;\n\n if (token.type === 'REF' || token.type === 'RANGE') {\n const normalizedToken = token.stringify();\n const existsIndex = exists[normalizedToken];\n if (existsIndex !== undefined) {\n return (\n <TokenSpan\n key={tokenKey}\n token={token}\n tokenKey={tokenKey}\n color={COLOR_PALETTE[existsIndex % COLOR_PALETTE.length]}\n />\n );\n }\n const color = COLOR_PALETTE[palletIndex % COLOR_PALETTE.length];\n exists[normalizedToken] = palletIndex++;\n return (\n <TokenSpan\n key={tokenKey}\n token={token}\n tokenKey={tokenKey}\n color={color}\n className={`gs-token-type-${token.type}`}\n />\n );\n }\n\n return (\n <TokenSpan\n key={tokenKey}\n token={token}\n tokenKey={tokenKey}\n className={`gs-token-type-${token.type} gs-token-entity-type-${typeof token.entity}`}\n />\n );\n })}\n </>\n );\n};\n","import type { ReactNode } from 'react';\nimport { createContext, useContext, useState } from 'react';\n\nimport type { StoreType } from '../types';\nimport type { Dispatcher } from '../store';\n\nexport type PluginContextType = {\n provided: boolean;\n store?: StoreType;\n apply?: Dispatcher;\n setStore: (store: StoreType) => void;\n setApply: (apply: Dispatcher) => void;\n};\n\nexport const PluginContext = createContext({} as PluginContextType);\n\nexport function useInitialPluginContext(): PluginContextType {\n const [store, setStore] = useState<StoreType | undefined>(undefined);\n const [apply, setApply] = useState<Dispatcher>();\n return {\n provided: true,\n store,\n apply,\n setStore,\n setApply,\n };\n}\n\nexport function usePluginContext(): [boolean, PluginContextType] {\n const ctx = useContext(PluginContext);\n if (ctx?.provided == null) {\n return [false, ctx];\n }\n return [true, ctx];\n}\n\nexport function usePluginDispatch() {\n const sync = useContext(PluginContext);\n if (!sync) {\n return undefined;\n }\n return sync;\n}\n\ntype Props = {\n children: ReactNode;\n context: PluginContextType;\n};\n\nexport function PluginBase({ children, context }: Props) {\n const [provided] = usePluginContext();\n if (provided) {\n return <>{children}</>;\n }\n return <PluginContext.Provider value={context}>{children}</PluginContext.Provider>;\n}\n","import type { FC, MutableRefObject } from 'react';\nimport { createRef, useContext, useEffect, useRef, useState } from 'react';\n\nimport type { OptionsType, Props, SheetHandle, StoreHandle } from '../types';\nimport { Context } from '../store';\n\nimport { setStore, updateSheet, submitAutofill, setDragging, setAutofillDraggingTo, drag } from '../store/actions';\n\nimport { usePluginContext } from './PluginBase';\nimport { Sheet } from '@gridsheet/web';\n\ntype StoreObserverProps = Omit<OptionsType, 'sheetHeight' | 'sheetWidth'> & {\n // GridSheet always passes the resolved pixel size here, even in string-based fill mode.\n sheetHeight?: number;\n sheetWidth?: number;\n fixedWidth?: boolean;\n fixedHeight?: boolean;\n sheetName?: string;\n sheetRef?: MutableRefObject<SheetHandle | null>;\n storeRef?: MutableRefObject<StoreHandle | null>;\n};\n\nexport const createSheetRef = () => createRef<SheetHandle | null>();\nexport const useSheetRef = () => useRef<SheetHandle | null>(null);\nexport const createStoreRef = () => createRef<StoreHandle | null>();\nexport const useStoreRef = () => useRef<StoreHandle | null>(null);\nexport const StoreObserver: FC<StoreObserverProps> = ({\n sheetName,\n sheetHeight,\n sheetWidth,\n fixedWidth,\n fixedHeight,\n sheetRef,\n storeRef,\n editingOnEnter,\n mode,\n}) => {\n const { store, dispatch } = useContext(Context);\n const { sheetReactive } = store;\n const sheet = sheetReactive.current;\n\n // Drag-during-scroll + robust drag-end. A capture-phase mousemove tracks the\n // cursor (Tabular stopPropagations mousemove, so bubble listeners never see it over\n // the grid). While a drag is active and the cursor is at/past a container edge (incl.\n // over the toolbar below the grid) an rAF loop scrolls and extends the selection to\n // the cell now under the cursor — but ONLY when that cell CHANGES, so holding at the\n // bottom dispatches nothing (no re-render/edit flood, no freeze). A capture mouseup\n // (and a button-up mousemove for releases we never got a mouseup for) ends it exactly\n // once and submits/clears, so autofillDraggingTo can never stay set and block clicks.\n const dragRef = useRef({ store, dispatch });\n dragRef.current = { store, dispatch };\n useEffect(() => {\n let raf = 0;\n let running = false;\n let dead = false;\n let cx = 0;\n let cy = 0;\n let lastCell = '';\n let lastExtend = 0;\n const EDGE = 0;\n const SPEED = 18;\n\n const stop = () => {\n running = false;\n cancelAnimationFrame(raf);\n };\n\n const finish = () => {\n if (dead) {\n return;\n }\n dead = true;\n stop();\n const { store: s, dispatch: d } = dragRef.current;\n if (s.autofillDraggingTo) {\n d(submitAutofill(s.autofillDraggingTo));\n }\n if (s.dragging) {\n d(setDragging(false));\n }\n };\n\n const tick = () => {\n if (dead || !running) {\n return;\n }\n const { store: s, dispatch: d } = dragRef.current;\n const el = s.tabularRef?.current;\n if (!el || !(s.dragging || s.autofillDraggingTo)) {\n running = false;\n return;\n }\n const r = el.getBoundingClientRect();\n const dy = cy > r.bottom - EDGE ? SPEED : cy < r.top + EDGE ? -SPEED : 0;\n const dx = cx > r.right - EDGE ? SPEED : cx < r.left + EDGE ? -SPEED : 0;\n if (dy || dx) {\n el.scrollTop += dy;\n el.scrollLeft += dx;\n const px = Math.min(Math.max(cx, r.left + 1), r.right - 1);\n const py = Math.min(Math.max(cy, r.top + 1), r.bottom - 1);\n const cell = (document.elementFromPoint(px, py) as HTMLElement | null)?.closest('.gs-cell') as HTMLElement | null;\n if (cell) {\n const y = Number(cell.dataset.y);\n const x = Number(cell.dataset.x);\n const key = y + ':' + x;\n const now = performance.now();\n // Dispatch only when the target cell CHANGES (holding still — e.g. at the\n // bottom over the toolbar — dispatches nothing → no freeze) AND at most every\n // 80ms (so a fast scroll doesn't re-render every frame and starve mousemove,\n // which would freeze `cy` and make the scroll unstoppable).\n if (!Number.isNaN(y) && !Number.isNaN(x) && key !== lastCell && now - lastExtend > 80) {\n lastCell = key;\n lastExtend = now;\n d(s.autofillDraggingTo ? setAutofillDraggingTo({ x, y }) : drag({ y, x }));\n }\n }\n }\n raf = requestAnimationFrame(tick);\n };\n\n const onMove = (e: MouseEvent) => {\n if (e.buttons === 0) {\n // Button up. End the drag once (covers a release we never got a mouseup for).\n const { store: s } = dragRef.current;\n if (!dead && (running || s.autofillDraggingTo != null || s.dragging)) {\n finish();\n }\n return;\n }\n cx = e.clientX;\n cy = e.clientY;\n const { store: s } = dragRef.current;\n if (!dead && !running && (s.dragging || s.autofillDraggingTo)) {\n running = true;\n lastCell = '';\n raf = requestAnimationFrame(tick);\n }\n };\n\n const onDown = () => {\n dead = false;\n };\n\n // onUp is the SOLE authority for ending a mouse drag. It is a capture-phase\n // WINDOW listener, so it fires on every mouseup before anything can stopPropagation\n // it — strictly more reliable than a cell's own onMouseUp, which in the VS Code\n // webview did NOT clear autofillDraggingTo when the release landed on a cell (it\n // stayed set and blocked every later click + froze scrolling). We submit/clear here\n // from the live store; the cell's handleDragEnd no longer submits, so there is no\n // double-fill despite this firing first (capture) then the cell's handler (bubble).\n const onUp = () => {\n dead = true;\n stop();\n const { store: s, dispatch: d } = dragRef.current;\n if (s.autofillDraggingTo) {\n d(submitAutofill(s.autofillDraggingTo));\n }\n if (s.dragging) {\n d(setDragging(false));\n }\n };\n\n // A drag can end WITHOUT a mouseup we ever see: the user drags the autofill\n // handle past the grid, out of the webview/window entirely, and releases there.\n // No mouseup → the old code left dragging/autofillDraggingTo stuck and the\n // rAF loop scrolling+extending forever. Ending the drag when the pointer leaves\n // the document (mouseleave) or the window loses focus (blur) closes that hole.\n // Scrolling OVER the in-grid toolbar still works: that stays inside the document,\n // so neither fires until the cursor exits the webview.\n const onLeaveWindow = () => finish();\n\n window.addEventListener('mousedown', onDown, true);\n window.addEventListener('mousemove', onMove, true);\n window.addEventListener('mouseup', onUp, true);\n window.addEventListener('blur', onLeaveWindow);\n document.addEventListener('mouseleave', onLeaveWindow);\n return () => {\n window.removeEventListener('mousedown', onDown, true);\n window.removeEventListener('mousemove', onMove, true);\n window.removeEventListener('mouseup', onUp, true);\n window.removeEventListener('blur', onLeaveWindow);\n document.removeEventListener('mouseleave', onLeaveWindow);\n cancelAnimationFrame(raf);\n };\n }, []);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n if (sheetName && sheetName !== sheet.name) {\n sheet.name = sheetName;\n sheet.registry.sheetIdsByName[sheetName] = sheet.id;\n delete sheet.registry.sheetIdsByName[sheet.prevName];\n sheet.prevName = sheetName;\n //book.transmit();\n }\n }, [sheetName]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n const { registry } = sheet;\n requestAnimationFrame(() => registry.boot());\n registry.contextsBySheetId[sheet.id] = { store, dispatch };\n registry.transmit();\n\n if (sheetRef) {\n sheetRef.current = {\n sheet,\n apply: (sheet) => {\n dispatch(updateSheet(sheet as Sheet));\n },\n };\n }\n if (storeRef) {\n storeRef.current = {\n store,\n apply: (store) => {\n dispatch(setStore(store));\n },\n dispatch,\n };\n }\n }, [store, sheet, sheetRef, storeRef]);\n\n useEffect(() => {\n if (sheetHeight) {\n dispatch(setStore({ sheetHeight }));\n }\n }, [sheetHeight, dispatch]);\n useEffect(() => {\n if (sheetWidth) {\n dispatch(setStore({ sheetWidth }));\n }\n }, [sheetWidth]);\n useEffect(() => {\n dispatch(setStore({ fixedWidth: !!fixedWidth, fixedHeight: !!fixedHeight }));\n }, [fixedWidth, fixedHeight]);\n useEffect(() => {\n if (typeof editingOnEnter !== 'undefined') {\n dispatch(setStore({ editingOnEnter }));\n }\n }, [editingOnEnter]);\n useEffect(() => {\n if (mode) {\n dispatch(setStore({ mode }));\n }\n }, [mode]);\n\n const [pluginProvided, pluginContext] = usePluginContext();\n useEffect(() => {\n if (!pluginProvided) {\n return;\n }\n pluginContext.setStore(store);\n pluginContext.setApply(() => dispatch);\n }, [store, pluginProvided, pluginContext]);\n\n return <></>;\n};\n","import { useContext } from 'react';\nimport type { MouseEvent } from 'react';\n\nimport { Context } from '../store';\nimport { setResizingPositionY, setResizingPositionX, updateSheet, setStore } from '../store/actions';\n\nimport { DEFAULT_HEIGHT, DEFAULT_WIDTH, MIN_WIDTH, MIN_HEIGHT } from '@gridsheet/web';\nimport { zoneToArea, makeSequence, between } from '@gridsheet/web';\nimport type { CellsByAddressType } from '../types';\nimport { p2a } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\n\nexport const Resizer = () => {\n const { store, dispatch } = useContext(Context);\n const {\n resizingPositionY: posY,\n resizingPositionX: posX,\n sheetReactive: sheetRef,\n leftHeaderSelecting,\n topHeaderSelecting,\n selectingZone,\n editorRef,\n mainRef,\n } = store;\n const sheet = sheetRef.current;\n\n const [y, startY, endY] = posY;\n const [x, startX, endX] = posX;\n\n if (mainRef.current == null || editorRef.current == null || !sheet) {\n return <div className=\"gs-resizing gs-hidden\" />;\n }\n\n const cell = sheet.getCell({ y: y === -1 ? 0 : y, x: x === -1 ? 0 : x }, { resolution: 'SYSTEM' });\n const { y: offsetY, x: offsetX } = mainRef.current.getBoundingClientRect();\n\n const baseWidth = cell?.width || DEFAULT_WIDTH;\n const baseHeight = cell?.height || DEFAULT_HEIGHT;\n\n const width = baseWidth + (endX - startX);\n const height = baseHeight + (endY - startY);\n\n const handleResizeEnd = () => {\n const selectingArea = zoneToArea(selectingZone);\n const { top, left, bottom, right } = selectingArea;\n const diff: CellsByAddressType = {};\n if (x !== -1) {\n let xs = [x];\n if (topHeaderSelecting && between({ start: left, end: right }, x)) {\n xs = makeSequence(left, right + 1);\n }\n xs.forEach((x) => {\n diff[p2a({ y: 0, x })] = { width };\n });\n }\n if (y !== -1) {\n let ys = [y];\n if (leftHeaderSelecting && between({ start: top, end: bottom }, y)) {\n ys = makeSequence(top, bottom + 1);\n }\n ys.forEach((y) => {\n diff[p2a({ y, x: 0 })] = { height };\n });\n }\n sheet.update({\n diff,\n partial: true,\n operator: 'USER',\n undoReflection: { selectingZone, sheetId: sheet.id },\n });\n dispatch(\n setStore({\n sheetReactive: { current: sheet },\n }),\n );\n dispatch(setResizingPositionY([-1, -1, -1]));\n dispatch(setResizingPositionX([-1, -1, -1]));\n focus(editorRef.current);\n };\n const handleResizeMove = (e: MouseEvent) => {\n if (y !== -1) {\n let endY = e.clientY;\n const height = baseHeight + (endY - startY);\n if (height < MIN_HEIGHT) {\n endY += MIN_HEIGHT - height;\n }\n dispatch(setResizingPositionY([y, startY, endY]));\n } else if (x !== -1) {\n let endX = e.clientX;\n const width = baseWidth + (endX - startX);\n if (width < MIN_WIDTH) {\n endX += MIN_WIDTH - width;\n }\n dispatch(setResizingPositionX([x, startX, endX]));\n }\n };\n\n return (\n <div\n className={`gs-resizing ${y === -1 && x === -1 ? 'gs-hidden' : ''}`}\n onMouseUp={handleResizeEnd}\n onMouseMove={handleResizeMove}\n >\n <div className={`gs-line-vertical ${x === -1 ? 'gs-hidden' : ''}`}>\n <div className={'gs-line'} style={{ width: 1, height: '100%', left: endX - offsetX }}>\n <span style={{ left: '-50%' }}>{width}px</span>\n </div>\n </div>\n <div className={`gs-line-horizontal ${y === -1 ? 'gs-hidden' : ''}`}>\n <div className={'gs-line'} style={{ width: '100%', height: 1, top: endY - offsetY }}>\n <span style={{ top: '-50%' }}>{height}px</span>\n </div>\n </div>\n </div>\n );\n};\n","import type { FC } from 'react';\nimport { useContext, useEffect, useRef } from 'react';\nimport { Context } from '../store';\n\nexport const Emitter: FC = () => {\n const { store } = useContext(Context);\n const { choosing: pointing, selectingZone: zone, sheetReactive } = store;\n const sheet = sheetReactive.current;\n\n useEffect(() => {\n if (sheet?.isInitialized && sheet.currentVersion > 0 && sheet.registry.onChange) {\n sheet.registry.onChange({\n sheet,\n points: {\n pointing,\n selectingFrom: { y: zone.startY, x: zone.startX },\n selectingTo: { y: zone.endY, x: zone.endX },\n },\n });\n }\n }, [sheetReactive]);\n\n useEffect(() => {\n if (sheet && sheet.registry.onSelect) {\n sheet.registry.onSelect({\n sheet,\n points: {\n pointing,\n selectingFrom: { y: zone.startY, x: zone.startX },\n selectingTo: { y: zone.endY, x: zone.endX },\n },\n });\n }\n }, [pointing, zone]);\n return null;\n};\n","import type { StoreDispatchType, FilterConfig, RawCellType } from '../types';\nimport { areaToZone, zoneShape, zoneToArea } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { p2a } from '@gridsheet/web';\nimport {\n copy,\n cut,\n paste,\n undo,\n redo,\n insertRowsAbove,\n insertRowsBelow,\n insertColsLeft,\n insertColsRight,\n removeRows,\n removeCols,\n sortRows,\n filterRows,\n setSearchQuery,\n setEntering,\n updateSheet,\n} from './actions';\nimport { clip } from '../lib/clipboard';\nimport { parseHTML, parseText } from '../lib/paste';\n\nexport const copier = async ({ store, dispatch }: StoreDispatchType) => {\n const { editorRef } = store;\n const area = clip(store);\n dispatch(copy(areaToZone(area)));\n focus(editorRef.current);\n};\n\nexport const cutter = async ({ store, dispatch }: StoreDispatchType) => {\n const { editorRef } = store;\n const area = clip(store);\n dispatch(cut(areaToZone(area)));\n focus(editorRef.current);\n};\n\nexport const paster = async ({ store, dispatch }: StoreDispatchType, onlyValue = false) => {\n const { editorRef } = store;\n const items = await navigator.clipboard.read();\n let cells: RawCellType[][] = [];\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n if (item.types.indexOf('text/html') !== -1) {\n const blob = await item.getType('text/html');\n const html = await blob.text();\n if (html) {\n cells = parseHTML(html, onlyValue);\n break;\n }\n } else if (item.types.indexOf('text/plain') !== -1) {\n const blob = await item.getType('text/plain');\n const text = await blob.text();\n if (text) {\n cells = parseText(text);\n break;\n }\n }\n }\n dispatch(paste({ matrix: cells, onlyValue }));\n focus(editorRef.current);\n};\n\nexport const undoer = async ({ store, dispatch }: StoreDispatchType) => {\n const { editorRef } = store;\n dispatch(undo(null));\n focus(editorRef.current);\n};\n\nexport const redoer = async ({ store, dispatch }: StoreDispatchType) => {\n const { editorRef } = store;\n dispatch(redo(null));\n focus(editorRef.current);\n};\n\nexport const rowsInserterAbove = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { top } = zoneToArea(selectingZone);\n const numRows = zoneShape(selectingZone).rows;\n dispatch(insertRowsAbove({ numRows, y: top, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const rowsInserterBelow = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { bottom } = zoneToArea(selectingZone);\n const numRows = zoneShape(selectingZone).rows;\n dispatch(insertRowsBelow({ numRows, y: bottom, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const colsInserterLeft = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { left } = zoneToArea(selectingZone);\n const numCols = zoneShape(selectingZone).cols;\n dispatch(insertColsLeft({ numCols, x: left, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const colsInserterRight = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { right } = zoneToArea(selectingZone);\n const numCols = zoneShape(selectingZone).cols;\n dispatch(insertColsRight({ numCols, x: right, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const rowsRemover = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { top } = zoneToArea(selectingZone);\n const numRows = zoneShape(selectingZone).rows;\n dispatch(removeRows({ numRows, y: top, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const colsRemover = async ({ store, dispatch }: StoreDispatchType) => {\n const { selectingZone, editorRef } = store;\n const { left } = zoneToArea(selectingZone);\n const numCols = zoneShape(selectingZone).cols;\n dispatch(removeCols({ numCols, x: left, operator: 'USER' }));\n focus(editorRef.current);\n};\n\nexport const rowsSorterAsc = async ({ store, dispatch }: StoreDispatchType, x: number) => {\n const sheet = store.sheetReactive.current;\n if (sheet && (sheet.hasPendingCells() || sheet.registry.asyncPending.size > 0)) {\n await sheet.waitForPending();\n }\n dispatch(sortRows({ x, direction: 'asc' }));\n focus(store.editorRef.current);\n};\n\nexport const rowsSorterDesc = async ({ store, dispatch }: StoreDispatchType, x: number) => {\n const sheet = store.sheetReactive.current;\n if (sheet && (sheet.hasPendingCells() || sheet.registry.asyncPending.size > 0)) {\n await sheet.waitForPending();\n }\n dispatch(sortRows({ x, direction: 'desc' }));\n focus(store.editorRef.current);\n};\n\nexport const rowsFilterer = async ({ store, dispatch }: StoreDispatchType, x: number, filter: FilterConfig) => {\n const sheet = store.sheetReactive.current;\n if (sheet && (sheet.hasPendingCells() || sheet.registry.asyncPending.size > 0)) {\n await sheet.waitForPending();\n }\n dispatch(filterRows({ x, filter }));\n focus(store.editorRef.current);\n};\n\nexport const rowsFilterClearer = async ({ store, dispatch }: StoreDispatchType, x?: number) => {\n dispatch(filterRows({ x }));\n focus(store.editorRef.current);\n};\n\nexport const rowSortFixedToggler = ({ store, dispatch }: StoreDispatchType, y: number) => {\n const sheet = store.sheetReactive.current;\n if (!sheet) {\n return;\n }\n const addr = p2a({ y, x: 0 });\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n const next = !rowCell?.sortFixed || undefined;\n sheet.update({ diff: { [addr]: { sortFixed: next } }, partial: true });\n dispatch(updateSheet(sheet));\n focus(store.editorRef.current);\n};\n\nexport const rowFilterFixedToggler = ({ store, dispatch }: StoreDispatchType, y: number) => {\n const sheet = store.sheetReactive.current;\n if (!sheet) {\n return;\n }\n const addr = p2a({ y, x: 0 });\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n const next = !rowCell?.filterFixed || undefined;\n sheet.update({ diff: { [addr]: { filterFixed: next } }, partial: true });\n dispatch(updateSheet(sheet));\n focus(store.editorRef.current);\n};\n\nexport const searcher = async ({ store, dispatch }: StoreDispatchType) => {\n if (typeof store.searchQuery === 'undefined') {\n dispatch(setSearchQuery(''));\n }\n dispatch(setEntering(false));\n requestAnimationFrame(() => focus(store.searchInputRef.current));\n};\n\nexport const applyers = {\n copy: copier,\n cut: cutter,\n paste: paster,\n undo: undoer,\n redo: redoer,\n insertRowsAbove: rowsInserterAbove,\n insertRowsBelow: rowsInserterBelow,\n insertColsLeft: colsInserterLeft,\n insertColsRight: colsInserterRight,\n removeRows: rowsRemover,\n removeCols: colsRemover,\n sortRowsAsc: rowsSorterAsc,\n sortRowsDesc: rowsSorterDesc,\n filterRows: rowsFilterer,\n clearFilter: rowsFilterClearer,\n toggleSortFixed: rowSortFixedToggler,\n toggleFilterFixed: rowFilterFixedToggler,\n search: searcher,\n};\n","/**\n * Menu system — types, default descriptors, and MenuContext builder.\n */\n\n// ---- types ----------------------------------------------------------------\n\nimport type { PointType, ZoneType, FilterConfig } from '../types';\nimport type { UserSheet } from '@gridsheet/web';\nimport type { StoreType } from '../types';\nimport type { Dispatcher } from '../store';\nimport { operations as prevention } from '@gridsheet/web';\nimport { zoneShape } from '@gridsheet/web';\nimport { p2a } from '@gridsheet/web';\nimport {\n copier,\n cutter,\n paster,\n undoer,\n redoer,\n rowsSorterAsc,\n rowsSorterDesc,\n rowsFilterer,\n rowsFilterClearer,\n rowSortFixedToggler,\n rowFilterFixedToggler,\n searcher,\n} from '../store/applyers';\nimport {\n insertRowsAbove as _insertRowsAbove,\n insertRowsBelow as _insertRowsBelow,\n removeRows as _removeRows,\n insertColsLeft as _insertColsLeft,\n insertColsRight as _insertColsRight,\n removeCols as _removeCols,\n setStore as _setStore,\n} from '../store/actions';\n\nexport type MenuContext = {\n /** Current sheet instance */\n sheet: UserSheet;\n /** Currently focused cell */\n choosing: PointType;\n /** Currently selected zone */\n selectingZone: ZoneType;\n /** True when the left (row) header is being selected */\n leftHeaderSelecting: boolean;\n /** True when the top (column) header is being selected */\n topHeaderSelecting: boolean;\n\n // ---- actions ----\n cut(): Promise<void>;\n copy(): Promise<void>;\n paste(onlyValue?: boolean): Promise<void>;\n undo(): void;\n redo(): void;\n insertRowsAbove(y: number, numRows: number): void;\n insertRowsBelow(y: number, numRows: number): void;\n removeRows(y: number, numRows: number): void;\n insertColsLeft(x: number, numCols: number): void;\n insertColsRight(x: number, numCols: number): void;\n removeCols(x: number, numCols: number): void;\n sortRows(x: number, direction: 'asc' | 'desc'): Promise<void>;\n filterRows(x: number, filter?: FilterConfig): Promise<void>;\n clearFilter(x?: number): void;\n toggleSortFixed(y: number): void;\n toggleFilterFixed(y: number): void;\n search(): void;\n updateColLabel(x: number, label: string | undefined): void;\n /** Close the currently open menu */\n close(): void;\n};\n\nexport type MenuDividerItem = { type: 'divider'; visible?: (ctx: MenuContext) => boolean };\n\n/**\n * Base structure shared by all menu item descriptors.\n * `Args` is the tuple of coordinate arguments passed after `ctx`:\n * - `[]` → ContextMenu (no coordinate)\n * - `[y: number]` → RowMenu\n * - `[x: number]` → ColMenu\n */\nexport type MenuItemBase<Args extends unknown[] = []> = {\n type?: 'item';\n id?: string;\n label: string | ((ctx: MenuContext, ...args: Args) => string);\n shortcuts?: string[] | ((ctx: MenuContext, ...args: Args) => string[]);\n visible?: (ctx: MenuContext, ...args: Args) => boolean;\n disabled?: (ctx: MenuContext, ...args: Args) => boolean;\n /** Render a checkmark prefix when defined. */\n checked?: (ctx: MenuContext, ...args: Args) => boolean;\n onClick: (ctx: MenuContext, ...args: Args) => void | Promise<void>;\n};\n\n/**\n * A menu entry that renders a registered React component.\n * Use `registerMenuComponent(id, Component)` to associate an id with a component,\n * then reference it here as `{ type: 'component', componentId: id }`.\n */\nexport type MenuComponentItem<Args extends unknown[] = []> = {\n type: 'component';\n componentId: string;\n visible?: (ctx: MenuContext, ...args: Args) => boolean;\n};\n\n/**\n * A menu entry that opens a nested flyout of child items on hover. `children` uses the same\n * descriptor shape (items, dividers, or further submenus), so menus can nest arbitrarily —\n * useful when a category (e.g. cell \"Format\") has more options than fit in one flat list.\n */\nexport type MenuSubmenuItem<Args extends unknown[] = []> = {\n type: 'submenu';\n id?: string;\n label: string | ((ctx: MenuContext, ...args: Args) => string);\n visible?: (ctx: MenuContext, ...args: Args) => boolean;\n disabled?: (ctx: MenuContext, ...args: Args) => boolean;\n children: (MenuDividerItem | MenuItemBase<Args> | MenuSubmenuItem<Args>)[];\n};\n\nexport type ContextMenuItemDescriptor = MenuDividerItem | MenuItemBase | MenuComponentItem | MenuSubmenuItem;\nexport type RowMenuItemDescriptor =\n | MenuDividerItem\n | MenuItemBase<[y: number]>\n | MenuComponentItem<[y: number]>\n | MenuSubmenuItem<[y: number]>;\nexport type ColMenuItemDescriptor =\n | MenuDividerItem\n | MenuItemBase<[x: number]>\n | MenuComponentItem<[x: number]>\n | MenuSubmenuItem<[x: number]>;\n\n// ---- helpers ---------------------------------------------------------------\n\nconst rowInsertCount = (ctx: MenuContext, y: number): number => {\n const { selectingZone } = ctx;\n const selStart = Math.min(selectingZone.startY, selectingZone.endY);\n const selEnd = Math.max(selectingZone.startY, selectingZone.endY);\n const isFullRow = selectingZone.startX === 1 && selectingZone.endX === ctx.sheet.numCols;\n return isFullRow && y >= selStart && y <= selEnd ? selEnd - selStart + 1 : 1;\n};\n\nconst colInsertCount = (ctx: MenuContext, x: number): number => {\n const { selectingZone } = ctx;\n const selStart = Math.min(selectingZone.startX, selectingZone.endX);\n const selEnd = Math.max(selectingZone.startX, selectingZone.endX);\n const isFullCol = selectingZone.startY === 1 && selectingZone.endY === ctx.sheet.numRows;\n return isFullCol && x >= selStart && x <= selEnd ? selEnd - selStart + 1 : 1;\n};\n\n// ---- default descriptors ---------------------------------------------------\n\nexport const defaultContextMenuDescriptors: ContextMenuItemDescriptor[] = [\n {\n id: 'cut',\n label: 'Cut',\n shortcuts: ['X'],\n onClick: (ctx) => ctx.cut(),\n },\n {\n id: 'copy',\n label: 'Copy',\n shortcuts: ['C'],\n onClick: (ctx) => ctx.copy(),\n },\n {\n id: 'paste',\n label: 'Paste',\n shortcuts: ['V'],\n onClick: (ctx) => ctx.paste(false),\n },\n {\n id: 'paste-only-value',\n label: 'Paste only value',\n shortcuts: ['Shift+V'],\n onClick: (ctx) => ctx.paste(true),\n },\n { type: 'divider', visible: (ctx) => ctx.leftHeaderSelecting || ctx.topHeaderSelecting },\n {\n id: 'insert-rows-above',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n return `Insert ${n} row${n > 1 ? 's' : ''} above`;\n },\n visible: (ctx) => ctx.leftHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y: ctx.choosing.y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumRows !== -1 && sheet.numRows + n > sheet.maxNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.InsertRowsAbove)\n );\n },\n onClick: (ctx) => ctx.insertRowsAbove(ctx.choosing.y, zoneShape(ctx.selectingZone).rows),\n },\n {\n id: 'insert-rows-below',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n return `Insert ${n} row${n > 1 ? 's' : ''} below`;\n },\n visible: (ctx) => ctx.leftHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y: ctx.choosing.y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumRows !== -1 && sheet.numRows + n > sheet.maxNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.InsertRowsBelow)\n );\n },\n onClick: (ctx) => ctx.insertRowsBelow(ctx.choosing.y, zoneShape(ctx.selectingZone).rows),\n },\n {\n id: 'insert-cols-left',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n return `Insert ${n} column${n > 1 ? 's' : ''} left`;\n },\n visible: (ctx) => ctx.topHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x: ctx.choosing.x }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumCols !== -1 && sheet.numCols + n > sheet.maxNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.InsertColsLeft)\n );\n },\n onClick: (ctx) => ctx.insertColsLeft(ctx.choosing.x, zoneShape(ctx.selectingZone).cols),\n },\n {\n id: 'insert-cols-right',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n return `Insert ${n} column${n > 1 ? 's' : ''} right`;\n },\n visible: (ctx) => ctx.topHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x: ctx.choosing.x }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumCols !== -1 && sheet.numCols + n > sheet.maxNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.InsertColsRight)\n );\n },\n onClick: (ctx) => ctx.insertColsRight(ctx.choosing.x, zoneShape(ctx.selectingZone).cols),\n },\n {\n id: 'remove-rows',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n return `Remove ${n} row${n > 1 ? 's' : ''}`;\n },\n visible: (ctx) => ctx.leftHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).rows;\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y: ctx.choosing.y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.minNumRows !== -1 && sheet.numRows - n < sheet.minNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.RemoveRows)\n );\n },\n onClick: (ctx) => ctx.removeRows(ctx.choosing.y, zoneShape(ctx.selectingZone).rows),\n },\n {\n id: 'remove-cols',\n label: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n return `Remove ${n} column${n > 1 ? 's' : ''}`;\n },\n visible: (ctx) => ctx.topHeaderSelecting,\n disabled: (ctx) => {\n const n = zoneShape(ctx.selectingZone).cols;\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x: ctx.choosing.x }, { resolution: 'SYSTEM' });\n return (\n (sheet.minNumCols !== -1 && sheet.numCols - n < sheet.minNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.RemoveCols)\n );\n },\n onClick: (ctx) => ctx.removeCols(ctx.choosing.x, zoneShape(ctx.selectingZone).cols),\n },\n { type: 'divider' },\n {\n id: 'undo',\n label: 'Undo',\n shortcuts: ['Z'],\n disabled: (ctx) => ctx.sheet.historyIndex() <= -1,\n onClick: (ctx) => ctx.undo(),\n },\n {\n id: 'redo',\n label: 'Redo',\n shortcuts: ['R', 'Y', 'Shift+Z'],\n disabled: (ctx) => ctx.sheet.historyIndex() >= ctx.sheet.historySize() - 1,\n onClick: (ctx) => ctx.redo(),\n },\n { type: 'divider' },\n {\n id: 'search',\n label: 'Search',\n shortcuts: ['F'],\n onClick: (ctx) => ctx.search(),\n },\n];\n\nexport const defaultRowMenuDescriptors: RowMenuItemDescriptor[] = [\n {\n id: 'cut',\n label: 'Cut',\n shortcuts: ['X'],\n onClick: (ctx) => ctx.cut(),\n },\n {\n id: 'copy',\n label: 'Copy',\n shortcuts: ['C'],\n onClick: (ctx) => ctx.copy(),\n },\n {\n id: 'paste',\n label: 'Paste',\n shortcuts: ['V'],\n onClick: (ctx) => ctx.paste(false),\n },\n {\n id: 'paste-only-value',\n label: 'Paste only value',\n shortcuts: ['Shift+V'],\n onClick: (ctx) => ctx.paste(true),\n },\n { type: 'divider' },\n {\n id: 'insert-rows-above',\n label: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n return `Insert ${n} row${n > 1 ? 's' : ''} above`;\n },\n disabled: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumRows !== -1 && sheet.numRows + n > sheet.maxNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.InsertRowsAbove)\n );\n },\n onClick: (ctx, y) => ctx.insertRowsAbove(y, rowInsertCount(ctx, y)),\n },\n {\n id: 'insert-rows-below',\n label: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n return `Insert ${n} row${n > 1 ? 's' : ''} below`;\n },\n disabled: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumRows !== -1 && sheet.numRows + n > sheet.maxNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.InsertRowsBelow)\n );\n },\n onClick: (ctx, y) => ctx.insertRowsBelow(y, rowInsertCount(ctx, y)),\n },\n {\n id: 'remove-rows',\n label: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n return `Remove ${n} row${n > 1 ? 's' : ''}`;\n },\n disabled: (ctx, y) => {\n const n = rowInsertCount(ctx, y);\n const sheet = ctx.sheet;\n const rowCell = sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n return (\n (sheet.minNumRows !== -1 && sheet.numRows - n < sheet.minNumRows) ||\n prevention.hasOperation(rowCell?.prevention, prevention.RemoveRows)\n );\n },\n onClick: (ctx, y) => ctx.removeRows(y, rowInsertCount(ctx, y)),\n },\n { type: 'divider' },\n {\n id: 'toggle-sort-fixed',\n label: 'Fix row for sorting',\n checked: (ctx, y) => !!ctx.sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' })?.sortFixed,\n onClick: (ctx, y) => ctx.toggleSortFixed(y),\n },\n {\n id: 'toggle-filter-fixed',\n label: 'Fix row for filtering',\n checked: (ctx, y) => !!ctx.sheet.getCell({ y, x: 0 }, { resolution: 'SYSTEM' })?.filterFixed,\n onClick: (ctx, y) => ctx.toggleFilterFixed(y),\n },\n { type: 'divider' },\n {\n id: 'search',\n label: 'Search',\n shortcuts: ['F'],\n onClick: (ctx) => ctx.search(),\n },\n];\n\n// The col menu composes registered section components (filter, sort, label) and\n// simple menu items. Use `registerMenuComponent` to override built-in sections.\nexport const defaultColMenuDescriptors: ColMenuItemDescriptor[] = [\n { type: 'component', componentId: 'col-label' },\n { type: 'divider' },\n { type: 'component', componentId: 'col-filter' },\n { type: 'divider' },\n { type: 'component', componentId: 'col-sort' },\n { type: 'divider' },\n {\n id: 'cut',\n label: 'Cut',\n shortcuts: ['X'],\n onClick: (ctx) => ctx.cut(),\n },\n {\n id: 'copy',\n label: 'Copy',\n shortcuts: ['C'],\n onClick: (ctx) => ctx.copy(),\n },\n {\n id: 'paste',\n label: 'Paste',\n shortcuts: ['V'],\n onClick: (ctx) => ctx.paste(false),\n },\n {\n id: 'paste-only-value',\n label: 'Paste only value',\n shortcuts: ['Shift+V'],\n onClick: (ctx) => ctx.paste(true),\n },\n { type: 'divider' },\n {\n id: 'insert-cols-left',\n label: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n return `Insert ${n} column${n > 1 ? 's' : ''} left`;\n },\n disabled: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumCols !== -1 && sheet.numCols + n > sheet.maxNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.InsertColsLeft)\n );\n },\n onClick: (ctx, x) => ctx.insertColsLeft(x, colInsertCount(ctx, x)),\n },\n {\n id: 'insert-cols-right',\n label: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n return `Insert ${n} column${n > 1 ? 's' : ''} right`;\n },\n disabled: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n return (\n (sheet.maxNumCols !== -1 && sheet.numCols + n > sheet.maxNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.InsertColsRight)\n );\n },\n onClick: (ctx, x) => ctx.insertColsRight(x, colInsertCount(ctx, x)),\n },\n {\n id: 'remove-cols',\n label: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n return `Remove ${n} column${n > 1 ? 's' : ''}`;\n },\n disabled: (ctx, x) => {\n const n = colInsertCount(ctx, x);\n const sheet = ctx.sheet;\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n return (\n (sheet.minNumCols !== -1 && sheet.numCols - n < sheet.minNumCols) ||\n prevention.hasOperation(colCell?.prevention, prevention.RemoveCols)\n );\n },\n onClick: (ctx, x) => ctx.removeCols(x, colInsertCount(ctx, x)),\n },\n { type: 'divider' },\n {\n id: 'search',\n label: 'Search',\n shortcuts: ['F'],\n onClick: (ctx) => ctx.search(),\n },\n];\n\n// ---- buildMenuContext -------------------------------------------------------\n\nexport function buildMenuContext(store: StoreType, dispatch: Dispatcher, close: () => void): MenuContext {\n const props = { store, dispatch };\n const sheet = store.sheetReactive.current!;\n\n return {\n sheet,\n choosing: store.choosing,\n selectingZone: store.selectingZone,\n leftHeaderSelecting: store.leftHeaderSelecting,\n topHeaderSelecting: store.topHeaderSelecting,\n\n cut: () => cutter(props),\n copy: () => copier(props),\n paste: (onlyValue = false) => paster(props, onlyValue),\n undo: () => undoer(props),\n redo: () => redoer(props),\n\n insertRowsAbove: (y, numRows) => {\n dispatch(_insertRowsAbove({ numRows, y, operator: 'USER' }));\n },\n insertRowsBelow: (y, numRows) => {\n dispatch(_insertRowsBelow({ numRows, y, operator: 'USER' }));\n },\n removeRows: (y, numRows) => {\n dispatch(_removeRows({ numRows, y, operator: 'USER' }));\n },\n insertColsLeft: (x, numCols) => {\n dispatch(_insertColsLeft({ numCols, x, operator: 'USER' }));\n },\n insertColsRight: (x, numCols) => {\n dispatch(_insertColsRight({ numCols, x, operator: 'USER' }));\n },\n removeCols: (x, numCols) => {\n dispatch(_removeCols({ numCols, x, operator: 'USER' }));\n },\n\n sortRows: async (x, direction) => {\n if (direction === 'asc') {\n await rowsSorterAsc(props, x);\n } else {\n await rowsSorterDesc(props, x);\n }\n },\n filterRows: async (x, filter) => {\n if (filter) {\n await rowsFilterer(props, x, filter);\n } else {\n rowsFilterClearer(props, x);\n }\n },\n clearFilter: (x) => rowsFilterClearer(props, x),\n\n toggleSortFixed: (y) => rowSortFixedToggler(props, y),\n toggleFilterFixed: (y) => rowFilterFixedToggler(props, y),\n\n search: () => searcher(props),\n\n updateColLabel: (x, label) => {\n if (!sheet) {\n return;\n }\n const addr = p2a({ y: 0, x });\n sheet.update({\n diff: { [addr]: { label: label || undefined } },\n partial: true,\n undoReflection: {\n sheetId: sheet.id,\n selectingZone: store.selectingZone,\n choosing: store.choosing,\n },\n redoReflection: {\n sheetId: sheet.id,\n selectingZone: store.selectingZone,\n choosing: store.choosing,\n },\n });\n dispatch(_setStore({ sheetReactive: { current: sheet } }));\n },\n\n close,\n };\n}\n\n// ---- menu component registry -----------------------------------------------\n\nimport type { FC } from 'react';\n\nexport type ContextMenuSectionProps = {\n close: () => void;\n};\n\nexport type RowMenuSectionProps = {\n y: number;\n close: () => void;\n};\n\nexport type ColMenuSectionProps = {\n x: number;\n close: () => void;\n /** Signal waiting state to parent menu. Pass null to clear. */\n onWaiting?: (message: string | null, cancel?: () => void) => void;\n};\n\nconst _menuComponentRegistry = new Map<string, FC<any>>();\n\n/**\n * Register a React component under a string id so it can be referenced in menu\n * descriptors via `{ type: 'component', componentId: '...' }`.\n *\n * Built-in ids: `'col-filter'`, `'col-sort'`, `'col-label'`.\n * You can override any built-in by registering your own component with the same id.\n */\n\nexport function registerMenuComponent(id: string, component: FC<any>): void {\n _menuComponentRegistry.set(id, component);\n}\n\n/** Look up a previously registered component by id. */\n\nexport function getMenuComponent(id: string): FC<any> | undefined {\n return _menuComponentRegistry.get(id);\n}\n","import type { FC } from 'react';\n\ntype MenuItemProps = {\n label: string;\n shortcuts?: string[];\n disabled?: boolean;\n /**\n * undefined → no check column\n * true/false → displayed as a toggle row with a checkmark\n */\n checked?: boolean;\n testId?: string;\n onClick?: () => void;\n className?: string;\n};\n\nexport const MenuItem: FC<MenuItemProps> = ({\n label,\n shortcuts,\n disabled = false,\n checked,\n testId,\n onClick,\n className,\n}) => {\n const hasCheck = checked !== undefined;\n return (\n <li\n className={`gs-menu-item ${disabled ? 'gs-disabled' : 'gs-enabled'}${className ? ` ${className}` : ''}`}\n data-testid={testId}\n onClick={disabled ? undefined : onClick}\n >\n <div className={`gs-menu-name${hasCheck ? ' gs-row-fixed-toggle' : ''}`}>\n {hasCheck && <span className={`gs-row-fixed-check${checked ? ' gs-row-fixed-active' : ''}`}>✓</span>}\n {label}\n </div>\n {shortcuts != null && shortcuts.length > 0 && (\n <div className=\"gs-menu-shortcut\">\n {shortcuts.map((shortcut, i) => (\n <span key={i}>\n {i > 0 && <span className=\"gs-menu-shortcut-sep\">, </span>}\n <span className=\"gs-menu-shortcut-badge\">\n {shortcut.split('+').map((part, j, arr) =>\n j < arr.length - 1 ? (\n <span key={j}>{part}+</span>\n ) : (\n <span key={j} className=\"gs-menu-underline\">\n {part}\n </span>\n ),\n )}\n </span>\n </span>\n ))}\n </div>\n )}\n </li>\n );\n};\n\nexport const MenuDivider: FC = () => <li className=\"gs-menu-divider\" />;\n","import { type FC, type ReactNode, useState, useRef, useLayoutEffect } from 'react';\nimport type { MenuContext } from '../lib/menu';\nimport { MenuItem, MenuDivider } from './MenuItem';\n\n// Loose structural view of a menu descriptor shared by all three menus (context/row/col).\n// The public descriptor unions in menu.ts stay type-safe per menu; this renderer takes the\n// trailing coordinate args generically (`[]` / `[x]` / `[y]`) so one implementation drives\n// items, dividers, registered components, and nested submenus for every menu.\nexport type MenuNode = {\n type?: 'item' | 'divider' | 'component' | 'submenu';\n id?: string;\n componentId?: string;\n label?: string | ((ctx: MenuContext, ...args: any[]) => string);\n shortcuts?: string[] | ((ctx: MenuContext, ...args: any[]) => string[]);\n visible?: (ctx: MenuContext, ...args: any[]) => boolean;\n disabled?: (ctx: MenuContext, ...args: any[]) => boolean;\n checked?: (ctx: MenuContext, ...args: any[]) => boolean;\n onClick?: (ctx: MenuContext, ...args: any[]) => void | Promise<void>;\n children?: MenuNode[];\n};\n\ntype MenuNodesProps = {\n items: MenuNode[];\n ctx: MenuContext;\n /** Trailing coordinate args passed after ctx to every callback: [] | [x] | [y]. */\n args: number[];\n /** Called after a leaf item is chosen, to close the whole menu. */\n onSelect: () => void;\n /** Renders a `type: 'component'` descriptor (e.g. the column menu's sort/filter sections). */\n renderComponent?: (componentId: string, key: number) => ReactNode;\n};\n\n/** Renders a list of menu descriptors (with nested submenu support) as `<li>` rows. */\nexport const MenuNodes: FC<MenuNodesProps> = ({ items, ctx, args, onSelect, renderComponent }) => {\n return (\n <>\n {items.map((d, i) => {\n if (d.type === 'divider') {\n if (d.visible && !d.visible(ctx, ...args)) {\n return null;\n }\n return <MenuDivider key={i} />;\n }\n if (d.type === 'component') {\n if (d.visible && !d.visible(ctx, ...args)) {\n return null;\n }\n return renderComponent && d.componentId ? renderComponent(d.componentId, i) : null;\n }\n if (d.visible && !d.visible(ctx, ...args)) {\n return null;\n }\n const label = typeof d.label === 'function' ? d.label(ctx, ...args) : (d.label ?? '');\n const disabled = d.disabled?.(ctx, ...args) ?? false;\n if (d.type === 'submenu') {\n return (\n <SubmenuNode\n key={i}\n label={label}\n disabled={disabled}\n testId={d.id}\n items={d.children ?? []}\n ctx={ctx}\n args={args}\n onSelect={onSelect}\n renderComponent={renderComponent}\n />\n );\n }\n const shortcuts = typeof d.shortcuts === 'function' ? d.shortcuts(ctx, ...args) : d.shortcuts;\n const checked = d.checked?.(ctx, ...args);\n return (\n <MenuItem\n key={i}\n label={label}\n shortcuts={shortcuts}\n disabled={disabled}\n checked={checked}\n testId={d.id ? `${d.id}-item` : undefined}\n onClick={() => {\n d.onClick?.(ctx, ...args);\n onSelect();\n }}\n />\n );\n })}\n </>\n );\n};\n\ntype SubmenuNodeProps = {\n label: string;\n disabled: boolean;\n testId?: string;\n items: MenuNode[];\n ctx: MenuContext;\n args: number[];\n onSelect: () => void;\n renderComponent?: (componentId: string, key: number) => ReactNode;\n};\n\nconst SubmenuNode: FC<SubmenuNodeProps> = ({ label, disabled, testId, items, ctx, args, onSelect, renderComponent }) => {\n const [open, setOpen] = useState(false);\n const liRef = useRef<HTMLLIElement>(null);\n const flyoutRef = useRef<HTMLUListElement>(null);\n // The flyout is position:fixed and placed in viewport coordinates so it can never be\n // clipped by an ancestor. Preferred side is to the right of the parent row; it flips left\n // and clamps vertically when it would spill off the viewport. `null` until measured.\n const [pos, setPos] = useState<{ left: number; top: number } | null>(null);\n\n useLayoutEffect(() => {\n if (!open || disabled) {\n setPos(null);\n return;\n }\n const li = liRef.current;\n const fly = flyoutRef.current;\n if (!li || !fly) {\n return;\n }\n const p = li.getBoundingClientRect();\n const f = fly.getBoundingClientRect();\n const margin = 6;\n let left = p.right;\n if (left + f.width > window.innerWidth - margin) {\n left = p.left - f.width; // flip to the left of the parent\n if (left < margin) {\n left = Math.max(margin, window.innerWidth - f.width - margin);\n }\n }\n let top = p.top;\n if (top + f.height > window.innerHeight - margin) {\n top = window.innerHeight - f.height - margin;\n }\n if (top < margin) {\n top = margin;\n }\n setPos({ left, top });\n }, [open, disabled]);\n\n return (\n <li\n ref={liRef}\n className={`gs-menu-item gs-submenu-parent ${disabled ? 'gs-disabled' : 'gs-enabled'}`}\n data-testid={testId ? `${testId}-item` : undefined}\n onMouseEnter={() => setOpen(true)}\n onMouseLeave={() => setOpen(false)}\n // Clicking the parent row opens the flyout (so it also works without hover, e.g. touch)\n // but must never bubble to the menu backdrop, which would close the whole menu.\n onClick={(e) => {\n e.stopPropagation();\n setOpen(true);\n }}\n >\n <div className=\"gs-menu-name\">{label}</div>\n <span className=\"gs-submenu-arrow\">▸</span>\n {open && !disabled && (\n <ul\n ref={flyoutRef}\n className=\"gs-menu-items gs-submenu-flyout\"\n style={{\n position: 'fixed',\n left: pos ? pos.left : -9999,\n top: pos ? pos.top : -9999,\n visibility: pos ? 'visible' : 'hidden',\n }}\n >\n <MenuNodes items={items} ctx={ctx} args={args} onSelect={onSelect} renderComponent={renderComponent} />\n </ul>\n )}\n </li>\n );\n};\n","import { useContext, useRef, useEffect } from 'react';\n\nimport { setContextMenuPosition } from '../store/actions';\n\nimport { Context } from '../store';\nimport { Fixed } from './Fixed';\nimport type { ContextMenuItemDescriptor } from '../lib/menu';\nimport { buildMenuContext } from '../lib/menu';\nimport { MenuNodes, type MenuNode } from './MenuNodes';\nimport { clampPopup } from '@gridsheet/web';\n\nexport const ContextMenu = () => {\n const { store, dispatch } = useContext(Context);\n const { contextMenuPosition, contextMenu } = store;\n const { y: top, x: left } = contextMenuPosition;\n const menuRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (menuRef.current) {\n clampPopup(menuRef.current);\n }\n });\n\n if (top === -1) {\n return null;\n }\n\n const close = () => dispatch(setContextMenuPosition({ y: -1, x: -1 }));\n const ctx = buildMenuContext(store, dispatch, close);\n\n return (\n <Fixed\n className=\"gs-menu-modal gs-context-menu-modal\"\n onClick={(e: MouseEvent) => {\n e.preventDefault();\n close();\n return false;\n }}\n >\n <div ref={menuRef} className={'gs-context-menu'} style={{ top: top, left: left }}>\n <ul className=\"gs-menu-items\">\n <MenuNodes items={contextMenu as MenuNode[]} ctx={ctx} args={[]} onSelect={close} />\n </ul>\n </div>\n </Fixed>\n );\n};\n","import { type FC, useContext, useState, useCallback, useEffect } from 'react';\nimport { Context } from '../store';\nimport { filterRows } from '../store/actions';\nimport type { FilterCondition, FilterConditionMethod } from '../types';\nimport { operations as prevention } from '@gridsheet/web';\nimport { registerMenuComponent, type ColMenuSectionProps } from '../lib/menu';\n\nconst METHOD_LABELS: Record<FilterConditionMethod, string> = {\n eq: '=',\n ne: '≠',\n gt: '>',\n gte: '≥',\n lt: '<',\n lte: '≤',\n blank: 'Blank',\n nonblank: 'Nonblank',\n includes: 'Includes',\n excludes: 'Excludes',\n};\n\nconst NO_VALUE_METHODS: FilterConditionMethod[] = ['blank', 'nonblank'];\nconst DEFAULT_CONDITION: FilterCondition = { method: 'eq', value: [''] };\n\ntype PendingFilter = {\n x: number;\n conditions: FilterCondition[];\n mode: 'and' | 'or';\n};\n\nconst FilterSection: FC<ColMenuSectionProps> = ({ x, close, onWaiting }) => {\n const { store, dispatch } = useContext(Context);\n const { sheetReactive: sheetRef } = store;\n const sheet = sheetRef.current;\n\n const [conditions, setConditions] = useState<FilterCondition[]>([{ ...DEFAULT_CONDITION }]);\n const [mode, setMode] = useState<'and' | 'or'>('or');\n const [pending, setPending] = useState<PendingFilter | null>(null);\n\n // Auto-focus first value input when x changes\n const firstValueRef = useCallback(\n (node: HTMLInputElement | null) => {\n if (node) {\n node.focus();\n }\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [x],\n );\n\n // Restore conditions from existing filter on the column cell when x changes\n useEffect(() => {\n if (sheet) {\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const existing = colCell?.filter;\n if (existing && existing.conditions.length > 0) {\n setConditions(existing.conditions.map((c) => ({ ...c, value: [...c.value] })));\n setMode(existing.mode || 'or');\n } else {\n setConditions([{ ...DEFAULT_CONDITION, value: [''] }]);\n setMode('or');\n }\n }\n }, [x, sheet]);\n\n // Escape key cancels during waiting\n const handleCancel = useCallback(() => {\n setPending(null);\n onWaiting?.(null);\n close();\n }, [close, onWaiting]);\n\n // Notify parent about waiting state\n useEffect(() => {\n if (pending) {\n onWaiting?.('Filtering…', handleCancel);\n }\n // Do NOT include onWaiting/handleCancel in deps to avoid re-triggering execute\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pending]);\n\n // Execute pending filter after async formulas resolve\n useEffect(() => {\n if (!pending) {\n return;\n }\n let cancelled = false;\n const execute = () => {\n if (cancelled) {\n return;\n }\n const currentSheet = sheetRef.current;\n if (!currentSheet) {\n return;\n }\n const { x: actionX, conditions: validConditions, mode: filterMode } = pending;\n if (validConditions.length > 0) {\n dispatch(filterRows({ x: actionX, filter: { mode: filterMode, conditions: validConditions } }));\n } else {\n dispatch(filterRows({ x: actionX }));\n }\n onWaiting?.(null);\n setPending(null);\n close();\n };\n const currentSheet = sheetRef.current;\n if (currentSheet && (currentSheet.hasPendingCells() || currentSheet.registry.asyncPending.size > 0)) {\n currentSheet.waitForPending().then(execute);\n } else {\n execute();\n }\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pending]);\n\n const updateCondition = useCallback((index: number, patch: Partial<FilterCondition>) => {\n setConditions((prev) => {\n const next = [...prev];\n next[index] = { ...next[index], ...patch };\n return next;\n });\n }, []);\n\n const addCondition = useCallback(() => {\n setConditions((prev) => [...prev, { ...DEFAULT_CONDITION, value: [''] }]);\n }, []);\n\n const removeCondition = useCallback((index: number) => {\n setConditions((prev) => {\n if (prev.length <= 1) {\n return [{ ...DEFAULT_CONDITION, value: [''] }];\n }\n return prev.filter((_, i) => i !== index);\n });\n }, []);\n\n const handleApplyFilter = useCallback(() => {\n const valid = conditions.filter((c) => {\n if (NO_VALUE_METHODS.includes(c.method)) {\n return true;\n }\n return c.value.some((v) => v.trim() !== '');\n });\n setPending({ x, conditions: valid, mode });\n }, [x, conditions, mode]);\n\n const handleResetColumn = useCallback(() => {\n setPending(null);\n dispatch(filterRows({ x }));\n close();\n }, [dispatch, x, close]);\n\n const handleResetAll = useCallback(() => {\n setPending(null);\n dispatch(filterRows({}));\n close();\n }, [dispatch, close]);\n\n if (!sheet) {\n return null;\n }\n\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const filterDisabled = prevention.hasOperation(colCell?.prevention, prevention.Filter);\n const hasAnyFilter = sheet.hasActiveFilters();\n\n return (\n <li className={`gs-column-menu-filter${filterDisabled ? ' gs-disabled' : ''}`}>\n <>\n <div className=\"gs-filter-header\">\n <div className=\"gs-menu-name\">Filter:</div>\n <button className=\"gs-filter-add-btn\" onClick={addCondition} disabled={filterDisabled}>\n + ADD\n </button>\n <div className={`gs-filter-mode-toggle${conditions.length <= 1 ? ' gs-disabled' : ''}`}>\n <label className={mode === 'and' ? 'gs-active' : ''}>\n <input\n type=\"radio\"\n name=\"gs-filter-mode\"\n checked={mode === 'and'}\n onChange={() => setMode('and')}\n disabled={filterDisabled || conditions.length <= 1}\n />\n AND\n </label>\n <label className={mode === 'or' ? 'gs-active' : ''}>\n <input\n type=\"radio\"\n name=\"gs-filter-mode\"\n checked={mode === 'or'}\n onChange={() => setMode('or')}\n disabled={filterDisabled || conditions.length <= 1}\n />\n OR\n </label>\n </div>\n </div>\n <div className=\"gs-filter-conditions\">\n {conditions.map((cond, i) => (\n <div className=\"gs-filter-condition-row\" key={i}>\n <select\n className=\"gs-filter-method-select\"\n value={cond.method}\n disabled={filterDisabled}\n tabIndex={i * 2 + 1}\n onChange={(e) => updateCondition(i, { method: e.target.value as FilterConditionMethod })}\n >\n {(Object.keys(METHOD_LABELS) as FilterConditionMethod[]).map((m) => (\n <option key={m} value={m}>\n {METHOD_LABELS[m]}\n </option>\n ))}\n </select>\n {!NO_VALUE_METHODS.includes(cond.method) && (\n <input\n ref={i === 0 ? firstValueRef : undefined}\n className=\"gs-filter-value-input\"\n type=\"text\"\n placeholder=\"Value\"\n value={cond.value[0] || ''}\n disabled={filterDisabled}\n tabIndex={i * 2 + 2}\n onChange={(e) => updateCondition(i, { value: [e.target.value] })}\n onKeyDown={(e) => {\n if (e.nativeEvent.isComposing) {\n return;\n }\n if (e.key === 'Enter') {\n handleApplyFilter();\n }\n if (e.key === 'Escape') {\n close();\n }\n }}\n />\n )}\n <button\n className=\"gs-filter-remove-btn\"\n onClick={() => removeCondition(i)}\n disabled={filterDisabled}\n title=\"Remove condition\"\n >\n ✕\n </button>\n </div>\n ))}\n </div>\n <div className=\"gs-filter-actions\">\n {hasAnyFilter && (\n <button className=\"gs-filter-reset-all-btn\" onClick={handleResetAll}>\n RESET ALL\n </button>\n )}\n <div className=\"gs-filter-actions-right\">\n {colCell?.filter && (\n <button className=\"gs-filter-reset-btn\" onClick={handleResetColumn}>\n RESET\n </button>\n )}\n <button className=\"gs-filter-apply-btn\" onClick={handleApplyFilter} disabled={filterDisabled}>\n APPLY\n </button>\n </div>\n </div>\n </>\n </li>\n );\n};\n\nregisterMenuComponent('col-filter', FilterSection);\nexport { FilterSection };\n","import { type FC, useContext, useState, useCallback, useEffect } from 'react';\nimport { Context } from '../store';\nimport { sortRows } from '../store/actions';\nimport { operations as prevention } from '@gridsheet/web';\nimport { registerMenuComponent, type ColMenuSectionProps } from '../lib/menu';\n\ntype PendingSort = {\n x: number;\n direction: 'asc' | 'desc';\n};\n\nconst SortSection: FC<ColMenuSectionProps> = ({ x, close, onWaiting }) => {\n const { store, dispatch } = useContext(Context);\n const { sheetReactive: sheetRef } = store;\n const sheet = sheetRef.current;\n\n const [pending, setPending] = useState<PendingSort | null>(null);\n\n const handleCancel = useCallback(() => {\n setPending(null);\n onWaiting?.(null);\n close();\n }, [close, onWaiting]);\n\n // Notify parent about waiting state\n useEffect(() => {\n if (pending) {\n onWaiting?.('Sorting\\u2026', handleCancel);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pending]);\n\n // Execute pending sort after async formulas resolve\n useEffect(() => {\n if (!pending) {\n return;\n }\n let cancelled = false;\n const execute = () => {\n if (cancelled) {\n return;\n }\n const currentSheet = sheetRef.current;\n if (!currentSheet) {\n return;\n }\n dispatch(sortRows({ x: pending.x, direction: pending.direction }));\n onWaiting?.(null);\n setPending(null);\n close();\n };\n const currentSheet = sheetRef.current;\n if (currentSheet && (currentSheet.hasPendingCells() || currentSheet.registry.asyncPending.size > 0)) {\n currentSheet.waitForPending().then(execute);\n } else {\n execute();\n }\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pending]);\n\n if (!sheet) {\n return null;\n }\n\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const sortDisabled = prevention.hasOperation(colCell?.prevention, prevention.Sort);\n\n return (\n <li className={`gs-menu-item gs-column-menu-sort${sortDisabled ? ' gs-disabled' : ''}`}>\n <div className=\"gs-menu-name\">Sort:</div>\n <div className=\"gs-sort-buttons\">\n <button\n className=\"gs-sort-btn gs-sort-btn-asc\"\n onClick={(e) => {\n e.stopPropagation();\n if (!sortDisabled) {\n setPending({ x, direction: 'asc' });\n }\n }}\n disabled={sortDisabled}\n >\n ↓ A to Z\n </button>\n <button\n className=\"gs-sort-btn gs-sort-btn-desc\"\n onClick={(e) => {\n e.stopPropagation();\n if (!sortDisabled) {\n setPending({ x, direction: 'desc' });\n }\n }}\n disabled={sortDisabled}\n >\n ↑ Z to A\n </button>\n </div>\n </li>\n );\n};\n\nregisterMenuComponent('col-sort', SortSection);\nexport { SortSection };\n","import { type FC, useContext, useState, useCallback, useEffect, useRef } from 'react';\nimport { Context } from '../store';\nimport { setStore } from '../store/actions';\nimport { operations as prevention } from '@gridsheet/web';\nimport { x2c, p2a } from '@gridsheet/web';\nimport { getLabel } from '@gridsheet/web';\nimport { registerMenuComponent, type ColMenuSectionProps } from '../lib/menu';\n\nconst LabelSection: FC<ColMenuSectionProps> = ({ x, close }) => {\n const { store, dispatch } = useContext(Context);\n const { sheetReactive: sheetRef } = store;\n const sheet = sheetRef.current;\n const labelInputRef = useRef<HTMLInputElement>(null);\n const [label, setLabel] = useState('');\n\n // Restore label value when x changes\n useEffect(() => {\n if (sheet) {\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n setLabel(colCell?.label ?? '');\n }\n // When the menu was opened by double-clicking the header, jump straight into\n // renaming: focus the label input and select its text so a keystroke replaces\n // it. Double rAF so the controlled value has committed to the DOM before we\n // set the selection (otherwise React moves the caret to the end afterwards).\n if (store.columnMenuState?.focusLabel) {\n requestAnimationFrame(() =>\n requestAnimationFrame(() => {\n const input = labelInputRef.current;\n if (input) {\n input.focus();\n input.setSelectionRange(0, input.value.length);\n }\n }),\n );\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [x, sheet]);\n\n const handleApplyLabel = useCallback(() => {\n if (!sheet) {\n return;\n }\n const address = p2a({ y: 0, x });\n sheet.update({\n diff: { [address]: { label: label || undefined } },\n partial: true,\n ignoreFields: [],\n undoReflection: {\n sheetId: sheet.id,\n selectingZone: store.selectingZone,\n choosing: store.choosing,\n },\n redoReflection: {\n sheetId: sheet.id,\n selectingZone: store.selectingZone,\n choosing: store.choosing,\n },\n });\n dispatch(setStore({ sheetReactive: { current: sheet } }));\n close();\n }, [dispatch, x, label, close, sheet, store.selectingZone, store.choosing]);\n\n if (!sheet) {\n return null;\n }\n\n const colCell = sheet.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const labelDisabled = prevention.hasOperation(colCell?.prevention, prevention.SetLabel);\n const labelPlaceholder = getLabel(sheet, colCell?.label, { y: 0, x }, x) ?? x2c(x);\n\n return (\n <li className={`gs-menu-item gs-column-menu-label${labelDisabled ? ' gs-disabled' : ''}`}>\n <label className=\"gs-label-input-row\">\n <div className=\"gs-label-input-label\">Label:</div>\n <input\n ref={labelInputRef}\n className=\"gs-label-input\"\n type=\"text\"\n placeholder={labelPlaceholder}\n value={label}\n disabled={labelDisabled}\n onChange={(e) => setLabel(e.target.value)}\n onKeyDown={(e) => {\n if (e.nativeEvent.isComposing) {\n return;\n }\n if (e.key === 'Enter') {\n handleApplyLabel();\n }\n if (e.key === 'Escape') {\n close();\n }\n }}\n />\n <button className=\"gs-label-apply-btn\" onClick={handleApplyLabel} disabled={labelDisabled}>\n UPDATE\n </button>\n </label>\n </li>\n );\n};\n\nregisterMenuComponent('col-label', LabelSection);\nexport { LabelSection };\n","import { type FC, useContext, useCallback, useState } from 'react';\nimport { Context } from '../store';\nimport { setColumnMenu } from '../store/actions';\nimport { Fixed } from './Fixed';\nimport { focus } from '@gridsheet/web';\nimport { buildMenuContext } from '../lib/menu';\nimport { getMenuComponent } from '../lib/menu';\nimport { MenuNodes, type MenuNode } from './MenuNodes';\n\n// Import section modules so their registerMenuComponent() calls run at load time.\n// Users may override any of these ids via registerMenuComponent() after import.\nimport './ColumnMenuFilterSection';\nimport './ColumnMenuSortSection';\nimport './ColumnMenuLabelSection';\n\nexport const ColumnMenu: FC = () => {\n const { store, dispatch } = useContext(Context);\n const { columnMenuState, editorRef, colMenu } = store;\n const sheet = store.sheetReactive.current;\n\n const x = columnMenuState?.x;\n const position = columnMenuState?.position;\n\n const [waitingState, setWaitingState] = useState<{ message: string; cancel: () => void } | null>(null);\n\n const handleClose = useCallback(() => {\n dispatch(setColumnMenu(null));\n focus(editorRef.current);\n }, [dispatch, editorRef]);\n\n const handleWaiting = useCallback(\n (message: string | null, cancel?: () => void) => {\n if (message) {\n setWaitingState({ message, cancel: cancel ?? handleClose });\n } else {\n setWaitingState(null);\n }\n },\n [handleClose],\n );\n\n if (!columnMenuState || !sheet || x == null || !position) {\n return null;\n }\n\n const ctx = buildMenuContext(store, dispatch, handleClose);\n\n return (\n <Fixed\n className=\"gs-menu-modal gs-column-menu-modal\"\n onClick={(e: MouseEvent) => {\n e.preventDefault();\n if (!waitingState) {\n handleClose();\n }\n return false;\n }}\n >\n <div\n className=\"gs-column-menu\"\n style={{ top: position.y, left: position.x, display: waitingState ? 'none' : undefined }}\n onClick={(e) => e.stopPropagation()}\n >\n <ul className=\"gs-menu-items\">\n <MenuNodes\n items={colMenu as MenuNode[]}\n ctx={ctx}\n args={[x]}\n onSelect={() => dispatch(setColumnMenu(null))}\n renderComponent={(componentId, key) => {\n const Section = getMenuComponent(componentId);\n return Section ? <Section key={key} x={x} close={handleClose} onWaiting={handleWaiting} /> : null;\n }}\n />\n </ul>\n </div>\n {waitingState && (\n <div\n className=\"gs-column-menu gs-column-menu-waiting\"\n style={{ top: position.y, left: position.x }}\n onClick={(e) => e.stopPropagation()}\n >\n <div className=\"gs-waiting-message\">{waitingState.message}</div>\n <div className=\"gs-waiting-spinner\" />\n <button className=\"gs-waiting-cancel-btn\" onClick={waitingState.cancel}>\n CANCEL\n </button>\n </div>\n )}\n </Fixed>\n );\n};\n","import { type FC, useContext } from 'react';\nimport { Context } from '../store';\nimport { setRowMenu } from '../store/actions';\nimport { Fixed } from './Fixed';\nimport { focus } from '@gridsheet/web';\nimport { buildMenuContext } from '../lib/menu';\nimport { MenuNodes, type MenuNode } from './MenuNodes';\n\nexport const RowMenu: FC = () => {\n const { store, dispatch } = useContext(Context);\n const { rowMenuState, sheetReactive: sheetRef, editorRef, rowMenu } = store;\n const sheet = sheetRef.current;\n\n const y = rowMenuState?.y;\n const position = rowMenuState?.position;\n\n const handleClose = () => {\n dispatch(setRowMenu(null));\n focus(editorRef.current);\n };\n\n if (!rowMenuState || !sheet || y == null || !position) {\n return null;\n }\n\n const ctx = buildMenuContext(store, dispatch, handleClose);\n\n return (\n <Fixed\n className=\"gs-menu-modal gs-row-menu-modal\"\n onClick={(e: MouseEvent) => {\n e.preventDefault();\n handleClose();\n return false;\n }}\n >\n <div className=\"gs-row-menu\" style={{ top: position.y, left: position.x }} onClick={(e) => e.stopPropagation()}>\n <ul className=\"gs-menu-items\">\n <MenuNodes items={rowMenu as MenuNode[]} ctx={ctx} args={[y]} onSelect={handleClose} />\n </ul>\n </div>\n </Fixed>\n );\n};\n","export const isTouching = (e: React.TouchEvent | React.MouseEvent): boolean => {\n if (e.type.startsWith('touch')) {\n return (e as React.TouchEvent).touches.length > 0;\n }\n if (e.type.startsWith('mouse')) {\n const mouseEvent = e as React.MouseEvent;\n // left click only\n return !!(mouseEvent.buttons & 1) && mouseEvent.button === 0;\n }\n return false;\n};\n\n/**\n * Safely call preventDefault to avoid errors on touch events\n */\nexport const safePreventDefault = (e: React.MouseEvent | React.TouchEvent): void => {\n if (!e.type.startsWith('touch')) {\n e.preventDefault();\n }\n};\n","import { useContext, useRef, useCallback, useEffect, memo, useMemo, useState } from 'react';\nimport { x2c, y2r } from '@gridsheet/web';\nimport { zoneToArea, among, areaToRange } from '@gridsheet/web';\nimport {\n choose,\n select,\n drag,\n write,\n setEditorRect,\n setContextMenuPosition,\n setAutofillDraggingTo,\n setEditingAddress,\n setDragging,\n setStore,\n} from '../store/actions';\n\nimport { Context } from '../store';\nimport { FormulaError } from '@gridsheet/web';\nimport { Pending } from '@gridsheet/web';\nimport { insertRef, isRefInsertable } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { isXSheetFocused } from '../store/helpers';\nimport type { FC, RefObject } from 'react';\nimport { isTouching, safePreventDefault } from '../lib/events';\nimport type { UserSheet } from '@gridsheet/web';\nimport { calcBelowPosition, hAlignTransform, type PopupPosition } from '@gridsheet/web';\n\ntype Props = {\n y: number;\n x: number;\n};\n\nexport const Cell: FC<Props> = memo(({ y, x }) => {\n const rowId = y2r(y);\n const colId = x2c(x);\n const address = `${colId}${rowId}`;\n const { store, dispatch } = useContext(Context);\n const isFirstPointed = useRef(true);\n\n const cellRef = useRef<HTMLTableCellElement>(null);\n const [errorTooltipPos, setErrorTooltipPos] = useState<PopupPosition | null>(null);\n const {\n sheetReactive,\n editingAddress,\n choosing,\n selectingZone,\n leftHeaderSelecting,\n topHeaderSelecting,\n editorRef,\n autofillDraggingTo,\n contextMenu,\n } = store;\n const sheet = sheetReactive.current;\n\n // Whether the focus is on another sheet\n const xSheetFocused = isXSheetFocused(store);\n\n const lastFocused = sheet?.registry.lastFocused;\n\n const selectingArea = zoneToArea(selectingZone); // (top, left) -> (bottom, right)\n\n const editing = editingAddress === address;\n const pointed = choosing.y === y && choosing.x === x;\n const _setEditorRect = useCallback(() => {\n const rect = cellRef.current?.getBoundingClientRect();\n if (rect == null) {\n return null;\n }\n dispatch(\n setEditorRect({\n y: rect.y,\n x: rect.x,\n height: rect.height,\n width: rect.width,\n }),\n );\n }, [dispatch]);\n\n useEffect(() => {\n // Avoid setting coordinates on the initial render to account for shifts caused by redrawing due to virtualization.\n if (pointed && !isFirstPointed.current) {\n _setEditorRect();\n return;\n }\n isFirstPointed.current = false;\n }, [pointed, editing, _setEditorRect]);\n\n const cell = sheet?.getCell({ y, x }, { resolution: 'SYSTEM' });\n\n const writeCell = useCallback(\n (value: string) => {\n dispatch(write({ value }));\n },\n [dispatch],\n );\n\n const apply = useCallback(\n (sheet: UserSheet) => {\n dispatch(setStore({ sheetReactive: { current: sheet.__raw__ } }));\n },\n [dispatch],\n );\n\n let errorMessage = '';\n let rendered: any;\n try {\n if (sheet) {\n rendered = sheet.render({ sheet, point: { y, x }, apply, value: undefined });\n }\n } catch (e: any) {\n if (FormulaError.is(e)) {\n errorMessage = e.message;\n rendered = e.code;\n } else {\n errorMessage = e.message;\n rendered = '#UNKNOWN';\n }\n }\n const [, v] = sheet?.getSolvedCache({ y, x }) ?? [undefined, undefined];\n const isPendingCell = Pending.is(v);\n const input = editorRef.current;\n\n const editingAnywhere = !!(sheet?.registry.editingAddress || editingAddress);\n\n const handleDragStart = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n safePreventDefault(e);\n\n if (!sheet) {\n return false;\n }\n if (!isTouching(e)) {\n return false;\n }\n if (!input) {\n return false;\n }\n\n // Single cell selection only for touch events\n if (e.type.startsWith('touch')) {\n // Blur the input field to commit current value when selecting via touch\n if (editingAnywhere && input) {\n input.blur();\n }\n dispatch(choose({ y, x }));\n dispatch(select({ startY: y, startX: x, endY: y, endX: x }));\n return true;\n }\n\n // Normal drag operation for mouse events\n if (e.shiftKey) {\n dispatch(drag({ y, x }));\n } else {\n dispatch(select({ startY: y, startX: x, endY: -1, endX: -1 }));\n }\n\n dispatch(setDragging(true));\n const fullAddress = `${sheet.sheetPrefix(!xSheetFocused)}${address}`;\n if (editingAnywhere) {\n const inserted = insertRef({ input: lastFocused || null, ref: fullAddress });\n if (inserted) {\n return false;\n }\n }\n\n sheet.registry.lastFocused = input;\n focus(input);\n dispatch(setEditingAddress(''));\n\n if (autofillDraggingTo) {\n return false;\n }\n\n if (editingAnywhere) {\n writeCell(input.value);\n }\n if (!e.shiftKey) {\n dispatch(choose({ y, x }));\n }\n return true;\n },\n [editingAnywhere, input, address, xSheetFocused, lastFocused, autofillDraggingTo, writeCell, sheet],\n );\n\n const handleDragEnd = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n if (e.type.startsWith('touch')) {\n return;\n }\n\n safePreventDefault(e);\n dispatch(setDragging(false));\n // Autofill submit/clear is owned by StoreObserver's capture-phase window mouseup\n // (onUp) — the reliable place that always fires. Doing it here too would double-fill\n // (this bubble handler runs after onUp already cleared the store, with a stale\n // autofillDraggingTo closure). We only handle the formula-range-drag end.\n if (editingAnywhere) {\n dispatch(drag({ y: -1, x: -1 }));\n }\n },\n [editingAnywhere],\n );\n\n const handleDragging = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n if (!isTouching(e)) {\n return false;\n }\n\n // Do nothing for touch events\n if (e.type.startsWith('touch')) {\n return false;\n }\n\n if (!sheet) {\n return false;\n }\n\n safePreventDefault(e);\n e.stopPropagation();\n\n if (autofillDraggingTo) {\n dispatch(setAutofillDraggingTo({ x, y }));\n return false;\n }\n if (leftHeaderSelecting) {\n dispatch(drag({ y, x: sheet.numCols }));\n return false;\n }\n if (topHeaderSelecting) {\n dispatch(drag({ y: sheet.numRows, x }));\n return false;\n }\n if (editingAnywhere && !isRefInsertable(lastFocused || null)) {\n return false;\n }\n dispatch(drag({ y, x }));\n\n if (editingAnywhere) {\n const newArea = zoneToArea({ ...selectingZone, endY: y, endX: x });\n const fullRange = `${sheet.sheetPrefix(!xSheetFocused)}${areaToRange(newArea)}`;\n insertRef({ input: lastFocused || null, ref: fullRange });\n }\n //sheet.registry.transmit(); // Force drawing because the formula is not reflected in largeInput\n return true;\n },\n [\n autofillDraggingTo,\n leftHeaderSelecting,\n topHeaderSelecting,\n sheet,\n editingAnywhere,\n lastFocused,\n selectingZone,\n xSheetFocused,\n ],\n );\n\n const handleAutofillMouseDown = useCallback(\n (e: React.MouseEvent) => {\n dispatch(setAutofillDraggingTo({ x, y }));\n dispatch(setDragging(true));\n e.stopPropagation();\n },\n [dispatch, x, y],\n );\n\n const handleErrorTriangleEnter = useCallback(() => {\n const rect = cellRef.current?.getBoundingClientRect();\n if (!rect) {\n return;\n }\n setErrorTooltipPos(calcBelowPosition(rect));\n }, []);\n\n const handleErrorTriangleLeave = useCallback(() => {\n setErrorTooltipPos(null);\n }, []);\n\n // --- Memoize event handlers with useCallback ---\n const onContextMenu = useCallback(\n (e: React.MouseEvent<HTMLTableCellElement>) => {\n if (contextMenu.length > 0) {\n e.stopPropagation();\n safePreventDefault(e);\n dispatch(setContextMenuPosition({ y: e.clientY, x: e.clientX }));\n return false;\n }\n return true;\n },\n [contextMenu.length],\n );\n\n const onDoubleClick = useCallback(\n (e: React.MouseEvent<HTMLTableCellElement>) => {\n e.stopPropagation();\n safePreventDefault(e);\n setEditingAddress(address);\n const dblclick = document.createEvent('MouseEvents');\n dblclick.initEvent('dblclick', true, true);\n input?.dispatchEvent(dblclick);\n return false;\n },\n [address, input],\n );\n\n const autofillDragClass = useMemo(() => {\n if (!editing && pointed && selectingArea.bottom === -1) {\n return 'gs-autofill-drag';\n }\n\n if (selectingArea.bottom === y && selectingArea.right === x) {\n return 'gs-autofill-drag';\n }\n return 'gs-autofill-drag gs-hidden';\n }, [editing, pointed, selectingArea]);\n\n if (!sheet) {\n return null;\n }\n\n if (!input) {\n return (\n <td key={x} data-x={x} data-y={y} data-address={address} className=\"gs-cell gs-hidden\">\n <div className=\"gs-cell-inner-wrap\">\n <div className=\"gs-cell-inner\">\n <div className=\"gs-cell-rendered\"></div>\n </div>\n <div className=\"gs-autofill-drag\"></div>\n </div>\n </td>\n );\n }\n\n return (\n <td\n key={x}\n ref={cellRef}\n data-x={x}\n data-y={y}\n data-address={address}\n className={`gs-cell ${among(selectingArea, { y, x }) ? 'gs-selecting' : ''} ${pointed ? 'gs-choosing' : ''} ${\n editing ? 'gs-editing' : ''\n } ${isPendingCell ? 'gs-pending' : ''}`}\n style={{\n ...cell?.style,\n }}\n onContextMenu={onContextMenu}\n onDoubleClick={onDoubleClick}\n >\n <div\n className={`gs-cell-inner-wrap`}\n onMouseDown={handleDragStart}\n onTouchStart={handleDragStart}\n onMouseEnter={handleDragging}\n onMouseUp={handleDragEnd}\n >\n <div\n className={'gs-cell-inner'}\n style={{\n ...cell?.style,\n textAlign: cell?.style?.textAlign || cell?.justifyContent || 'left',\n alignItems: cell?.alignItems || 'start',\n }}\n >\n {errorMessage && (\n <div\n className=\"gs-formula-error-triangle\"\n onMouseEnter={handleErrorTriangleEnter}\n onMouseLeave={handleErrorTriangleLeave}\n />\n )}\n <div\n className=\"gs-cell-rendered\"\n style={\n cell?.alignItems\n ? {\n display: 'flex',\n flexDirection: 'column',\n justifyContent:\n cell.alignItems === 'center' ? 'center' : cell.alignItems === 'end' ? 'flex-end' : undefined,\n }\n : undefined\n }\n >\n {rendered}\n </div>\n </div>\n {errorMessage && errorTooltipPos && (\n <div\n className=\"gs-formula-error-tooltip\"\n style={{\n top: errorTooltipPos.y + 4,\n left: errorTooltipPos.x,\n transform: hAlignTransform(errorTooltipPos.hAlign),\n }}\n >\n {errorMessage}\n </div>\n )}\n <div className={autofillDragClass} onMouseDown={handleAutofillMouseDown}></div>\n </div>\n </td>\n );\n});\n","import type { CSSProperties } from 'react';\nimport { useEffect, useRef, useContext, useCallback } from 'react';\nimport { Context } from '../store';\nimport { drag, setAutofillDraggingTo, setDragging, submitAutofill } from '../store/actions';\nimport { getAreaInTabular } from '@gridsheet/web';\nimport { insertRef, isFocus } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { areaToRange, zoneToArea } from '@gridsheet/web';\nimport { isXSheetFocused } from '../store/helpers';\n\ntype Props = {\n className?: string;\n style: CSSProperties;\n horizontal?: number;\n vertical?: number;\n};\n\nconst acceleration = 0.4;\nconst maxSpeed = 200;\n\nlet lastScrollTime = new Date().getTime();\nlet currentSpeed = 0;\n\nexport function ScrollHandle({ style, horizontal = 0, vertical = 0, className = '' }: Props) {\n const scrollRef = useRef<number | null>(null);\n const { store, dispatch } = useContext(Context);\n const {\n tabularRef,\n autofillDraggingTo,\n dragging,\n selectingZone,\n editorRef,\n sheetReactive: sheetRef,\n searchInputRef,\n editingAddress,\n } = store;\n const sheet = sheetRef.current;\n\n // The rAF scroll loop below closes over one render's props. When it dispatches\n // (re-render), the running loop keeps the OLD closure — including a stale, still-truthy\n // autofillDraggingTo — so it re-arms the autofill every frame. Read the LIVE store\n // through a ref instead, so the loop sees the drag end and stops.\n const storeRef = useRef(store);\n storeRef.current = store;\n\n let isScrolling = false;\n const xSheetFocused = isXSheetFocused(store);\n const editingAnywhere = !!(sheet?.registry.editingAddress || editingAddress);\n\n const getDestEdge = useCallback(\n (e: React.MouseEvent) => {\n if (!sheet) {\n return { x: -1, y: -1 };\n }\n if (horizontal == 0 && vertical == 0) {\n const tabularRect = tabularRef.current!.getBoundingClientRect();\n const { left, top, right, bottom } = tabularRect;\n horizontal = e.pageX > right ? 1 : e.pageX < left ? -1 : 0;\n if (horizontal === 0) {\n vertical = e.pageY > bottom ? 1 : e.pageY < top ? -1 : 0;\n }\n }\n const area = getAreaInTabular(tabularRef.current!);\n let { endX: x, endY: y } = selectingZone;\n if (horizontal) {\n x = horizontal > 0 ? area.right : area.left;\n } else if (vertical) {\n y = vertical > 0 ? area.bottom : area.top;\n }\n return { x, y };\n },\n [sheet, horizontal, vertical, selectingZone],\n );\n\n const scrollStep = useCallback(\n (e: React.MouseEvent) => {\n if (!isScrolling || tabularRef.current === null || !sheet) {\n return;\n }\n // The drag has ended (the mouseup landed off this strip, e.g. on a cell, or the\n // strip hid at the edge so its onMouseUp/onMouseLeave never fired). Stop now —\n // otherwise this loop keeps scrolling and re-dispatching setAutofillDraggingTo\n // forever, so the autofill can never be cleared and the grid can't be scrolled.\n const live = storeRef.current;\n if (!live.dragging && !live.autofillDraggingTo) {\n if (scrollRef.current !== null) {\n cancelAnimationFrame(scrollRef.current);\n scrollRef.current = null;\n }\n isScrolling = false;\n return;\n }\n const now = new Date().getTime();\n if (now - lastScrollTime > 1000) {\n currentSpeed = 0;\n }\n lastScrollTime = now;\n\n tabularRef.current.scrollBy({\n left: currentSpeed * horizontal!,\n top: currentSpeed * vertical!,\n });\n focus(editorRef.current);\n\n const { x, y } = getDestEdge(e);\n if (live.autofillDraggingTo) {\n const { y: curY, x: curX } = live.autofillDraggingTo;\n dispatch(setAutofillDraggingTo({ y: y === -1 ? curY : y, x: x === -1 ? curX : x }));\n } else {\n if (editingAnywhere) {\n const newArea = zoneToArea({ ...selectingZone, endY: y, endX: x });\n const sheetPrefix = sheet.sheetPrefix(!xSheetFocused);\n const sheetRange = areaToRange(newArea);\n const fullRange = `${sheetPrefix}${sheetRange}`;\n insertRef({ input: editorRef.current, ref: fullRange });\n }\n dispatch(drag({ y, x }));\n }\n currentSpeed = Math.min(currentSpeed + acceleration, maxSpeed);\n scrollRef.current = requestAnimationFrame(() => scrollStep(e));\n },\n [\n isScrolling,\n sheet,\n horizontal,\n vertical,\n autofillDraggingTo,\n editingAnywhere,\n selectingZone,\n xSheetFocused,\n getDestEdge,\n ],\n );\n\n const handleMouseEnter = useCallback(\n (e: React.MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n if (isScrolling) {\n return;\n }\n isScrolling = true;\n\n if (horizontal === 0 || vertical === 0) {\n const tabularRect = tabularRef.current!.getBoundingClientRect();\n const { left, top, right, bottom } = tabularRect;\n\n horizontal ||= e.pageX > right ? 1 : e.pageX < left ? -1 : 0;\n if (horizontal === 0) {\n vertical ||= e.pageY > bottom ? 1 : e.pageY < top ? -1 : 0;\n }\n }\n scrollRef.current = requestAnimationFrame(() => scrollStep(e));\n },\n [isScrolling, horizontal, vertical, scrollStep],\n );\n\n const stopScroll = useCallback(() => {\n if (scrollRef.current !== null) {\n cancelAnimationFrame(scrollRef.current);\n scrollRef.current = null;\n }\n isScrolling = false;\n if (!isFocus(searchInputRef.current)) {\n // Pressing Enter on a search result will not focus the editor.\n focus(editorRef.current);\n }\n }, []);\n\n const handleMouseUp = useCallback(\n (e: React.MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n const area = getAreaInTabular(tabularRef.current!);\n if (area.bottom === -1 || area.right === -1) {\n return;\n }\n\n const { x, y } = getDestEdge(e);\n if (autofillDraggingTo) {\n const { y: curY, x: curX } = autofillDraggingTo;\n dispatch(submitAutofill({ y: y === -1 ? curY : y, x: x === -1 ? curX : x }));\n focus(editorRef.current);\n } else {\n if (editingAnywhere) {\n // inserting a range\n dispatch(drag({ y: -1, x: -1 })); // Reset dragging\n }\n }\n },\n [autofillDraggingTo, editingAnywhere, getDestEdge],\n );\n\n const handleMouseUpWrapper = useCallback(\n (e: React.MouseEvent) => {\n stopScroll();\n dispatch(setDragging(false));\n requestAnimationFrame(() => handleMouseUp(e));\n },\n [stopScroll, handleMouseUp],\n );\n\n const handleMouseLeave = useCallback(() => {\n stopScroll();\n }, [stopScroll]);\n\n useEffect(() => {\n return stopScroll;\n }, [stopScroll]);\n\n // The directional auto-scroll strips (right/bottom/left/top edges) sit on top of the\n // grid (zIndex). At an edge where there is nothing left to scroll to, such a strip only\n // gets in the way — e.g. it covers the rightmost column's cells, so dragging the\n // autofill handle straight down stays over the strip and never reaches the cells below.\n // Only render a directional strip while it can actually scroll in that direction; the\n // beyond-edge catch-all handle (horizontal === 0 && vertical === 0) always renders.\n const t = tabularRef.current;\n const cannotScrollHere =\n !!t &&\n ((horizontal > 0 && t.scrollLeft + t.clientWidth >= t.scrollWidth - 1) ||\n (horizontal < 0 && t.scrollLeft <= 0) ||\n (vertical > 0 && t.scrollTop + t.clientHeight >= t.scrollHeight - 1) ||\n (vertical < 0 && t.scrollTop <= 0));\n\n if (!editorRef.current || (!dragging && !autofillDraggingTo) || cannotScrollHere) {\n return <div className={`gs-scroll-handle gs-hidden ${className}`} />;\n }\n\n return (\n <div\n style={style}\n className={`gs-scroll-handle ${className}`}\n onMouseUp={(e) => {\n handleMouseUpWrapper(e);\n }}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n />\n );\n}\n","import type { FC } from 'react';\nimport { useContext, useCallback, memo, useRef } from 'react';\nimport { x2c } from '@gridsheet/web';\nimport { getLabel } from '@gridsheet/web';\nimport { between, zoneToArea } from '@gridsheet/web';\nimport { Context } from '../store';\nimport {\n choose,\n drag,\n select,\n selectCols,\n setAutofillDraggingTo,\n setColumnMenu,\n setContextMenuPosition,\n setDragging,\n setEditingAddress,\n setResizingPositionX,\n submitAutofill,\n write,\n} from '../store/actions';\nimport { DEFAULT_WIDTH } from '@gridsheet/web';\nimport { operations as prevention } from '@gridsheet/web';\nimport { insertRef } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { isXSheetFocused } from '../store/helpers';\nimport { ScrollHandle } from './ScrollHandle';\nimport { isTouching, safePreventDefault } from '../lib/events';\nimport { useDebounceCallback } from '../lib/hooks';\n\ntype Props = {\n x: number;\n};\n\nexport const HeaderCellTop: FC<Props> = memo(({ x }) => {\n const colId = x2c(x);\n const { store, dispatch } = useContext(Context);\n\n const {\n sheetReactive: sheetRef,\n editingAddress,\n choosing,\n selectingZone,\n topHeaderSelecting,\n editorRef,\n autofillDraggingTo,\n dragging,\n contextMenu,\n columnMenuState,\n } = store;\n const sheet = sheetRef.current;\n\n const col = sheet?.getCell({ y: 0, x }, { resolution: 'SYSTEM' });\n const width = col?.width || DEFAULT_WIDTH;\n const hasFilter = !!(col?.filter && col.filter.conditions.length > 0);\n\n const xSheetFocused = isXSheetFocused(store);\n const lastFocused = sheet?.registry.lastFocused;\n\n const editingAnywhere = !!(sheet?.registry.editingAddress || editingAddress);\n\n const writeCell = useCallback(\n (value: string) => {\n dispatch(write({ value, point: choosing }));\n },\n [choosing],\n );\n\n const handleResizeMouseDown = useCallback((e: React.MouseEvent) => {\n dispatch(setResizingPositionX([x, e.clientX, e.clientX]));\n e.stopPropagation();\n safePreventDefault(e);\n }, []);\n\n const handleDragStart = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n safePreventDefault(e);\n\n if (!isTouching(e) || !sheet) {\n return false;\n }\n\n if (dragging) {\n return false;\n }\n\n // Single column selection only for touch events\n if (e.type.startsWith('touch')) {\n // Blur the input field to commit current value when selecting via touch\n if (editingAnywhere && editorRef.current) {\n editorRef.current.blur();\n }\n dispatch(choose({ y: 1, x }));\n dispatch(select({ startY: 1, startX: x, endY: sheet.numRows, endX: x }));\n return true;\n }\n\n dispatch(select({ startY: 1, startX: x, endY: -1, endX: x }));\n const fullAddress = `${sheet.sheetPrefix(!xSheetFocused)}${colId}:${colId}`;\n if (editingAnywhere) {\n const inserted = insertRef({ input: lastFocused || null, ref: fullAddress });\n if (inserted) {\n dispatch(select({ startY: sheet.numRows, startX: x, endY: 0, endX: x }));\n return false;\n }\n }\n\n let startX = e.shiftKey ? selectingZone.startX : x;\n if (startX === -1) {\n startX = choosing.x;\n }\n\n dispatch(\n selectCols({\n range: { start: startX, end: x },\n numRows: sheet.numRows,\n }),\n );\n\n if (editingAnywhere) {\n writeCell(lastFocused?.value ?? '');\n }\n dispatch(setEditingAddress(''));\n dispatch(setDragging(true));\n focus(editorRef.current);\n\n if (autofillDraggingTo) {\n return false;\n }\n return true;\n },\n [\n dragging,\n editingAnywhere,\n xSheetFocused,\n colId,\n lastFocused,\n selectingZone,\n choosing,\n autofillDraggingTo,\n editorRef,\n ],\n );\n\n const handleDragEnd = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n if (e.type.startsWith('touch')) {\n return;\n }\n\n safePreventDefault(e);\n dispatch(setDragging(false));\n if (autofillDraggingTo) {\n focus(editorRef.current);\n return false;\n }\n },\n [autofillDraggingTo],\n );\n\n const handleDragging = useDebounceCallback((e: React.MouseEvent | React.TouchEvent) => {\n if (!isTouching(e) || !sheet) {\n return false;\n }\n\n if (e.type.startsWith('touch')) {\n return false;\n }\n\n safePreventDefault(e);\n e.stopPropagation();\n\n if (autofillDraggingTo) {\n dispatch(setAutofillDraggingTo({ y: 1, x }));\n return false;\n }\n\n if (editingAnywhere) {\n const newArea = zoneToArea({ ...selectingZone, endY: 1, endX: x });\n const [left, right] = [x2c(newArea.left), x2c(newArea.right)];\n const fullRange = `${sheet.sheetPrefix(!xSheetFocused)}${left}:${right}`;\n insertRef({ input: lastFocused || null, ref: fullRange });\n }\n\n if (autofillDraggingTo == null) {\n const { startY } = selectingZone;\n if (startY === 1) {\n dispatch(drag({ y: sheet.numRows, x }));\n } else {\n dispatch(drag({ y: 1, x }));\n }\n }\n return false;\n }, 100);\n\n if (!sheet) {\n return (\n <th data-x={x} className=\"gs-th gs-th-top gs-hidden\">\n <div className=\"gs-th-inner-wrap\">\n <div className=\"gs-th-inner\">\n <ScrollHandle style={{ position: 'absolute' }} vertical={-1} />\n <div className=\"gs-resizer\"></div>\n </div>\n </div>\n </th>\n );\n }\n\n return (\n <th\n data-x={x}\n className={`gs-th gs-th-top ${choosing.x === x ? 'gs-choosing' : ''} ${\n between({ start: selectingZone.startX, end: selectingZone.endX }, x)\n ? topHeaderSelecting\n ? 'gs-th-selecting'\n : 'gs-selecting'\n : ''\n }`}\n style={{ ...col?.style, width, minWidth: width, maxWidth: width }}\n onDoubleClick={(e) => {\n // Double-clicking the header opens the column menu straight into label\n // editing (label section is first, its input focused + all-selected).\n // Ignore double-clicks on the resizer or the ⋮ menu button.\n const target = e.target as HTMLElement;\n if (target.closest('.gs-resizer, .gs-menu-btn')) {\n return;\n }\n if (prevention.hasOperation(col?.prevention, prevention.ColumnMenu)) {\n return;\n }\n e.stopPropagation();\n const inner = (e.currentTarget as HTMLElement).querySelector('.gs-th-inner') as HTMLElement | null;\n const rect = (inner ?? (e.currentTarget as HTMLElement)).getBoundingClientRect();\n const alreadySelected =\n between({ start: selectingZone.startX, end: selectingZone.endX }, x) &&\n selectingZone.startY === 1 &&\n selectingZone.endY === sheet.numRows;\n if (!alreadySelected) {\n dispatch(selectCols({ range: { start: x, end: x }, numRows: sheet.numRows }));\n }\n dispatch(setColumnMenu({ x, position: { y: rect.bottom, x: rect.left }, focusLabel: true }));\n }}\n onContextMenu={(e) => {\n if (contextMenu.length > 0) {\n e.stopPropagation();\n safePreventDefault(e);\n dispatch(setContextMenuPosition({ y: e.clientY, x: e.clientX }));\n return false;\n }\n return true;\n }}\n >\n <div\n className=\"gs-th-inner-wrap\"\n onMouseDown={handleDragStart}\n onTouchStart={handleDragStart}\n onMouseEnter={handleDragging}\n onMouseUp={handleDragEnd}\n >\n <div className=\"gs-th-inner\" style={{ height: sheet.headerHeight, position: 'relative' }}>\n <ScrollHandle\n style={{\n position: 'absolute',\n zIndex: topHeaderSelecting ? -1 : 1,\n }}\n vertical={-1}\n />\n {(() => {\n const displayedLabel = getLabel(sheet, col?.label, { y: 0, x }, x) ?? colId;\n if (displayedLabel !== colId) {\n return (\n <>\n <span className=\"gs-col-addr\">{colId}</span>\n {displayedLabel}\n </>\n );\n }\n return displayedLabel;\n })()}\n {!prevention.hasOperation(col?.prevention, prevention.ColumnMenu) && (\n <button\n className={`gs-menu-btn gs-column-menu-btn ${hasFilter ? 'gs-filtered' : ''} ${columnMenuState?.x === x ? 'gs-active' : ''}`}\n onMouseDown={(e) => {\n e.stopPropagation();\n e.preventDefault();\n (e.currentTarget as HTMLElement).dataset.pressX = String(e.clientX);\n (e.currentTarget as HTMLElement).dataset.pressY = String(e.clientY);\n }}\n onMouseUp={(e) => {\n e.stopPropagation();\n const btn = e.currentTarget as HTMLElement;\n const pressX = Number(btn.dataset.pressX ?? e.clientX);\n const pressY = Number(btn.dataset.pressY ?? e.clientY);\n const moved = Math.abs(e.clientX - pressX) > 4 || Math.abs(e.clientY - pressY) > 4;\n if (moved) {\n return; // was a drag, ignore\n }\n const rect = btn.getBoundingClientRect();\n if (columnMenuState?.x === x) {\n dispatch(setColumnMenu(null));\n } else {\n const alreadySelected =\n between({ start: selectingZone.startX, end: selectingZone.endX }, x) &&\n selectingZone.startY === 1 &&\n selectingZone.endY === sheet.numRows;\n if (!alreadySelected) {\n dispatch(selectCols({ range: { start: x, end: x }, numRows: sheet.numRows }));\n }\n dispatch(setColumnMenu({ x, position: { y: rect.bottom, x: rect.left } }));\n }\n }}\n >\n ⋮\n </button>\n )}\n <div\n className={`\n gs-resizer \n ${prevention.hasOperation(col?.prevention, prevention.Resize) ? 'gs-protected' : ''}\n ${dragging ? 'gs-hidden' : ''}`}\n style={{ height: sheet.headerHeight }}\n onMouseDown={handleResizeMouseDown}\n >\n <i />\n </div>\n </div>\n </div>\n </th>\n );\n});\n","import type { FC } from 'react';\nimport { useContext, useCallback, memo, useRef } from 'react';\nimport { y2r } from '@gridsheet/web';\nimport { getLabel } from '@gridsheet/web';\nimport { between, zoneToArea } from '@gridsheet/web';\nimport { Context } from '../store';\nimport {\n choose,\n drag,\n select,\n selectRows,\n setAutofillDraggingTo,\n setContextMenuPosition,\n setDragging,\n setEditingAddress,\n setResizingPositionY,\n setRowMenu,\n submitAutofill,\n write,\n} from '../store/actions';\nimport { DEFAULT_HEIGHT } from '@gridsheet/web';\nimport { operations as prevention } from '@gridsheet/web';\nimport { insertRef } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { isXSheetFocused } from '../store/helpers';\nimport { ScrollHandle } from './ScrollHandle';\nimport { isTouching, safePreventDefault } from '../lib/events';\nimport { useDebounceCallback } from '../lib/hooks';\n\ntype Props = {\n y: number;\n};\n\nexport const HeaderCellLeft: FC<Props> = memo(({ y }) => {\n const rowId = `${y2r(y)}`;\n const { store, dispatch } = useContext(Context);\n\n const {\n choosing,\n editingAddress,\n selectingZone,\n leftHeaderSelecting,\n editorRef,\n sheetReactive: sheetRef,\n autofillDraggingTo,\n dragging,\n contextMenu,\n rowMenuState,\n } = store;\n const sheet = sheetRef.current;\n\n const row = sheet?.getCell({ y, x: 0 }, { resolution: 'SYSTEM' });\n const height = row?.height || DEFAULT_HEIGHT;\n\n const xSheetFocused = isXSheetFocused(store);\n const lastFocused = sheet?.registry.lastFocused;\n\n const editingAnywhere = !!(sheet?.registry.editingAddress || editingAddress);\n\n const writeCell = useCallback(\n (value: string) => {\n dispatch(write({ value, point: choosing }));\n },\n [choosing],\n );\n\n const handleResizeMouseDown = useCallback((e: React.MouseEvent) => {\n dispatch(setResizingPositionY([y, e.clientY, e.clientY]));\n e.stopPropagation();\n safePreventDefault(e);\n }, []);\n\n const handleDragStart = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n safePreventDefault(e);\n\n if (!isTouching(e) || !sheet) {\n return false;\n }\n if (dragging) {\n return false;\n }\n\n // Single row selection only for touch events\n if (e.type.startsWith('touch')) {\n // Blur the input field to commit current value when selecting via touch\n if (editingAnywhere && editorRef.current) {\n editorRef.current.blur();\n }\n dispatch(choose({ y, x: 1 }));\n dispatch(select({ startY: y, startX: 1, endY: y, endX: sheet.numCols }));\n return true;\n }\n\n // Normal drag operation for mouse events\n dispatch(select({ startY: y, startX: 1, endY: y, endX: -1 }));\n const fullAddress = `${sheet.sheetPrefix(!xSheetFocused)}${rowId}:${rowId}`;\n if (editingAnywhere) {\n const inserted = insertRef({ input: lastFocused || null, ref: fullAddress });\n if (inserted) {\n dispatch(select({ startY: y, startX: sheet.numCols, endY: y, endX: 0 }));\n return false;\n }\n }\n\n let startY = e.shiftKey ? selectingZone.startY : y;\n if (startY === -1) {\n startY = choosing.y;\n }\n\n dispatch(\n selectRows({\n range: { start: startY, end: y },\n numCols: sheet.numCols,\n }),\n );\n\n if (editingAnywhere) {\n writeCell(lastFocused?.value ?? '');\n }\n dispatch(setEditingAddress(''));\n dispatch(setDragging(true));\n focus(editorRef.current);\n\n if (autofillDraggingTo) {\n return false;\n }\n return true;\n },\n [\n dragging,\n editingAnywhere,\n xSheetFocused,\n rowId,\n lastFocused,\n selectingZone,\n choosing,\n autofillDraggingTo,\n editorRef,\n ],\n );\n\n const handleDragEnd = useCallback(\n (e: React.MouseEvent | React.TouchEvent) => {\n e.stopPropagation();\n if (e.type.startsWith('touch')) {\n return;\n }\n\n safePreventDefault(e);\n dispatch(setDragging(false));\n if (autofillDraggingTo) {\n focus(editorRef.current);\n return false;\n }\n },\n [autofillDraggingTo],\n );\n\n const handleDragging = useDebounceCallback((e: React.MouseEvent | React.TouchEvent) => {\n if (!isTouching(e) || !sheet) {\n return false;\n }\n\n // Do nothing for touch events\n if (e.type.startsWith('touch')) {\n return false;\n }\n\n safePreventDefault(e);\n e.stopPropagation();\n\n if (autofillDraggingTo) {\n dispatch(setAutofillDraggingTo({ y, x: 1 }));\n return false;\n }\n\n if (editingAnywhere) {\n const newArea = zoneToArea({ ...selectingZone, endY: y, endX: 1 });\n const [top, bottom] = [y2r(newArea.top), y2r(newArea.bottom)];\n const fullRange = `${sheet.sheetPrefix(!xSheetFocused)}${top}:${bottom}`;\n insertRef({ input: lastFocused || null, ref: fullRange });\n }\n\n if (autofillDraggingTo == null) {\n const { startX } = selectingZone;\n if (startX === 1) {\n dispatch(drag({ y, x: sheet.numCols }));\n } else {\n dispatch(drag({ y, x: 1 }));\n }\n }\n return false;\n }, 100);\n\n const handleContextMenu = useCallback(\n (e: React.MouseEvent<HTMLTableCellElement>) => {\n if (contextMenu.length > 0) {\n e.stopPropagation();\n safePreventDefault(e);\n dispatch(setContextMenuPosition({ y: e.clientY, x: e.clientX }));\n return false;\n }\n return true;\n },\n [contextMenu.length],\n );\n\n if (!sheet) {\n return null;\n }\n\n return (\n <th\n data-y={y}\n className={`gs-th gs-th-left ${choosing.y === y ? 'gs-choosing' : ''} ${\n between({ start: selectingZone.startY, end: selectingZone.endY }, y)\n ? leftHeaderSelecting\n ? 'gs-th-selecting'\n : 'gs-selecting'\n : ''\n } ${row?.filterFixed ? 'gs-filter-fixed' : ''} ${row?.sortFixed ? 'gs-sort-fixed' : ''}`}\n style={{ ...row?.style, height }}\n onContextMenu={handleContextMenu}\n >\n <div\n className=\"gs-th-inner-wrap\"\n onMouseDown={handleDragStart}\n onTouchStart={handleDragStart}\n onMouseEnter={handleDragging}\n onMouseUp={handleDragEnd}\n >\n <div className=\"gs-th-inner\" style={{ width: sheet.headerWidth, position: 'relative' }}>\n <ScrollHandle\n style={{\n position: 'absolute',\n zIndex: leftHeaderSelecting ? -1 : 1,\n }}\n horizontal={-1}\n />\n {getLabel(sheet, row?.label, { y, x: 0 }, y) ?? rowId}\n {!prevention.hasOperation(row?.prevention, prevention.RowMenu) && (\n <button\n className={`gs-menu-btn gs-row-menu-btn ${rowMenuState?.y === y ? 'gs-active' : ''}`}\n onMouseDown={(e) => {\n e.stopPropagation();\n e.preventDefault();\n (e.currentTarget as HTMLElement).dataset.pressX = String(e.clientX);\n (e.currentTarget as HTMLElement).dataset.pressY = String(e.clientY);\n }}\n onMouseUp={(e) => {\n e.stopPropagation();\n const btn = e.currentTarget as HTMLElement;\n const pressX = Number(btn.dataset.pressX ?? e.clientX);\n const pressY = Number(btn.dataset.pressY ?? e.clientY);\n const moved = Math.abs(e.clientX - pressX) > 4 || Math.abs(e.clientY - pressY) > 4;\n if (moved) {\n return; // was a drag, ignore\n }\n const rect = btn.getBoundingClientRect();\n if (rowMenuState?.y === y) {\n dispatch(setRowMenu(null));\n } else {\n const alreadySelected =\n between({ start: selectingZone.startY, end: selectingZone.endY }, y) &&\n selectingZone.startX === 1 &&\n selectingZone.endX === sheet.numCols;\n if (!alreadySelected) {\n dispatch(selectRows({ range: { start: y, end: y }, numCols: sheet.numCols }));\n }\n dispatch(setRowMenu({ y, position: { y: rect.bottom, x: rect.right } }));\n }\n }}\n >\n ⋮\n </button>\n )}\n <div\n className={`\n gs-resizer\n ${prevention.hasOperation(row?.prevention, prevention.Resize) ? 'gs-protected' : ''}\n ${dragging ? 'gs-hidden' : ''}`}\n style={{ width: sheet.headerWidth }}\n onMouseDown={handleResizeMouseDown}\n ></div>\n </div>\n </div>\n </th>\n );\n});\n","import { useContext, useEffect, useRef, useCallback } from 'react';\nimport { Context } from '../store';\nimport { zoneToArea } from '@gridsheet/web';\nimport { between } from '@gridsheet/web';\nimport { a2p } from '@gridsheet/web';\nimport { COLOR_PALETTE } from '@gridsheet/web';\nimport { Autofill } from '@gridsheet/web';\nimport { getCellRectPositions, getVisibleRowRange, getVisibleColRange, toVirtualScrollTop } from '@gridsheet/web';\nimport type { Sheet } from '@gridsheet/web';\nimport type { FC } from 'react';\nimport type { RefPaletteType, AreaType, ModeType } from '../types';\n\nconst COLOR_POINTED = 'rgba(0, 119, 255, 1)';\nconst COLOR_SELECTED = 'rgba(0, 119, 255, 0.6)';\nconst SELECTING_FILL = 'rgba(0, 128, 255, 0.2)';\nconst COLOR_COPYING = '#0077ff';\nconst COLOR_CUTTING = '#0077ff';\nconst SEARCH_MATCHING_BACKGROUND = 'rgba(0, 200, 100, 0.2)';\nconst COLOR_SEARCH_MATCHING = '#00aa78';\nconst COLOR_AUTOFILL = '#0077aa';\n\nconst HEADER_COLORS = {\n light: {\n selecting: 'rgba(0, 0, 0, 0.1)',\n choosing: 'rgba(0, 0, 0, 0.2)',\n thSelecting: 'rgba(0, 0, 0, 0.55)',\n },\n dark: {\n selecting: 'rgba(255, 255, 255, 0.08)',\n choosing: 'rgba(255, 255, 255, 0.18)',\n thSelecting: 'rgba(255, 255, 255, 0.4)',\n },\n} as const;\n\ntype Props = {\n refs?: RefPaletteType;\n};\n\ntype Ctx2D = CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\n\nconst fillRect = (ctx: Ctx2D, x: number, y: number, width: number, height: number, color: string) => {\n ctx.fillStyle = color;\n ctx.fillRect(x, y, width, height);\n};\n\nconst drawRect = (\n ctx: Ctx2D,\n x: number,\n y: number,\n width: number,\n height: number,\n color: string,\n lineWidth: number = 2,\n dashPattern: number[] = [],\n fillColor?: string,\n) => {\n if (fillColor) {\n ctx.fillStyle = fillColor;\n ctx.fillRect(x, y, width, height);\n }\n\n ctx.strokeStyle = color;\n ctx.lineWidth = lineWidth;\n ctx.setLineDash(dashPattern);\n ctx.strokeRect(x + lineWidth / 2, y + lineWidth / 2, width - lineWidth, height - lineWidth);\n ctx.setLineDash([]);\n};\n\n// Draw an area rect in viewport coordinates (absolute coords - scroll offset, clamped to viewport)\nconst drawAreaRectViewport = (\n ctx: Ctx2D,\n sheet: Sheet,\n scrollTop: number,\n scrollLeft: number,\n viewW: number,\n viewH: number,\n area: AreaType,\n color: string,\n lineWidth: number = 2,\n dashPattern: number[] = [],\n fillColor?: string,\n) => {\n const { top, left, bottom, right } = area;\n if (top === -1 || left === -1 || bottom === -1 || right === -1) {\n return;\n }\n\n const topLeft = getCellRectPositions(sheet, { y: top, x: left });\n const bottomRight = getCellRectPositions(sheet, { y: bottom, x: right });\n\n const x1 = topLeft.left - scrollLeft;\n const y1 = topLeft.top - scrollTop;\n const x2 = bottomRight.right - scrollLeft;\n const y2 = bottomRight.bottom - scrollTop;\n\n // Quick reject if entirely off-screen\n if (x2 < 0 || x1 > viewW || y2 < 0 || y1 > viewH) {\n return;\n }\n\n drawRect(ctx, x1, y1, x2 - x1, y2 - y1, color, lineWidth, dashPattern, fillColor);\n};\n\nexport const CellStateOverlay: FC<Props> = ({ refs = {} }) => {\n const { store } = useContext(Context);\n const {\n sheetReactive,\n tabularRef,\n choosing,\n selectingZone,\n matchingCells,\n matchingCellIndex,\n autofillDraggingTo,\n topHeaderSelecting,\n leftHeaderSelecting,\n mode,\n dragging,\n } = store;\n const sheet = sheetReactive.current;\n const canvasRef = useRef<HTMLCanvasElement>(null);\n const rafIdRef = useRef<number>(0);\n const storeRef = useRef(store);\n storeRef.current = store;\n\n const drawCanvas = useCallback(() => {\n if (!sheet || !tabularRef.current || !canvasRef.current) {\n return;\n }\n\n const canvas = canvasRef.current;\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n return;\n }\n\n const container = tabularRef.current;\n const dpr = window.devicePixelRatio || 1;\n const w = container.clientWidth;\n const h = container.clientHeight;\n\n // Resize canvas to viewport\n if (canvas.width !== w * dpr || canvas.height !== h * dpr) {\n canvas.style.width = `${w}px`;\n canvas.style.height = `${h}px`;\n canvas.width = w * dpr;\n canvas.height = h * dpr;\n }\n ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n ctx.clearRect(0, 0, w, h);\n\n const { registry } = sheet;\n // Vertical overlay math is all in virtual space (getCellRectPositions.top is virtual),\n // so map the DOM's capped physical scrollTop into virtual space. Horizontal columns\n // aren't remapped, so scrollLeft stays physical.\n const scrollTop = toVirtualScrollTop(sheet, container.scrollTop, container.clientHeight);\n const scrollLeft = container.scrollLeft;\n const headerW = sheet.headerWidth;\n const headerH = sheet.headerHeight;\n\n // Clip cell-area drawing to exclude header region\n ctx.save();\n ctx.beginPath();\n ctx.rect(headerW, headerH, w - headerW, h - headerH);\n ctx.clip();\n\n // 1. Selecting zone (border + fill)\n const selectingArea = zoneToArea(selectingZone);\n drawAreaRectViewport(ctx, sheet, scrollTop, scrollLeft, w, h, selectingArea, COLOR_SELECTED, 1, [], SELECTING_FILL);\n\n // 2. Autofill dragging\n if (autofillDraggingTo) {\n const autofill = new Autofill(storeRef.current, autofillDraggingTo);\n drawAreaRectViewport(ctx, sheet, scrollTop, scrollLeft, w, h, autofill.wholeArea, COLOR_AUTOFILL, 1, [5, 5]);\n }\n\n // 3. Choosing (pointed cell)\n {\n const { y, x } = choosing;\n if (y !== -1 && x !== -1) {\n const pos = getCellRectPositions(sheet, { y, x });\n const vx = pos.left - scrollLeft;\n const vy = pos.top - scrollTop;\n drawRect(ctx, vx, vy, pos.width, pos.height, COLOR_POINTED, 2, []);\n }\n }\n\n // 4. Copying/Cutting zone\n const { copyingSheetId, copyingZone, cutting } = registry;\n if (sheet.id === copyingSheetId) {\n const copyingArea = zoneToArea(copyingZone);\n const color = cutting ? COLOR_CUTTING : COLOR_COPYING;\n const dashPattern = cutting ? [4, 4] : [6, 4];\n drawAreaRectViewport(ctx, sheet, scrollTop, scrollLeft, w, h, copyingArea, color, 2.5, dashPattern);\n }\n\n // 5. Formula references (from palette)\n Object.entries(refs).forEach(([ref, i]) => {\n const palette = COLOR_PALETTE[i % COLOR_PALETTE.length];\n try {\n const refArea = sheet.rangeToArea(ref);\n drawAreaRectViewport(ctx, sheet, scrollTop, scrollLeft, w, h, refArea, palette, 2, [5, 5]);\n } catch (e) {\n // Invalid reference, skip\n }\n });\n\n // 6. Search matching cells\n matchingCells.forEach((address, index) => {\n const { y, x } = a2p(address);\n const pos = getCellRectPositions(sheet, { y, x });\n const vx = pos.left - scrollLeft;\n const vy = pos.top - scrollTop;\n\n // Skip if off-screen\n if (vx + pos.width < 0 || vx > w || vy + pos.height < 0 || vy > h) {\n return;\n }\n\n const isCurrentMatch = index === matchingCellIndex;\n drawRect(\n ctx,\n vx,\n vy,\n pos.width,\n pos.height,\n isCurrentMatch ? COLOR_SEARCH_MATCHING : 'transparent',\n isCurrentMatch ? 2 : 0,\n [],\n SEARCH_MATCHING_BACKGROUND,\n );\n });\n\n // Restore full canvas for header drawing\n ctx.restore();\n\n // 7. Header highlights (top and left) — draw bottom border for top headers, right border for left headers.\n // Only visible rows/cols can produce an on-screen highlight, so bound the scans to the viewport range.\n // Iterating 1..numRows here made every overlay redraw (e.g. after inserting rows, which bumps the sheet\n // version) O(numRows) AND materialized every row-header cell via isRowFiltered — ~150ms at a million rows.\n const [firstCol, lastCol] = getVisibleColRange(sheet, scrollLeft, w);\n const [firstRow, lastRow] = getVisibleRowRange(sheet, scrollTop, h);\n\n // Top headers - draw bottom border and background\n for (let x = firstCol; x <= lastCol; x++) {\n let color: string | null = null;\n let backgroundColor: string | null = null;\n if (between({ start: selectingZone.startX, end: selectingZone.endX }, x)) {\n color = 'rgba(80, 180, 255, 1)';\n backgroundColor = topHeaderSelecting ? 'rgba(128, 128, 128, 0.25)' : 'rgba(0, 119, 255, 0.05)';\n }\n if (choosing.x === x) {\n color = COLOR_POINTED;\n backgroundColor = topHeaderSelecting ? 'rgba(128, 128, 128, 0.45)' : 'rgba(0, 119, 255, 0.15)';\n }\n if (!color) {\n continue;\n }\n\n const pos = getCellRectPositions(sheet, { y: 1, x });\n const left = pos.left - scrollLeft;\n if (left + pos.width < headerW || left > w) {\n continue;\n }\n const drawLeft = Math.max(left, headerW);\n const drawWidth = Math.min(left + pos.width, w) - drawLeft;\n if (drawWidth > 0) {\n if (backgroundColor) {\n fillRect(ctx, drawLeft, 0, drawWidth, headerH, backgroundColor);\n }\n // Draw bottom border of the header\n ctx.strokeStyle = color;\n ctx.lineWidth = 2;\n ctx.beginPath();\n ctx.moveTo(drawLeft, headerH + 1);\n ctx.lineTo(drawLeft + drawWidth, headerH + 1);\n ctx.stroke();\n }\n }\n\n // Left headers - draw right border and background\n for (let y = firstRow; y <= lastRow; y++) {\n if (sheet.isRowFiltered(y)) {\n continue;\n }\n let color: string | null = null;\n let backgroundColor: string | null = null;\n if (between({ start: selectingZone.startY, end: selectingZone.endY }, y)) {\n color = 'rgba(80, 180, 255, 1)';\n backgroundColor = leftHeaderSelecting ? 'rgba(128, 128, 128, 0.25)' : 'rgba(0, 119, 255, 0.05)';\n }\n if (choosing.y === y) {\n color = COLOR_POINTED;\n backgroundColor = leftHeaderSelecting ? 'rgba(128, 128, 128, 0.45)' : 'rgba(0, 119, 255, 0.15)';\n }\n if (!color) {\n continue;\n }\n\n const pos = getCellRectPositions(sheet, { y, x: 1 });\n const top = pos.top - scrollTop;\n if (top + pos.height < headerH || top > h) {\n continue;\n }\n const drawTop = Math.max(top, headerH);\n const drawHeight = Math.min(top + pos.height, h) - drawTop;\n if (drawHeight > 0) {\n if (backgroundColor) {\n fillRect(ctx, 0, drawTop, headerW, drawHeight, backgroundColor);\n }\n // Draw right border of the header\n ctx.strokeStyle = color;\n ctx.lineWidth = 2;\n ctx.beginPath();\n ctx.moveTo(headerW + 1, drawTop);\n ctx.lineTo(headerW + 1, drawTop + drawHeight);\n ctx.stroke();\n }\n }\n }, [\n sheet,\n // The Sheet instance is mutated in place, so its identity stays stable across structural\n // changes (insert/remove rows & cols, resize, sort, filter). Depend on its monotonic version\n // so the overlay redraws when the grid layout shifts; otherwise the old box stays misaligned.\n sheet?.currentVersion,\n tabularRef,\n choosing,\n selectingZone,\n matchingCells,\n matchingCellIndex,\n autofillDraggingTo,\n topHeaderSelecting,\n leftHeaderSelecting,\n mode,\n dragging,\n refs,\n ]);\n\n // Schedule a draw on the next animation frame (for state changes)\n const scheduleDrawCanvas = useCallback(() => {\n cancelAnimationFrame(rafIdRef.current);\n rafIdRef.current = requestAnimationFrame(drawCanvas);\n }, [drawCanvas]);\n\n // Draw synchronously on scroll to avoid 1-frame lag\n const handleScroll = useCallback(() => {\n drawCanvas();\n }, [drawCanvas]);\n\n useEffect(() => {\n scheduleDrawCanvas();\n return () => cancelAnimationFrame(rafIdRef.current);\n }, [scheduleDrawCanvas]);\n\n useEffect(() => {\n const container = tabularRef.current;\n if (!container) {\n return;\n }\n container.addEventListener('scroll', handleScroll);\n const ro = new ResizeObserver(() => drawCanvas());\n ro.observe(container);\n return () => {\n container.removeEventListener('scroll', handleScroll);\n ro.disconnect();\n };\n }, [tabularRef, handleScroll, drawCanvas]);\n\n return (\n <div\n style={{\n position: 'sticky',\n top: 0,\n left: 0,\n width: 0,\n height: 0,\n overflow: 'visible',\n pointerEvents: 'none',\n zIndex: 10,\n }}\n >\n <canvas\n ref={canvasRef}\n className=\"gs-cell-state-overlay\"\n style={{\n pointerEvents: 'none',\n display: 'block',\n }}\n />\n </div>\n );\n};\n","import { useEffect, useContext, useState, useCallback } from 'react';\n\nimport { Cell } from './Cell';\nimport { HeaderCellTop } from './HeaderCellTop';\nimport { HeaderCellLeft } from './HeaderCellLeft';\nimport { CellStateOverlay } from './CellStateOverlay';\n\nimport { Context } from '../store';\nimport { choose, select, setContextMenuPosition } from '../store/actions';\n\nimport type { RefPaletteType, Virtualization } from '../types';\nimport { virtualize, physicalScrollHeight } from '@gridsheet/web';\nimport { p2a, stripAddressAbsolute } from '@gridsheet/web';\nimport { Lexer, stripSheetName } from '@gridsheet/web';\nimport { ScrollHandle } from './ScrollHandle';\nimport { preventSafariBounce } from '@gridsheet/web';\n\nexport const Tabular = () => {\n const [palette, setPalette] = useState<RefPaletteType>({});\n const { store, dispatch } = useContext(Context);\n const {\n sheetReactive,\n choosing,\n editingAddress,\n tabularRef,\n mainRef,\n sheetWidth,\n sheetHeight,\n fixedWidth,\n fixedHeight,\n inputting,\n leftHeaderSelecting,\n topHeaderSelecting,\n contextMenu,\n } = store;\n const sheet = sheetReactive.current;\n\n const [virtualized, setVirtualized] = useState<Virtualization | null>(null);\n\n // Mark on .gs-main whether the grid overflows the viewport per axis, so the matrix outer\n // border hugs the content when it fits (border on the inner) and switches to a fixed\n // viewport overlay when it scrolls. Runs after every render (so it always catches the\n // ready flip, content growth and size changes) but reads layout inside rAF — after paint\n // — so it never blocks the render/paint the way a synchronous reflow would, and only\n // writes the attribute when the value actually changes.\n useEffect(() => {\n const t = tabularRef.current;\n const m = mainRef.current;\n if (!t || !m) {\n return;\n }\n const raf = requestAnimationFrame(() => {\n const ox = String(t.scrollWidth > t.clientWidth + 1);\n const oy = String(t.scrollHeight > t.clientHeight + 1);\n if (m.getAttribute('data-overflow-x') !== ox) {\n m.setAttribute('data-overflow-x', ox);\n }\n if (m.getAttribute('data-overflow-y') !== oy) {\n m.setAttribute('data-overflow-y', oy);\n }\n });\n return () => cancelAnimationFrame(raf);\n });\n\n const handleMouseMove = useCallback((e: React.MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n }, []);\n\n const handleScroll = useCallback(\n (e: React.UIEvent<HTMLDivElement>) => {\n if (sheet) {\n setVirtualized(virtualize(sheet, e.currentTarget));\n }\n },\n [sheetReactive],\n );\n\n const handleSelectAllClick = useCallback(() => {\n if (!sheet) {\n return;\n }\n dispatch(choose({ y: -1, x: -1 }));\n requestAnimationFrame(() => {\n dispatch(choose({ y: 1, x: 1 }));\n dispatch(\n select({\n startY: 1,\n startX: 1,\n endY: sheet.numRows,\n endX: sheet.numCols,\n }),\n );\n });\n }, [sheetReactive]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n const formulaEditing = editingAddress && inputting.startsWith('=');\n if (!formulaEditing) {\n setPalette({});\n sheet.registry.paletteBySheetName = {};\n return;\n }\n const palette: RefPaletteType = {};\n const paletteBySheetName: { [sheetName: string]: RefPaletteType } = {};\n const lexer = new Lexer(inputting.substring(1));\n lexer.tokenize();\n\n let i = 0;\n for (const token of lexer.tokens) {\n if (token.type === 'REF' || token.type === 'RANGE') {\n const normalizedRef = stripAddressAbsolute(token.stringify());\n const splitterIndex = normalizedRef.indexOf('!');\n if (splitterIndex !== -1) {\n const sheetName = normalizedRef.substring(0, splitterIndex);\n const ref = normalizedRef.substring(splitterIndex + 1);\n const stripped = stripSheetName(sheetName);\n const upperRef = ref.toUpperCase();\n if (paletteBySheetName[stripped] == null) {\n paletteBySheetName[stripped] = {};\n }\n if (paletteBySheetName[stripped][upperRef] == null) {\n paletteBySheetName[stripped][upperRef] = i++;\n }\n } else {\n const upperRef = normalizedRef.toUpperCase();\n if (palette[upperRef] == null) {\n palette[upperRef] = i++;\n }\n }\n }\n }\n setPalette(palette);\n sheet.registry.paletteBySheetName = paletteBySheetName;\n }, [store.inputting, store.editingAddress, sheetReactive]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n sheet.registry.choosingAddress = p2a(choosing);\n sheet.registry.choosingSheetId = sheet.id;\n }, [choosing]);\n\n useEffect(() => {\n if (!sheet) {\n return;\n }\n setVirtualized(virtualize(sheet, tabularRef.current));\n }, [\n tabularRef.current,\n sheetReactive,\n mainRef.current?.clientHeight,\n mainRef.current?.clientWidth,\n sheetHeight,\n sheetWidth,\n ]);\n\n useEffect(() => {\n const el = tabularRef.current;\n if (!el) {\n return;\n }\n return preventSafariBounce(el);\n }, [sheetReactive]);\n\n // Eager resolution: virtualization only renders/solves visible cells, so\n // off-screen async formulas would never fire. When the sheet opts in via\n // `eager`, fire every off-screen async cell after each update. resolveAll()\n // is idempotent — resolved/pending cells are cache hits — so it converges\n // once all async formulas have settled.\n useEffect(() => {\n if (!sheet || !sheet.eager || !sheet.registry.ready) {\n return;\n }\n sheet.resolveAll();\n }, [sheet, sheetReactive]);\n\n const mergedRefs: RefPaletteType = {\n ...palette,\n ...(sheet ? sheet.registry.paletteBySheetName[sheet.name] : {}),\n };\n\n if (!sheet || !sheet.registry.ready) {\n return null;\n }\n\n return (\n <>\n <div\n className=\"gs-tabular\"\n style={{\n // When a size is explicitly configured, keep that box so a smaller grid can be\n // centered within it (see .gs-tabular in tabular.less); otherwise shrink to fit.\n width:\n sheetWidth === -1 ? undefined : fixedWidth ? sheetWidth : Math.min(sheetWidth, sheet.totalWidth),\n height:\n sheetHeight === -1 ? undefined : fixedHeight ? sheetHeight : Math.min(sheetHeight, sheet.totalHeight),\n }}\n ref={tabularRef}\n onMouseMove={handleMouseMove}\n onScroll={handleScroll}\n >\n <div\n className={'gs-tabular-inner'}\n style={{\n width: sheet.totalWidth,\n // Physical scroll height is capped below the browser's ~2^24px precision limit;\n // virtualize() maps this back to the sheet's full virtual height (see SCROLL_CAP).\n height: physicalScrollHeight(sheet),\n overflow: 'clip',\n }}\n >\n <CellStateOverlay refs={mergedRefs} />\n <table className={`gs-table`}>\n <thead className=\"gs-thead\" style={{ height: sheet.headerHeight }}>\n <tr className=\"gs-row\">\n <th\n className=\"gs-th gs-th-left gs-th-top\"\n style={{ position: 'sticky', width: sheet.headerWidth, height: sheet.headerHeight }}\n onClick={handleSelectAllClick}\n >\n <div className=\"gs-th-inner\">\n <ScrollHandle\n className={leftHeaderSelecting || topHeaderSelecting ? 'gs-hidden' : ''}\n style={{ position: 'absolute' }}\n horizontal={leftHeaderSelecting ? 0 : -1}\n vertical={topHeaderSelecting ? 0 : -1}\n />\n {contextMenu.length > 0 && (\n <button\n className=\"gs-menu-btn gs-corner-menu-btn\"\n onClick={(e) => e.stopPropagation()}\n onMouseDown={(e) => {\n e.preventDefault();\n (e.currentTarget as HTMLElement).dataset.pressX = String(e.clientX);\n (e.currentTarget as HTMLElement).dataset.pressY = String(e.clientY);\n }}\n onMouseUp={(e) => {\n e.stopPropagation();\n const btn = e.currentTarget as HTMLElement;\n const pressX = Number(btn.dataset.pressX ?? e.clientX);\n const pressY = Number(btn.dataset.pressY ?? e.clientY);\n const moved = Math.abs(e.clientX - pressX) > 4 || Math.abs(e.clientY - pressY) > 4;\n if (moved) {\n return;\n }\n const rect = btn.getBoundingClientRect();\n dispatch(setContextMenuPosition({ y: rect.bottom, x: rect.left }));\n }}\n >\n ⋮\n </button>\n )}\n </div>\n </th>\n <th\n className=\"gs-adjuster gs-adjuster-horizontal gs-adjuster-horizontal-left\"\n style={{ width: virtualized?.adjuster?.left ?? 1 }}\n ></th>\n {virtualized?.xs?.map?.((x) => <HeaderCellTop x={x} key={x} />)}\n <th\n className=\"gs-adjuster gs-adjuster-horizontal gs-adjuster-horizontal-right\"\n style={{ width: virtualized?.adjuster?.right }}\n ></th>\n </tr>\n </thead>\n\n <tbody className=\"gs-sheet-body-adjuster\">\n <tr className=\"gs-row\">\n <th\n className={`gs-adjuster gs-adjuster-horizontal gs-adjuster-vertical`}\n style={{ height: virtualized?.adjuster?.top ?? 1 }}\n ></th>\n <td className=\"gs-adjuster gs-adjuster-vertical\"></td>\n {virtualized?.xs?.map((x) => <td className=\"gs-adjuster gs-adjuster-vertical\" key={x}></td>)}\n <th className={`gs-adjuster gs-adjuster-horizontal gs-adjuster-vertical`}></th>\n </tr>\n </tbody>\n\n <tbody className=\"gs-sheet-body-data\">\n {virtualized?.ys?.map((y) => {\n return (\n <tr key={y} className={`gs-row ${y % 2 === 0 ? 'gs-row-even' : 'gs-row-odd'}`}>\n <HeaderCellLeft y={y} />\n <td className=\"gs-adjuster gs-adjuster-horizontal gs-adjuster-horizontal-left\" />\n {virtualized?.xs?.map((x) => <Cell key={x} y={y} x={x} />)}\n <td className=\"gs-adjuster gs-adjuster-horizontal gs-adjuster-horizontal-right\" />\n </tr>\n );\n })}\n </tbody>\n </table>\n </div>\n </div>\n </>\n );\n};\n","import type { KeyboardEvent } from 'react';\nimport React, { useCallback, useEffect, useRef, useState, useContext } from 'react';\nimport { createPortal } from 'react-dom';\nimport { FunctionGuide } from './FunctionGuide';\nimport { EditorOptions } from './EditorOptions';\nimport { Context } from '../store';\nimport { p2a, a2p } from '@gridsheet/web';\nimport { setEditingAddress, setInputting, setEditorHovering, walk, write, updateSheet } from '../store/actions';\nimport { operations as prevention } from '@gridsheet/web';\nimport { insertTextAtCursor, isFocus } from '@gridsheet/web';\nimport { focus } from '@gridsheet/web';\nimport { editorStyle } from './Editor';\nimport { ScrollHandle } from './ScrollHandle';\nimport { useAutocomplete } from './useAutocomplete';\n\ntype FormulaBarProps = {\n ready: boolean;\n};\n\nexport const FormulaBar = ({ ready }: FormulaBarProps) => {\n const { store, dispatch } = useContext(Context);\n const [before, setBefore] = useState('');\n const [selectionStart, setSelectionStart] = useState(0);\n const [isFocused, setIsFocused] = useState(false);\n const {\n choosing,\n selectingZone,\n editorRef,\n largeEditorRef,\n sheetReactive: sheetRef,\n inputting,\n editingAddress: editingCell,\n dragging,\n } = store;\n const sheet = sheetRef.current;\n const hlRef = useRef<HTMLDivElement | null>(null);\n\n const address = choosing.x === -1 ? '' : p2a(choosing);\n const cell = sheet?.getCell(choosing, { resolution: 'SYSTEM' });\n const spilledFromAddress = sheet?.getSystem(choosing)?.spilledFrom;\n const originPoint = spilledFromAddress ? a2p(spilledFromAddress) : undefined;\n const originAddress = originPoint != null ? p2a(originPoint) : undefined;\n useEffect(() => {\n if (!sheet) {\n return;\n }\n let value = sheet.getCell(choosing, { resolution: 'SYSTEM' })?.value ?? '';\n // debug to remove this line\n value = sheet.getSerializedValue({ point: choosing, cell: { ...cell, value }, resolution: 'RAW' });\n largeEditorRef.current!.value = value;\n setBefore(value as string);\n }, [address, sheet]);\n\n const writeCell = useCallback(\n (value: string) => {\n if (before !== value) {\n dispatch(write({ value }));\n }\n dispatch(setEditingAddress(''));\n focus(editorRef.current);\n },\n [before],\n );\n\n useEffect(() => {\n const observer = new ResizeObserver((entries) => {\n entries.forEach(updateScroll);\n });\n if (largeEditorRef.current) {\n observer.observe(largeEditorRef.current);\n }\n return () => {\n observer.disconnect();\n };\n }, []);\n\n const policy = sheet?.getPolicy(choosing);\n const optionsAll = policy?.getSelectOptions() || [];\n\n const {\n filteredOptions,\n selected,\n setSelected,\n replaceWithOption,\n handleArrowUp,\n handleArrowDown,\n isFormula,\n activeFunctionHelp,\n activeArgIndex,\n } = useAutocomplete({\n inputting,\n selectionStart,\n optionsAll,\n functions: sheet?.registry.functions,\n });\n\n const composingRef = useRef(false);\n const largeInput = largeEditorRef.current;\n\n const handleInput = useCallback((e: React.SyntheticEvent<HTMLTextAreaElement>) => {\n dispatch(setInputting(e.currentTarget.value));\n setSelectionStart(e.currentTarget.selectionStart);\n }, []);\n\n const handleSelect = useCallback((e: React.SyntheticEvent<HTMLTextAreaElement>) => {\n setSelectionStart(e.currentTarget.selectionStart);\n }, []);\n\n const updateScroll = useCallback(() => {\n if (!hlRef.current || !largeEditorRef.current) {\n return;\n }\n hlRef.current.style.height = `${largeEditorRef.current.clientHeight}px`;\n hlRef.current.scrollLeft = largeEditorRef.current.scrollLeft;\n hlRef.current.scrollTop = largeEditorRef.current.scrollTop;\n }, []);\n\n const handleFocus = useCallback(\n (e: React.FocusEvent<HTMLTextAreaElement>) => {\n if (!largeInput || !sheet) {\n return;\n }\n setIsFocused(true);\n dispatch(setEditingAddress(address));\n sheet.registry.lastFocused = e.currentTarget;\n },\n [largeInput, address, sheet],\n );\n\n const handleBlur = useCallback(\n (e: React.FocusEvent<HTMLTextAreaElement>) => {\n setIsFocused(false);\n if (e.currentTarget.value!.startsWith('=')) {\n return true;\n } else {\n if (editingCell) {\n writeCell(e.currentTarget.value);\n }\n }\n },\n [editingCell, writeCell],\n );\n\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if ((e.nativeEvent as any).isComposing || composingRef.current) {\n return;\n }\n if (e.ctrlKey || !sheet) {\n return true;\n }\n const input = e.currentTarget;\n\n switch (e.key) {\n case 'Tab': // TAB\n e.preventDefault();\n if (filteredOptions.length) {\n const option = filteredOptions[selected];\n const isFunc = option?.isFunction;\n\n if (isFunc) {\n const { value: newValue, selectionStart: newCursor } = replaceWithOption(option);\n dispatch(setInputting(newValue));\n setTimeout(() => {\n if (largeEditorRef.current) {\n focus(largeEditorRef.current);\n largeEditorRef.current.setSelectionRange(newCursor, newCursor);\n }\n }, 0);\n return false;\n } else {\n // ... regular completion ...\n const t = sheet.update({ diff: { [address]: { value: option.value } }, partial: true });\n dispatch(updateSheet(t.clone()));\n dispatch(setEditingAddress(''));\n dispatch(setInputting(''));\n }\n }\n break;\n case 'ArrowUp':\n if (handleArrowUp(e as unknown as React.KeyboardEvent<HTMLTextAreaElement>)) {\n return true;\n }\n break;\n case 'ArrowDown':\n if (handleArrowDown(e as unknown as React.KeyboardEvent<HTMLTextAreaElement>)) {\n return true;\n }\n break;\n case 'Enter': {\n if (filteredOptions.length) {\n const option = filteredOptions[selected];\n if (option?.isFunction) {\n const { value: newValue, selectionStart: newCursor } = replaceWithOption(option);\n dispatch(setInputting(newValue));\n setTimeout(() => {\n if (largeEditorRef.current) {\n focus(largeEditorRef.current);\n largeEditorRef.current.setSelectionRange(newCursor, newCursor);\n }\n }, 0);\n e.preventDefault();\n return false;\n }\n }\n\n if (e.altKey) {\n insertTextAtCursor(input, '\\n');\n } else {\n writeCell(input.value);\n dispatch(setInputting(''));\n dispatch(\n walk({\n numRows: sheet.numRows,\n numCols: sheet.numCols,\n deltaY: 1,\n deltaX: 0,\n }),\n );\n e.preventDefault();\n return false;\n }\n break;\n }\n case 'Escape': {\n input.value = before;\n dispatch(setInputting(before));\n dispatch(setEditingAddress(''));\n e.preventDefault();\n focus(editorRef.current);\n\n break;\n }\n case 'a': // A\n if (e.ctrlKey || e.metaKey) {\n return true;\n }\n case 'c': // C\n if (e.ctrlKey || e.metaKey) {\n return true;\n }\n break;\n case 'v': // V\n if (e.ctrlKey || e.metaKey) {\n return true;\n }\n break;\n }\n\n const cell = sheet.getCell(choosing, { resolution: 'SYSTEM' });\n if (prevention.hasOperation(cell?.prevention, prevention.Write)) {\n console.warn('This cell is protected from writing.');\n e.preventDefault();\n }\n updateScroll();\n return false;\n },\n [\n sheet,\n choosing,\n address,\n before,\n writeCell,\n updateScroll,\n filteredOptions,\n selected,\n replaceWithOption,\n handleArrowUp,\n handleArrowDown,\n inputting,\n ],\n );\n\n const handleOptionMouseDown = useCallback(\n (e: React.MouseEvent, i: number) => {\n e.preventDefault();\n e.stopPropagation();\n const option = filteredOptions[i];\n if (option.isFunction) {\n const { value: newValue, selectionStart: newCursor } = replaceWithOption(option);\n writeCell(newValue);\n dispatch(setInputting(newValue));\n setTimeout(() => {\n if (largeEditorRef.current) {\n focus(largeEditorRef.current);\n largeEditorRef.current.setSelectionRange(newCursor, newCursor);\n }\n }, 0);\n }\n },\n [filteredOptions, replaceWithOption, writeCell, dispatch],\n );\n\n const style: React.CSSProperties = ready ? {} : { visibility: 'hidden' };\n if (!sheet) {\n return (\n <label className=\"gs-formula-bar gs-hidden\" style={style}>\n <div className=\"gs-selecting-address\"></div>\n <div className=\"gs-fx\">fx</div>\n <div className=\"gs-formula-bar-editor-inner\">\n <textarea />\n </div>\n </label>\n );\n }\n const renderOverlays = () => {\n if (!isFocused || typeof document === 'undefined') {\n return null;\n }\n if (largeEditorRef.current !== document.activeElement) {\n return null;\n }\n\n const rect = largeEditorRef.current?.getBoundingClientRect();\n if (!rect) {\n return null;\n }\n\n const top = rect.bottom;\n const left = rect.left;\n\n return createPortal(\n <>\n {activeFunctionHelp &&\n filteredOptions.length === 0 &&\n (!selectingZone || (selectingZone.endY === -1 && selectingZone.endX === -1)) && (\n <FunctionGuide\n activeFunctionGuide={activeFunctionHelp}\n activeArgIndex={activeArgIndex}\n top={top}\n left={left}\n />\n )}\n {filteredOptions.length > 0 && choosing.x !== -1 && (\n <EditorOptions\n filteredOptions={filteredOptions}\n top={top}\n left={left}\n selected={selected}\n onOptionMouseDown={handleOptionMouseDown}\n />\n )}\n </>,\n document.body,\n );\n };\n\n return (\n <div\n className=\"gs-formula-bar\"\n data-sheet-id={store.sheetId}\n data-spill={originAddress != null ? 'true' : undefined}\n style={style}\n >\n <ScrollHandle style={{ position: 'absolute', left: 0, top: 0, zIndex: 2 }} vertical={-1} />\n <div className=\"gs-selecting-address\">{originAddress != null ? originAddress : address}</div>\n <div className=\"gs-fx\">fx</div>\n <div className=\"gs-formula-bar-editor-inner\">\n <div\n className=\"gs-editor-hl\"\n ref={hlRef}\n style={{\n height: largeEditorRef.current?.clientHeight,\n width: '100%',\n }}\n >\n {(cell?.formulaEnabled ?? true) ? editorStyle(inputting) : inputting}\n </div>\n <textarea\n name=\"gs-formula-bar-editor\"\n data-sheet-id={store.sheetId}\n data-size=\"large\"\n rows={1}\n spellCheck={false}\n ref={largeEditorRef}\n value={inputting}\n // Spilled cells must not be edited from the FormulaBar — input here\n // would modify `inputting` one character at a time (via onInput) even\n // though the underlying cell cannot be written to.\n readOnly={originAddress != null}\n onInput={handleInput}\n onFocus={handleFocus}\n onSelect={handleSelect}\n onPaste={(e) => {\n e.stopPropagation();\n }}\n onKeyDown={handleKeyDown}\n onKeyUp={updateScroll}\n onCompositionStart={() => {\n composingRef.current = true;\n }}\n onCompositionEnd={(e) => {\n composingRef.current = false;\n dispatch(setInputting(e.currentTarget.value));\n }}\n onScroll={updateScroll}\n onMouseEnter={(e) => {\n dispatch(setEditorHovering(true));\n }}\n onMouseLeave={(e) => {\n dispatch(setEditorHovering(false));\n }}\n ></textarea>\n {renderOverlays()}\n </div>\n </div>\n );\n};\n","import type { ReactNode, CSSProperties } from 'react';\n\nexport interface IconProps {\n style?: CSSProperties;\n color?: string;\n size?: number;\n}\n\ninterface BaseProps extends IconProps {\n children?: ReactNode;\n}\n\n// https://tabler.io/icons\n\nexport const Base = ({ style, size = 24, children }: BaseProps) => {\n return (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width={size}\n height={size}\n viewBox={`0 0 24 24`}\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n style={style}\n className=\"icon-tabler\"\n >\n {children}\n </svg>\n );\n};\n","import { type IconProps, Base } from './Base';\n\n// https://tabler.io/icons\n\nexport const SearchIcon = ({ style, color = 'none', size = 24 }: IconProps) => {\n return (\n <Base style={style} size={size}>\n <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill={color} />\n <path d=\"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0\" fill={color} />\n <path d=\"M21 21l-6 -6\" fill={color} />\n </Base>\n );\n};\n","import { type IconProps, Base } from './Base';\n\n// https://tabler.io/icons\n\nexport const CloseIcon = ({ style, color = 'none', size = 24 }: IconProps) => {\n return (\n <Base style={style} size={size}>\n <path stroke=\"none\" d=\"M0 0h24v24H0z\" fill={color} />\n <path d=\"M18 6l-12 12\" fill={color} />\n <path d=\"M6 6l12 12\" fill={color} />\n </Base>\n );\n};\n","import { useContext, useEffect, useRef, useCallback, useMemo } from 'react';\n\nimport { a2p, x2c, y2r } from '@gridsheet/web';\nimport { isZoneNotSelected } from '@gridsheet/web';\n\nimport { Context } from '../store';\nimport { setSearchQuery, search, setSearchCaseSensitive, setSearchRegex, setSearchRange } from '../store/actions';\nimport { smartScroll } from '@gridsheet/web';\nimport { SearchIcon } from './svg/SearchIcon';\nimport { CloseIcon } from './svg/CloseIcon';\nimport { focus } from '@gridsheet/web';\n\nexport const SearchBar = () => {\n const { store, dispatch } = useContext(Context);\n const {\n rootRef,\n editorRef,\n searchInputRef,\n tabularRef,\n searchQuery,\n searchCaseSensitive,\n searchRegex,\n searchRange,\n selectingZone,\n matchingCellIndex,\n matchingCells,\n sheetReactive: sheetRef,\n } = store;\n const sheet = sheetRef.current;\n\n const matchingCell = matchingCells[matchingCellIndex];\n useEffect(() => {\n if (!matchingCell || !sheet) {\n return;\n }\n const point = a2p(matchingCell);\n if (typeof point === 'undefined') {\n return;\n }\n smartScroll(sheet, tabularRef.current, point);\n }, [searchQuery, matchingCellIndex, searchCaseSensitive, searchRegex, sheet, tabularRef]);\n\n const handleProgressClick = useCallback((e: React.MouseEvent) => {\n const input = e.currentTarget.previousSibling as HTMLInputElement;\n input?.nodeName === 'INPUT' && focus(input);\n }, []);\n\n const handleSearchClick = useCallback(() => {\n dispatch(search(1));\n }, []);\n\n const handleChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>) => {\n dispatch(setSearchQuery(e.currentTarget.value));\n }, []);\n\n const handleKeyDown = useCallback(\n (e: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (e.key === 'Escape') {\n const el = editorRef?.current;\n if (el) {\n focus(el);\n }\n dispatch(setSearchQuery(undefined));\n }\n if (e.key === 'f' && (e.ctrlKey || e.metaKey)) {\n e.preventDefault();\n return false;\n }\n if (e.key === 'Enter') {\n dispatch(search(e.shiftKey ? -1 : 1));\n e.preventDefault();\n return false;\n }\n return true;\n },\n [editorRef],\n );\n\n const handleCaseSensitiveClick = useCallback(() => {\n dispatch(setSearchCaseSensitive(!searchCaseSensitive));\n }, [searchCaseSensitive]);\n\n const handleRegexClick = useCallback(() => {\n dispatch(setSearchRegex(!searchRegex));\n }, [searchRegex]);\n\n const hasSelection = useMemo(() => {\n if (!selectingZone) {\n return false;\n }\n if (isZoneNotSelected(selectingZone)) {\n return false;\n }\n const { startY, startX, endY, endX } = selectingZone;\n return !(startY === endY && startX === endX);\n }, [selectingZone]);\n\n const selectionLabel = useMemo(() => {\n if (!selectingZone || !hasSelection) {\n return '';\n }\n const { startY, startX, endY, endX } = selectingZone;\n const topLeft = `${x2c(Math.min(startX, endX))}${y2r(Math.min(startY, endY))}`;\n const bottomRight = `${x2c(Math.max(startX, endX))}${y2r(Math.max(startY, endY))}`;\n return `${topLeft}:${bottomRight}`;\n }, [selectingZone, hasSelection]);\n\n const handleRangeClick = useCallback(() => {\n if (searchRange) {\n // Clear search range\n dispatch(setSearchRange(undefined));\n } else if (selectingZone && hasSelection) {\n // Set search range to current selection\n const { startY, startX, endY, endX } = selectingZone;\n dispatch(\n setSearchRange({\n startY: Math.min(startY, endY),\n startX: Math.min(startX, endX),\n endY: Math.max(startY, endY),\n endX: Math.max(startX, endX),\n }),\n );\n }\n }, [searchRange, selectingZone, hasSelection]);\n\n const searchRangeLabel = useMemo(() => {\n if (!searchRange) {\n return '';\n }\n const { startY, startX, endY, endX } = searchRange;\n const topLeft = `${x2c(startX)}${y2r(startY)}`;\n const bottomRight = `${x2c(endX)}${y2r(endY)}`;\n return `${topLeft}:${bottomRight}`;\n }, [searchRange]);\n\n const handleCloseClick = useCallback(() => {\n dispatch(setSearchQuery(undefined));\n focus(editorRef.current);\n }, [editorRef]);\n\n if (typeof searchQuery === 'undefined') {\n return null;\n }\n if (rootRef.current === null) {\n return null;\n }\n return (\n <label className={`gs-search-bar ${matchingCells.length > 0 ? 'gs-search-found' : ''}`}>\n <div className=\"gs-search-progress\" onClick={handleProgressClick}>\n {matchingCells.length === 0 ? 0 : matchingCellIndex + 1} / {matchingCells.length}\n </div>\n <div className=\"gs-search-bar-icon\" onClick={handleSearchClick}>\n <SearchIcon style={{ verticalAlign: 'middle', marginLeft: '5px' }} />\n </div>\n <div className=\"gs-search-input-wrapper\">\n <div className=\"gs-search-input-ghost\">\n <span className=\"gs-search-ghost-text\">{searchQuery}</span>\n {searchQuery && <span className=\"gs-search-ghost-hint\"> ↵ Next</span>}\n </div>\n <textarea\n ref={searchInputRef}\n value={searchQuery}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n placeholder=\"Search\"\n title=\"Press Enter to next, Shift+Enter to previous\"\n ></textarea>\n </div>\n <div className=\"gs-search-buttons\">\n {searchRange && (\n <div className=\"gs-search-button gs-search-range\">\n <span\n className=\"gs-search-button-on\"\n onClick={handleRangeClick}\n title={`Search range: ${searchRangeLabel}`}\n >\n in {searchRangeLabel}\n </span>\n </div>\n )}\n {!searchRange && hasSelection && (\n <div className=\"gs-search-button gs-search-range\">\n <span onClick={handleRangeClick} title={`Limit to range: ${selectionLabel}`}>\n in {selectionLabel}\n </span>\n </div>\n )}\n <div className=\"gs-search-button gs-search-casesensitive\">\n <span\n className={`${searchCaseSensitive ? 'gs-search-button-on' : ''}`}\n onClick={handleCaseSensitiveClick}\n title={`Case sensitive`}\n >\n Aa\n </span>\n </div>\n <div className=\"gs-search-button gs-search-regex\">\n <span\n className={`${searchRegex ? 'gs-search-button-on' : ''}`}\n onClick={handleRegexClick}\n title={`Regular expression`}\n >\n .*\n </span>\n </div>\n </div>\n <a className=\"gs-search-close\" onClick={handleCloseClick}>\n <CloseIcon style={{ verticalAlign: 'middle' }} />\n </a>\n </label>\n );\n};\n","import { useEffect, useState, useRef, useReducer, createRef, useCallback } from 'react';\nimport type { CSSProperties } from 'react';\nimport type { BorderSides, CellsByAddressType, SheetHandle, StoreHandle, OptionsType, Props, StoreType } from '../types';\nimport {\n DEFAULT_HEIGHT,\n DEFAULT_WIDTH,\n HEADER_HEIGHT,\n HEADER_WIDTH,\n SHEET_HEIGHT,\n SHEET_WIDTH,\n DEFAULT_COL_KEY,\n DEFAULT_ROW_KEY,\n} from '@gridsheet/web';\nimport { Context } from '../store';\nimport { reducer as defaultReducer, isMutationAction, isAsyncMutationAction, commitAsyncOp } from '../store/actions';\nimport { AsyncProgressOverlay, type AsyncProgressHandle } from './AsyncProgressOverlay';\nimport { ProgressOverlay } from './ProgressOverlay';\nimport { Editor } from './Editor';\nimport { StoreObserver } from './StoreObserver';\nimport { Resizer } from './Resizer';\nimport { Emitter } from './Emitter';\nimport { ContextMenu } from './ContextMenu';\nimport { ColumnMenu } from './ColumnMenu';\nimport { RowMenu } from './RowMenu';\nimport { Sheet } from '@gridsheet/web';\nimport { Tabular } from './Tabular';\nimport { getMaxSizesFromCells } from '@gridsheet/web';\nimport { x2c, y2r } from '@gridsheet/web';\nimport { embedStyle } from '@gridsheet/web';\nimport { FormulaBar } from './FormulaBar';\nimport { SearchBar } from './SearchBar';\nimport { useBook } from '../lib/hooks';\nimport { ScrollHandle } from './ScrollHandle';\nimport { defaultContextMenuDescriptors, defaultRowMenuDescriptors, defaultColMenuDescriptors } from '../lib/menu';\n\nexport const createSheetRef = () => createRef<SheetHandle | null>();\nexport const useSheetRef = () => useRef<SheetHandle | null>(null);\nexport const createStoreRef = () => createRef<StoreHandle | null>();\nexport const useStoreRef = () => useRef<StoreHandle | null>(null);\n\nexport function GridSheet({\n initialCells,\n sheetName = '',\n sheetRef: initialSheetRef,\n storeRef: initialStoreRef,\n options = {},\n className,\n style,\n book: initialBook,\n loading: loadingProp,\n}: Props) {\n const {\n sheetResize,\n showFormulaBar = true,\n mode = 'light',\n density = 'compact',\n gridLines = 'all',\n formulaBarBorders = { all: true },\n matrixBorders = { all: true },\n } = options;\n // Translate the border config objects into CSS custom properties consumed by the\n // stylesheet (--gs-fb-* for the formula bar, --gs-mx-* for the matrix). A specific side\n // overrides `all`.\n const bw = (b: BorderSides, side: 'left' | 'top' | 'right' | 'bottom') =>\n (b[side] ?? b.all ?? false) ? '1px' : '0';\n const borderVars = {\n '--gs-fb-bl': bw(formulaBarBorders, 'left'),\n '--gs-fb-bt': bw(formulaBarBorders, 'top'),\n '--gs-fb-br': bw(formulaBarBorders, 'right'),\n '--gs-fb-bb': bw(formulaBarBorders, 'bottom'),\n '--gs-mx-bl': bw(matrixBorders, 'left'),\n '--gs-mx-bt': bw(matrixBorders, 'top'),\n '--gs-mx-br': bw(matrixBorders, 'right'),\n '--gs-mx-bb': bw(matrixBorders, 'bottom'),\n } as CSSProperties;\n const rootRef = useRef<HTMLDivElement>(null);\n const flashRef = useRef<HTMLDivElement>(null);\n const mainRef = useRef<HTMLDivElement>(null);\n const searchInputRef = useRef<HTMLTextAreaElement>(null);\n const editorRef = useRef<HTMLTextAreaElement>(null);\n const largeEditorRef = useRef<HTMLTextAreaElement>(null);\n const tabularRef = useRef<HTMLDivElement>(null);\n\n const internalSheetRef = useSheetRef();\n const sheetRef = initialSheetRef ?? internalSheetRef;\n const internalStoreRef = useStoreRef();\n const storeRef = initialStoreRef ?? internalStoreRef;\n\n const internalBook = useBook({});\n const book = initialBook ?? internalBook;\n const { registry } = book;\n\n const [sheetId] = useState<number>(() => {\n if (sheetName) {\n // Named sheets: use sheetName as stable dedup key to prevent double-increment in Strict Mode.\n if (!registry._componentSheetIds.has(sheetName)) {\n registry._componentSheetIds.set(sheetName, ++registry.sheetHead);\n }\n return registry._componentSheetIds.get(sheetName)!;\n }\n // Unnamed sheets: accept double-increment in Strict Mode (IDs may skip, but remain unique).\n return ++registry.sheetHead;\n });\n\n // Initialize sheetReactive\n const sheetReactive = useRef<Sheet | null>(null);\n\n const [initialState] = useState<StoreType>(() => {\n if (!sheetName) {\n sheetName = `Sheet${sheetId}`;\n console.debug('GridSheet: sheetName is not provided, using default name:', sheetName);\n }\n const { limits, contextMenu, rowMenu, colMenu, eager } = options;\n const sheet = new Sheet({\n limits,\n name: sheetName,\n registry,\n eager,\n });\n sheet.id = sheetId;\n registry.sheetIdsByName[sheetName] = sheetId;\n\n sheet.initialize(initialCells);\n registry.onInit?.({ sheet });\n\n sheet.setTotalSize();\n sheetReactive.current = sheet;\n\n const store: StoreType = {\n sheetId,\n sheetReactive,\n rootRef,\n flashRef,\n mainRef,\n searchInputRef,\n editorRef,\n largeEditorRef,\n tabularRef,\n choosing: { y: 1, x: 1 },\n inputting: '',\n selectingZone: { startY: 1, startX: 1, endY: -1, endX: -1 },\n autofillDraggingTo: null,\n leftHeaderSelecting: false,\n topHeaderSelecting: false,\n editingAddress: '',\n editorRect: { y: 0, x: 0, height: 0, width: 0 },\n dragging: false,\n sheetHeight: 0,\n sheetWidth: 0,\n fixedWidth: false,\n fixedHeight: false,\n entering: false,\n matchingCells: [],\n matchingCellIndex: 0,\n searchCaseSensitive: false,\n searchRegex: false,\n editingOnEnter: true,\n contextMenuPosition: { y: -1, x: -1 },\n contextMenu: contextMenu ?? defaultContextMenuDescriptors,\n rowMenu: rowMenu ?? defaultRowMenuDescriptors,\n colMenu: colMenu ?? defaultColMenuDescriptors,\n resizingPositionY: [-1, -1, -1],\n resizingPositionX: [-1, -1, -1],\n columnMenuState: null,\n rowMenuState: null,\n editorHovering: true,\n mode: 'light',\n pendingAsyncOp: null,\n };\n return store;\n });\n\n type ReducerWithoutAction<S> = (prevState: S) => S;\n\n const [store, dispatch] = useReducer(\n defaultReducer as unknown as ReducerWithoutAction<StoreType>,\n initialState,\n () => initialState,\n );\n\n useEffect(() => {\n embedStyle();\n }, []);\n\n // When sheetWidth/sheetHeight is a string, the sheet stretches to its parent (fill mode)\n // and the rendered pixel size is measured via ResizeObserver instead of being fixed.\n const fillWidth = typeof options.sheetWidth === 'string';\n const fillHeight = typeof options.sheetHeight === 'string';\n // matrixAlignment picks which axes may center. A fixed box (that a smaller grid centers\n // within) only exists when the size is *intentionally* larger than the content — an\n // explicit sheetWidth/sheetHeight, or a manual resize — never from the content estimate\n // or the formula-bar width, so nothing but those produces an empty gap. 'none' keeps the\n // old shrink-to-content behavior.\n const matrixAlignment = options.matrixAlignment ?? 'none';\n const centersWidth = matrixAlignment === 'horizontal' || matrixAlignment === 'both';\n const centersHeight = matrixAlignment === 'vertical' || matrixAlignment === 'both';\n const [resizedWidth, setResizedWidth] = useState(false);\n const [resizedHeight, setResizedHeight] = useState(false);\n const fixedWidth = centersWidth && (options.sheetWidth != null || resizedWidth);\n const fixedHeight = centersHeight && (options.sheetHeight != null || resizedHeight);\n const [sheetHeight, setSheetHeight] = useState(\n typeof options?.sheetHeight === 'number' ? options.sheetHeight : estimateSheetHeight(initialCells),\n );\n const [sheetWidth, setSheetWidth] = useState(\n typeof options?.sheetWidth === 'number' ? options.sheetWidth : estimateSheetWidth(initialCells),\n );\n useEffect(() => {\n const el = mainRef.current;\n if (!el) {\n return;\n }\n let first = true;\n const ro = new ResizeObserver(() => {\n // CSS `resize` writes an inline width/height when the user drags the handle; that is\n // the signal that the box was intentionally sized, so a smaller grid may now center.\n if (el.style.width) {\n setResizedWidth(true);\n }\n if (el.style.height) {\n setResizedHeight(true);\n }\n if (first) {\n first = false;\n // In fill mode we want the initial measurement; otherwise keep the provided/estimated size.\n if (!fillWidth && !fillHeight) {\n return;\n }\n }\n const root = rootRef.current;\n // Height is re-measured only when it is genuinely container-driven: fill mode,\n // or after the user dragged the resize handle. Otherwise `Math.min` would\n // ratchet a fixed-height grid smaller on every layout change (e.g. content\n // updates) and never recover, collapsing it over time. Width keeps auto-\n // fitting the container so wide grids stay responsive.\n if (fillHeight || el.style.height) {\n setSheetHeight(root ? Math.min(el.clientHeight, root.clientHeight) : el.clientHeight);\n }\n setSheetWidth(root ? Math.min(el.clientWidth, root.clientWidth) : el.clientWidth);\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, [fillWidth, fillHeight]);\n useEffect(() => {\n if (typeof options.sheetHeight === 'number') {\n setSheetHeight(options.sheetHeight);\n }\n }, [options.sheetHeight]);\n useEffect(() => {\n if (typeof options.sheetWidth === 'number') {\n setSheetWidth(options.sheetWidth);\n }\n }, [options.sheetWidth]);\n\n const [loading, setLoading] = useState(false);\n\n // Latest store, so wrappedDispatch (memoized) can read pendingAsyncOp for the lock.\n const latestStoreRef = useRef(store);\n latestStoreRef.current = store;\n\n const wrappedDispatch = useCallback(\n ((action: { type: number; value: any }) => {\n const async = isAsyncMutationAction(action.type);\n const mutating = isMutationAction(action.type);\n // Lock: while a chunked async op is in flight the sheet is mid-mutation, so\n // reject any other mutation (edit/undo/paste/fill) until it commits. Read-only\n // actions (selection, scroll) still pass through.\n if (latestStoreRef.current.pendingAsyncOp != null && (async || mutating)) {\n return;\n }\n if (async) {\n // Its reduce just sets pendingAsyncOp (cheap); the runner effect drives it.\n (dispatch as any)(action);\n return;\n }\n if (!mutating) {\n (dispatch as any)(action);\n return;\n }\n setLoading(true);\n // TWO rAFs before running the (synchronous, possibly multi-second) mutation:\n // a single rAF fires BEFORE the overlay's first paint, so the overlay never\n // actually showed during the block. The second rAF runs after that paint, so\n // the spinner is on screen (and its compositor-driven animation keeps moving)\n // while the main thread is blocked. Clear right after dispatch — React batches\n // loading:false with the mutation's own re-render, so the overlay lifts exactly\n // when the result appears.\n requestAnimationFrame(() =>\n requestAnimationFrame(() => {\n (dispatch as any)(action);\n setLoading(false);\n }),\n );\n }) as typeof dispatch,\n [dispatch],\n );\n\n // Runner for chunked async mutations (large fill/paste): when an action sets\n // store.pendingAsyncOp, run it off the reducer — reporting progress into the store\n // and committing the mutated sheet when done. Two rAFs first so the progress\n // overlay paints before the (still-synchronous) diff-build inside run() starts.\n const overlayRef = useRef<AsyncProgressHandle>(null);\n const pendingAsyncOp = store.pendingAsyncOp;\n useEffect(() => {\n if (pendingAsyncOp == null) {\n return;\n }\n let cancelled = false;\n const raf = requestAnimationFrame(() =>\n requestAnimationFrame(async () => {\n if (cancelled) {\n return;\n }\n try {\n const nextSheet = await pendingAsyncOp.run((ratio) => {\n // Imperative — updates only the overlay, never the grid.\n overlayRef.current?.setProgress(ratio);\n });\n if (!cancelled) {\n (dispatch as any)(\n commitAsyncOp({\n sheet: nextSheet,\n selectingZone: pendingAsyncOp.selectingZone,\n finalize: pendingAsyncOp.finalize,\n }),\n );\n pendingAsyncOp.postCommit?.();\n }\n } catch (e) {\n // eslint-disable-next-line no-console\n console.error('[gridsheet] async op failed:', e);\n if (!cancelled) {\n (dispatch as any)(commitAsyncOp({ sheet: latestStoreRef.current.sheetReactive.current!, selectingZone: pendingAsyncOp.selectingZone }));\n }\n }\n }),\n );\n return () => {\n cancelled = true;\n cancelAnimationFrame(raf);\n };\n }, [pendingAsyncOp, dispatch]);\n\n return (\n <Context.Provider value={{ store, dispatch: wrappedDispatch }}>\n <div\n className={`gs-root1 ${registry.ready ? 'gs-initialized' : ''}`}\n ref={rootRef}\n data-sheet-name={sheetName}\n data-mode={mode}\n data-density={density}\n data-gridlines={gridLines}\n data-matrix-align={matrixAlignment}\n data-rows={store.sheetReactive.current?.numRows ?? 0}\n data-cols={store.sheetReactive.current?.numCols ?? 0}\n style={\n fillWidth || fillHeight\n ? {\n ...borderVars,\n // inline-flex (when width isn't filled) keeps the prior shrink-to-content width.\n display: fillWidth ? 'flex' : 'inline-flex',\n flexDirection: 'column',\n ...(fillWidth ? { width: options.sheetWidth as string } : null),\n ...(fillHeight ? { height: options.sheetHeight as string } : null),\n }\n : borderVars\n }\n >\n <div className=\"gs-flash-overlay\" ref={flashRef} />\n <ScrollHandle style={{ position: 'fixed', top: 0, left: 0 }} />\n <ScrollHandle style={{ position: 'absolute', zIndex: 4, right: 0, top: 0, width: 5 }} horizontal={1} />\n <ScrollHandle style={{ position: 'absolute', zIndex: 4, left: 0, bottom: 0, height: 5 }} vertical={1} />\n\n {typeof store.searchQuery === 'undefined' ? (\n showFormulaBar && <FormulaBar ready={registry.ready} />\n ) : (\n <SearchBar />\n )}\n <div\n className={`gs-main ${className || ''}`}\n ref={mainRef}\n style={{\n ...(fillWidth ? { width: '100%' } : null),\n maxWidth: '100%',\n // In fill-height mode the parent's height is the limit (flex:1 fills the remaining\n // space below the formula bar). With an explicit fixed height, honor it exactly\n // (never shrink to the viewport — otherwise a grid placed low on a page or in a\n // short viewport collapses). Only the shrink-to-content case caps at the viewport\n // bottom so a very tall grid stays usable within the current view.\n ...(fillHeight\n ? { flex: 1, minHeight: 0, maxHeight: '100%' }\n : fixedHeight\n ? { maxHeight: sheetHeight }\n : {\n maxHeight: mainRef.current\n ? window.innerHeight - mainRef.current.getBoundingClientRect().top\n : (store.sheetReactive.current?.fullHeight || 0) + 2,\n }),\n resize: sheetResize,\n ...style,\n }}\n >\n <Editor mode={mode} />\n <Tabular />\n <StoreObserver\n {...{ ...options, sheetHeight, sheetWidth, fixedWidth, fixedHeight, sheetName, sheetRef, storeRef }}\n />\n <ContextMenu />\n <ColumnMenu />\n <RowMenu />\n <Resizer />\n <Emitter />\n {store.pendingAsyncOp != null ? (\n // Chunked async mutation (large fill/paste): imperative progress, grid not re-rendered.\n <AsyncProgressOverlay ref={overlayRef} label={store.pendingAsyncOp.label} />\n ) : loading ? (\n // Internal sync mutation in flight: brief indeterminate spinner.\n <div className=\"gs-loading-overlay\">\n <div className=\"gs-loading-spinner\" />\n </div>\n ) : loadingProp ? (\n // Consumer-driven initial loading (data not ready yet).\n <ProgressOverlay\n progress={typeof loadingProp === 'object' ? (loadingProp.progress ?? null) : null}\n label={typeof loadingProp === 'object' ? loadingProp.label : undefined}\n />\n ) : null}\n </div>\n </div>\n </Context.Provider>\n );\n}\n\nconst estimateSheetHeight = (initialCells: CellsByAddressType) => {\n const auto = getMaxSizesFromCells(initialCells);\n let estimatedHeight = initialCells[0]?.height ?? HEADER_HEIGHT;\n for (let y = 1; y <= auto.numRows; y++) {\n const row = y2r(y);\n const height =\n initialCells?.[row]?.height ||\n initialCells?.['0' + row]?.height ||\n initialCells?.[DEFAULT_ROW_KEY]?.height ||\n initialCells?.default?.height ||\n DEFAULT_HEIGHT;\n if (estimatedHeight + height > SHEET_HEIGHT) {\n return SHEET_HEIGHT;\n }\n estimatedHeight += height;\n }\n return estimatedHeight + 3;\n};\n\nconst estimateSheetWidth = (initialCells: CellsByAddressType) => {\n const auto = getMaxSizesFromCells(initialCells);\n let estimatedWidth = initialCells[0]?.width ?? HEADER_WIDTH;\n for (let x = 1; x <= auto.numCols; x++) {\n const col = x2c(x);\n const width =\n initialCells?.[col]?.width ||\n initialCells?.[col + '0']?.width ||\n initialCells?.[DEFAULT_COL_KEY]?.width ||\n initialCells?.default?.width ||\n DEFAULT_WIDTH;\n if (estimatedWidth + width > SHEET_WIDTH) {\n return SHEET_WIDTH;\n }\n estimatedWidth += width;\n }\n return estimatedWidth + 3;\n};\n","import type { PolicyMixinType, RenderProps } from '@gridsheet/web';\n\nexport const CheckboxPolicyMixin: PolicyMixinType = {\n renderBool({ value, apply, sheet, point }: RenderProps<boolean>): any {\n return (\n <input\n type=\"checkbox\"\n checked={value}\n onChange={(e) => {\n if (apply) {\n apply(sheet.write({ point, value: e.currentTarget.checked.toString() }));\n }\n e.currentTarget.blur();\n }}\n />\n );\n },\n};\n","import type { CSSProperties } from 'react';\n\ntype BorderStyleValue = string;\n\ninterface BorderOptions {\n all?: BorderStyleValue;\n top?: BorderStyleValue;\n right?: BorderStyleValue;\n bottom?: BorderStyleValue;\n left?: BorderStyleValue;\n}\n\nexport function makeBorder(options: BorderOptions): CSSProperties {\n const result: CSSProperties = {};\n const all = options.all;\n if (options.top ?? all) {\n result.borderTop = options.top ?? all;\n }\n if (options.right ?? all) {\n result.borderRight = options.right ?? all;\n }\n if (options.bottom ?? all) {\n result.borderBottom = options.bottom ?? all;\n }\n if (options.left ?? all) {\n result.borderLeft = options.left ?? all;\n }\n return result;\n}\n"],"names":["Context","createContext","ProgressOverlay","progress","label","determinate","pct","jsxs","jsx","AsyncProgressOverlay","forwardRef","ref","setProgress","useState","useImperativeHandle","FunctionGuide","option","activeFunctionGuide","activeArgIndex","top","left","useRef","guide1Ref","store","useContext","isHidden","useLayoutEffect","el","calcSideStyle","clampPopup","e","React","Fragment","arg","j","args","numIterable","a","variadicStart","isActive","offset","resolvedIndex","activeArg","EditorOptions","filteredOptions","selected","onOptionMouseDown","ulRef","adjustedLeft","setAdjustedLeft","width","clampLeft","i","clip","selectingZone","choosing","editorRef","sheetRef","sheet","y","x","area","zoneToArea","input","trimmed","tsv","sheet2csv","point","html","sheet2html","tsvBlob","htmlBlob","focus","getter","filteredRowsIncluded","trailingEmptyRowsOmitted","separator","newline","rows","cols","rowIsEmpty","value","r","valueEscaped","useAutocomplete","inputting","selectionStart","optionsAll","functions","setSelected","matchParams","activeFunctionHelp","useMemo","isFormula","textBeforeCursor","textAfterCursor","textToCursor","lexer","Lexer","functionStack","token","nextToken","activeItem","helps","getFunctionHelps","h","wordBefore","_a","wordAfter","_b","currentWord","hasOpenParenAssigned","filtered","isOnAddress","fullLexer","currentIndex","tLen","help","keywordLower","startsWith","index","hasNoArgs","b","keywords","bestMatch","keyword","replaceWithOption","useCallback","beforeMatch","afterMatch","handleArrowUp","s","handleArrowDown","Fixed","children","style","className","attrs","document","useBrowser","createPortal","parseHTML","onlyValue","doc","results","processSheet","spans","row","caption","cells","result","cell","childStyle","parseStyleString","rowSpan","colSpan","c","processNodeSequentially","node","currentLine","tagName","blockTags","child","lines","line","element","styleString","styleObj","d","rawKey","rawValue","key","_","letter","parseText","sep","entering","word","restoreDoubleQuote","text","Editor","mode","dispatch","shiftKey","setShiftKey","setSelectionStart","isFocused","setIsFocused","composingRef","editorRect","editingAddress","matchingCells","matchingCellIndex","searchQuery","largeEditorRef","searchInputRef","editingOnEnter","sheetId","dragging","renderOverlays","editing","rect","handleOptionMouseDown","policy","handleSelect","useEffect","setEditingAddress","expandInput","rowId","y2r","address","x2c","currentString","before","setBefore","writeCell","write","selectValue","selectedIndex","newValue","newCursor","setInputting","t","updateSheet","resetInput","height","numLines","isKeyDown","setIsKeyDown","handleKeyDown","handleFormulaQuoteAutoClose","isFunction","walk","insertTextAtCursor","dblclick","_c","clear","_d","escape","setSearchQuery","selectToDataEdge","arrow","select","copy","areaToZone","fillDown","setEntering","fillRight","redo","_f","_e","cut","undo","prevention","handleFocus","handleDoubleClick","length","handleBlur","isRefInsertable","handleChange","handlePaste","paste","handleKeyUpInternal","selectingArea","editorStyle","setEditorHovering","TokenSpan","memo","tokenKey","color","prevProps","nextProps","palletIndex","exists","formulaHash","hash","char","normalizedToken","existsIndex","COLOR_PALETTE","PluginContext","useInitialPluginContext","setStore","apply","setApply","usePluginContext","ctx","PluginBase","context","provided","StoreObserver","sheetName","sheetHeight","sheetWidth","fixedWidth","fixedHeight","storeRef","sheetReactive","dragRef","raf","running","dead","cx","cy","lastCell","lastExtend","EDGE","SPEED","stop","finish","submitAutofill","setDragging","tick","dy","dx","px","py","now","setAutofillDraggingTo","drag","onMove","onDown","onUp","onLeaveWindow","registry","pluginProvided","pluginContext","Resizer","posY","posX","leftHeaderSelecting","topHeaderSelecting","mainRef","startY","endY","startX","endX","offsetY","offsetX","baseWidth","DEFAULT_WIDTH","baseHeight","DEFAULT_HEIGHT","bottom","right","diff","xs","between","makeSequence","p2a","ys","setResizingPositionY","setResizingPositionX","MIN_HEIGHT","MIN_WIDTH","Emitter","pointing","zone","copier","cutter","paster","items","item","undoer","redoer","rowsInserterAbove","numRows","zoneShape","insertRowsAbove","rowsInserterBelow","insertRowsBelow","colsInserterLeft","numCols","insertColsLeft","colsInserterRight","insertColsRight","rowsRemover","removeRows","colsRemover","removeCols","rowsSorterAsc","sortRows","rowsSorterDesc","rowsFilterer","filter","filterRows","rowsFilterClearer","rowSortFixedToggler","addr","rowCell","next","rowFilterFixedToggler","searcher","applyers","rowInsertCount","selStart","selEnd","colInsertCount","defaultContextMenuDescriptors","colCell","defaultRowMenuDescriptors","n","defaultColMenuDescriptors","buildMenuContext","close","props","_insertRowsAbove","_insertRowsBelow","_removeRows","_insertColsLeft","_insertColsRight","_removeCols","direction","_setStore","_menuComponentRegistry","registerMenuComponent","id","component","getMenuComponent","MenuItem","shortcuts","disabled","checked","testId","onClick","hasCheck","shortcut","part","arr","MenuDivider","MenuNodes","onSelect","renderComponent","SubmenuNode","open","setOpen","liRef","flyoutRef","pos","setPos","li","fly","p","f","margin","ContextMenu","contextMenuPosition","contextMenu","menuRef","setContextMenuPosition","METHOD_LABELS","NO_VALUE_METHODS","DEFAULT_CONDITION","FilterSection","onWaiting","conditions","setConditions","setMode","pending","setPending","firstValueRef","existing","handleCancel","cancelled","execute","actionX","validConditions","filterMode","currentSheet","updateCondition","patch","prev","addCondition","removeCondition","handleApplyFilter","valid","v","handleResetColumn","handleResetAll","filterDisabled","hasAnyFilter","cond","m","SortSection","sortDisabled","LabelSection","labelInputRef","setLabel","handleApplyLabel","labelDisabled","labelPlaceholder","getLabel","ColumnMenu","columnMenuState","colMenu","position","waitingState","setWaitingState","handleClose","setColumnMenu","handleWaiting","message","cancel","componentId","Section","RowMenu","rowMenuState","rowMenu","setRowMenu","isTouching","mouseEvent","safePreventDefault","Cell","isFirstPointed","cellRef","errorTooltipPos","setErrorTooltipPos","autofillDraggingTo","xSheetFocused","isXSheetFocused","lastFocused","pointed","_setEditorRect","setEditorRect","errorMessage","rendered","FormulaError","isPendingCell","Pending","editingAnywhere","handleDragStart","choose","fullAddress","insertRef","handleDragEnd","handleDragging","newArea","fullRange","areaToRange","handleAutofillMouseDown","handleErrorTriangleEnter","calcBelowPosition","handleErrorTriangleLeave","onContextMenu","onDoubleClick","autofillDragClass","among","hAlignTransform","acceleration","maxSpeed","lastScrollTime","currentSpeed","ScrollHandle","horizontal","vertical","scrollRef","tabularRef","isScrolling","getDestEdge","tabularRect","getAreaInTabular","scrollStep","live","curY","curX","sheetPrefix","sheetRange","handleMouseEnter","stopScroll","isFocus","handleMouseUp","handleMouseUpWrapper","handleMouseLeave","cannotScrollHere","HeaderCellTop","colId","col","hasFilter","handleResizeMouseDown","selectCols","useDebounceCallback","displayedLabel","btn","pressX","pressY","HeaderCellLeft","selectRows","handleContextMenu","COLOR_POINTED","COLOR_SELECTED","SELECTING_FILL","COLOR_COPYING","COLOR_CUTTING","SEARCH_MATCHING_BACKGROUND","COLOR_SEARCH_MATCHING","COLOR_AUTOFILL","fillRect","drawRect","lineWidth","dashPattern","fillColor","drawAreaRectViewport","scrollTop","scrollLeft","viewW","viewH","topLeft","getCellRectPositions","bottomRight","x1","y1","x2","y2","CellStateOverlay","refs","canvasRef","rafIdRef","drawCanvas","canvas","container","dpr","w","toVirtualScrollTop","headerW","headerH","autofill","Autofill","vx","vy","copyingSheetId","copyingZone","cutting","copyingArea","palette","refArea","a2p","isCurrentMatch","firstCol","lastCol","getVisibleColRange","firstRow","lastRow","getVisibleRowRange","backgroundColor","drawLeft","drawWidth","drawTop","drawHeight","scheduleDrawCanvas","handleScroll","ro","Tabular","setPalette","virtualized","setVirtualized","ox","oy","handleMouseMove","virtualize","handleSelectAllClick","paletteBySheetName","normalizedRef","stripAddressAbsolute","splitterIndex","stripped","stripSheetName","upperRef","preventSafariBounce","mergedRefs","physicalScrollHeight","_g","_h","FormulaBar","ready","editingCell","hlRef","spilledFromAddress","originPoint","originAddress","observer","entries","updateScroll","largeInput","handleInput","Base","size","SearchIcon","CloseIcon","SearchBar","rootRef","searchCaseSensitive","searchRegex","searchRange","matchingCell","smartScroll","handleProgressClick","handleSearchClick","search","handleCaseSensitiveClick","setSearchCaseSensitive","handleRegexClick","setSearchRegex","hasSelection","isZoneNotSelected","selectionLabel","handleRangeClick","setSearchRange","searchRangeLabel","handleCloseClick","createSheetRef","createRef","useSheetRef","createStoreRef","useStoreRef","GridSheet","initialCells","initialSheetRef","initialStoreRef","options","initialBook","loadingProp","sheetResize","showFormulaBar","density","gridLines","formulaBarBorders","matrixBorders","bw","side","borderVars","flashRef","internalSheetRef","internalStoreRef","internalBook","useBook","book","initialState","limits","eager","Sheet","useReducer","defaultReducer","embedStyle","fillWidth","fillHeight","matrixAlignment","centersWidth","centersHeight","resizedWidth","setResizedWidth","resizedHeight","setResizedHeight","setSheetHeight","estimateSheetHeight","setSheetWidth","estimateSheetWidth","first","root","loading","setLoading","latestStoreRef","wrappedDispatch","action","async","isAsyncMutationAction","mutating","isMutationAction","overlayRef","pendingAsyncOp","nextSheet","ratio","commitAsyncOp","auto","getMaxSizesFromCells","estimatedHeight","HEADER_HEIGHT","DEFAULT_ROW_KEY","SHEET_HEIGHT","estimatedWidth","HEADER_WIDTH","DEFAULT_COL_KEY","SHEET_WIDTH","Check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