/** * End-to-end tests for the `editorRef` imperative handle. * * The handle is UI-interactions only: it opens a value-edit SESSION at a node, * commits or aborts it, and collapses nodes. It never mutates data directly * (the consumer owns `data`/`setData`). These pin the contract: * - `startEdit` returns `true` if it opened a session, else `'PATH_NOT_FOUND'` * (gone path) or `'RESTRICTED'` (`allowEdit` blocks it, bypassable with * `overrideRestrictions`); it auto-reveals a target collapsed below the * mount frontier. * - `confirm()` commits the open session through `onUpdate` (which may veto); * `cancel()` aborts. `overrideRestrictions` skips ONLY the filter. */ import { createRef } from 'react' import { act, fireEvent, render, screen, within } from '@testing-library/react' import userEvent from '@testing-library/user-event' import { JsonEditor } from '../src/JsonEditor' import { type CustomComponentProps, type CustomNodeDefinition, type JsonEditorHandle, type UpdateFunction, } from '../src/types' const noop = () => {} describe('editorRef handle — startEdit', () => { test('startEdit opens an editor at a visible leaf and returns true', () => { const ref = createRef() render() expect(screen.queryByRole('textbox')).toBeNull() let result: ReturnType | undefined act(() => { result = ref.current!.startEdit({ path: ['greeting'] }) }) expect(result).toBe(true) expect(screen.getByRole('textbox')).toBeInTheDocument() }) test('startEdit returns PATH_NOT_FOUND for a path that no longer exists', () => { const ref = createRef() render() let result: ReturnType | undefined act(() => { result = ref.current!.startEdit({ path: ['nope'] }) }) expect(result).toBe('PATH_NOT_FOUND') expect(screen.queryByRole('textbox')).toBeNull() }) test('startEdit respects allowEdit by default (RESTRICTED, no-op)', () => { const ref = createRef() render( ) let result: ReturnType | undefined act(() => { result = ref.current!.startEdit({ path: ['greeting'] }) }) expect(result).toBe('RESTRICTED') expect(screen.queryByRole('textbox')).toBeNull() }) test('startEdit with overrideRestrictions bypasses allowEdit', () => { const ref = createRef() render( ) let result: ReturnType | undefined act(() => { result = ref.current!.startEdit({ path: ['greeting'], overrideRestrictions: true }) }) expect(result).toBe(true) expect(screen.getByRole('textbox')).toBeInTheDocument() }) test('startEdit honours a per-node allowEdit function', () => { const ref = createRef() render( key !== 'b'} editorRef={ref} /> ) act(() => { expect(ref.current!.startEdit({ path: ['b'] })).toBe('RESTRICTED') }) expect(screen.queryByRole('textbox')).toBeNull() act(() => { expect(ref.current!.startEdit({ path: ['a'] })).toBe(true) }) expect(screen.getByRole('textbox')).toBeInTheDocument() }) test('startEdit reveals a target collapsed below the mount frontier', () => { const ref = createRef() render( ) expect(screen.queryByText('inner')).toBeNull() act(() => ref.current!.startEdit({ path: ['outer', 'inner', 'leaf'] })) expect(screen.getByRole('textbox')).toBeInTheDocument() }) }) describe('editorRef handle — confirm / cancel', () => { test('cancel() leaves the session without committing', () => { const setData = jest.fn() const ref = createRef() render() act(() => ref.current!.startEdit({ path: ['greeting'] })) expect(screen.getByRole('textbox')).toBeInTheDocument() act(() => ref.current!.cancel()) expect(screen.queryByRole('textbox')).toBeNull() expect(setData).not.toHaveBeenCalled() }) test('confirm() commits the open value-edit session via setData', async () => { const user = userEvent.setup() const setData = jest.fn() const ref = createRef() render() act(() => ref.current!.startEdit({ path: ['greeting'] })) const textbox = screen.getByRole('textbox') await user.clear(textbox) await user.type(textbox, 'world') await act(async () => { ref.current!.confirm() }) expect(setData).toHaveBeenCalledWith({ greeting: 'world' }) expect(screen.queryByRole('textbox')).toBeNull() }) test('confirm() runs onUpdate, which can veto (onError fires, value not committed)', async () => { const user = userEvent.setup() const setData = jest.fn() const onError = jest.fn() const onUpdate = jest.fn, Parameters>(() => ({ error: 'nope', })) const ref = createRef() render( ) act(() => ref.current!.startEdit({ path: ['greeting'] })) const textbox = screen.getByRole('textbox') await user.clear(textbox) await user.type(textbox, 'world') await act(async () => { ref.current!.confirm() }) expect(onUpdate).toHaveBeenCalled() expect(onError).toHaveBeenCalledWith( expect.objectContaining({ error: expect.objectContaining({ code: 'UPDATE_ERROR', message: 'nope' }), }) ) // Synchronous veto: the reject is known before the optimistic apply, so // the apply is skipped and `setData` is never called — the edit nets out // uncommitted with no transient write. expect(setData).not.toHaveBeenCalled() }) test('confirm() is a no-op with no value-edit control (does not cancel a key rename)', async () => { const user = userEvent.setup() const onEditEvent = jest.fn() const ref = createRef() render( ) // Start a key-rename session via the UI (the handle has no opener for it). await user.dblClick(screen.getByText('oldName')) expect(screen.getByDisplayValue('oldName')).toBeInTheDocument() onEditEvent.mockClear() // There's no live value-edit confirm control, so confirm() must be a no-op // — NOT tear down the unrelated rename session via the trailing cancel. await act(async () => { ref.current!.confirm() }) expect(onEditEvent.mock.calls.map(([e]: [{ event: string }]) => e.event)).not.toContain( 'cancelRename' ) expect(screen.getByDisplayValue('oldName')).toBeInTheDocument() }) test('overrideRestrictions opens past the filter, but onUpdate still runs at confirm', async () => { // The invariant: `overrideRestrictions` skips ONLY the `allowEdit` // filter; the consumer's `onUpdate` always runs and may reject. const user = userEvent.setup() const onUpdate = jest.fn, Parameters>(() => false) const onError = jest.fn() const ref = createRef() render( ) act(() => { expect(ref.current!.startEdit({ path: ['greeting'], overrideRestrictions: true })).toBe(true) }) const textbox = screen.getByRole('textbox') await user.clear(textbox) await user.type(textbox, 'world') await act(async () => { ref.current!.confirm() }) expect(onUpdate).toHaveBeenCalled() expect(onError).toHaveBeenCalled() }) }) describe('editorRef handle — confirm with custom-node fromStandardType', () => { const CustomEditor = (props: CustomComponentProps) => { const { value, setValue, isEditing, setIsEditing } = props return isEditing ? ( setValue(e.target.value)} /> ) : ( setIsEditing(true)}> {String(value)} ) } const bigintDef: CustomNodeDefinition = { condition: ({ value }) => typeof value === 'bigint', component: CustomEditor, showOnEdit: true, fromStandardType: (buffer) => { if (typeof buffer === 'bigint') return buffer if (!/^\d+$/.test(String(buffer))) throw new Error('Invalid BigInt') return BigInt(String(buffer)) }, } test('confirm() commits through the definition transform', async () => { const setData = jest.fn() const ref = createRef() render( ) act(() => ref.current!.startEdit({ path: ['x'] })) fireEvent.change(screen.getByTestId('custom-input'), { target: { value: '123' } }) await act(async () => { ref.current!.confirm() }) expect(setData).toHaveBeenCalledWith({ x: BigInt(123) }) expect(screen.queryByTestId('custom-input')).toBeNull() }) test('confirm() on an invalid buffer rejects and the session stays open; cancel() still closes it', async () => { const setData = jest.fn() const onError = jest.fn() const ref = createRef() render( ) act(() => ref.current!.startEdit({ path: ['x'] })) fireEvent.change(screen.getByTestId('custom-input'), { target: { value: 'abc' } }) await act(async () => { ref.current!.confirm() }) expect(setData).not.toHaveBeenCalled() expect(onError).toHaveBeenCalled() expect(screen.getByTestId('custom-input')).toBeInTheDocument() act(() => ref.current!.cancel()) expect(screen.queryByTestId('custom-input')).toBeNull() expect(setData).not.toHaveBeenCalled() }) test('confirm() on a collection JSON edit with invalid JSON keeps the session open', async () => { const user = userEvent.setup() const setData = jest.fn() const ref = createRef() render( ) const row = screen.getByText('obj').closest('.jer-component') as HTMLElement await user.click(within(row).getAllByTitle('Edit')[0]) const textarea = screen.getByRole('textbox') fireEvent.change(textarea, { target: { value: '{ not json' } }) await act(async () => { ref.current!.confirm() }) // The parse failure rejects the commit — the session must survive the // imperative confirm rather than being torn down by its trailing cancel. expect(screen.getByRole('textbox')).toBeInTheDocument() expect(setData).not.toHaveBeenCalled() act(() => ref.current!.cancel()) expect(screen.queryByRole('textbox')).toBeNull() }) })