Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 12 additions & 11 deletions src/renderer/src/components/shell/ShellEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export const ShellEditor = forwardRef<ShellEditorHandle, ShellEditorProps>(funct
// drive native commands (undo/redo/select-all, search) and to
// read the selection / locate the current statement for "Run Current Statement".
const viewRef = useRef<EditorView | null>(null)
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null)
const [menu, setMenu] = useState<{ x: number; y: number; editorState: EditorState } | null>(null)

useImperativeHandle(ref, () => ({ getSelectedCode: () => selectionCode(viewRef.current?.state) }), [])

Expand Down Expand Up @@ -276,9 +276,10 @@ export const ShellEditor = forwardRef<ShellEditorHandle, ShellEditorProps>(funct
if (__WEB__) tsAutocomplete.warm()
}}
onContextMenu={(e) => {
if (!viewRef.current) return
const editorState = viewRef.current?.state
if (!editorState) return
e.preventDefault()
setMenu({ x: e.clientX, y: e.clientY })
setMenu({ x: e.clientX, y: e.clientY, editorState })
}}
>
<CodeMirror
Expand All @@ -300,7 +301,7 @@ export const ShellEditor = forwardRef<ShellEditorHandle, ShellEditorProps>(funct
<ContextMenu
x={menu.x}
y={menu.y}
items={buildMenu()}
items={buildMenu(menu.editorState)}
onClose={() => {
setMenu(null)
requestAnimationFrame(() => {
Expand Down Expand Up @@ -364,7 +365,7 @@ export const ShellEditor = forwardRef<ShellEditorHandle, ShellEditorProps>(funct
})
}

async function paste(): Promise<void> {
async function paste(editorState: EditorState): Promise<void> {
const view = viewRef.current
if (!view) return
let text: string
Expand All @@ -379,18 +380,18 @@ export const ShellEditor = forwardRef<ShellEditorHandle, ShellEditorProps>(funct
})
return
}
if (!text || !view.dom.isConnected) return
// Replace CodeMirror's selection directly; execCommand('paste') is blocked
// by Chromium. Keep the operation in the editor's normal undo history.
if (!text || !view.dom.isConnected || view.state.doc !== editorState.doc) return
// The context menu can collapse the live selection while reading the clipboard.
// Dispatch an undoable edit using the selection captured when the menu opened.
view.dispatch({
...view.state.replaceSelection(text),
...editorState.replaceSelection(text),
scrollIntoView: true,
userEvent: 'input.paste'
})
view.focus()
}

function buildMenu(): ContextMenuEntry[] {
function buildMenu(editorState: EditorState): ContextMenuEntry[] {
const { busy: isBusy, saveBusy: isSaveBusy, running: isRunning } = handlers.current
const view = viewRef.current
const hasSel = view ? !view.state.selection.main.empty : false
Expand All @@ -401,7 +402,7 @@ export const ShellEditor = forwardRef<ShellEditorHandle, ShellEditorProps>(funct
return [
{ label: t('shell.menu.cut'), shortcut: `${primary}X`, disabled: !hasText, onClick: () => withView(() => document.execCommand('cut')) },
{ label: t('shell.menu.copy'), shortcut: `${primary}C`, disabled: !hasText, onClick: () => withView(() => document.execCommand('copy')) },
{ label: t('shell.menu.paste'), shortcut: `${primary}V`, onClick: () => void paste() },
{ label: t('shell.menu.paste'), shortcut: `${primary}V`, onClick: () => void paste(editorState) },
{ label: t('shell.menu.selectAll'), shortcut: `${primary}A`, disabled: !hasText, onClick: () => withView((v) => selectAll(v)) },
'separator',
{ label: t('shell.menu.undo'), shortcut: `${primary}Z`, disabled: !view || undoDepth(view.state) === 0, onClick: () => withView((v) => undo(v)) },
Expand Down
18 changes: 10 additions & 8 deletions test/e2e/charts.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ test('Chart examples teach a configuration and map it to compatible result field
const dialog = 'document.querySelector("[role=dialog]")'
const button = (label, root = 'document') => `[...${root}.querySelectorAll('button')].find(button => (button.getAttribute('aria-label') || button.textContent.trim()) === ${JSON.stringify(label)})`
const option = (name) => `[...document.querySelectorAll('.amdm-field-select-popup [role=option]')].find(option => option.textContent.trim() === ${JSON.stringify(name)})`
async function selectRegion() {
await waitForExpression(renderer, `${dialog}?.contains(document.activeElement) && document.activeElement.getAttribute('aria-label') === 'Add dimension'`)
await key('ArrowDown', 'ArrowDown', 40)
await waitForExpression(renderer, '!!document.querySelector(".amdm-field-select-popup input:focus")')
await clickElement(renderer, option('region'))
}
await enterQuery('[{region:"north",price:100},{region:"north",price:50},{region:"south",price:80},{region:null,orphan:200}]')
await key('Enter', 'Enter', 13, modifier)
await clickElement(renderer, button('Chart'))
Expand All @@ -36,8 +42,7 @@ test('Chart examples teach a configuration and map it to compatible result field
const mappedBounds = await renderer.evaluate(dialogBounds)
assert.deepEqual([mappedBounds.y, mappedBounds.height], [y, height])
assert.ok(await renderer.evaluate(`${button('Apply chart', dialog)}.disabled`))
await clickElement(renderer, button('Add dimension', dialog))
await clickElement(renderer, option('region'))
await selectRegion()
await clickElement(renderer, button('Add metric', dialog))
await waitForExpression(renderer, `!!(${option('price')})`)
assert.equal(await renderer.evaluate(`!!(${option('orphan')})`), false)
Expand All @@ -49,16 +54,14 @@ test('Chart examples teach a configuration and map it to compatible result field

await clickElement(renderer, button('Examples'))
await clickElement(renderer, button('Use with current result', dialog))
await clickElement(renderer, button('Add dimension', dialog))
await clickElement(renderer, option('region'))
await selectRegion()
await clickElement(renderer, button('Back to examples', dialog))
await key('Escape', 'Escape', 27)
await waitForExpression(renderer, `!${dialog}`)
assert.match(await renderer.evaluate(`document.querySelector('[data-chart-type]').getAttribute('aria-label')`), /region \/ price · Average/)
await clickElement(renderer, button('Examples'))
await clickElement(renderer, button('Use with current result', dialog))
await clickElement(renderer, button('Add dimension', dialog))
await clickElement(renderer, option('region'))
await selectRegion()
await clickElement(renderer, button('Apply chart', dialog))
await waitForExpression(renderer, `!${dialog} && document.querySelector('[data-chart-type]')?.getAttribute('aria-label').includes('region / Record count')`)
report.steps.push('leaving the example preserves the chart and applying record count needs just a dimension')
Expand All @@ -68,8 +71,7 @@ test('Chart examples teach a configuration and map it to compatible result field
await clickElement(renderer, button('Aggregation for amount', dialog))
await clickElement(renderer, '[...document.querySelectorAll(".amdm-select-popup [role=option]")].find(el => el.checkVisibility() && el.textContent.trim() === "Raw")')
await clickElement(renderer, button('Use with current result', dialog))
await clickElement(renderer, button('Add dimension', dialog))
await clickElement(renderer, option('region'))
await selectRegion()
await clickElement(renderer, button('Add metric', dialog))
await clickElement(renderer, option('price'))
await clickElement(renderer, button('Apply chart', dialog))
Expand Down
19 changes: 12 additions & 7 deletions test/e2e/shell.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,14 @@ test('Query context menu editing commands preserve text, selection, and focus',
try {
const original = 'db.items.find({ n: 1 })'
const replacement = 'db.items.find({ n: 2 })'
async function pasteFromMenu(text) {
const expectSelection = text => waitForExpression(renderer, `window.getSelection().toString() === ${JSON.stringify(text)}`)
async function pasteFromMenu(text, selection) {
await expectSelection(selection)
await main.evaluate(`pasteTest.clipboard.writeText(${JSON.stringify(text)})`)
await queryMenuCommand(renderer, 'Paste')
await openQueryMenu(renderer)
await expectSelection(selection)
await clickElement(renderer, queryMenuItem('Paste'))
await waitForExpression(renderer, '!document.querySelector(".ctx-menu")')
}
const expectCode = code => waitForExpression(renderer, `document.querySelector('.cm-content')?.textContent === ${JSON.stringify(code)}`)
await clickElement(renderer, 'document.querySelector(".cm-content")')
Expand Down Expand Up @@ -103,7 +108,7 @@ test('Query context menu editing commands preserve text, selection, and focus',

await enterQuery(original)
await key('a', 'KeyA', 65, modifier)
await pasteFromMenu(replacement)
await pasteFromMenu(replacement, original)
await expectCode(replacement)
assert.equal(await renderer.evaluate('document.activeElement?.classList.contains("cm-content")'), true)
await key('z', 'KeyZ', 90, modifier)
Expand All @@ -113,26 +118,26 @@ test('Query context menu editing commands preserve text, selection, and focus',
await enterQuery(original)
for (let i = 0; i < 3; i++) await key('ArrowLeft', 'ArrowLeft', 37)
await key('ArrowLeft', 'ArrowLeft', 37, 8)
assert.equal(await renderer.evaluate('window.getSelection().toString()'), '1')
await pasteFromMenu('2')
await pasteFromMenu('2', '1')
await expectCode(replacement)
report.steps.push('Paste replaces a partial selection without changing the surrounding code')

await enterQuery(original)
await pasteFromMenu('\n// pasted')
await pasteFromMenu('\n// pasted', '')
await expectCode(original + '// pasted') // textContent omits CodeMirror line boundaries.
report.steps.push('Paste inserts multiline text at an empty cursor')

await enterQuery(original)
await key('a', 'KeyA', 65, modifier)
await expectSelection(original)
await main.evaluate(`pasteTest.clipboard.writeText(${JSON.stringify(replacement)})`)
await main.evaluate('pasteTest.contents.paste(); true')
await expectCode(replacement)
report.steps.push('native paste command also replaces the selection')

await enterQuery(original)
await queryMenuCommand(renderer, 'Select all')
await waitForExpression(renderer, `window.getSelection().toString() === ${JSON.stringify(original)}`)
await expectSelection(original)
await queryMenuCommand(renderer, 'Copy')
await waitForExpression(main, `pasteTest.clipboard.readText().then(text => text === ${JSON.stringify(original)})`)
await expectCode(original)
Expand Down
Loading