This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-07 20:43:49 +09:00
1 parent d4e8493cc5
commit 6ac83ce14e
4 files changed
+737 -24

No files matched your search

+37 -5
View File
@@ -86,14 +86,17 @@
directory: currentPath,
selectedFile,
expanded: [...expandedDirs],
preview: filePreviewRef?.captureView(),
preview: (commentPreviewRef ?? filePreviewRef)?.captureView(),
dirty: dirty || saving,
scrollTop: viewerRoot?.scrollTop ?? 0
};
const restoreView = async () => {
if (disposed || viewRestored || !initialView) return;
const view = initialView;
if (view.preview && selectedFile === view.selectedFile) {
if (view.preview?.kind === 'xlsx' && selectedFile === view.selectedFile) {
await tick();
await commentPreviewRef?.restoreView(view.preview);
} else if (view.preview && selectedFile === view.selectedFile) {
diskChanged = view.preview.dirty && fileContent !== view.preview.baseText;
await tick();
await filePreviewRef?.restoreView(
@@ -211,14 +214,14 @@
if (!confirmed) return false;
if (sending) {
try {
await filePreviewRef.save();
await (commentPreviewRef ?? filePreviewRef).save();
} catch (error) {
toast.error(String(error));
return false;
}
if (dirty) return false;
} else {
filePreviewRef?.discard();
await (commentPreviewRef ?? filePreviewRef)?.discard();
dirty = false;
}
return true;
@@ -644,6 +647,7 @@
let fileDocxData: ArrayBuffer | null = null;
let fileLoading = false;
let filePreviewRef: FilePreview;
let commentPreviewRef: CommentFilePreview;
let commentGeneration = 0;
let fileSearchTarget: FileSearchTarget | null = null;
let documentTargetPage: number | null = null;
@@ -2312,6 +2316,25 @@
</button>
</Tooltip>
{#if getFileExt(selectedFile) === 'xlsx' && selectedTerminal}
<Tooltip content={$i18n.t('Save')}>
<button
type="button"
class="shrink-0 flex h-5 w-5 items-center justify-center rounded transition-colors duration-100 text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 disabled:opacity-30 disabled:hover:bg-transparent"
on:click={() =>
commentPreviewRef?.save().catch((error) => toast.error(String(error)))}
disabled={saving || !dirty || !selectedFileWritable}
aria-label={$i18n.t('Save')}
>
{#if saving}
<Spinner className="size-3.5" />
{:else}
<Icon name="check" size={11} strokeWidth={1.7} />
{/if}
</button>
</Tooltip>
{/if}
{#if isTextFile}
{#if isHtml && showRaw}
<Tooltip content={$i18n.t('Save')}>
@@ -2488,7 +2511,8 @@
>
<button
class="underline"
on:click={() => filePreviewRef.save().catch((e) => toast.error(String(e)))}
on:click={() =>
(commentPreviewRef ?? filePreviewRef).save().catch((e) => toast.error(String(e)))}
>{$i18n.t('Save local changes')}</button
>
</div>{/if}
@@ -2524,6 +2548,14 @@
{#if supportsComments(selectedFile) && selectedTerminal}
{#key `${selectedTerminal.url}|${selectedTerminal.key}|${chatId}|${selectedFile}|${commentGeneration}`}
<CommentFilePreview
bind:this={commentPreviewRef}
bind:dirty
bind:saving
readOnly={!selectedFileWritable}
onSaved={(preview) => {
diskChanged = false;
onViewChange?.({ ...captureView(), preview, dirty: preview?.dirty ?? false });
}}
path={selectedFile}
baseUrl={selectedTerminal.url}
apiKey={selectedTerminal.key}
@@ -1,5 +1,5 @@
<script lang="ts">
import { getContext, onMount, onDestroy } from 'svelte';
import { getContext, onMount, onDestroy, tick } from 'svelte';
import type { WorkBook } from 'xlsx';
export let onReady = () => {};
export let currentSlide = 0;
@@ -13,7 +13,7 @@
};
$: (loading, previewError, reportReady());
import { downloadFileBlob, downloadFilePreview } from '$lib/apis/terminal';
import { downloadFileBlob, downloadFilePreview, uploadToTerminal } from '$lib/apis/terminal';
import { readOfficeComments } from '$lib/utils/comments/office';
import {
commentThreads,
@@ -21,7 +21,8 @@
type CommentResult,
type CommentState
} from '$lib/utils/comments/types';
import FilePreview from './FilePreview.svelte';
import ExcelPreview from '$lib/components/common/ExcelPreview.svelte';
import { ExcelWorkbookEditor } from '$lib/utils/excelToTable';
import Icon from './Icon.svelte';
import DocxPreview from '$lib/components/common/DocxPreview.svelte';
import PdfPagesPreview from '$lib/components/common/PdfPagesPreview.svelte';
@@ -33,6 +34,78 @@
export let apiKey: string;
export let chatId: string | null = null;
export let targetPage: number | null = null;
export let readOnly = true;
export let dirty = false;
export let saving = false;
export let onSaved: (preview: any) => void = () => {};
let editor: ExcelWorkbookEditor | null = null;
let excelPreview: ExcelPreview;
let loadingTask: Promise<void>;
let editingError = '';
export const captureView = () => {
return editor
? { ...editor.capture(), dirty, sheet, draft: excelPreview?.captureEdit() }
: null;
};
export async function restoreView(view: any) {
await loadingTask;
if (!alive || view?.kind !== 'xlsx') return;
const { readExcelWorkbook } = await import('$lib/utils/excelToTable');
workbook = await readExcelWorkbook(view.original);
editor = await ExcelWorkbookEditor.open(workbook, view.original);
editor.restore(view);
dirty = editor.dirty;
await setSheet(workbook.Sheets[view.sheet] ? view.sheet : workbook.SheetNames[0]);
await tick();
await excelPreview?.restoreEdit(view.draft);
}
export async function save() {
if (excelPreview && !excelPreview.flushEdit())
throw new Error('Finish or cancel the cell edit before saving.');
if (!editor || !editor.dirty) return;
if (readOnly || saving) throw new Error('File is not writable right now.');
saving = true;
try {
const bytes = await editor.bytes();
const current = await downloadFileBlob(baseUrl, apiKey, path, chatId ?? undefined);
if (!current)
throw new Error('Could not check the current file. Your changes are still in the editor.');
if (!editor.matches(await current.blob.arrayBuffer()))
throw new Error(
'The workbook changed on disk. Your edits are preserved. Reload the file before saving.'
);
// shortcut: the terminal upload API has no conditional write; it cannot prevent a concurrent write after this check.
const result = await uploadToTerminal(
baseUrl,
apiKey,
path.slice(0, path.lastIndexOf('/') + 1) || '/',
new File([bytes], path.split('/').pop()!, {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}),
chatId ?? undefined
);
if (!result)
throw new Error('Failed to save workbook. Your changes are still in the editor.');
editor.markSaved(bytes);
original = bytes;
dirty = editor.dirty;
onSaved(captureView());
} finally {
saving = false;
}
}
export async function discard() {
excelPreview?.cancelEdit();
dirty = false;
if (!original || !editor) return;
const { readExcelWorkbook } = await import('$lib/utils/excelToTable');
const fresh = await readExcelWorkbook(original);
if (!alive) return;
workbook = fresh;
editor = await ExcelWorkbookEditor.open(fresh, original);
await setSheet(sheet);
}
let comments: FileComment[] = [];
let warnings: string[] = [];
let commentState: CommentState = 'loading';
@@ -209,6 +282,13 @@
const { readExcelWorkbook } = await import('$lib/utils/excelToTable');
if (!alive) return;
workbook = await readExcelWorkbook(bytes);
if (ext === 'xlsx' && !readOnly) {
try {
editor = await ExcelWorkbookEditor.open(workbook, bytes);
} catch (error) {
editingError = String(error).replace(/^Error: /, '');
}
}
await setSheet(workbook.Sheets[initialSheet] ? initialSheet : workbook.SheetNames[0]);
loading = false;
}
@@ -241,7 +321,7 @@
}
}
onMount(() => {
void load();
loadingTask = load();
});
onDestroy(() => {
alive = false;
@@ -313,12 +393,19 @@
{:else if ext === 'pptx' && slides.length}
<PptxPreview bind:currentSlide {slides} {targetPage} className="h-full" {comments} />
{:else if table !== null}
<FilePreview
selectedFile={path}
fileOfficeHtml={table}
excelSheetNames={workbook?.SheetNames ?? []}
selectedExcelSheet={sheet}
{#if editingError}<p role="status" class="px-2 py-1 text-xs text-gray-500">
{editingError}
</p>{/if}
<ExcelPreview
bind:this={excelPreview}
html={table}
sheetNames={workbook?.SheetNames ?? []}
selectedSheet={sheet}
onSheetChange={setSheet}
editor={readOnly ? null : editor}
{saving}
onDirtyChange={(value) => (dirty = value)}
onSave={save}
/>
{:else if previewError}<p class="p-4 text-sm text-gray-500 dark:text-gray-400">
{$i18n.t('Preview failed')}
+265 -7
View File
@@ -2,6 +2,10 @@
import { getContext, tick } from 'svelte';
import Icon from '$lib/components/chat/FileNav/Icon.svelte';
import {
excelToTable,
parseSpreadsheetPaste,
type ExcelWorkbookEditor,
type CellEdit,
cellAddress,
intersects,
selectionBounds,
@@ -13,6 +17,19 @@
export let sheetNames: string[] = [];
export let selectedSheet = '';
export let onSheetChange: ((sheet: string) => void) | null = null;
export let editor: ExcelWorkbookEditor | null = null;
export let onDirtyChange: (dirty: boolean) => void = () => {};
export let onSave: (() => Promise<void>) | null = null;
export let saving = false;
let changed = false,
canUndo = false,
canRedo = false;
let input: HTMLTextAreaElement | null = null;
let editingCell: Cell | null = null;
let editStart = '';
let renderedSheet = '';
let restoreAddress = '';
let renderVersion = 0;
const i18n: any = getContext('i18n');
const t = (value: string) => $i18n.t(value);
type Cell = GridCell & { element: HTMLTableCellElement };
@@ -32,6 +49,21 @@
}
function shortcuts(node: HTMLDivElement) {
const handler = (event: KeyboardEvent) => {
if (editor && (event.ctrlKey || event.metaKey)) {
const key = event.key.toLowerCase();
if (key === 's') {
event.preventDefault();
event.stopPropagation();
void saveWorkbook();
return;
}
if (!input && ['z', 'y'].includes(key) && !(event.target instanceof HTMLInputElement)) {
event.preventDefault();
event.stopPropagation();
history(key === 'y' || event.shiftKey);
return;
}
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'f') {
event.preventDefault();
void openSearch();
@@ -67,6 +99,144 @@
: [];
$: if (query) matchIndex = -1;
$: (editor, saving, notifyChange());
export const captureEdit = () =>
input && editingCell ? { address: editingCell.address, text: input.value } : null;
export async function restoreEdit(draft: { address: string; text: string } | null) {
await tick();
if (!draft) return;
const cell = cells.find((cell) => cell.address === draft.address);
if (cell) startEdit(cell, draft.text);
}
function notifyChange() {
changed = !!editor?.dirty || (!!input && input.value !== editStart);
canUndo = !!editor?.canUndo;
canRedo = !!editor?.canRedo;
onDirtyChange(changed);
}
async function renderEdits() {
if (!editor) return;
const version = ++renderVersion;
const sheet = selectedSheet;
let result;
try {
result = await excelToTable(editor.workbook.Sheets[sheet]);
} catch (error) {
status = String(error);
return;
}
if (version !== renderVersion || sheet !== selectedSheet) return;
restoreAddress = focus?.address ?? '';
html = result.html;
}
function applyEdits(edits: CellEdit[]) {
if (!editor || saving) return false;
try {
editor.apply(selectedSheet, edits);
notifyChange();
void renderEdits();
return true;
} catch (error) {
status = String(error).replace(/^Error: /, '');
return false;
}
}
export function flushEdit() {
if (!input || !editingCell) return true;
const cell = editingCell,
text = input.value;
if (text !== editStart && !applyEdits([{ address: cell.address, text }])) return false;
const removed = input;
input = null;
editingCell = null;
removed.remove();
notifyChange();
return true;
}
export function cancelEdit() {
const removed = input;
input = null;
editingCell = null;
removed?.remove();
notifyChange();
focus?.element.focus();
}
function startEdit(cell: Cell, replacement?: string) {
if (!editor || saving || !flushEdit()) return;
if (!editor.canEdit(selectedSheet, cell.address)) {
status = t('Formula cells, table headers, and protected sheets are read-only.');
return;
}
select(cell);
editingCell = cell;
editStart = editor.input(selectedSheet, cell.address);
input = document.createElement('textarea');
input.className = 'excel-cell-input';
input.setAttribute('aria-label', `${t('Edit cell')} ${cell.address}`);
input.spellcheck = false;
input.value = replacement ?? editStart;
input.addEventListener('input', notifyChange);
input.addEventListener('blur', () => {
flushEdit();
});
input.addEventListener('keydown', (event) => {
if (event.isComposing) return;
if (event.key === 'Escape') {
event.preventDefault();
event.stopPropagation();
cancelEdit();
}
if ((event.key === 'Enter' && !event.altKey) || event.key === 'Tab') {
event.preventDefault();
event.stopPropagation();
if (!flushEdit()) return;
const target =
event.key === 'Tab'
? at(cell.row, cell.col + (event.shiftKey ? -1 : 1))
: at(cell.row + (event.shiftKey ? -1 : 1), cell.col);
if (target) select(target);
}
});
cell.element.append(input);
input.focus();
input.setSelectionRange(input.value.length, input.value.length);
notifyChange();
}
function paste(event: ClipboardEvent) {
if (!editor || saving || input || !focus || !fromTarget(event.target)) return;
event.preventDefault();
try {
const matrix = parseSpreadsheetPaste(event.clipboardData?.getData('text/plain') ?? '');
if (matrix.length * matrix[0].length > 10000)
throw new Error('Paste up to 10,000 cells at a time.');
const start = anchor ? selectionBounds(anchor, focus, cells) : focus;
applyEdits(
matrix.flatMap((row, r) =>
row.map((text, c) => ({ address: cellAddress(start.row + r, start.col + c), text }))
)
);
} catch (error) {
status = String(error).replace(/^Error: /, '');
}
}
function history(redo: boolean) {
if (!editor || saving || !flushEdit()) return;
if (redo) editor.redo();
else editor.undo();
notifyChange();
void renderEdits();
}
async function saveWorkbook() {
if (!flushEdit() || !onSave || saving) return;
try {
await onSave();
notifyChange();
status = t('Saved');
} catch (error) {
status = String(error).replace(/^Error: /, '');
}
}
function select(cell: Cell, extend = false, moveFocus = true) {
if (!extend || !anchor) anchor = cell;
focus = cell;
@@ -148,12 +318,21 @@
}
function doubleClick(event: MouseEvent) {
const handle = (event.target as Element).closest<HTMLElement>('[data-resize]');
if (!handle) return;
if (!handle) {
const cell = fromTarget(event.target);
if (cell && !(event.target as Element).closest('a')) startEdit(cell);
return;
}
event.preventDefault();
fitColumn(Number(handle.dataset.resize));
}
function pointerDown(event: PointerEvent) {
if (event.button !== 0) return;
if (event.button !== 0 || event.target === input) return;
if (!flushEdit()) {
event.preventDefault();
input?.focus();
return;
}
const handle = (event.target as Element).closest<HTMLElement>('[data-resize]');
if (handle) {
const col = Number(handle.dataset.resize);
@@ -188,6 +367,7 @@
resizing = null;
};
function keydown(event: KeyboardEvent) {
if (event.target === input || event.isComposing) return;
const command = event.ctrlKey || event.metaKey;
const handle = (event.target as Element).closest<HTMLElement>('[data-resize]');
@@ -204,6 +384,23 @@
return;
}
if (!fromTarget(event.target) || !focus) return;
if (editor && !saving) {
if (event.key === 'F2' || (!command && !event.altKey && event.key.length === 1)) {
event.preventDefault();
startEdit(focus, event.key === 'F2' ? undefined : event.key);
return;
}
if (['Backspace', 'Delete'].includes(event.key)) {
event.preventDefault();
const range = selectionBounds(anchor ?? focus, focus, cells);
applyEdits(
cells
.filter((cell) => intersects(cell, range))
.map((cell) => ({ address: cell.address, text: '' }))
);
return;
}
}
if (command && event.key.toLowerCase() === 'a') {
event.preventDefault();
anchor = cells[0];
@@ -287,7 +484,7 @@
const copiedText = () =>
anchor && focus ? selectionTSV(cells, rows, cols, selectionBounds(anchor, focus, cells)) : '';
function copy(event: ClipboardEvent) {
if (!anchor || !focus || !fromTarget(event.target)) return;
if (input || !anchor || !focus || !fromTarget(event.target)) return;
event.preventDefault();
event.clipboardData?.setData('text/plain', copiedText());
status = t('Copied to clipboard');
@@ -429,6 +626,12 @@
});
};
async function refresh() {
const sameSheet = renderedSheet === selectedSheet;
const previousAnchor = sameSheet ? anchor?.address : '';
const previousFocus = sameSheet ? restoreAddress || focus?.address : '';
const focusGrid = !!restoreAddress || node.contains(document.activeElement);
const previousRows = sameSheet ? rows[rows.length - 1] : 0,
previousCols = sameSheet ? cols[cols.length - 1] : 0;
const version = ++generation;
await tick();
if (version !== generation) return;
@@ -451,6 +654,11 @@
Number(col.getAttribute('data-col'))
);
const table = node.querySelector('table');
table?.setAttribute('aria-readonly', String(!editor || saving));
extendGrid(
Math.max(0, (previousRows ?? 0) - rows[rows.length - 1]),
Math.max(0, (previousCols ?? 0) - cols[cols.length - 1])
);
usedRange = table?.dataset.usedRange ?? '';
lastUsedRow = Number(table?.dataset.lastRow ?? 0);
lastUsedCol = Number(table?.dataset.lastCol ?? 0);
@@ -460,14 +668,19 @@
formula = '';
matchIndex = -1;
for (const [col, width] of widths.get(selectedSheet) ?? []) setWidth(col, width);
const target = cells.find((c) => c.address === pendingLink) ?? cells[0];
if (target) select(target, false, !!pendingLink);
const target = cells.find((c) => c.address === (pendingLink || previousFocus)) ?? cells[0];
anchor = cells.find((c) => c.address === previousAnchor) ?? null;
if (target) select(target, !!anchor, !!pendingLink || focusGrid);
pendingLink = '';
restoreAddress = '';
renderedSheet = selectedSheet;
notifyChange();
}
node.addEventListener('scroll', scroll, { passive: true });
node.addEventListener('pointerdown', pointerDown);
node.addEventListener('keydown', keydown);
node.addEventListener('copy', copy);
node.addEventListener('paste', paste);
node.addEventListener('click', followLink);
node.addEventListener('dblclick', doubleClick);
window.addEventListener('pointermove', pointerMove);
@@ -484,6 +697,7 @@
node.removeEventListener('pointerdown', pointerDown);
node.removeEventListener('keydown', keydown);
node.removeEventListener('copy', copy);
node.removeEventListener('paste', paste);
node.removeEventListener('click', followLink);
node.removeEventListener('dblclick', doubleClick);
window.removeEventListener('pointermove', pointerMove);
@@ -567,13 +781,38 @@
class="shrink-0 px-2 py-1 text-xs rounded-md transition-colors {selectedSheet === name
? 'bg-gray-100/40 dark:bg-gray-800/25 text-gray-700 dark:text-gray-200 font-normal'
: 'text-gray-500 dark:text-gray-400 hover:bg-gray-100/30 dark:hover:bg-gray-800/20 hover:text-gray-600 dark:hover:text-gray-300'}"
on:click={() => onSheetChange?.(name)}>{name}</button
disabled={saving}
on:click={() => {
if (flushEdit()) onSheetChange?.(name);
}}>{name}</button
>{/each}
</div>
<span class="excel-status text-gray-400 dark:text-gray-500" aria-live="polite"
<span
class="excel-status text-gray-400 dark:text-gray-500"
role="status"
title={status}
aria-live="polite"
>{status || (usedRange ? `${t('Used range')}: ${usedRange}` : t('Empty sheet'))}</span
>
<div class="flex shrink-0 items-center gap-0.5 text-gray-500 dark:text-gray-400">
{#if editor}
<button
type="button"
class="excel-control"
aria-label={t('Undo')}
title={t('Undo')}
disabled={!canUndo || saving}
on:click={() => history(false)}><Icon name="undo" size={13} /></button
>
<button
type="button"
class="excel-control"
aria-label={t('Redo')}
title={t('Redo')}
disabled={!canRedo || saving}
on:click={() => history(true)}><Icon name="redo" size={13} /></button
>
{/if}
<button
class="excel-control"
type="button"
@@ -797,6 +1036,25 @@
:global(.dark) .excel-viewport :global(.excel-resize:focus-visible) {
background: linear-gradient(to left, var(--color-gray-400) 1px, transparent 1px);
}
.excel-viewport :global(.excel-cell-input) {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
min-height: 26px;
padding: 4px 7px;
margin: 0;
resize: none;
border: 1px solid var(--color-gray-600, #4b5563);
outline: none;
box-shadow: none;
border-radius: 0;
background: white;
color: #111827;
font: inherit;
line-height: inherit;
text-align: inherit;
}
.excel-footer {
display: flex;
align-items: center;
+339 -3
View File
@@ -1,3 +1,5 @@
import * as XLSX from 'xlsx';
import { OfficePackage, attr, children, elements } from './comments/package';
import type { CellObject, Range, WorkBook, WorkSheet } from 'xlsx';
export type PreviewSheet = WorkSheet & { '!previewStyles'?: Record<string, string> };
@@ -5,10 +7,8 @@ export type PreviewSheet = WorkSheet & { '!previewStyles'?: Record<string, strin
// SheetJS CE reads values and number formats, but not fonts, borders or alignment.
// Keep presentation metadata separate from the workbook's editable cell values.
export async function readExcelWorkbook(data: ArrayBuffer): Promise<WorkBook> {
const XLSX = await import('xlsx');
const workbook = XLSX.read(data, { type: 'array', cellStyles: true, cellNF: true });
if (new Uint8Array(data)[0] !== 0x50 || new Uint8Array(data)[1] !== 0x4b) return workbook; // XLS / CSV have no OOXML styles.
const { OfficePackage, elements, children, attr } = await import('./comments/package');
const pkg = await OfficePackage.open(data);
const main = await pkg.main();
const rels = await pkg.relationships(main);
@@ -247,7 +247,6 @@ export interface ExcelTableResult {
/** Render from cells, not sheet_to_json: formatted text, formulas and coordinates matter. */
export async function excelToTable(worksheet: PreviewSheet): Promise<ExcelTableResult> {
const XLSX = await import('xlsx');
const range = XLSX.utils.decode_range(worksheet['!ref'] ?? 'A1');
const merges = worksheet['!merges'] ?? [];
for (const merge of merges) {
@@ -425,3 +424,340 @@ export function selectionTSV(
)
.join('\n');
}
export type CellEdit = { address: string; text: string };
type Change = { sheet: string; address: string; before?: CellObject; after?: CellObject };
type Transaction = Change[];
const signature = (cell?: CellObject) =>
JSON.stringify([cell?.t === 'z' ? undefined : cell?.t, cell?.v, cell?.f]);
const key = (sheet: string, address: string) => `${sheet}\0${address}`;
/** Spreadsheet clipboard text, including quoted tabs, newlines and doubled quotes. */
export function parseSpreadsheetPaste(text: string): string[][] {
if (text.length > 4 * 1024 * 1024) throw new Error('Paste up to 4 MiB of text at a time.');
const rows: string[][] = [[]];
let value = '',
quoted = false;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (c === '"' && (quoted || !value)) {
if (quoted && text[i + 1] === '"') {
value += '"';
i++;
} else quoted = !quoted;
} else if (!quoted && (c === '\t' || c === '\n' || c === '\r')) {
if (rows.length > 10000 || rows[rows.length - 1].length >= 10000)
throw new Error('Paste up to 10,000 cells at a time.');
rows[rows.length - 1].push(value);
value = '';
if (c !== '\t') {
if (c === '\r' && text[i + 1] === '\n') i++;
rows.push([]);
}
} else value += c;
}
if (quoted) throw new Error('The pasted text has an unclosed quote.');
rows[rows.length - 1].push(value);
if (rows.length > 1 && /[\r\n]$/.test(text)) rows.pop();
const width = Math.max(...rows.map((row) => row.length));
if (rows.length * width > 10000) throw new Error('Paste up to 10,000 cells at a time.');
return rows.map((row) => [...row, ...Array(width - row.length).fill('')]);
}
export class ExcelWorkbookEditor {
private history: Transaction[] = [];
private position = 0;
private changes = new Map<string, Change>();
private savedState = '[]';
private protectedSheets = new Set<string>();
private readOnlyRanges = new Map<string, XLSX.Range[]>();
private sheetPaths = new Map<string, string>();
private original: ArrayBuffer;
private expected: ArrayBuffer;
private constructor(
readonly workbook: WorkBook,
bytes: ArrayBuffer
) {
this.original = this.expected = bytes;
}
static async open(workbook: WorkBook, bytes: ArrayBuffer) {
const editor = new ExcelWorkbookEditor(workbook, bytes);
const pkg = await OfficePackage.open(bytes);
if (Object.keys(pkg.zip.files).some((path) => path.startsWith('_xmlsignatures/')))
throw new Error('Signed workbooks are read-only.');
const main = await pkg.main(),
doc = await pkg.xml(main);
if (!doc) throw new Error('Could not read workbook.');
const rels = await pkg.relationships(main);
for (const sheet of elements(doc, 'sheet')) {
const path = rels.find((r) => r.id === attr(sheet, 'id'))?.path;
if (!path) continue;
const xml = await pkg.xml(path);
const name = attr(sheet, 'name');
if (!xml) continue;
editor.sheetPaths.set(name, path);
editor.readOnlyRanges.set(
name,
elements(xml, 'f')
.filter((f) => attr(f, 'ref'))
.map((f) => XLSX.utils.decode_range(attr(f, 'ref')))
);
// Table header names also live in table definitions and structured formula references.
for (const rel of (await pkg.relationships(path)).filter((r) => r.type.endsWith('/table'))) {
const table = (await pkg.xml(rel.path))?.documentElement;
if (!table || attr(table, 'headerRowCount') === '0') continue;
const range = XLSX.utils.decode_range(attr(table, 'ref'));
range.e.r = range.s.r;
editor.readOnlyRanges.get(name)!.push(range);
}
if (elements(xml, 'sheetProtection').length) editor.protectedSheets.add(name);
}
return editor;
}
canEdit(sheet: string, address: string) {
const ws = this.workbook.Sheets[sheet];
if (!ws || !this.sheetPaths.has(sheet) || this.protectedSheets.has(sheet)) return false;
const { r, c } = XLSX.utils.decode_cell(address);
if (
this.readOnlyRanges
.get(sheet)
?.some((range) => r >= range.s.r && r <= range.e.r && c >= range.s.c && c <= range.e.c)
)
return false;
const cell = ws[address];
return !cell?.f && !cell?.F;
}
input(sheet: string, address: string) {
const cell = this.workbook.Sheets[sheet]?.[address];
return cell?.f ? `=${cell.f}` : cell?.v == null ? '' : String(cell.v);
}
get canUndo() {
return this.position > 0;
}
get canRedo() {
return this.position < this.history.length;
}
private state() {
return JSON.stringify(
[...this.changes]
.filter(([, c]) => signature(c.before) !== signature(c.after))
.map(([id, c]) => [id, signature(c.after)])
.sort(([a], [b]) => a.localeCompare(b))
);
}
get dirty() {
return this.state() !== this.savedState;
}
apply(sheet: string, edits: CellEdit[]) {
const ws = this.workbook.Sheets[sheet];
if (edits.length > 10000) throw new Error('Paste up to 10,000 cells at a time.');
const transaction: Transaction = [];
const bounds = XLSX.utils.decode_range(ws?.['!ref'] ?? edits[0]?.address ?? 'A1');
for (const { address, text } of edits) {
if (!/^[A-Z]{1,3}[1-9]\d{0,6}$/.test(address)) throw new Error('Invalid cell address.');
const { r, c } = XLSX.utils.decode_cell(address);
if (r > 1048575 || c > 16383) throw new Error('The paste exceeds the worksheet boundary.');
if (!this.canEdit(sheet, address))
throw new Error('Formula cells, table headers, and protected sheets are read-only.');
if (text.length > 32767 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text))
throw new Error('Cell text is too long or contains unsupported control characters.');
const merge = ws['!merges']?.find(
(m) => r >= m.s.r && r <= m.e.r && c >= m.s.c && c <= m.e.c
);
if (merge && (r !== merge.s.r || c !== merge.s.c || edits.length > 1))
throw new Error('Paste into unmerged cells.');
bounds.s.r = Math.min(bounds.s.r, r);
bounds.s.c = Math.min(bounds.s.c, c);
bounds.e.r = Math.max(bounds.e.r, r);
bounds.e.c = Math.max(bounds.e.c, c);
if ((bounds.e.r - bounds.s.r + 1) * (bounds.e.c - bounds.s.c + 1) > 200000)
throw new Error('This edit would exceed the preview size limit.');
const before: CellObject | undefined = ws[address];
if (text === this.input(sheet, address)) continue;
const after = { ...before } as CellObject;
delete after.w;
delete after.h;
delete after.r;
if (text.startsWith('='))
throw new Error(
'Formula editing is not supported yet. Start with an apostrophe to enter literal text.'
);
if (text === '') {
after.t = 'z';
delete after.v;
} else if (text.startsWith("'")) {
after.t = 's';
after.v = text.slice(1);
} else if (/^(true|false)$/i.test(text)) {
after.t = 'b';
after.v = text.toLowerCase() === 'true';
} else if (
/^[+-]?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?%?$/.test(text) &&
Number.isFinite(Number(text.replace(/%$/, ''))) &&
text
.replace(/[eE].*|%$/g, '')
.replace(/[^0-9]/g, '')
.replace(/^0+/, '').length <= 15
) {
after.t = 'n';
after.v = Number(text.replace(/%$/, '')) / (text.endsWith('%') ? 100 : 1);
} else {
after.t = 's';
after.v = text;
}
if (signature(before) !== signature(after))
transaction.push({ sheet, address, before, after });
}
// Validate the entire transaction before touching any cells.
if (!transaction.length) return;
this.history.splice(this.position);
this.history.push(transaction);
this.position++;
this.applyChanges(transaction, false);
}
private applyChanges(transaction: Transaction, undo: boolean) {
for (const change of transaction) {
const cell = undo ? change.before : change.after;
const ws = this.workbook.Sheets[change.sheet];
if (cell) ws[change.address] = cell;
else delete ws[change.address];
const id = key(change.sheet, change.address);
const first = this.changes.get(id) ?? change;
this.changes.set(id, { ...first, after: cell });
const range = XLSX.utils.decode_range(ws['!ref'] ?? change.address);
const { r, c } = XLSX.utils.decode_cell(change.address);
range.s.r = Math.min(range.s.r, r);
range.s.c = Math.min(range.s.c, c);
range.e.r = Math.max(range.e.r, r);
range.e.c = Math.max(range.e.c, c);
ws['!ref'] = XLSX.utils.encode_range(range);
}
}
undo() {
if (this.canUndo) this.applyChanges(this.history[--this.position], true);
}
redo() {
if (this.canRedo) this.applyChanges(this.history[this.position++], false);
}
matches(bytes: ArrayBuffer) {
const a = new Uint8Array(this.expected),
b = new Uint8Array(bytes);
return a.length === b.length && a.every((v, i) => v === b[i]);
}
markSaved(bytes: ArrayBuffer) {
this.expected = bytes;
this.savedState = this.state();
}
capture() {
return {
kind: 'xlsx',
original: this.original,
expected: this.expected,
history: this.history.slice(),
position: this.position,
savedState: this.savedState,
changes: [...this.changes]
};
}
restore(view: ReturnType<ExcelWorkbookEditor['capture']>) {
this.original = view.original;
this.expected = view.expected;
this.history = view.history;
this.position = view.position;
this.savedState = view.savedState;
this.changes = new Map(view.changes);
this.applyChanges([...this.changes.values()], false);
}
async bytes(): Promise<ArrayBuffer> {
const pkg = await OfficePackage.open(this.original);
const changed = [...this.changes.values()].filter(
(c) => signature(c.before) !== signature(c.after)
);
for (const sheet of new Set(changed.map((c) => c.sheet))) {
const path = this.sheetPaths.get(sheet)!;
const doc = await pkg.xml(path);
if (!doc) throw new Error('Could not read worksheet.');
const data = elements(doc, 'sheetData')[0];
if (!data) throw new Error('Could not read worksheet cells.');
const create = (name: string) =>
doc.createElementNS(data.namespaceURI, `${data.prefix ? data.prefix + ':' : ''}${name}`);
for (const change of changed.filter((c) => c.sheet === sheet)) {
const { r, c } = XLSX.utils.decode_cell(change.address);
let row = children(data).find((row) => Number(attr(row, 'r')) === r + 1);
if (!row) {
row = create('row');
row.setAttribute('r', String(r + 1));
data.insertBefore(row, children(data).find((n) => Number(attr(n, 'r')) > r + 1) ?? null);
}
row.removeAttribute('spans');
let cell = children(row).find((cell) => attr(cell, 'r') === change.address);
if (!cell) {
cell = create('c');
cell.setAttribute('r', change.address);
row.insertBefore(
cell,
children(row).find((n) => XLSX.utils.decode_cell(attr(n, 'r')).c > c) ?? null
);
}
for (const n of children(cell).filter((n) => ['v', 'is', 'f'].includes(n.localName)))
cell.removeChild(n);
cell.removeAttribute('t');
const value = change.after;
if (value?.v != null) {
const node = create(value.t === 's' ? 'is' : 'v');
if (value.t === 's') {
cell.setAttribute('t', 'inlineStr');
const text = create('t');
text.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve');
text.textContent = String(value.v).replace(
/_x[0-9a-f]{4}_/gi,
(value) => '_x005F_' + value.slice(1)
);
node.appendChild(text);
} else {
cell.setAttribute('t', value.t === 'b' ? 'b' : 'n');
node.textContent = value.t === 'b' ? (value.v ? '1' : '0') : String(value.v);
}
cell.insertBefore(node, cell.firstChild);
}
}
const dimension = elements(doc, 'dimension')[0];
if (dimension) dimension.setAttribute('ref', this.workbook.Sheets[sheet]['!ref'] ?? 'A1');
pkg.zip.file(path, new XMLSerializer().serializeToString(doc), { createFolders: false });
}
// Excel recalculates dependent formulas on open; no browser formula engine is involved.
if (changed.length) {
const main = await pkg.main(),
doc = await pkg.xml(main);
if (!doc) throw new Error('Could not read workbook.');
let calc = elements(doc, 'calcPr')[0];
if (!calc) {
const root = doc.documentElement;
calc = doc.createElementNS(
root.namespaceURI,
`${root.prefix ? root.prefix + ':' : ''}calcPr`
);
const following = [
'oleSize',
'customWorkbookViews',
'pivotCaches',
'smartTagPr',
'smartTagTypes',
'webPublishing',
'fileRecoveryPr',
'webPublishObjects',
'extLst'
];
root.insertBefore(
calc,
children(root).find((n) => following.includes(n.localName)) ?? null
);
}
calc.setAttribute('fullCalcOnLoad', '1');
calc.setAttribute('forceFullCalc', '1');
calc.setAttribute('calcMode', 'auto');
pkg.zip.file(main, new XMLSerializer().serializeToString(doc), { createFolders: false });
}
return pkg.zip.generateAsync({ type: 'arraybuffer', compression: 'DEFLATE' });
}
}