Skip to content

Commit

Permalink
chore(supersearch): Codemirror extension for preventing newlines (#1164)
Browse files Browse the repository at this point in the history
* Add CodeMirror extension for preventing newlines

* Add test

* Add hidden textarea inside component for name and value attributes
  • Loading branch information
johanbissemattsson authored Nov 14, 2024
1 parent 8a2431e commit d8ebe00
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/supersearch/e2e/supersearch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,20 @@ test('submits form identified by form attribute on enter key press', async ({ pa
await page.keyboard.press('Enter');
await expect(page).toHaveURL('/test2?q=hello+world');
});

test('prevents new line characters (e.g. when pasting multi-lined text', async ({
page,
context
}) => {
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
await page.locator('[data-test-id="test1"]').getByRole('textbox').locator('div').click();
await page.evaluate(() =>
navigator.clipboard.writeText(`One
two
three`)
);
await page.keyboard.press(`ControlOrMeta+v`);
await expect(page.locator('[data-test-id="test1"]').getByRole('textbox').locator('div')).toHaveText(
'One two three'
);
});
2 changes: 2 additions & 0 deletions packages/supersearch/src/lib/components/SuperSearch.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import { Compartment } from '@codemirror/state';
import { type LRLanguage } from '@codemirror/language';
import submitFormOnEnterKey from '$lib/extensions/submitFormOnEnterKey.js';
import preventNewLine from '$lib/extensions/preventNewLine.js';
interface Props {
name: string;
Expand All @@ -22,6 +23,7 @@
const extensions = [
submitFormOnEnterKey(form),
preventNewLine({ replaceWithSpace: true }),
...(language ? [language] : []),
placeholderCompartment.of(placeholderExtension(placeholder))
];
Expand Down
30 changes: 30 additions & 0 deletions packages/supersearch/src/lib/extensions/preventNewLine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { EditorState, Prec } from '@codemirror/state';

/**
* CodeMirror extension thats prevents inserted newlines (either by typing or pasting).
*
* @param {boolean} replaceWithSpace Controls if newline characters should be replaced with spaces.
*/

const preventNewLine = ({ replaceWithSpace = false }: { replaceWithSpace: boolean }) =>
Prec.highest(
EditorState.transactionFilter.of((tr) => {
if (tr.newDoc.lines > 1) {
return [
tr,
{
changes: {
from: 0,
to: tr.newDoc.length,
insert: tr.newDoc.sliceString(0, undefined, replaceWithSpace ? ' ' : '') // flatten multi-lined text
},
sequential: true
}
];
} else {
return [tr];
}
})
);

export default preventNewLine;

0 comments on commit d8ebe00

Please sign in to comment.