|
| 1 | +/** |
| 2 | + * ObjectUI |
| 3 | + * Copyright (c) 2024-present ObjectStack Inc. |
| 4 | + * |
| 5 | + * This source code is licensed under the MIT license found in the |
| 6 | + * LICENSE file in the root directory of this source tree. |
| 7 | + */ |
| 8 | + |
| 9 | +/** |
| 10 | + * A keystroke in a master-detail header reaches the header's form even when |
| 11 | + * the page has other work pending at that instant (objectstack#28471). |
| 12 | + * |
| 13 | + * The form host's `input` listener (the scrape that feeds the line grids' |
| 14 | + * `parent`) runs BEFORE React's root listener, because the host sits inside |
| 15 | + * the React root. In a browser, the microtask checkpoint between those two |
| 16 | + * listeners flushed the scrape's update, which was sync priority, together |
| 17 | + * with the page's pending default-priority work. That render repainted the |
| 18 | + * header input with its old controlled value, React's value tracker then saw |
| 19 | + * no change, and the keystroke never reached react-hook-form: the live |
| 20 | + * showcase page's Create failed "Project Name is required" with no request. |
| 21 | + * |
| 22 | + * happy-dom runs every listener of a dispatch inside one JS call, with no |
| 23 | + * microtask checkpoint between them, so this file supplies the checkpoint: a |
| 24 | + * listener on the element between the host and the React root calls |
| 25 | + * `flushSync()`, which flushes exactly the work React's microtask would. The |
| 26 | + * pending work is a page re-render scheduled just before the keystroke. |
| 27 | + */ |
| 28 | +import { describe, it, expect, vi, afterEach } from 'vitest'; |
| 29 | +import { render, screen, waitFor, act } from '@testing-library/react'; |
| 30 | +import React from 'react'; |
| 31 | +import { flushSync } from 'react-dom'; |
| 32 | +import { registerAllFields } from '@object-ui/fields'; |
| 33 | +import { MasterDetailForm } from './MasterDetailForm'; |
| 34 | + |
| 35 | +registerAllFields(); |
| 36 | + |
| 37 | +type Props = React.ComponentProps<typeof MasterDetailForm>; |
| 38 | + |
| 39 | +const INV_SCHEMA = { name: 'inv', fields: { status: { type: 'text', label: 'Status' } } }; |
| 40 | + |
| 41 | +const SCHEMA = { |
| 42 | + objectName: 'inv', |
| 43 | + mode: 'create', |
| 44 | + fields: ['status'], |
| 45 | + details: [ |
| 46 | + { |
| 47 | + childObject: 'inv_line', |
| 48 | + relationshipField: 'inv', |
| 49 | + columns: [ |
| 50 | + { name: 'product', label: 'Product', type: 'text' }, |
| 51 | + { name: 'qty', label: 'Qty', type: 'number', readonlyWhen: "parent.status == 'paid'" }, |
| 52 | + ], |
| 53 | + }, |
| 54 | + ], |
| 55 | +} as unknown as Props['schema']; |
| 56 | + |
| 57 | +function dataSource() { |
| 58 | + return { |
| 59 | + getObjectSchema: vi.fn().mockResolvedValue(INV_SCHEMA), |
| 60 | + find: vi.fn().mockResolvedValue({ data: [] }), |
| 61 | + create: vi.fn(), |
| 62 | + update: vi.fn(), |
| 63 | + delete: vi.fn(), |
| 64 | + bulk: vi.fn(), |
| 65 | + } as unknown as Props['dataSource']; |
| 66 | +} |
| 67 | + |
| 68 | +/** The page around the form; `bump.current()` schedules a re-render of it. */ |
| 69 | +const bump = { current: () => {} }; |
| 70 | +function Page({ ds }: { ds: Props['dataSource'] }) { |
| 71 | + const [n, setN] = React.useState(0); |
| 72 | + React.useEffect(() => { |
| 73 | + bump.current = () => setN((x) => x + 1); |
| 74 | + }, []); |
| 75 | + return <MasterDetailForm schema={{ ...SCHEMA, className: `page-${n}` }} dataSource={ds} />; |
| 76 | +} |
| 77 | + |
| 78 | +/** |
| 79 | + * Type `value` into `input` the way a browser delivers a keystroke, with the |
| 80 | + * two pieces of browser behaviour happy-dom leaves out: |
| 81 | + * |
| 82 | + * - `window.event` is the event while it is dispatched. React reads it to |
| 83 | + * price an update scheduled from a non-React listener; without it every |
| 84 | + * such update is default priority and nothing is flushed mid-dispatch. |
| 85 | + * - A microtask checkpoint runs after each listener, where React flushes its |
| 86 | + * sync work. `checkpointAt` gets a bubble listener that does that flush, |
| 87 | + * so it falls after the listeners below it and before those above it. |
| 88 | + * |
| 89 | + * The native value changes first, past React's value tracker (which sees |
| 90 | + * only writes through its own setter), then one bubbling `input` event. |
| 91 | + */ |
| 92 | +function typeLikeABrowser(input: HTMLInputElement, value: string, checkpointAt: HTMLElement) { |
| 93 | + const before = Object.getOwnPropertyDescriptor(window, 'event'); |
| 94 | + const checkpoint = () => flushSync(() => {}); |
| 95 | + const ev = new Event('input', { bubbles: true }); |
| 96 | + Object.defineProperty(window, 'event', { configurable: true, get: () => ev }); |
| 97 | + checkpointAt.addEventListener('input', checkpoint); |
| 98 | + try { |
| 99 | + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value); |
| 100 | + input.dispatchEvent(ev); |
| 101 | + } finally { |
| 102 | + checkpointAt.removeEventListener('input', checkpoint); |
| 103 | + if (before) Object.defineProperty(window, 'event', before); |
| 104 | + else delete (window as { event?: unknown }).event; |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +const actEnv = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; |
| 109 | +const actEnvBefore = actEnv.IS_REACT_ACT_ENVIRONMENT; |
| 110 | +afterEach(() => { |
| 111 | + actEnv.IS_REACT_ACT_ENVIRONMENT = actEnvBefore; |
| 112 | +}); |
| 113 | + |
| 114 | +describe('MasterDetailForm — a header keystroke is never dropped (objectstack#28471)', () => { |
| 115 | + it('keeps the typed value when the page has default-priority work pending at the keystroke', async () => { |
| 116 | + const { container } = render(<Page ds={dataSource()} />); |
| 117 | + const status = await waitFor(() => { |
| 118 | + const el = container.querySelector('input[name="status"]') as HTMLInputElement | null; |
| 119 | + if (!el) throw new Error('header not ready'); |
| 120 | + return el; |
| 121 | + }); |
| 122 | + const qty = () => screen.getAllByLabelText('Qty')[0] as HTMLInputElement; |
| 123 | + await waitFor(() => expect(qty().disabled).toBe(false)); |
| 124 | + |
| 125 | + // The element right under the React root container: above the form host, |
| 126 | + // below React's root listener — where the browser's checkpoint fell. |
| 127 | + let checkpointAt: HTMLElement = status; |
| 128 | + while (checkpointAt.parentElement && checkpointAt.parentElement !== container) { |
| 129 | + checkpointAt = checkpointAt.parentElement; |
| 130 | + } |
| 131 | + |
| 132 | + // The page's pending work is a real default-priority update, the kind a |
| 133 | + // landing fetch schedules, so it is scheduled outside `act`. |
| 134 | + actEnv.IS_REACT_ACT_ENVIRONMENT = false; |
| 135 | + bump.current(); |
| 136 | + typeLikeABrowser(status, 'paid', checkpointAt); |
| 137 | + actEnv.IS_REACT_ACT_ENVIRONMENT = actEnvBefore; |
| 138 | + |
| 139 | + // The keystroke reached the form: the input still shows it once the |
| 140 | + // pending work and the lines' update have rendered… |
| 141 | + await act(async () => { |
| 142 | + await new Promise((r) => setTimeout(r, 50)); |
| 143 | + }); |
| 144 | + expect(status.value).toBe('paid'); |
| 145 | + // …and the lines read the same header the form holds. |
| 146 | + await waitFor(() => expect(qty().disabled).toBe(true)); |
| 147 | + }); |
| 148 | +}); |
0 commit comments