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
43 changes: 39 additions & 4 deletions src/js/components/EditMenu/SnippetForm/SnippetForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,48 @@ interface EditFormProps extends PropsWithChildren {
className?: string
}

const useSubmitAction = () => {
const formRef = useRef<HTMLFormElement>(null)
const isSubmittingFromTextField = useRef(false)

// Pressing Enter in a text field submits through the form's first button, which can be Save and Deactivate.
useEffect(() => {
const form = formRef.current

const handleKeyDown = (event: KeyboardEvent) => {
const { target } = event
if ('Enter' === event.key && target instanceof HTMLInputElement &&
'submit' !== target.type && 'button' !== target.type) {
isSubmittingFromTextField.current = true
setTimeout(() => {
isSubmittingFromTextField.current = false
})
}
}

form?.addEventListener('keydown', handleKeyDown)
return () => form?.removeEventListener('keydown', handleKeyDown)
}, [])

const getSubmitAction = (event: React.FormEvent<HTMLFormElement>): SubmitSnippetAction | undefined => {
const submitter = isSubmittingFromTextField.current
? null
: (event.nativeEvent as SubmitEvent).submitter

return Object.values(SubmitSnippetAction).find(actionName =>
actionName === submitter?.getAttribute('name'))
}

return { formRef, getSubmitAction }
}

const EditForm: React.FC<EditFormProps> = ({ children, className }) => {
const { submitSnippet } = useSubmitSnippet()
const { snippet } = useSnippetForm()
const { refreshSnippetsList } = useSnippetsList()

const { formRef, getSubmitAction } = useSubmitAction()

const [validationWarning, setValidationWarning] = useState<string | undefined>()
const [submitAction, setSubmitAction] = useState<SubmitSnippetAction | undefined>()

Expand All @@ -108,9 +145,7 @@ const EditForm: React.FC<EditFormProps> = ({ children, className }) => {
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()

const action = Object.values(SubmitSnippetAction).find(actionName =>
actionName === document.activeElement?.getAttribute('name'))

const action = getSubmitAction(event)
const validationWarning = validateSnippet(snippet)

if (validationWarning) {
Expand All @@ -123,7 +158,7 @@ const EditForm: React.FC<EditFormProps> = ({ children, className }) => {

return (
<>
<form aria-labelledby="snippet-form-heading" id="snippet-form" method="post" onSubmit={handleSubmit} className={className}>
<form aria-labelledby="snippet-form-heading" id="snippet-form" method="post" onSubmit={handleSubmit} className={className} ref={formRef}>
{children}
</form>

Expand Down
90 changes: 90 additions & 0 deletions tests/e2e/editor-submit-actions.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { expect, test } from '@playwright/test'
import { SnippetsTestHelper } from './helpers/SnippetsTestHelper'
import { SELECTORS, TIMEOUTS } from './helpers/constants'
import { wpCli } from './helpers/wpCli'
import type { Page } from '@playwright/test'

/**
* Safari and Firefox on macOS do not focus a button when it is clicked, so the editor
* has to tell which submit button was pressed without relying on focus.
*/

const PREFIX = 'E2E Submit Action'

const getActiveState = async (name: string): Promise<string> =>
(await wpCli(['eval', `
foreach (\\Code_Snippets\\get_snippets() as $snippet) {
if ($snippet->name === ${JSON.stringify(name)}) {
echo $snippet->active ? 'active' : 'inactive';
exit;
}
}
echo 'missing';
`])).trim()

const createSnippet = async (name: string, active: boolean): Promise<void> => {
await wpCli(['eval', `
$snippet = new \\Code_Snippets\\Model\\Snippet([
'name' => ${JSON.stringify(name)},
'code' => ${JSON.stringify('// submit action\n')},
'scope' => 'global',
'active' => ${active ? 'true' : 'false'},
]);
echo \\Code_Snippets\\save_snippet($snippet)->id;
`])
}

const clickWithoutFocus = async (page: Page, name: RegExp): Promise<void> => {
const button = page.getByRole('button', { name }).first()
await button.evaluate(element => element.addEventListener('mousedown', event => event.preventDefault()))
await button.click()
}

const waitForSave = async (page: Page): Promise<void> => {
await page.locator(SELECTORS.SAVE_SETTLED_NOTICE).first().waitFor({ state: 'visible', timeout: TIMEOUTS.DEFAULT })
}

test.describe('Snippet editor submit actions', () => {
let helper: SnippetsTestHelper
let snippetName: string

test.beforeEach(({ page }) => {
helper = new SnippetsTestHelper(page)
snippetName = SnippetsTestHelper.makeUniqueSnippetName(PREFIX)
})

test.afterEach(async () => {
await SnippetsTestHelper.cleanupSnippetsByPrefix(PREFIX)
})

test('Save and Activate activates a new snippet when the click does not move focus', async ({ page }) => {
await helper.clickAddNewSnippet()
await helper.fillSnippetForm({ name: snippetName, code: '// submit action\n' })

await clickWithoutFocus(page, /^Save and Activate$/)
await waitForSave(page)

expect(await getActiveState(snippetName)).toBe('active')
})

test('Save and Deactivate deactivates a snippet when the click does not move focus', async ({ page }) => {
await createSnippet(snippetName, true)
await helper.openSnippet(snippetName)

await clickWithoutFocus(page, /^Save and Deactivate$/)
await waitForSave(page)

expect(await getActiveState(snippetName)).toBe('inactive')
})

test('pressing Enter in the title field saves without deactivating an active snippet', async ({ page }) => {
await createSnippet(snippetName, true)
await helper.openSnippet(snippetName)

await page.focus(SELECTORS.TITLE_INPUT)
await page.keyboard.press('Enter')
await waitForSave(page)

expect(await getActiveState(snippetName)).toBe('active')
})
})