Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(sheets): handle Cmd+C / Cmd+V whenever the sheet is the active block (#7698)

teo2f7f227bad02
diff --git a/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx b/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx
index 287a05fa7f..77aab6ee0f 100644
--- a/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx
+++ b/apps/web/src/features/block-spreadsheet/SpreadsheetBlock.tsx
@@ -9,7 +9,10 @@ import {
SplitHeaderRight,
} from '@components/app/split-layout/components/SplitHeader';
import { BlockItemSplitLabel } from '@components/app/split-layout/components/SplitLabel';
-import { useCanAutofocusSplitContent } from '@components/app/split-layout/layoutUtils';
+import {
+ useCanAutofocusSplitContent,
+ useSplitPanel,
+} from '@components/app/split-layout/layoutUtils';
import { useNavigatedFromJK } from '@components/app/useNavigatedFromJK';
import { useBlockId } from '@core/block';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
@@ -27,6 +30,7 @@ import { useUserId } from '@core/context/user';
import { blockDataSignal } from '@core/internal/BlockLoader';
import { isMobile } from '@core/mobile/isMobile';
import { createMethodRegistration } from '@core/orchestrator';
+import { blockElementSignal } from '@core/signal/blockElement';
import { blockHandleSignal, blockMetadataSignal } from '@core/signal/load';
import { useCanEdit, useGetPermissions } from '@core/signal/permissions';
import { getDisplayName, tryMacroId } from '@core/user';
@@ -36,6 +40,7 @@ import IconShared from '@icon/share.svg';
import { Badge } from '@ui';
import { onMount, Show } from 'solid-js';
import { spreadsheetChatContext } from './core/chat-context';
+import { clipboardTargetInScope } from './core/clipboard-scope';
import type { SpreadsheetData } from './definition';
import { createSpreadsheetStore } from './primitives/create-spreadsheet-store';
import { useSpreadsheetAccess } from './primitives/use-spreadsheet-access';
@@ -73,6 +78,18 @@ function SpreadsheetBlockContent(props: { share?: string }) {
const canEdit = useCanEdit();
const userId = useUserId();
const permissions = useGetPermissions();
+ const splitPanel = useSplitPanel();
+ const blockElement = blockElementSignal.get;
+ const ownsClipboard = (event: ClipboardEvent) =>
+ !!splitPanel?.isPanelActive() &&
+ clipboardTargetInScope(event.target, {
+ block: blockElement(),
+ // An inline preview shares its host's panel with the host's own content.
+ panel: splitPanel.isInlinePreview
+ ? undefined
+ : (splitPanel.panelRef() ?? undefined),
+ chrome: Object.values(splitPanel.layoutRefs),
+ });
const canAutofocus = useCanAutofocusSplitContent();
const { navigatedFromJK } = useNavigatedFromJK();
const openShare = useShareModal(() => ({
@@ -180,6 +197,7 @@ function SpreadsheetBlockContent(props: { share?: string }) {
autoFocus={canAutofocus && !navigatedFromJK()}
commentLocation={commentLocation()}
comments={comments}
+ ownsClipboard={ownsClipboard}
mentions={spreadsheetMentions}
store={store}
name={name()}
diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx
index d815df9b5c..4e9863952e 100644
--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx
+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.test.tsx
@@ -49,6 +49,7 @@ function renderGrid(
| 'sheetId'
| 'onFill'
| 'onResizeColumn'
+ | 'ownsClipboard'
> & {
values?: ComponentProps<typeof SpreadsheetGrid>['values'];
readonly?: boolean;
@@ -141,6 +142,7 @@ function renderGrid(
onCopy={onCopy}
onCopyMetadata={onCopyMetadata}
onPaste={onPaste}
+ ownsClipboard={options.ownsClipboard}
onClear={onClear}
onGridReady={() => {}}
/>
@@ -169,10 +171,10 @@ function renderGrid(
}
function clipboardEvent(
- type: 'paste' | 'cut',
+ type: 'paste' | 'cut' | 'copy' | 'beforecopy',
data: {
types: string[];
- getData: () => string;
+ getData: (format: string) => string;
setData?: (format: string, value: string) => void;
} | null
): Event {
@@ -570,6 +572,90 @@ describe('spreadsheet grid clipboard and editing', () => {
expect(view.cells().A1.value).toBe('');
});
+ it('handles clipboard shortcuts while focus rests outside the grid in its block', () => {
+ const toolbarButton = document.createElement('button');
+ document.body.append(toolbarButton);
+ const view = renderGrid(
+ { A1: { value: 'copied' } },
+ { ownsClipboard: (event) => event.target === toolbarButton }
+ );
+ const setData = vi.fn();
+ const copy = clipboardEvent('copy', {
+ types: [],
+ getData: () => '',
+ setData,
+ });
+ fireEvent(toolbarButton, copy);
+ expect(copy.defaultPrevented).toBe(true);
+ expect(view.onCopy).toHaveBeenCalledTimes(1);
+ expect(setData).toHaveBeenCalledWith('text/plain', 'copied');
+
+ const beforeCopy = clipboardEvent('beforecopy', null);
+ fireEvent(toolbarButton, beforeCopy);
+ expect(beforeCopy.defaultPrevented).toBe(true);
+
+ fireEvent(
+ toolbarButton,
+ clipboardEvent('paste', {
+ types: ['text/plain'],
+ getData: (format: string) => (format === 'text/plain' ? 'pasted' : ''),
+ })
+ );
+ expect(view.onPaste).toHaveBeenCalledWith('pasted', undefined);
+ expect(view.cells().A1.value).toBe('pasted');
+
+ // Another block's focus, or an event the grid already handled, is left alone.
+ const elsewhere = document.createElement('button');
+ document.body.append(elsewhere);
+ const foreign = clipboardEvent('copy', {
+ types: [],
+ getData: () => '',
+ setData,
+ });
+ fireEvent(elsewhere, foreign);
+ expect(foreign.defaultPrevented).toBe(false);
+ fireEvent(
+ view.element,
+ clipboardEvent('copy', { types: [], getData: () => '', setData })
+ );
+ expect(view.onCopy).toHaveBeenCalledTimes(2);
+ toolbarButton.remove();
+ elsewhere.remove();
+ });
+
+ it('leaves outside inputs and text selections to the browser', () => {
+ const host = document.createElement('div');
+ const input = document.createElement('input');
+ const text = document.createElement('p');
+ text.textContent = 'selectable text';
+ host.append(input, text);
+ document.body.append(host);
+ const view = renderGrid(
+ { A1: { value: 'keep' } },
+ { ownsClipboard: () => true }
+ );
+ const paste = clipboardEvent('paste', {
+ types: ['text/plain'],
+ getData: () => 'typed',
+ });
+ fireEvent(input, paste);
+ expect(paste.defaultPrevented).toBe(false);
+ expect(view.onPaste).not.toHaveBeenCalled();
+
+ const selection = document.getSelection()!;
+ selection.selectAllChildren(text);
+ const copy = clipboardEvent('copy', {
+ types: [],
+ getData: () => '',
+ setData: vi.fn(),
+ });
+ fireEvent(text, copy);
+ expect(copy.defaultPrevented).toBe(false);
+ expect(view.onCopy).not.toHaveBeenCalled();
+ selection.removeAllRanges();
+ host.remove();
+ });
+
it('preserves multiline input and focus while editing, then commits on Enter', () => {
const view = renderGrid({ A1: { value: 'line\nbreak' } });
fireEvent.keyDown(view.element, { key: 'F2' });
diff --git a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx
index 5ac1c1b5b9..e98c37081e 100644
--- a/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx
+++ b/apps/web/src/features/block-spreadsheet/components/SpreadsheetGrid.tsx
@@ -238,6 +238,8 @@ export function SpreadsheetGrid(props: {
onKeyDown: (event: KeyboardEvent) => void;
onCopy: (cut?: boolean) => string;
onPaste: (text: string, metadata?: string) => void;
+ /** Whether a clipboard shortcut fired outside the grid is meant for it. */
+ ownsClipboard?: (event: ClipboardEvent) => boolean;
onClear: () => void;
onGridReady: (element: HTMLDivElement) => void;
}) {
@@ -960,17 +962,97 @@ export function SpreadsheetGrid(props: {
}
}
+ function copyCells(event: ClipboardEvent) {
+ event.preventDefault();
+ event.clipboardData?.setData('text/plain', props.onCopy());
+ if (props.onCopyMetadata)
+ event.clipboardData?.setData(
+ SPREADSHEET_CLIPBOARD_TYPE,
+ props.onCopyMetadata()
+ );
+ }
+ function cutCells(event: ClipboardEvent) {
+ if (!event.clipboardData) return;
+ event.preventDefault();
+ // A viewer can copy with the cut shortcut, but no cells move. Mark its
+ // metadata as a copy so formulas still translate on a later paste.
+ const cut = !props.readonly;
+ event.clipboardData.setData('text/plain', props.onCopy(cut));
+ if (props.onCopyMetadata)
+ event.clipboardData.setData(
+ SPREADSHEET_CLIPBOARD_TYPE,
+ props.onCopyMetadata(cut)
+ );
+ if (cut) props.onClear();
+ }
+ function pasteCells(event: ClipboardEvent) {
+ event.preventDefault();
+ if (!props.readonly && event.clipboardData?.types.includes('text/plain'))
+ props.onPaste(
+ event.clipboardData.getData('text/plain'),
+ event.clipboardData.getData(SPREADSHEET_CLIPBOARD_TYPE) || undefined
+ );
+ }
+ // Focus often rests on the toolbar, sheet tabs, split chrome, or the body
+ // while the sheet is the active block; the shortcut still targets cells.
+ function claimsClipboard(event: ClipboardEvent) {
+ const target = event.target;
+ if (
+ event.defaultPrevented ||
+ props.editing ||
+ !(target instanceof Element) ||
+ grid.contains(target) ||
+ isInput(target) ||
+ target.closest('[role="dialog"], [role="menu"], [role="listbox"]')
+ )
+ return false;
+ // Leave a text selection outside the grid to the browser's own copy.
+ const selection = document.getSelection();
+ if (
+ !event.type.endsWith('paste') &&
+ selection &&
+ !selection.isCollapsed &&
+ !grid.contains(selection.anchorNode)
+ )
+ return false;
+ return props.ownsClipboard?.(event) ?? false;
+ }
+ const onDocumentClipboard = (event: ClipboardEvent) => {
+ if (!claimsClipboard(event)) return;
+ if (event.type === 'copy') copyCells(event);
+ else if (event.type === 'cut') cutCells(event);
+ else if (event.type === 'paste') pasteCells(event);
+ // WebKit only dispatches the clipboard event from a non-editable focus
+ // when its before* event is cancelled.
+ else event.preventDefault();
+ };
+ const clipboardEvents = [
+ 'beforecopy',
+ 'beforecut',
+ 'beforepaste',
+ 'copy',
+ 'cut',
+ 'paste',
+ ] as const;
+
onMount(() => {
props.onGridReady(grid);
window.addEventListener('pointerup', endPointer);
window.addEventListener('pointermove', movePointer, { passive: false });
window.addEventListener('pointercancel', cancelPointer);
window.addEventListener('blur', cancelPointer);
+ for (const type of clipboardEvents)
+ document.addEventListener(type, onDocumentClipboard as EventListener);
onCleanup(() => {
window.removeEventListener('pointerup', endPointer);
window.removeEventListener('pointermove', movePointer);
window.removeEventListener('pointercancel', cancelPointer);
window.removeEventListener('blur', cancelPointer);
+ for (const type of clipboardEvents)
+ document.removeEventListener(
+ type,
+ onDocumentClipboard as EventListener
+ );
stopTouchGesture();
});
});
@@ -1162,42 +1244,13 @@ export function SpreadsheetGrid(props: {
revealSelection();
}}
onCopy={(event) => {
- if (isInput(event.target)) return;
- event.preventDefault();
- event.clipboardData?.setData('text/plain', props.onCopy());
- if (props.onCopyMetadata)
- event.clipboardData?.setData(
- SPREADSHEET_CLIPBOARD_TYPE,
- props.onCopyMetadata()
- );
+ if (!isInput(event.target)) copyCells(event);
}}
onCut={(event) => {
- if (isInput(event.target)) return;
- if (!event.clipboardData) return;
- event.preventDefault();
- // A viewer can copy with the cut shortcut, but no cells move. Mark its
- // metadata as a copy so formulas still translate on a later paste.
- const cut = !props.readonly;
- event.clipboardData.setData('text/plain', props.onCopy(cut));
- if (props.onCopyMetadata)
- event.clipboardData.setData(
- SPREADSHEET_CLIPBOARD_TYPE,
- props.onCopyMetadata(cut)
- );
- if (cut) props.onClear();
+ if (!isInput(event.target)) cutCells(event);
}}
onPaste={(event) => {
- if (isInput(event.target)) return;
- event.preventDefault();
- if (
- !props.readonly &&
- event.clipboardData?.types.includes('text/plain')
- )
- props.onPaste(
- event.clipboardData.getData('text/plain'),
- event.clipboardData.getData(SPREADSHEET_CLIPBOARD_TYPE) ||
- undefined
- );
+ if (!isInput(event.target)) pasteCells(event);
}}
>
<div
diff --git a/apps/web/src/features/block-spreadsheet/core/clipboard-scope.test.ts b/apps/web/src/features/block-spreadsheet/core/clipboard-scope.test.ts
new file mode 100644
index 0000000000..83264a4909
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/clipboard-scope.test.ts
@@ -0,0 +1,72 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { clipboardTargetInScope } from './clipboard-scope';
+
+afterEach(() => {
+ document.body.replaceChildren();
+});
+
+function layout(html: string) {
+ document.body.innerHTML = html;
+ const get = (id: string) => document.getElementById(id) ?? undefined;
+ return get;
+}
+
+describe('clipboardTargetInScope', () => {
+ it('claims the block, its chrome, and its focused wrappers', () => {
+ const get = layout(`
+ <div id="panel" tabindex="-1">
+ <div id="preview" tabindex="-1">
+ <div id="toolbar"><button id="tool"></button></div>
+ <div id="block" data-block-type="spreadsheet"><button id="tab"></button></div>
+ </div>
+ </div>
+ <div id="sidebar"><button id="row"></button></div>
+ `);
+ const scope = {
+ block: get('block'),
+ panel: undefined,
+ chrome: [get('toolbar')],
+ };
+ for (const id of ['block', 'tab', 'tool', 'preview', 'panel'])
+ expect(clipboardTargetInScope(get(id)!, scope)).toBe(true);
+ expect(clipboardTargetInScope(get('row')!, scope)).toBe(false);
+ expect(clipboardTargetInScope(null, scope)).toBe(false);
+ });
+
+ it('claims the split panel and the body when the sheet is its main content', () => {
+ const get = layout(`
+ <div id="panel"><button id="close"></button><div id="block"></div></div>
+ `);
+ const scope = { block: get('block'), panel: get('panel'), chrome: [] };
+ expect(clipboardTargetInScope(get('close')!, scope)).toBe(true);
+ expect(clipboardTargetInScope(document.body, scope)).toBe(true);
+ });
+
+ it('leaves the body to the host when the sheet is an inline preview', () => {
+ const get = layout(`
+ <div><div id="block" data-block-type="spreadsheet"></div></div>
+ `);
+ expect(
+ clipboardTargetInScope(document.body, {
+ block: get('block'),
+ panel: undefined,
+ chrome: [],
+ })
+ ).toBe(false);
+ });
+
+ it('leaves a host block that embeds the sheet in charge of its clipboard', () => {
+ const get = layout(`
+ <div id="canvas" data-block-type="canvas" tabindex="0">
+ <div id="block" data-block-type="spreadsheet"></div>
+ </div>
+ `);
+ expect(
+ clipboardTargetInScope(get('canvas')!, {
+ block: get('block'),
+ panel: undefined,
+ chrome: [],
+ })
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/block-spreadsheet/core/clipboard-scope.ts b/apps/web/src/features/block-spreadsheet/core/clipboard-scope.ts
new file mode 100644
index 0000000000..d8fe80882f
--- /dev/null
+++ b/apps/web/src/features/block-spreadsheet/core/clipboard-scope.ts
@@ -0,0 +1,34 @@
+export type ClipboardScope = {
+ /** The spreadsheet's block element. */
+ block: Element | undefined;
+ /** The split panel, when the sheet is its main content. */
+ panel: Element | undefined;
+ /** Header and toolbar slots the sheet renders its controls into. */
+ chrome: (Element | undefined)[];
+};
+
+/**
+ * Whether a clipboard event fired from `target` belongs to the sheet: from its
+ * block, its header or toolbar controls, a container wrapping it (such as a
+ * focused panel), or the body after focus was dropped when the sheet is the
+ * panel's main content.
+ */
+export function clipboardTargetInScope(
+ target: EventTarget | null,
+ scope: ClipboardScope
+): boolean {
+ if (!(target instanceof Element)) return false;
+ // Body focus can't tell an inline preview from its host's content, so only
+ // a sheet that is the panel's main content claims it.
+ if (target === target.ownerDocument.body) return !!scope.panel;
+ if (scope.block?.contains(target)) return true;
+ if (scope.panel?.contains(target)) return true;
+ if (scope.chrome.some((slot) => slot?.contains(target))) return true;
+ // A wrapper inside another block, like a canvas holding this sheet, keeps
+ // the clipboard for that block.
+ return (
+ !!scope.block &&
+ target.contains(scope.block) &&
+ !target.closest('[data-block-type]')
+ );
+}
diff --git a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
index b51d8caefe..ae02f98bc2 100644
--- a/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
+++ b/apps/web/src/features/block-spreadsheet/views/SpreadsheetEditor.tsx
@@ -76,6 +76,8 @@ export function SpreadsheetEditor(props: {
autoFocus?: boolean;
commentLocation?: SpreadsheetCommentAnchor;
comments?: SpreadsheetCommentsCapability;
+ /** Whether a clipboard shortcut fired outside the grid is meant for it. */
+ ownsClipboard?: (event: ClipboardEvent) => boolean;
onExport: (content: string) => void;
onExportXlsx: (bytes: Uint8Array) => void;
}) {
@@ -972,6 +974,7 @@ export function SpreadsheetEditor(props: {
onPaste={(text, metadata) => {
actions.pasteText(text, metadata);
}}
+ ownsClipboard={props.ownsClipboard}
onClear={grid.clear}
onGridReady={(element) => {
gridElement = element;