diff --git a/.changeset/36023-rich-text-cell-panel.md b/.changeset/36023-rich-text-cell-panel.md new file mode 100644 index 00000000000..fc4ae9d9d75 --- /dev/null +++ b/.changeset/36023-rich-text-cell-panel.md @@ -0,0 +1,13 @@ +--- +'@object-ui/fields': patch +'@object-ui/plugin-grid': patch +--- + +feat(grid): a markdown, HTML or rich text cell opens a text box in a panel under the cell + +Clause-②: yes (widening) +Metadata-protocol: none + +**The list grid edits the rich-content field types in place** (objectstack#36023). On a select-first grid, selecting a `markdown`, `html` or `richtext` cell and pressing Enter, F2, typing or double-clicking opens the record form's own text box over the stored source in a panel under the cell, at least as wide as the column; the cell keeps showing its value and the row keeps its height. Enter in the panel is a new line; on a select-first grid Ctrl/Cmd+Enter saves and keeps the cell selected, Esc discards, and a click outside saves. Backspace or Delete on the selected cell of a select-first grid clears it as for any other editable cell. On a grid without the select-first cell model (an `ObjectGrid` or `object-grid` mounted without `cellSelection`), one click opens the text box over the cell, not in a panel under it: Enter is a new line, Ctrl/Cmd+Enter does nothing, Esc discards, and a click outside keeps the text as a pending change for the grid's save buttons. Before, these cells opened no editor and said "This field can't be edited in a list". The related tab on the record page draws the same grid and behaves the same way. + +**Only the grid's cell changes.** The three types stay in `INLINE_EXCLUDED_FIELD_TYPES`, and `hasFieldEditWidget` and `isInlineExcludedFieldType` answer as before, so the record page's field editor, the required-fields dialogs, the kanban and timesheet editors keep them out. `@object-ui/fields` exports `hasInCellPanelEditWidget(type)`, true for the three types, and `FieldEditWidget` draws their editor only when the host asks for the cell face (`inCell`); the editor loads lazily. `html` is edited as text; what the cell then draws goes through the sanitizing HTML renderer, as on every other read surface. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 8db647681dd..d68092393d7 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -365,6 +365,11 @@ through the host's data source (`dataSource.update`) with no callback to wire. definition**, not by a column key — a field marked `readonly`, and computed/binary field types (formula, autonumber, file, …), never open an editor. There is no `editable` key on `ListColumn`. +- **Rich text edits in a panel** (objectstack#36023): a `markdown`, `html` or + `richtext` cell opens the record form's text box over the stored source in a + panel under the cell, at least as wide as the column, while the cell keeps + showing its value. Enter there is a new line; on a select-first grid + Ctrl/Cmd+Enter saves, Esc discards and a click outside saves. - **Visual feedback**: editable cells show a hover state, and the input is focused and selected when editing begins - **The editor floats over its cell** (objectstack#35688): it opens on a layer diff --git a/ui/packages/fields/README.md b/ui/packages/fields/README.md index a0c53ba517e..3f5121745ca 100644 --- a/ui/packages/fields/README.md +++ b/ui/packages/fields/README.md @@ -137,6 +137,14 @@ pick and the in-cell colour face after a swatch. A host that passes neither gets the form faces unchanged; `ObjectGrid` passes both. +`inCell` also unlocks the rich-content types (`markdown`, `html`, `richtext`): +they stay in `INLINE_EXCLUDED_FIELD_TYPES` and `hasFieldEditWidget` answers +`false` for them, so every other host keeps them out, while +`hasInCellPanelEditWidget(type)` answers `true` and `FieldEditWidget` draws the +form's rich-text box for them (loaded lazily) when the host asks for the cell +face. The list grid opens it in a panel under the cell, where Enter is a new +line. + ### Resolving declared action params An action param is declared either inline (`name` + `type`) or field-backed diff --git a/ui/packages/fields/src/FieldEditWidget.tsx b/ui/packages/fields/src/FieldEditWidget.tsx index 4508d33d3f3..b3449c56b8a 100644 --- a/ui/packages/fields/src/FieldEditWidget.tsx +++ b/ui/packages/fields/src/FieldEditWidget.tsx @@ -69,6 +69,9 @@ import { isRetiredFieldType, reportRetiredFieldType, } from './field-type-alias.js'; +// The rich-content types' one list (the keys `RichTextField` serves); its +// module is already in the eager closure through `getCellRenderer`. +import { RICH_TEXT_FIELD_TYPES } from './widgets/richTextDisplay.js'; /** * The platform date picker (objectui#12622, objectui#12642), the face the @@ -96,10 +99,21 @@ const DateTimePickerEditWidget = React.lazy(() => import('./widgets/date-picker/DatePickerField.js').then((m) => ({ default: m.DateTimePickerField })), ); -/** The {@link EDIT_WIDGETS} entries that load lazily and need a `Suspense` boundary. */ +/** + * The rich-content editor (`RichTextField`, a text box over the stored + * markdown or HTML source), LAZY through the same `import()` `fieldWidgetMap` + * uses for these three types, for the list grid's cell panel + * ({@link IN_CELL_PANEL_EDIT_WIDGETS}). + */ +const RichTextPanelEditWidget = React.lazy(() => + import('./widgets/RichTextField.js').then((m) => ({ default: m.RichTextField })), +); + +/** The edit widgets that load lazily and need a `Suspense` boundary. */ const LAZY_EDIT_WIDGETS: ReadonlySet = new Set([ DatePickerEditWidget, DateTimePickerEditWidget, + RichTextPanelEditWidget, ]); /** @@ -193,6 +207,29 @@ export const INLINE_EXCLUDED_FIELD_TYPES = new Set([ 'notification-topic', 'notification-channel', 'quiet-hours', ]); +/** + * Members of {@link INLINE_EXCLUDED_FIELD_TYPES} that the LIST GRID's cell + * nevertheless edits, in a panel opened under the cell (objectstack#36023): + * the rich-content types, whose panel is the form's own text box over the + * stored source. Enter in it is a new line; the grid saves on Ctrl/Cmd+Enter + * or a click outside and discards on Esc. + * + * Only a host that asks for the cell face (`inCell`) gets them, so the record + * page's field editor, the required-fields dialogs and every other host of + * {@link FieldEditWidget} keep these types out, exactly as before: they ask + * {@link hasFieldEditWidget}, which still answers `false` for them. The + * exclusion set keeps them too, so `isInlineExcludedFieldType` answers as + * before for every host; the grid asks {@link hasInCellPanelEditWidget}. + * + * `html` is safe to edit as text here because what the cell then draws is + * the sanitizing renderer's output (`./widgets/sanitizedHtml.tsx`), as on + * every other read surface. + */ +const IN_CELL_PANEL_EDIT_WIDGETS: Readonly>>> = + // Derived from the one list of the keys `RichTextField` serves, so a type + // added to the display table gets its cell panel with no second spelling. + Object.fromEntries(RICH_TEXT_FIELD_TYPES.map((type) => [type, RichTextPanelEditWidget])); + /** Field types whose value is chosen in one discrete gesture (no free typing). */ export const DISCRETE_EDIT_TYPES = new Set([ 'boolean', 'toggle', 'select', 'status', 'radio', 'rating', @@ -239,6 +276,17 @@ export function hasFieldEditWidget(type: string | undefined): boolean { return resolveInlineEditType(type) in EDIT_WIDGETS; } +/** + * True when a field type has no in-place widget but the list grid's cell edits + * it in a panel under the cell (`inCell`, {@link IN_CELL_PANEL_EDIT_WIDGETS}). + * A retired spelling answers `false`, as {@link hasFieldEditWidget} does. + */ +export function hasInCellPanelEditWidget(type: string | undefined): boolean { + if (!type) return false; + if (isRetiredFieldType(type)) return false; + return Object.prototype.hasOwnProperty.call(IN_CELL_PANEL_EDIT_WIDGETS, resolveInlineEditType(type)); +} + /** * True when a field type is deliberately NOT inline-editable (alias-aware: * `composite` resolves to the excluded `object`, `video` to `file`, …). @@ -377,7 +425,10 @@ export function FieldEditWidget( return null; } const resolved = field?.type ? resolveInlineEditType(field.type) : undefined; - const Widget = resolved ? EDIT_WIDGETS[resolved] : undefined; + // The cell panel's widgets answer only the host that asks for the cell face. + const Widget = resolved + ? EDIT_WIDGETS[resolved] ?? (props.inCell && hasInCellPanelEditWidget(resolved) ? IN_CELL_PANEL_EDIT_WIDGETS[resolved] : undefined) + : undefined; if (!Widget) return null; // `compact` is a declared widget prop (objectui#3221 closed this type), so // the spread no longer needs an `any` escape hatch to get past it. diff --git a/ui/packages/fields/src/__tests__/inCellFaces-35688.test.tsx b/ui/packages/fields/src/__tests__/inCellFaces-35688.test.tsx index 1d87046ea80..f6eab688afc 100644 --- a/ui/packages/fields/src/__tests__/inCellFaces-35688.test.tsx +++ b/ui/packages/fields/src/__tests__/inCellFaces-35688.test.tsx @@ -23,7 +23,10 @@ import { TagsField } from '../widgets/TagsField'; import { ColorField } from '../widgets/ColorField'; import { TimeField } from '../widgets/TimeField'; import { DatePickerField, DateTimePickerField } from '../widgets/date-picker/DatePickerField'; -import { FieldEditWidget } from '../FieldEditWidget'; +import { FieldEditWidget, hasFieldEditWidget, hasInCellPanelEditWidget, isInlineExcludedFieldType } from '../FieldEditWidget'; +// The rich-content panel's widget sits behind `React.lazy` in `FieldEditWidget`; +// imported here so its factory resolves at once (ui/AGENTS.md, flaky tests). +import '../widgets/RichTextField'; import { TextField } from '../widgets/TextField'; import { EmailField } from '../widgets/EmailField'; import { PhoneField } from '../widgets/PhoneField'; @@ -458,3 +461,44 @@ describe('in-cell record picker (objectstack#35688)', () => { expect(screen.queryByRole('listbox')).toBeNull(); }); }); + +describe('in-cell rich-content panel (objectstack#36023)', () => { + it('markdown, html and rich text get the text box only when the cell face is asked for', () => { + for (const type of ['markdown', 'html', 'richtext']) { + expect(hasInCellPanelEditWidget(type), type).toBe(true); + // Every other host keeps them out, exactly as before. + expect(hasFieldEditWidget(type), type).toBe(false); + expect(isInlineExcludedFieldType(type), type).toBe(true); + } + // CONTROL: no other type, excluded or in-place, is a panel text box. + for (const type of ['text', 'textarea', 'address', 'password', 'secret', 'object', 'file', undefined]) { + expect(hasInCellPanelEditWidget(type), String(type)).toBe(false); + } + }); + + it('draws the stored source in a text box; typing stages it; Enter is left to the text box (a new line)', async () => { + const onChange = vi.fn(); + const onGridKey = vi.fn(); + render( + + + , + ); + const box = (await screen.findByRole('textbox')) as HTMLTextAreaElement; + expect(box.tagName).toBe('TEXTAREA'); + expect(box.value).toBe('

Hello

'); + fireEvent.change(box, { target: { value: '

Hello

\n

World

' } }); + expect(onChange).toHaveBeenLastCalledWith('

Hello

\n

World

'); + // The widget does not take Enter: it reaches the grid's wrapper with its + // default intact, and the wrapper commits a text box only on Ctrl/Cmd+Enter. + expect(fireEvent.keyDown(box, { key: 'Enter' })).toBe(true); + expect(onGridKey).toHaveBeenCalledWith('Enter'); + }); + + it('CONTROL: without the cell face the same field gets no editor', () => { + const { container } = render( + {}} />, + ); + expect(container.innerHTML).toBe(''); + }); +}); diff --git a/ui/packages/plugin-grid/README.md b/ui/packages/plugin-grid/README.md index 990d99f7523..699c0f1dc76 100644 --- a/ui/packages/plugin-grid/README.md +++ b/ui/packages/plugin-grid/README.md @@ -994,8 +994,12 @@ the host's data source (`dataSource.update`) with no callback to wire. - **Per-field read-only**: which cells open is decided by the **field definition**, not by a column key — a field marked `readonly`, and computed/binary field types (formula, autonumber, file, …), never open an editor - (`isFieldInlineEditable`, `src/inline-edit-options.ts:82`). There is no + (`isFieldInlineEditable` in `src/inline-edit-options.ts`). There is no `editable` key on `ListColumn`. +- **Rich text edits in a panel**: a `markdown`, `html` or `richtext` cell opens + the record form's text box in a panel under the cell (Enter is a new line, + Ctrl/Cmd+Enter saves, Escape discards, a click outside saves); the cell keeps + showing its value and the row its height. - **Visual feedback**: editable cells show a hover state - **Automatic focus**: the input is focused and selected when editing begins diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 5be74cc0aab..9c4a1a585bc 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -32,7 +32,7 @@ import { SchemaRenderer, isPermissionError, useDataScope, useNavigationOverlay, // what stops a seventh site picking a convention of its own. import { resolveGridCellRendering } from './cellRendererResolution'; import { isMaskedGridColumn } from './maskedColumn'; -import { formatCurrency, formatDate, getBadgeColorClasses, getBadgeHexAppearance, FieldEditWidget, hasFieldEditWidget, DISCRETE_EDIT_TYPES, coerceToSafeValue, MaskedCellRenderer, withKnownObjects, RICH_TEXT_FIELD_TYPES } from '@object-ui/fields'; +import { formatCurrency, formatDate, getBadgeColorClasses, getBadgeHexAppearance, FieldEditWidget, hasFieldEditWidget, hasInCellPanelEditWidget, DISCRETE_EDIT_TYPES, coerceToSafeValue, MaskedCellRenderer, withKnownObjects, RICH_TEXT_FIELD_TYPES } from '@object-ui/fields'; import { useLocalization, useDisplayLocale } from '@object-ui/i18n'; // Two resolvers, two vocabularies — the repo spells the distinction into the // NAMES (objectui#4167). `resolveInlineI18nLabel` is the spec's own @@ -803,12 +803,13 @@ function opensReferenceInPlace(fieldDef: { type?: unknown; reference?: unknown } * is never narrower than its cell and grows to fit this; the editor fills it. */ function cellEditorWidthClass(type: string): string { + // objectstack#36023 — a rich-content field's text box, as wide as a textarea's. + if ((RICH_TEXT_FIELD_TYPES as readonly string[]).includes(type)) return 'w-full min-w-80'; switch (type) { case 'address': case 'location': return 'w-full min-w-[22rem]'; case 'textarea': - case 'markdown': case 'code': case 'json': return 'w-full min-w-80'; @@ -3614,7 +3615,8 @@ export const ObjectGrid: React.FC = ({ renderCellEditor: inlineEditable ? (ctx: { column: any; row: any; pendingRow: any; value: any; stage: (v: any) => void; commit: (v?: any) => void }) => { const fieldDef = (objectSchema as any)?.fields?.[ctx.column?.accessorKey]; - if (!fieldDef || !hasFieldEditWidget(fieldDef.type)) return null; + // objectstack#36023 — a rich-content field edits in a panel under the cell. + if (!fieldDef || !(hasFieldEditWidget(fieldDef.type) || hasInCellPanelEditWidget(fieldDef.type))) return null; // objectstack#35688 — a `select` declared `multiple` draws the multi-select // check list (`SelectField` hands it to `MultiSelectField`): each check // stages, and the edit is saved when the user moves on. diff --git a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx index 953568ee83c..46519225f96 100644 --- a/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/ObjectGrid.cellSelection-35684.test.tsx @@ -28,6 +28,10 @@ * 6. With the host's `openReferencedRecord`, a lookup chip opens the record * it names through it on a single click and its cell draws an edit * button; a person's chip (`sys_user`) only selects (objectstack#36015). + * 7. objectstack#36023: a rich-content cell (markdown, HTML, rich text) + * opens a text box in a panel under the cell, which keeps its value + * drawn; Enter there is a new line, Ctrl/Cmd+Enter saves and stays on the + * cell, Esc discards, a click outside saves. */ import React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; @@ -56,6 +60,12 @@ vi.mock('@object-ui/permissions', async (importOriginal) => { // Registers `object-grid`, the block under test. import { ObjectGridRenderer } from '../index'; +import { ObjectGrid } from '../ObjectGrid'; +import { ActionProvider } from '@object-ui/react'; +import { registerAllFields } from '@object-ui/fields'; +// The rich-content panel's widget sits behind `React.lazy` in `FieldEditWidget` +// (`./widgets/RichTextField.js` there); loaded here so it resolves at once. +import '../../../fields/src/widgets/RichTextField'; import { RelatedRecordActionsProvider, type RelatedRecordActionsValue } from '@object-ui/react'; import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; import { __resetApprovalsServiceLatch } from '../hooks/useRowApprovalLocks'; @@ -428,3 +438,115 @@ describe('ObjectGrid cellSelection — a lookup chip opens its record in the hos expect(g.cell(1).querySelector('[data-testid="cell-edit-button"]')).toBeNull(); }); }); + +describe('ObjectGrid cellSelection — a rich-content cell edits in a panel under it (objectstack#36023)', () => { + registerAllFields(); + const FIELDS_RT = { + name: { type: 'text', label: 'Name' }, + notes: { type: 'richtext', label: 'Notes' }, + summary: { type: 'markdown', label: 'Summary' }, + body: { type: 'html', label: 'Body' }, + }; + + function makeDataSource() { + const store: Record = { + r1: { id: 'r1', name: 'Alpha', notes: '

First

', summary: '# Plan', body: 'Hi' }, + }; + return { + store, + find: vi.fn(async () => ({ data: Object.values(store).map((r) => ({ ...r })), total: 1, hasMore: false, pageSize: 50 })), + update: vi.fn(async (_object: string, id: string, changes: Record) => { + store[id] = { ...store[id], ...changes }; + return { ...store[id] }; + }), + getObjectSchema: async (name: string) => ({ name, fields: { id: { type: 'text' }, ...FIELDS_RT } }), + } as any; + } + + async function renderRichText() { + const ds = makeDataSource(); + const utils = render( + + + , + ); + await screen.findByText('Alpha', {}, { timeout: 5000 }); + const cell = (col: number) => utils.container.querySelectorAll('tbody tr td[data-grid-cell]')[col]; + const catcher = () => utils.container.querySelector('[data-slot="cell-type-catcher"]')!; + const open = async (col: number) => { + fireEvent.click(cell(col)); + fireEvent.keyDown(catcher(), { key: 'Enter' }); + const overlay = await waitFor(() => { + const el = cell(col).querySelector('[data-slot="cell-editor-overlay"]'); + expect(el).not.toBeNull(); + return el!; + }); + const box = await waitFor(() => { + const el = overlay.querySelector('textarea'); + expect(el).not.toBeNull(); + return el!; + }); + return { overlay, box }; + }; + return { ...utils, ds, cell, open }; + } + + it('markdown, HTML and rich text open a text box under the cell, which keeps its value drawn', async () => { + const g = await renderRichText(); + for (const [col, source] of [[1, '

First

'], [2, '# Plan'], [3, 'Hi']] as const) { + const { overlay, box } = await g.open(col); + expect(overlay).toHaveAttribute('data-placement', 'below'); + // The row's own cell is left as drawn: its rendered value, not the editor. + expect(g.cell(col).querySelector('[data-slot="cell-display"]')).not.toBeNull(); + expect(g.cell(col).querySelector('[data-slot="cell-display"] textarea')).toBeNull(); + // The panel is the text box over the stored source, never a read-only reason. + expect(box).toHaveValue(source); + expect(screen.queryByTestId('cell-readonly-reason')).toBeNull(); + fireEvent.keyDown(box, { key: 'Escape' }); + await waitFor(() => expect(g.cell(col).querySelector('[data-slot="cell-editor-overlay"]')).toBeNull()); + } + expect(g.ds.update).not.toHaveBeenCalled(); + }); + + it('Enter is a new line; Ctrl+Enter and Cmd+Enter save and the cell stays selected', async () => { + const g = await renderRichText(); + let { box } = await g.open(1); + fireEvent.change(box, { target: { value: '

First

' } }); + // Enter stays in the text box: nothing is written and the panel stays open. + expect(fireEvent.keyDown(box, { key: 'Enter' })).toBe(true); + expect(g.ds.update).not.toHaveBeenCalled(); + expect(g.cell(1).querySelector('[data-slot="cell-editor-overlay"] textarea')).toBe(box); + fireEvent.change(box, { target: { value: '

First

\n

Second

' } }); + fireEvent.keyDown(box, { key: 'Enter', ctrlKey: true }); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledTimes(1)); + expect(g.ds.update.mock.calls[0][2]).toEqual({ notes: '

First

\n

Second

' }); + await waitFor(() => expect(g.cell(1).querySelector('[data-slot="cell-editor-overlay"]')).toBeNull()); + expect(g.cell(1)).toHaveAttribute('data-selected-cell'); + + ({ box } = await g.open(2)); + fireEvent.change(box, { target: { value: '# Plan B' } }); + fireEvent.keyDown(box, { key: 'Enter', metaKey: true }); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledTimes(2)); + expect(g.ds.update.mock.calls[1][2]).toEqual({ summary: '# Plan B' }); + expect(g.cell(2)).toHaveAttribute('data-selected-cell'); + }); + + it('Esc discards the edit; a click outside saves it', async () => { + const g = await renderRichText(); + let { box } = await g.open(1); + fireEvent.change(box, { target: { value: 'thrown away' } }); + fireEvent.keyDown(box, { key: 'Escape' }); + await waitFor(() => expect(g.cell(1).querySelector('[data-slot="cell-editor-overlay"]')).toBeNull()); + expect(g.ds.update).not.toHaveBeenCalled(); + + ({ box } = await g.open(3)); + fireEvent.change(box, { target: { value: 'Kept' } }); + fireEvent.pointerDown(document.body); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledTimes(1)); + expect(g.ds.update.mock.calls[0][2]).toEqual({ body: 'Kept' }); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/relatedTab.cellEditing-36023.test.tsx b/ui/packages/plugin-grid/src/__tests__/relatedTab.cellEditing-36023.test.tsx new file mode 100644 index 00000000000..8f213312cca --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/relatedTab.cellEditing-36023.test.tsx @@ -0,0 +1,167 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36023 — the record page's related tab edits its cells as the + * list page does. Driven through the real chain the tab draws: `RelatedList` + * (enlarged, a list of the parent record) → `object-grid` → `data-table`'s + * select-first cells. Three of the card's acceptance lines, repeated on the + * tab: + * + * 1. a select cell opens its option list under the cell, and the cell keeps + * showing its value; + * 2. Enter in a text cell's editor saves and the cell stays selected; + * 3. a rich-content cell opens its text box under the cell; Enter there is + * a new line and Ctrl+Enter saves. + */ + +import { describe, it, expect, vi, beforeAll, afterEach } from 'vitest'; +import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + usePermissions: () => ({ isLoaded: false, checkField: () => true, getObjectApiOperations: () => undefined, can: () => true }), + }; +}); + +// Registers `object-grid`, the enlarged related tab's face. +import '../index'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, FilterScopeProvider, SchemaRendererProvider } from '@object-ui/react'; +import { RelatedList } from '../../../plugin-detail/src/RelatedList'; +import { RelatedListEnlargedContext } from '../../../plugin-detail/src/relatedListCompact'; +import { resetRelatedTabConditionsForTests } from '../../../plugin-detail/src/relatedTabConditions'; +// The rich-content panel's widget sits behind `React.lazy` in `FieldEditWidget`; +// loaded here so it resolves at once. +import '../../../fields/src/widgets/RichTextField'; +import { installExplainDouble } from './explainDouble'; + +registerAllFields(); + +beforeAll(() => { + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: 1440 }); + if (!Element.prototype.scrollIntoView) Element.prototype.scrollIntoView = vi.fn() as any; +}); + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); + resetRelatedTabConditionsForTests(); +}); + +const FIELDS = { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + stage: { type: 'select', label: 'Stage', options: [{ value: 'open', label: 'Open' }, { value: 'won', label: 'Won' }] }, + notes: { type: 'richtext', label: 'Notes' }, + opportunity: { type: 'lookup', reference: 'opportunity', label: 'Opportunity' }, +}; + +function makeDataSource() { + const store: Record = { + q1: { id: 'q1', name: 'Quote one', stage: 'open', notes: '

First

', opportunity: 'O-1' }, + }; + return { + store, + find: vi.fn(async () => ({ data: Object.values(store).map((r) => ({ ...r })), total: 1 })), + update: vi.fn(async (_object: string, id: string, changes: Record) => { + store[id] = { ...store[id], ...changes }; + return { ...store[id] }; + }), + getObjectSchema: vi.fn(async (name: string) => ({ name, fields: FIELDS })), + } as any; +} + +async function renderTab() { + installExplainDouble(); + const ds = makeDataSource(); + const utils = render( + + + + + + + + + , + ); + await screen.findByText('Quote one', {}, { timeout: 5000 }); + const cell = (col: number) => utils.container.querySelectorAll('tbody tr td[data-grid-cell]')[col]; + const catcher = () => utils.container.querySelector('[data-slot="cell-type-catcher"]')!; + const overlayOf = (col: number) => cell(col).querySelector('[data-slot="cell-editor-overlay"]'); + const open = async (col: number) => { + fireEvent.click(cell(col)); + fireEvent.keyDown(catcher(), { key: 'Enter' }); + return waitFor(() => { + const el = overlayOf(col); + expect(el).not.toBeNull(); + return el!; + }); + }; + return { ...utils, ds, cell, open, overlayOf }; +} + +describe('the related tab edits cells as the list page does (objectstack#36023)', () => { + it('a select opens its list under the cell; Enter saves a text cell and stays; rich text opens its panel', async () => { + const g = await renderTab(); + const col = { name: 0, stage: 1, notes: 2 }; + expect(g.cell(col.name)).toHaveTextContent('Quote one'); + + // 1. A picker opens under the cell, which keeps showing its value. + const picker = await g.open(col.stage); + expect(picker).toHaveAttribute('data-placement', 'below'); + expect(g.cell(col.stage).querySelector('[data-slot="cell-display"]')).toHaveTextContent('Open'); + expect(picker.querySelector('[role="listbox"], [role="option"]')).not.toBeNull(); + fireEvent.keyDown(picker.querySelector('input')!, { key: 'Escape' }); + await waitFor(() => expect(g.overlayOf(col.stage)).toBeNull()); + + // 2. Enter saves a text cell and the selection stays on it. + const textEditor = await g.open(col.name); + expect(textEditor).toHaveAttribute('data-placement', 'cover'); + const input = textEditor.querySelector('input')!; + fireEvent.change(input, { target: { value: 'Quote uno' } }); + fireEvent.keyDown(input, { key: 'Enter' }); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledTimes(1)); + expect(g.ds.update.mock.calls[0][1]).toBe('q1'); + expect(g.ds.update.mock.calls[0][2]).toEqual({ name: 'Quote uno' }); + await waitFor(() => expect(g.overlayOf(col.name)).toBeNull()); + expect(g.cell(col.name)).toHaveAttribute('data-selected-cell'); + + // 3. Rich text opens its text box under the cell; Enter is a new line, + // Ctrl+Enter saves. + const panel = await g.open(col.notes); + expect(panel).toHaveAttribute('data-placement', 'below'); + const box = await waitFor(() => { + const el = panel.querySelector('textarea'); + expect(el).not.toBeNull(); + return el!; + }); + expect(box).toHaveValue('

First

'); + expect(fireEvent.keyDown(box, { key: 'Enter' })).toBe(true); + expect(g.ds.update).toHaveBeenCalledTimes(1); + fireEvent.change(box, { target: { value: '

First

\n

Second

' } }); + fireEvent.keyDown(box, { key: 'Enter', ctrlKey: true }); + await waitFor(() => expect(g.ds.update).toHaveBeenCalledTimes(2)); + expect(g.ds.update.mock.calls[1][2]).toEqual({ notes: '

First

\n

Second

' }); + expect(g.cell(col.notes)).toHaveAttribute('data-selected-cell'); + }); +}); diff --git a/ui/packages/plugin-grid/src/inline-edit-options.test.ts b/ui/packages/plugin-grid/src/inline-edit-options.test.ts index df249cb0327..7976e19b319 100644 --- a/ui/packages/plugin-grid/src/inline-edit-options.test.ts +++ b/ui/packages/plugin-grid/src/inline-edit-options.test.ts @@ -7,7 +7,7 @@ */ import { describe, it, expect } from 'vitest'; -import { stateMachineNextValues, isFieldInlineEditable } from './inline-edit-options'; +import { stateMachineNextValues, isFieldInlineEditable, fieldInlineReadOnlyKind } from './inline-edit-options'; // Mirrors examples/app-showcase task.object.ts — the state machine that rejected // done → in_review live (done only transitions to in_progress). @@ -102,10 +102,20 @@ describe('isFieldInlineEditable', () => { } }); - it('keeps a markdown cell read-only — the detail row editor (objectui#11541) is not a grid one', () => { - // The detail page routes `markdown` to a multi-line textarea through its own - // carve-out from the shared exclusion; the cell has no room for one. - expect(isFieldInlineEditable({ type: 'markdown' })).toBe(false); + it('edits the rich-content types in a cell, in a panel under it (objectstack#36023)', () => { + // They stay in the fields package's shared exclusion (the record page and + // the required-fields dialogs keep them out); the cell's panel is the + // grid's own carve-out from it. + for (const type of ['markdown', 'html', 'richtext']) { + expect(fieldInlineReadOnlyKind({ type }), type).toBeNull(); + expect(isFieldInlineEditable({ type }), type).toBe(true); + } + // CONTROL: a declared read-only rich-content field stays read-only, and the + // carve-out lets no other excluded type through. + expect(fieldInlineReadOnlyKind({ type: 'richtext', readonly: true })).toBe('readonly'); + for (const type of ['password', 'secret', 'object', 'file']) { + expect(fieldInlineReadOnlyKind({ type }), type).toBe('notInline'); + } }); it('blocks an explicitly readonly field regardless of type', () => { diff --git a/ui/packages/plugin-grid/src/inline-edit-options.ts b/ui/packages/plugin-grid/src/inline-edit-options.ts index 8ba0887eab0..d66c2051075 100644 --- a/ui/packages/plugin-grid/src/inline-edit-options.ts +++ b/ui/packages/plugin-grid/src/inline-edit-options.ts @@ -12,7 +12,7 @@ * is bound to reject. */ -import { isInlineExcludedFieldType } from '@object-ui/fields'; +import { isInlineExcludedFieldType, hasInCellPanelEditWidget } from '@object-ui/fields'; import { isExpressionComputedField } from '@object-ui/core'; /** @@ -60,7 +60,11 @@ export function fieldInlineReadOnlyKind( if (isExpressionComputedField(fieldDef)) return 'computed'; if (typeof fieldDef.type !== 'string') return null; if (COMPUTED_FIELD_TYPES.has(fieldDef.type)) return 'computed'; - return NON_EDITABLE_FIELD_TYPES.has(fieldDef.type) || isInlineExcludedFieldType(fieldDef.type) ? 'notInline' : null; + if (NON_EDITABLE_FIELD_TYPES.has(fieldDef.type)) return 'notInline'; + // The rich-content types are excluded from in-place editing everywhere, and + // a cell still edits them, in a panel under it (objectstack#36023). + if (hasInCellPanelEditWidget(fieldDef.type)) return null; + return isInlineExcludedFieldType(fieldDef.type) ? 'notInline' : null; } /** @@ -72,7 +76,8 @@ export function fieldInlineReadOnlyKind( * for every type the fields package * excludes from inline editing (`isInlineExcludedFieldType` — alias-aware, * so `composite` → `object`, `repeater` → `grid` are read-only cells, never - * a plain text box). A null/unknown field is treated as editable so the + * a plain text box), save the rich-content types the cell edits in a panel + * (`hasInCellPanelEditWidget`). A null/unknown field is treated as editable so the * grid's own `editable` flag still governs. */ export function isFieldInlineEditable( diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts-35684.test.ts b/ui/packages/plugin-grid/src/objectGridCellFacts-35684.test.ts index 6d015910863..1cfe7422e2d 100644 --- a/ui/packages/plugin-grid/src/objectGridCellFacts-35684.test.ts +++ b/ui/packages/plugin-grid/src/objectGridCellFacts-35684.test.ts @@ -16,6 +16,7 @@ import { describe, it, expect } from 'vitest'; import { cellReadOnlyKind, inlineTyping, choiceFromText, inlineEditorPlacement, clearRefusalText, cellValueRefusal, type CellReadOnlyInputs } from './objectGridCellFacts'; import { fieldInlineReadOnlyKind, isFieldInlineEditable } from './inline-edit-options'; +import { RICH_TEXT_FIELD_TYPES, hasInCellPanelEditWidget } from '@object-ui/fields'; const OPEN: CellReadOnlyInputs = { fieldDef: { type: 'text' }, @@ -109,8 +110,8 @@ describe('choiceFromText — pasted text in a choice field (objectstack#35687)', const t = (key: string, o: Record = {}) => `${key}|${Object.entries(o).map(([k, v]) => `${k}=${v}`).join(',')}`; describe('the editor, Backspace and the commit rules a cell is given (objectstack#36023)', () => { - it('pickers open under the cell; typed input, long text and an address edit in place', () => { - for (const type of ['select', 'status', 'multiselect', 'tags', 'date', 'datetime', 'time', 'color', 'lookup', 'master_detail', 'user']) { + it('pickers and the rich-content text box open under the cell; typed input, long text and an address edit in place', () => { + for (const type of ['select', 'status', 'multiselect', 'tags', 'date', 'datetime', 'time', 'color', 'lookup', 'master_detail', 'user', 'markdown', 'html', 'richtext']) { expect(inlineEditorPlacement(type), type).toBe('below'); } for (const type of ['text', 'number', 'currency', 'percent', 'email', 'phone', 'url', 'textarea', 'address', 'rating', 'boolean', undefined]) { @@ -118,6 +119,18 @@ describe('the editor, Backspace and the commit rules a cell is given (objectstac } }); + it('every rich-content type the display table serves edits in a panel under the cell', () => { + // One list (`RICH_TEXT_FIELD_TYPES`, the keys `RichTextField` serves) decides + // all three answers, so a type added to it can never draw in the cell yet + // read as not editable in a list. + expect(RICH_TEXT_FIELD_TYPES.length).toBeGreaterThan(0); + for (const type of RICH_TEXT_FIELD_TYPES) { + expect(hasInCellPanelEditWidget(type), type).toBe(true); + expect(inlineEditorPlacement(type), type).toBe('below'); + expect(fieldInlineReadOnlyKind({ type }), type).toBeNull(); + } + }); + it('a required field refuses Backspace in the form\'s words, or its own message; any other may be cleared', () => { expect(clearRefusalText({ type: 'text', required: true, label: 'Name' }, 'name', t)).toBe('validation.required|field=Name'); expect(clearRefusalText({ type: 'text', required: true }, 'name', t)).toBe('validation.required|field=name'); diff --git a/ui/packages/plugin-grid/src/objectGridCellFacts.ts b/ui/packages/plugin-grid/src/objectGridCellFacts.ts index 8d12fdda036..211a3474760 100644 --- a/ui/packages/plugin-grid/src/objectGridCellFacts.ts +++ b/ui/packages/plugin-grid/src/objectGridCellFacts.ts @@ -12,7 +12,7 @@ * on it does, and what pasted text stands for. The table asks when the reader * acts on a cell, never while it draws. */ -import { buildValidationRules } from '@object-ui/fields'; +import { buildValidationRules, RICH_TEXT_FIELD_TYPES } from '@object-ui/fields'; import { fieldInlineReadOnlyKind } from './inline-edit-options'; /** Why a cell opens no editor, in the order a cell names them. */ @@ -130,12 +130,15 @@ export function choiceFromText( /** * Field types whose cell editor is a panel opened under the cell, which keeps * showing its value (objectstack#36023): a list to pick from, a calendar, a - * clock, a palette. Typed input, long text and an address edit in place. + * clock, a palette, and the text box of a rich-content field (markdown, HTML, + * rich text), whose Enter is a new line. Typed input, long text and an + * address edit in place. */ const PANEL_EDITOR_FIELD_TYPES: ReadonlySet = new Set([ 'select', 'status', 'radio', 'multiselect', 'checkboxes', 'tags', 'date', 'datetime', 'time', 'color', 'lookup', 'master_detail', 'user', 'owner', + ...RICH_TEXT_FIELD_TYPES, ]); /** Where the cell editor of this field type draws; `undefined` leaves it to the table. */