Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,21 @@ function insertTabWithUnit({ state, dispatch }) {
return true;
}

/* Tab and Shift+Tab indent in an editable editor and are always consumed
there. A read-only editor leaves them to the browser, so the keyboard can
move the focus out of it. */
export const tabKeyBinding = {
key: 'Tab',
run: (view)=>!view.state.readOnly && insertTabWithUnit(view),
shift: (view)=>{
if(view.state.readOnly) {
return false;
}
indentLess(view);
return true;
},
};

/* React wrapper for CodeMirror */
const defaultExtensions = [
highlightSpecialChars(),
Expand All @@ -167,12 +182,7 @@ const defaultExtensions = [
keymap.of([{
key: 'Tab',
run: acceptCompletion,
},{
key: 'Tab',
preventDefault: true,
run: insertTabWithUnit,
shift: indentLess,
},{
}, tabKeyBinding, {
key: 'Backspace',
preventDefault: true,
run: deleteCharBackwardStrict,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
// This software is released under the PostgreSQL Licence
//
//////////////////////////////////////////////////////////////
import React, {useContext, useCallback, useEffect, useState} from 'react';
import React, {useContext, useCallback, useEffect, useRef, useState} from 'react';
import { styled } from '@mui/material/styles';
import { Box, Portal } from '@mui/material';
import { Box, ClickAwayListener, Portal, Unstable_TrapFocus as FocusTrap } from '@mui/material';
import { DefaultButton, PgButtonGroup, PgIconButton } from '../../../../../../static/js/components/Buttons';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import PlaylistAddRoundedIcon from '@mui/icons-material/PlaylistAddRounded';
Expand Down Expand Up @@ -68,6 +68,7 @@ const StyledEditor = styled('div')(({theme})=>({
maxWidth:'50%',
overflow:'auto',
maxHeight:'35%',
outline: 0,
'& .textarea': {
border: 0,
outline: 0,
Expand All @@ -81,47 +82,102 @@ const StyledEditor = styled('div')(({theme})=>({
}
}));

function ShowDataOutputQueryPopup({query}) {
function suppressEnterKey(e) {
const TABBABLE_SELECTOR = 'input, select, textarea, a[href], button, [tabindex], [contenteditable]:not([contenteditable="false"])';

/* MUI's default for the focus trap does not skip hidden elements, and the
editor keeps its closed find and go to line dialogs in the DOM with
visibility hidden, so the trap would try to wrap the focus onto them. */
function getVisibleTabbable(root) {
const tabIndexOf = (node)=>(
(!node.hasAttribute('tabindex') && node.contentEditable === 'true') ? 0 : node.tabIndex
);
return Array.from(root.querySelectorAll(TABBABLE_SELECTOR))
.filter((node)=>tabIndexOf(node) >= 0 && !node.disabled
&& window.getComputedStyle(node).visibility != 'hidden')
.map((node, i)=>({node, i, tabIndex: tabIndexOf(node)}))
.sort((a, b)=>{
// Positive tab indexes come first, in order, then the rest in DOM order.
if(a.tabIndex == b.tabIndex) return a.i - b.i;
if(a.tabIndex == 0) return 1;
if(b.tabIndex == 0) return -1;
return a.tabIndex - b.tabIndex;
})
.map((a)=>a.node);
}

function ShowDataOutputQueryPopup({query, anchorRef, onClose}) {
function onKeyDown(e) {
if(e.keyCode == 13) {
e.stopPropagation();
} else if(e.key == 'Escape') {
e.stopPropagation();
/* The editor's find and go to line dialogs close themselves on Escape
and mark it handled without stopping it, so leave the popup open. */
if(e.defaultPrevented) {
return;
}
onClose();
anchorRef.current?.focus();
}
}

const popupRef = useRef(null);
const [isCopied, setIsCopied] = useState(false);
const revertCopied = useDelayedCaller(()=>{
setIsCopied(false);
});

/* The focus trap moves the focus into the popup when it opens and keeps
Tab and Shift+Tab inside it. It does not enforce the focus, so a mouse
click elsewhere still focuses whatever was clicked, and the click-away
listener then closes the popup. A click on something that cannot take
the focus leaves it on the body, so the focus goes back to the SQL
button instead. */
return (
<Portal container={document.body}>
<StyledEditor ref={(ele)=>{
setEditorPosition(document.getElementById('sql-query'), ele, '.MuiBox-root', 29);
}} onKeyDown={suppressEnterKey}>
{/* The popup closes when the SQL button loses focus, so keep the
focus there whilst the copy button is clicked. */}
<PgIconButton size="small" className='DataOutputQuery-copyButton'
icon={isCopied ? <CheckRoundedIcon /> : <FileCopyRoundedIcon />}
title={isCopied ? gettext('Copied!') : gettext('Copy SQL')}
onMouseDown={(e)=>e.preventDefault()}
onClick={async ()=>{
if(await copyToClipboard(query || '')) {
setIsCopied(true);
revertCopied(1500);
}
}}
/>
<CodeMirror
value={query || ''}
className={'textarea'}
readonly={true}
/>
</StyledEditor>
<ClickAwayListener onClickAway={(e)=>{
// The SQL button toggles the popup itself.
if(!anchorRef.current?.contains(e.target)) {
const active = document.activeElement;
onClose();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if(!active || active == document.body || popupRef.current?.contains(active)) {
anchorRef.current?.focus();
}
}
}}>
<div>
<FocusTrap open disableEnforceFocus disableRestoreFocus getTabbable={getVisibleTabbable}>
<StyledEditor ref={(ele)=>{
popupRef.current = ele;
setEditorPosition(anchorRef.current, ele, '.MuiBox-root', 29);
}} onKeyDown={onKeyDown} tabIndex={-1} role="dialog"
aria-label={gettext('SQL query of data')}>
<PgIconButton size="small" className='DataOutputQuery-copyButton'
icon={isCopied ? <CheckRoundedIcon /> : <FileCopyRoundedIcon />}
title={isCopied ? gettext('Copied!') : gettext('Copy SQL')}
onClick={async ()=>{
if(await copyToClipboard(query || '')) {
setIsCopied(true);
revertCopied(1500);
}
}}
/>
<CodeMirror
value={query || ''}
className={'textarea'}
readonly={true}
/>
Comment thread
dpage marked this conversation as resolved.
Resolved
</StyledEditor>
</FocusTrap>
</div>
</ClickAwayListener>
</Portal>
);
}
ShowDataOutputQueryPopup.propTypes = {
query: PropTypes.string,
anchorRef: PropTypes.object,
onClose: PropTypes.func,
};


Expand Down Expand Up @@ -296,6 +352,7 @@ export function ResultSetToolbar({query, canEdit, canInsert, totalRowCount, pagi
const eventBus = useContext(QueryToolEventsContext);
const queryToolCtx = useContext(QueryToolContext);
const [dataOutputQueryBtn,setDataOutputQueryBtn] = useState(false);
const dataOutputQueryBtnRef = useRef(null);
const [buttonsDisabled, setButtonsDisabled] = useState({
'save-data': true,
'delete-rows': true,
Expand Down Expand Up @@ -480,9 +537,11 @@ export function ResultSetToolbar({query, canEdit, canInsert, totalRowCount, pagi
<>
<PgButtonGroup size="small">
<PgIconButton title={gettext('SQL query of data')} icon={<SQLQueryIcon />}
onClick={()=>{setDataOutputQueryBtn(prev=>!prev);}} onBlur={()=>{setDataOutputQueryBtn(false);}} disabled={!query} id='sql-query'/>
ref={dataOutputQueryBtnRef} aria-haspopup="dialog" aria-expanded={dataOutputQueryBtn}
onClick={()=>{setDataOutputQueryBtn(prev=>!prev);}} disabled={!query} id='sql-query'/>
</PgButtonGroup>
{ dataOutputQueryBtn && <ShowDataOutputQueryPopup query={query} />}
{ dataOutputQueryBtn && <ShowDataOutputQueryPopup query={query} anchorRef={dataOutputQueryBtnRef}
onClose={()=>setDataOutputQueryBtn(false)} />}
</>
}
{
Expand Down
30 changes: 30 additions & 0 deletions web/regression/javascript/components/CodeMirror.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ import CustomEditorView from 'sources/components/ReactCodeMirror/CustomEditorVie
import fakePgAdmin from '../fake_pgadmin';
import { render, screen, fireEvent } from '@testing-library/react';
import * as CMSearch from '@codemirror/search';
import { EditorView, keymap, runScopeHandlers } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
import { tabKeyBinding } from 'sources/components/ReactCodeMirror/components/Editor';

jest.mock('sources/components/ReactCodeMirror/CustomEditorView');
jest.mock('@codemirror/search', () => ({
Expand Down Expand Up @@ -245,3 +248,30 @@ describe('CodeMirror', ()=>{
});
});
});

describe('CodeMirror Tab key binding', ()=>{
const pressTab = (readOnly, shiftKey)=>{
const view = new EditorView({state: EditorState.create({
doc: ' select 1',
extensions: [keymap.of([tabKeyBinding]), EditorState.readOnly.of(readOnly)],
})});
const handled = runScopeHandlers(view, new KeyboardEvent('keydown', {key: 'Tab', shiftKey}), 'editor');
const doc = view.state.doc.toString();
view.destroy();
return {handled, doc};
};

it.each([
['Tab', false, ' select 1'],
['Shift+Tab', true, 'select 1'],
])('%s indents and is consumed in an editable editor', (_key, shiftKey, doc)=>{
expect(pressTab(false, shiftKey)).toEqual({handled: true, doc});
});

it.each([
['Tab', false],
['Shift+Tab', true],
])('%s is left to the browser in a read-only editor', (_key, shiftKey)=>{
expect(pressTab(true, shiftKey)).toEqual({handled: false, doc: ' select 1'});
});
});
112 changes: 104 additions & 8 deletions web/regression/javascript/sqleditor/ResultSetCopyQuery.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
//////////////////////////////////////////////////////////////

// The SQL button on the Data Output toolbar shows the query that produced the
// result set in a popup that closes when the button loses focus, so the
// popup's copy button must copy the query without taking the focus.
// result set in a popup. The popup takes the focus when it opens, keeps Tab
// inside it, and closes on Escape or a click outside it.

jest.mock('sources/url_for', () => ({
__esModule: true,
Expand All @@ -25,10 +25,22 @@ jest.mock('../../../pgadmin/tools/sqleditor/static/js/components/QueryToolCompon
};
});

jest.mock('../../../pgadmin/static/js/components/ReactCodeMirror', () => ({
__esModule: true,
default: ({ value }) => value,
}));
// Like the real editor, render the focusable query text followed by a closed
// dialog that stays in the DOM with visibility hidden, and that, like the find
// and go to line dialogs, handles Escape with preventDefault() alone.
jest.mock('../../../pgadmin/static/js/components/ReactCodeMirror', () => {
const React = require('react');
return {
__esModule: true,
default: ({ value }) => React.createElement(React.Fragment, null,
React.createElement('div', { tabIndex: 0, 'data-test': 'query-text' }, value),
React.createElement('div', {
tabIndex: 0, style: { visibility: 'hidden' }, 'data-test': 'editor-dialog',
onKeyDown: (e) => { if(e.key === 'Escape') e.preventDefault(); },
}),
),
};
});

jest.mock('../../../pgadmin/static/js/components/JsonEditor', () => ({
__esModule: true,
Expand All @@ -40,6 +52,7 @@ jest.mock('../../../pgadmin/static/js/clipboard', () => ({
}));

import { render, fireEvent, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import Theme from 'sources/Theme';
import { copyToClipboard } from '../../../pgadmin/static/js/clipboard';
import { QueryToolContext, QueryToolEventsContext } from '../../../pgadmin/tools/sqleditor/static/js/components/QueryToolComponent.jsx';
Expand Down Expand Up @@ -70,17 +83,19 @@ describe('ResultSetToolbar SQL query popup', () => {
);
};

const getPopup = () => document.body.querySelector('[role="dialog"]');
const getCopyBtn = () => document.body.querySelector('button[data-label="Copy SQL"]');

const openPopup = () => {
const { container } = renderToolbar();
fireEvent.click(container.querySelector('#sql-query'));
return document.body.querySelector('button[data-label="Copy SQL"]');
};

it('copies the query without moving the focus off the SQL button', async () => {
it('copies the query and keeps the popup open', async () => {
copyToClipboard.mockResolvedValue(true);
const copyBtn = openPopup();
expect(copyBtn).not.toBeNull();
expect(fireEvent.mouseDown(copyBtn)).toBe(false);
await act(async () => { fireEvent.click(copyBtn); });

expect(copyToClipboard).toHaveBeenCalledWith(query);
Expand All @@ -96,4 +111,85 @@ describe('ResultSetToolbar SQL query popup', () => {
expect(document.body.querySelector('button[data-label="Copy SQL"]')).not.toBeNull();
expect(document.body.querySelector('button[data-label="Copied!"]')).toBeNull();
});

it('moves the focus into the popup when opened from the keyboard and keeps Tab inside it', async () => {
const user = userEvent.setup();
const { container } = renderToolbar();
const sqlBtn = container.querySelector('#sql-query');
act(() => { sqlBtn.focus(); });
await user.keyboard('{Enter}');

const popup = getPopup();
expect(popup).not.toBeNull();
expect(sqlBtn).toHaveAttribute('aria-expanded', 'true');
expect(popup.contains(document.activeElement)).toBe(true);

const queryText = popup.querySelector('[data-test="query-text"]');
await user.tab();
expect(document.activeElement).toBe(getCopyBtn());
await user.tab();
expect(document.activeElement).toBe(queryText);
// Tab wraps past the hidden dialog in both directions.
await user.tab();
expect(document.activeElement).toBe(getCopyBtn());
await user.tab({shift: true});
expect(document.activeElement).toBe(queryText);
expect(getPopup()).not.toBeNull();
});

it('closes on Escape and returns the focus to the SQL button', async () => {
const user = userEvent.setup();
const { container } = renderToolbar();
const sqlBtn = container.querySelector('#sql-query');
act(() => { sqlBtn.focus(); });
await user.keyboard('{Enter}');
await user.tab();
expect(document.activeElement).toBe(getCopyBtn());

await user.keyboard('{Escape}');
expect(getPopup()).toBeNull();
expect(document.activeElement).toBe(sqlBtn);
expect(sqlBtn).toHaveAttribute('aria-expanded', 'false');
});

it('stays open when Escape closes a dialog of the editor inside it', async () => {
const user = userEvent.setup();
const { container } = renderToolbar();
const sqlBtn = container.querySelector('#sql-query');
act(() => { sqlBtn.focus(); });
await user.keyboard('{Enter}');

fireEvent.keyDown(getPopup().querySelector('[data-test="editor-dialog"]'), {key: 'Escape'});
expect(getPopup()).not.toBeNull();
expect(sqlBtn).toHaveAttribute('aria-expanded', 'true');
});

it('closes on a click outside it, and the SQL button still toggles it', async () => {
const user = userEvent.setup();
const { container } = renderToolbar();
const sqlBtn = container.querySelector('#sql-query');

await user.click(sqlBtn);
expect(getPopup()).not.toBeNull();
await user.click(getPopup());
expect(getPopup()).not.toBeNull();
// A click on an area that cannot take the focus returns it to the button.
await user.click(document.body);
expect(getPopup()).toBeNull();
expect(document.activeElement).toBe(sqlBtn);

// A click on another control leaves the focus on that control.
const otherBtn = Array.from(container.querySelectorAll('button'))
.find((btn)=>btn !== sqlBtn && !btn.disabled);
await user.click(sqlBtn);
expect(getPopup()).not.toBeNull();
await user.click(otherBtn);
expect(getPopup()).toBeNull();
expect(document.activeElement).toBe(otherBtn);

await user.click(sqlBtn);
expect(getPopup()).not.toBeNull();
await user.click(sqlBtn);
expect(getPopup()).toBeNull();
});
});
Loading