app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

search-form.spec.ts (11101B)


      1 import { expect, test } from '@playwright/test';
      2 import { createHash } from 'node:crypto';
      3 import { execFileSync } from 'node:child_process';
      4 import {
      5   cp,
      6   mkdtemp,
      7   readFile,
      8   readdir,
      9   rm,
     10   writeFile
     11 } from 'node:fs/promises';
     12 import { tmpdir } from 'node:os';
     13 import path from 'node:path';
     14 import { fileURLToPath } from 'node:url';
     15 import { createStaticHarness } from '../integration/harness/static.ts';
     16 
     17 // Isolated qualification clone: actual components compile into disposable output.
     18 // The primary static payload and product route source are never overwritten.
     19 const capsule = fileURLToPath(new URL('../../../', import.meta.url));
     20 let directory: string;
     21 let server: Awaited<ReturnType<typeof createStaticHarness>>;
     22 test.beforeAll(async () => {
     23   test.setTimeout(86_400_000);
     24   directory = await mkdtemp(path.join(tmpdir(), 'hcp015-search-form-'));
     25   try {
     26     const checkout = path.join(directory, 'checkout');
     27     execFileSync('git', [
     28       'clone',
     29       '--quiet',
     30       '--no-hardlinks',
     31       capsule,
     32       checkout
     33     ]);
     34     for (const relative of [
     35       'web/package.json',
     36       'web/pnpm-lock.yaml',
     37       'web/src',
     38       'web/tools/source-boundaries.mjs',
     39       'web/src/lib/components/AppShell.svelte',
     40       'web/src/app.css',
     41       'web/src/routes/+layout.svelte',
     42       'web/src/lib/components/SearchForm.svelte',
     43       'web/src/routes/+page.svelte',
     44       'web/tests/unit/components/search-form.test.ts',
     45       'web/tests/e2e/search-form.spec.ts',
     46       'web/tests/e2e/harness/search-form.svelte',
     47       'web/tests/integration/harness/static.ts'
     48     ])
     49       await cp(path.join(capsule, relative), path.join(checkout, relative), {
     50         recursive: true
     51       });
     52     const fixture = await readFile(
     53       path.join(capsule, 'web/tests/e2e/harness/search-form.svelte'),
     54       'utf8'
     55     );
     56     await writeFile(
     57       path.join(checkout, 'web/src/routes/+page.svelte'),
     58       fixture.replaceAll('../../../src/lib/', '../lib/')
     59     );
     60     // Runtime store metadata is volume-specific; install the exact locked graph
     61     // into this disposable clone without a network or lock-repair fallback.
     62     const sourceStore = execFileSync('corepack', ['pnpm', 'store', 'path'], {
     63       cwd: path.join(capsule, 'web')
     64     })
     65       .toString()
     66       .trim();
     67     const installed = execFileSync(
     68       'corepack',
     69       [
     70         'pnpm',
     71         'install',
     72         '--offline',
     73         '--frozen-lockfile',
     74         '--store-dir',
     75         path.dirname(sourceStore)
     76       ],
     77       { cwd: path.join(checkout, 'web'), stdio: 'pipe', timeout: 86400000 }
     78     );
     79     const sourceAudit = execFileSync(
     80       process.execPath,
     81       ['tools/check-source.mjs'],
     82       { cwd: path.join(checkout, 'web') }
     83     ).toString();
     84     const identities = [];
     85     for (const relative of [
     86       'web/src/lib/components/AppShell.svelte',
     87       'web/src/lib/components/SearchForm.svelte',
     88       'web/src/lib/components/primitives/FormField.svelte',
     89       'web/src/lib/components/primitives/Button.svelte',
     90       'web/src/app.css',
     91       'web/src/theme.css',
     92       'web/src/routes/+layout.svelte'
     93     ]) {
     94       identities.push({
     95         name: relative,
     96         sha256: createHash('sha256')
     97           .update(await readFile(path.join(checkout, relative)))
     98           .digest('hex')
     99       });
    100     }
    101     execFileSync(process.execPath, ['tools/build-info.mjs'], {
    102       cwd: path.join(checkout, 'web')
    103     });
    104     const compiled = execFileSync(
    105       process.execPath,
    106       ['node_modules/vite/bin/vite.js', 'build'],
    107       {
    108         cwd: path.join(checkout, 'web'),
    109         stdio: 'pipe',
    110         timeout: 86400000
    111       }
    112     );
    113     async function payload(
    114       directory: string,
    115       prefix = ''
    116     ): Promise<{ path: string; sha256: string }[]> {
    117       const files = [];
    118       for (const entry of await readdir(directory, { withFileTypes: true })) {
    119         const relative = prefix + entry.name;
    120         if (entry.isDirectory())
    121           files.push(
    122             ...(await payload(path.join(directory, entry.name), relative + '/'))
    123           );
    124         else
    125           files.push({
    126             path: relative,
    127             sha256: createHash('sha256')
    128               .update(await readFile(path.join(directory, entry.name)))
    129               .digest('hex')
    130           });
    131       }
    132       return files.sort((left, right) => left.path.localeCompare(right.path));
    133     }
    134     console.log(
    135       JSON.stringify({
    136         fixture: 'HCP015_TEST_ONLY_COMPILE',
    137         identities,
    138         sourceAudit,
    139         productionRouteSha256: createHash('sha256')
    140           .update(
    141             await readFile(path.join(capsule, 'web/src/routes/+page.svelte'))
    142           )
    143           .digest('hex'),
    144         fixtureSourceSha256: createHash('sha256').update(fixture).digest('hex'),
    145         compiledRouteSha256: createHash('sha256')
    146           .update(
    147             await readFile(path.join(checkout, 'web/src/routes/+page.svelte'))
    148           )
    149           .digest('hex'),
    150         compiledLayoutSha256: createHash('sha256')
    151           .update(
    152             await readFile(path.join(checkout, 'web/src/routes/+layout.svelte'))
    153           )
    154           .digest('hex'),
    155         retention:
    156           'HASHLOGS_ONLY: disposable compiled fixture output is removed after tests',
    157         payload: await payload(path.join(checkout, 'web/build')),
    158         sourceStore,
    159         installed: installed.toString(),
    160         compiled: compiled.toString(),
    161         metadata: JSON.parse(
    162           await readFile(
    163             path.join(checkout, 'web/build/build-info.json'),
    164             'utf8'
    165           )
    166         ) as unknown
    167       })
    168     );
    169     server = await createStaticHarness({
    170       buildRoot: path.join(checkout, 'web/build')
    171     });
    172   } catch (error) {
    173     await rm(directory, { recursive: true, force: true });
    174     throw error;
    175   }
    176 });
    177 test.afterAll(async () => {
    178   await server?.close();
    179   if (directory) await rm(directory, { recursive: true, force: true });
    180   if (server)
    181     expect(server.state()).toEqual({ listening: false, childProcesses: 0 });
    182 });
    183 
    184 for (const width of [320, 1024]) {
    185   test(`actual shared form submits raw blank/multiline input and guards IME/unavailable at ${width}px`, async ({
    186     browser
    187   }) => {
    188     const context = await browser.newContext({
    189       viewport: { width, height: 900 }
    190     });
    191     const external: string[] = [];
    192     try {
    193       await context.route('**/*', (route) => {
    194         if (new URL(route.request().url()).origin === server.url)
    195           return route.continue();
    196         external.push(route.request().url());
    197         return route.abort();
    198       });
    199       const page = await context.newPage();
    200       await page.goto(server.url);
    201       const query = page.getByRole('textbox', {
    202         name: 'What are you looking for?'
    203       });
    204       const search = page.getByRole('button', { name: 'Search', exact: true });
    205       const status = page.getByRole('main').getByRole('status');
    206       await expect(query).toHaveCount(1);
    207       await expect(query).toHaveAttribute('rows', '2');
    208       await expect(search).toBeEnabled();
    209       await search.click();
    210       await expect(status).toHaveText('[""]');
    211       await query.fill('  carrots & Victoria  ');
    212       await query.press('End');
    213       await query.press('Enter');
    214       await query.press('x');
    215       await expect(query).toHaveValue('  carrots & Victoria  \nx');
    216       await expect(status).toHaveText('[""]');
    217       await query.press('Control+Enter');
    218       await query.press('Meta+Enter');
    219       await expect(status).toHaveText('[""]');
    220       await query.fill('  carrots & Victoria  \nx');
    221       await search.click();
    222       await expect(status).toHaveText(
    223         JSON.stringify(['', '  carrots & Victoria  \nx'])
    224       );
    225 
    226       await query.dispatchEvent('compositionstart', { data: '菜' });
    227       await query.dispatchEvent('keydown', {
    228         key: 'Enter',
    229         ctrlKey: true,
    230         isComposing: true
    231       });
    232       await query.dispatchEvent('keydown', {
    233         key: 'Enter',
    234         metaKey: true,
    235         isComposing: true
    236       });
    237       await page.locator('form').evaluate((form) => {
    238         if (
    239           form.dispatchEvent(
    240             new SubmitEvent('submit', { bubbles: true, cancelable: true })
    241           )
    242         )
    243           throw new Error('Composing submit was not prevented');
    244       });
    245       await expect(status).toHaveText(
    246         JSON.stringify(['', '  carrots & Victoria  \nx'])
    247       );
    248       await query.dispatchEvent('compositionend', { data: '菜' });
    249       await query.fill('菜');
    250       await query.press('Tab');
    251       await expect(search).toBeFocused();
    252       await page.keyboard.press('Enter');
    253       const expected = JSON.stringify(['', '  carrots & Victoria  \nx', '菜']);
    254       await expect(status).toHaveText(expected);
    255 
    256       for (const toggle of ['Toggle disabled', 'Toggle caller']) {
    257         await page.getByRole('button', { name: toggle }).click();
    258         await expect(search).toBeDisabled();
    259         await expect(
    260           page.getByText('Search is unavailable during development.')
    261         ).toBeVisible();
    262         await query.fill('not submitted');
    263         await query.press('Control+Enter');
    264         await query.press('Meta+Enter');
    265         await search.evaluate((button) =>
    266           button.dispatchEvent(new MouseEvent('click', { bubbles: true }))
    267         );
    268         await page.locator('form').evaluate((form) => {
    269           if (
    270             form.dispatchEvent(
    271               new SubmitEvent('submit', { bubbles: true, cancelable: true })
    272             )
    273           )
    274             throw new Error('Unavailable submit was not prevented');
    275         });
    276         await expect(status).toHaveText(expected);
    277         await page.getByRole('button', { name: toggle }).click();
    278         await expect(search).toBeEnabled();
    279       }
    280       const measured = await page.evaluate(() => ({
    281         width: innerWidth,
    282         scroll: globalThis.document.documentElement.scrollWidth,
    283         textarea: (() => {
    284           const rect = globalThis.document
    285             .querySelector('textarea')!
    286             .getBoundingClientRect();
    287           return { width: rect.width, height: rect.height, x: rect.x };
    288         })(),
    289         controls: Array.from(
    290           globalThis.document.querySelectorAll('button')
    291         ).map((element) => element.getBoundingClientRect().height)
    292       }));
    293       expect(measured.scroll).toBeLessThanOrEqual(width);
    294       expect(measured.textarea.width).toBeGreaterThan(0);
    295       expect(measured.textarea.x + measured.textarea.width).toBeLessThanOrEqual(
    296         width
    297       );
    298       for (const height of measured.controls)
    299         expect(height).toBeGreaterThanOrEqual(44);
    300       console.log(
    301         JSON.stringify({
    302           fixture: 'HCP015_CONTROLLED_FORM_ONLY',
    303           measured,
    304           submitted: ['', '  carrots & Victoria  \nx', '菜'],
    305           shortcut: 'OMITTED',
    306           composition: 'forced submit prevented until compositionend'
    307         })
    308       );
    309       expect(new URL(page.url()).pathname).toBe('/');
    310       expect(await page.evaluate(() => 'nostr' in window)).toBe(false);
    311       expect(external).toEqual([]);
    312     } finally {
    313       await context.close();
    314     }
    315   });
    316 }