diff --git a/.changeset/inline-name-input.md b/.changeset/inline-name-input.md new file mode 100644 index 0000000000..f7cc732a8a --- /dev/null +++ b/.changeset/inline-name-input.md @@ -0,0 +1,8 @@ +--- +'@hyperdx/app': patch +--- + +feat: rename dashboards and saved searches by clicking the title instead of a +pencil button + +The name is now edited in place: Enter or clicking away saves, Escape reverts. diff --git a/.claude/skills/naming-objects/SKILL.md b/.claude/skills/naming-objects/SKILL.md new file mode 100644 index 0000000000..2795fbc372 --- /dev/null +++ b/.claude/skills/naming-objects/SKILL.md @@ -0,0 +1,41 @@ +--- +name: naming-objects +description: + Name user-created objects (dashboards, saved searches, tiles, alerts) with the + shared InlineNameInput. Use when adding or changing the place where a user + names or renames something, building an editor or page header that shows an + object's name, or when tempted to add a pencil edit button, a "Name" field in + a save modal, or a bordered name TextInput. +--- + +# Naming objects + +Read **`agent_docs/naming_objects.md`** before changing how something is named. +It is the source of truth; this skill is the short version. + +## Quick rules + +1. Use `InlineNameInput` / `InlineNameInputControlled` from + `@/components/InlineNameInput/InlineNameInput`. Never build a separate + click-to-edit title, pencil button, or "Save name" button. +2. **Saved object shown on its page** → `InlineNameInput` with `onCommit`. Enter + or blur saves immediately; Escape and empty names revert. +3. **Draft in an editor** → `InlineNameInputControlled` with the form's + `control`. The name saves with the editor's save button. +4. Sizes are `xs`, `sm`, `md` only. Page titles use `size="md"` with + `headingLevel={3}`. Editor headers use `size="sm"` (default). Compact rows + use `size="xs"`. +5. Always set `aria-label` ("Dashboard name") and an "Untitled …" placeholder in + sentence case ("Untitled tile"). +6. Don't ask for a name inside a save modal. Name inline, then save. +7. In tests, assert the name with `toHaveValue`. In E2E, `fill()` then press + Enter. + +## Workflow + +1. Read `agent_docs/naming_objects.md`. +2. Look at the reference usages: `DBDashboardPage.tsx` (dashboard name) and + `DBSearchPage.tsx` (saved search name). +3. Check the stories in Storybook under **Components/InlineNameInput**. +4. Update E2E page objects that read the name as text. +5. Run `yarn lint:fix` in the repo root. diff --git a/AGENTS.md b/AGENTS.md index dd0e121418..3279b36c43 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,8 @@ directory: `useConfirm` for confirmation dialogs, `EmptyState`, and where shared code already lives), so copying the conventions of the component you are editing is not sufficient. +- `agent_docs/naming_objects.md` - How users name and rename objects + (`InlineNameInput`). Read before adding or changing any name field - `agent_docs/observability.md` - Instrumentation standards (tracing, metrics, context) and the shared helpers (read when adding or changing a feature) diff --git a/agent_docs/README.md b/agent_docs/README.md index 635f60f71b..2e3c1de63d 100644 --- a/agent_docs/README.md +++ b/agent_docs/README.md @@ -17,6 +17,7 @@ Instead of stuffing all instructions into `AGENTS.md` (which goes into every con - **`development.md`** - Development workflows, testing strategy, common tasks, debugging - **`code_style.md`** - Code patterns and best practices. Read before adding a type, Zod schema, helper, or component in any package (grep-first rule, plus a map of what already lives in `common-utils`), and before any `packages/app` UI change. - **`page_layout.md`** - PageHeader, PageLayout, and consistent page chrome (titles, actions, tool pages) +- **`naming_objects.md`** - How users name and rename objects (dashboards, saved searches, tiles) with `InlineNameInput`. Read before adding or changing any place where something gets a name. - **`data_viz_colors.md`** - Chart, heatmap, and semantic status colors. Read before adding or changing any color in a chart, sparkline, heatmap, legend, or status pill. - **`themes.md`** - How the brand theme system (HyperDX vs ClickStack) and color mode (light/dark/system) work. Read before changing anything in `packages/app/src/theme/`, adding semantic CSS variables, or touching brand-conditional UI. - **`observability.md`** - Instrumentation standards (tracing, metrics, context) and the shared helpers. Read when adding or changing a feature. diff --git a/agent_docs/code_style.md b/agent_docs/code_style.md index f9c0810e94..e47bd958d0 100644 --- a/agent_docs/code_style.md +++ b/agent_docs/code_style.md @@ -285,6 +285,14 @@ the copy). Exercise the real dialog in E2E instead. **Title copy**: Treat `title` as a short headline (like `Title` in the UI). Do **not** end it with a period. Use `description` for full sentences, which should use normal punctuation including a trailing period when appropriate. Match listing pages (e.g. dashboards and saved searches use parallel phrasing such as “No matching … yet” / “No … yet” without dots). +### Object names: use `InlineNameInput` (REQUIRED) + +**Name or rename a dashboard, saved search, tile, or any other user-created +object with `InlineNameInput` (`@/components/InlineNameInput/InlineNameInput`).** +Do not build a pencil-button edit mode, a bordered name `TextInput` in a +header, or a "Name" field inside a save modal. See +[naming_objects.md](naming_objects.md) for which variant to use. + ### Code snippets (REQUIRED) **Do not render raw `
`, ad-hoc `Paper` + monospace text, or unstyled ``.** Use the existing Mantine/product components so snippets match Terraform export, onboarding, and Storybook guidelines.
diff --git a/agent_docs/naming_objects.md b/agent_docs/naming_objects.md
new file mode 100644
index 0000000000..4ee29ac077
--- /dev/null
+++ b/agent_docs/naming_objects.md
@@ -0,0 +1,91 @@
+# Naming objects
+
+Every user-named object (dashboard, saved search, dashboard tile, alert, and so
+on) gets its name through one control: `InlineNameInput`. It looks like plain
+title text until you hover or click it, then edits in place. There is no pencil
+button, no double-click, no separate "Save name" button, and no naming step
+inside a save modal.
+
+```tsx
+import {
+  InlineNameInput,
+  InlineNameInputControlled,
+} from '@/components/InlineNameInput/InlineNameInput';
+```
+
+## Pick the variant by how the object is saved
+
+| The object is...                                                         | Use                                                   | When the name is saved                                                                                                                                                             |
+| ------------------------------------------------------------------------ | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Already saved, and the page shows it (dashboard page, saved search page) | `InlineNameInput` with `onCommit`                     | Enter or blur commits. The typed name stays until `value` updates. Return a rejected promise from `onCommit` to revert it. Escape reverts, and an empty or unchanged name reverts. |
+| A draft in an editor (tile editor, new chart, new saved search)          | `InlineNameInputControlled` with the form's `control` | With the rest of the form, when the user presses the editor's save button.                                                                                                         |
+
+A rename on a saved object is an arrangement change, like moving a tile, so it
+saves without a confirmation. A name on a draft is part of the draft's content,
+so it waits for the explicit save.
+
+## Size and placement
+
+Sizes go from `xs` to `md`. Don't add larger ones.
+
+- `size="md"`: the page title, top-left of the page body under the breadcrumbs.
+  Pass `headingLevel` so the name is still the page heading for screen readers
+  and `getByRole('heading')`. Use `headingLevel={3}` to match the existing
+  dashboard and saved search pages.
+- `size="sm"` (default): editor headers, next to the close button and before the
+  editor's actions.
+- `size="xs"`: compact rows, such as a name inside a dense form or list.
+
+## Copy
+
+- `aria-label` is required because there is no visible label: "Dashboard name",
+  "Saved search name", "Tile name".
+- The placeholder is "Untitled" plus the object type in sentence case: "Untitled
+  dashboard", "Untitled search", "Untitled tile". Don't use "Name".
+- Don't add a "Name" label or helper text next to the field.
+
+## Examples
+
+Saved object, saves on commit:
+
+```tsx
+ setDashboard({ ...dashboard, name })}
+  placeholder="Untitled dashboard"
+  aria-label="Dashboard name"
+  size="md"
+  headingLevel={3}
+  data-testid="dashboard-name-input"
+/>
+```
+
+Draft, saves with the form:
+
+```tsx
+
+```
+
+## Don't
+
+- Don't build a click-to-edit title with a pencil `ActionIcon` and an edit mode.
+  That was `EditablePageName`, which this replaces.
+- Don't use a bordered `TextInput` for an object's own name in a page or editor
+  header.
+- Don't ask for the name in a modal before saving. Name inline, then save.
+- Don't show a success toast for a rename. Show an error toast if the save
+  fails.
+
+## Testing
+
+- The field is a textbox, so assert with `toHaveValue`, not `toHaveText`.
+- To rename in E2E: `fill()` the input, then press Enter. See
+  `DashboardPage.renameDashboard` in `packages/app/tests/e2e/page-objects/`.
+- Storybook: **Components/InlineNameInput** shows both variants and sizes.
diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx
index 7b967c151d..5888314024 100644
--- a/packages/app/src/DBDashboardPage.tsx
+++ b/packages/app/src/DBDashboardPage.tsx
@@ -144,6 +144,7 @@ import { DBTimeChart } from '@/components/DBTimeChart';
 import { FavoriteButton } from '@/components/FavoriteButton';
 import FullscreenPanelModal from '@/components/FullscreenPanelModal';
 import ResourceTerraformPopover from '@/components/Iac/ResourceTerraformPopover';
+import { InlineNameInput } from '@/components/InlineNameInput/InlineNameInput';
 import { PageHeader } from '@/components/PageHeader';
 import { PageLayout } from '@/components/PageLayout';
 import { SqlVariablesProvider } from '@/components/SQLEditor/variableCompletions';
@@ -198,7 +199,6 @@ import {
 import { useConnections } from './connection';
 import { useDashboard } from './dashboard';
 import DashboardFilters from './DashboardFilters';
-import { EditablePageName } from './EditablePageName';
 import {
   GranularityPicker,
   GranularityPickerControlled,
@@ -2906,16 +2906,21 @@ function DBDashboardPage({
   );
 
   const dashboardName = (
-     {
-        if (dashboard != null) {
-          setDashboard({
-            ...dashboard,
-            name: editedName,
-          });
-        }
+      value={dashboard?.name ?? ''}
+      placeholder="Untitled dashboard"
+      aria-label="Dashboard name"
+      size="md"
+      headingLevel={3}
+      data-testid="dashboard-name-input"
+      onCommit={editedName => {
+        if (dashboard == null) return;
+        return new Promise((resolve, reject) => {
+          setDashboard({ ...dashboard, name: editedName }, resolve, () =>
+            reject(new Error('Unable to save dashboard')),
+          );
+        });
       }}
     />
   );
diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx
index 2a5e1c64c5..ad2248916d 100644
--- a/packages/app/src/DBSearchPage.tsx
+++ b/packages/app/src/DBSearchPage.tsx
@@ -96,6 +96,7 @@ import EmptyState from '@/components/EmptyState';
 import { ErrorBoundary } from '@/components/Error/ErrorBoundary';
 import { FavoriteButton } from '@/components/FavoriteButton';
 import ResourceTerraformPopover from '@/components/Iac/ResourceTerraformPopover';
+import { InlineNameInput } from '@/components/InlineNameInput/InlineNameInput';
 import { InputControlled } from '@/components/InputControlled';
 import OnboardingModal from '@/components/OnboardingModal';
 import SearchWhereInput, {
@@ -169,7 +170,6 @@ import {
 } from './utils/queryParsers';
 import { LOCAL_STORE_CONNECTIONS_KEY } from './connection';
 import { DBSearchPageAlertModal } from './DBSearchPageAlertModal';
-import { EditablePageName } from './EditablePageName';
 import { SearchConfig } from './types';
 import { FormatTime } from './useFormatTime';
 
@@ -2229,7 +2229,7 @@ function DBSearchPageContent() {
       )}
       
       {savedSearch && (
-        
+        
           
             
               
@@ -2239,7 +2239,7 @@ function DBSearchPageContent() {
                 {savedSearch.name}
               
             
-            
+            
               {savedSearch.createdBy && (
                 
                   Created by{' '}
@@ -2266,18 +2266,33 @@ function DBSearchPageContent() {
             
           
           
-            
- { - updateSavedSearch.mutate({ + + updateSavedSearch + .mutateAsync({ id: savedSearch.id, name: editedName, - }); - }} - /> -
+ }) + .catch(error => { + notifications.show({ + color: 'red', + title: 'Unable to save search', + message: + error instanceof Error + ? error.message.slice(0, 100) + : 'An error occurred while renaming your saved search.', + }); + throw error; + }) + } + /> void; -}) { - const [editing, setEditing] = useState(false); - const [editedName, setEditedName] = useState(name); - - const { hovered, ref } = useHover(); - - const cancelEditing = () => { - setEditedName(name); - setEditing(false); - }; - - return ( - setEditing(true)} - className="cursor-pointer" - title="Double click to edit" - > - {editing ? ( -
{ - e.preventDefault(); - if (!editedName.trim()) return; - onSave(editedName); - setEditing(false); - }} - onKeyDown={e => { - if (e.key === 'Escape') { - cancelEditing(); - } - }} - onBlur={e => { - if (!e.currentTarget.contains(e.relatedTarget)) { - cancelEditing(); - } - }} - > - ) => - setEditedName(e.target.value) - } - placeholder="Name" - autoFocus - /> - -
- ) : ( -
- - {name} - - {hovered && ( - - )} -
- )} -
- ); -} diff --git a/packages/app/src/components/InlineNameInput/InlineNameInput.module.scss b/packages/app/src/components/InlineNameInput/InlineNameInput.module.scss new file mode 100644 index 0000000000..f63e578e84 --- /dev/null +++ b/packages/app/src/components/InlineNameInput/InlineNameInput.module.scss @@ -0,0 +1,80 @@ +// The input and a hidden copy of its text share one grid cell, so the field +// grows with its content instead of reserving a fixed width. +.root { + display: inline-grid; + width: max-content; + min-width: 80px; + max-width: 100%; + margin: 0; + vertical-align: middle; + + &::after { + content: attr(data-value) ' '; + grid-area: 1 / 1; + visibility: hidden; + white-space: pre; + overflow: hidden; + } +} + +.input, +.root::after { + font: inherit; + padding: 2px 6px; + border: 1px solid transparent; + border-radius: var(--mantine-radius-sm); +} + +.input { + grid-area: 1 / 1; + width: 100%; + min-width: 0; + margin: 0; + color: var(--color-text); + background: transparent; + text-overflow: ellipsis; + transition: + background-color 100ms ease, + border-color 100ms ease; + + &::placeholder { + color: var(--mantine-color-placeholder); + } + + &:hover { + border-color: var(--color-border); + } + + &:focus { + outline: none; + border-color: var(--color-outline-focus); + background-color: var(--color-bg-field); + } + + &[aria-invalid='true'] { + border-color: var(--color-text-danger); + } +} + +.xs, +.sm, +.md { + font-weight: 500; + line-height: var(--mantine-line-height-sm); + + // Aligns the text with content around it, so only the hover border sits + // outside the column. Equals the input's padding plus border. + margin-inline-start: -7px; +} + +.xs { + font-size: var(--mantine-font-size-sm); +} + +.sm { + font-size: var(--mantine-font-size-md); +} + +.md { + font-size: var(--mantine-font-size-xl); +} diff --git a/packages/app/src/components/InlineNameInput/InlineNameInput.stories.tsx b/packages/app/src/components/InlineNameInput/InlineNameInput.stories.tsx new file mode 100644 index 0000000000..84b5471ddc --- /dev/null +++ b/packages/app/src/components/InlineNameInput/InlineNameInput.stories.tsx @@ -0,0 +1,187 @@ +import { useState } from 'react'; +import { useForm, useWatch } from 'react-hook-form'; +import { + ActionIcon, + Anchor, + Box, + Breadcrumbs, + Button, + Code, + Flex, + Group, + Stack, + Text, +} from '@mantine/core'; +import type { Meta, StoryObj } from '@storybook/nextjs'; +import { IconX } from '@tabler/icons-react'; + +import { InlineNameInput, InlineNameInputControlled } from './InlineNameInput'; + +const meta: Meta = { + title: 'Components/InlineNameInput', + component: InlineNameInput, + parameters: { + layout: 'padded', + docs: { + description: { + component: + 'The one way to name a user-created object. See Guidelines/Naming objects for when to use each variant.', + }, + }, + }, +}; + +export default meta; +type Story = StoryObj; + +function SavedObjectDemo({ initialName }: { initialName: string }) { + const [name, setName] = useState(initialName); + const [log, setLog] = useState([]); + return ( + + + + Dashboards + + + {name || 'Untitled'} + + + { + setName(next); + setLog(l => [...l, `Saved "${next}"`]); + }} + placeholder="Untitled dashboard" + aria-label="Dashboard name" + size="md" + headingLevel={3} + /> + + Hover, then click to edit. Enter or click away saves; Escape reverts. + + {log.length > 0 && {log.join('\n')}} + + ); +} + +/** A saved object: the rename is saved as soon as it is committed. */ +export const SavedObject: Story = { + render: () => , +}; + +/** A saved object with a name long enough to truncate at rest. */ +export const LongName: Story = { + render: () => ( + + + + ), +}; + +function DraftEditorDemo() { + const { control, handleSubmit, reset } = useForm({ + defaultValues: { name: '' }, + }); + const name = useWatch({ control, name: 'name' }); + const [saved, setSaved] = useState(); + return ( + + + + reset()} + > + + + + + + + Add to{' '} + + My dashboard + + + + + + + Draft name: {name || '(empty)'} + {saved != null && ( + <> + {' '} + · Saved: {saved} + + )} + + + ); +} + +/** + * A draft in an editor: the name is part of the form and only saves with the + * editor's save button. + */ +export const DraftInEditorHeader: Story = { + parameters: { layout: 'fullscreen' }, + render: () => , +}; + +const SIZE_USAGE: Record<'xs' | 'sm' | 'md', string> = { + xs: 'Compact rows, e.g. inside a form', + sm: 'Editor headers (default)', + md: 'Page titles', +}; + +const SIZES: Array<'xs' | 'sm' | 'md'> = ['xs', 'sm', 'md']; + +/** Every size, filled and empty. */ +export const Sizes: Story = { + render: () => ( + + {SIZES.map(size => ( + + + size="{size}" · {SIZE_USAGE[size]} + + {}} + aria-label={`Name (${size})`} + /> + {}} + placeholder="Untitled dashboard" + aria-label={`Empty name (${size})`} + /> + + ))} + + ), +}; diff --git a/packages/app/src/components/InlineNameInput/InlineNameInput.tsx b/packages/app/src/components/InlineNameInput/InlineNameInput.tsx new file mode 100644 index 0000000000..65608192c6 --- /dev/null +++ b/packages/app/src/components/InlineNameInput/InlineNameInput.tsx @@ -0,0 +1,188 @@ +import { useState } from 'react'; +import cx from 'classnames'; +import type { HTMLAttributes, ReactNode } from 'react'; +import type { InputHTMLAttributes, KeyboardEvent, Ref } from 'react'; +import { Control, Controller, FieldValues, Path } from 'react-hook-form'; + +import classes from './InlineNameInput.module.scss'; + +type NativeInputProps = Omit< + InputHTMLAttributes, + 'size' | 'value' | 'defaultValue' | 'onChange' | 'className' | 'style' +>; + +interface InlineNameFieldProps extends NativeInputProps { + value: string; + onChange: (value: string) => void; + /** `md` for page titles, `sm` for editor headers, `xs` for compact rows. */ + size?: 'xs' | 'sm' | 'md'; + /** Required: the field has no visible label. */ + 'aria-label': string; + /** Wraps the field in a heading when it is the page title. */ + headingLevel?: 1 | 2 | 3 | 4 | 5 | 6; + invalid?: boolean; + ref?: Ref; +} + +function NameRoot({ + level, + children, + ...props +}: { + level?: InlineNameFieldProps['headingLevel']; + children: ReactNode; +} & HTMLAttributes) { + if (level === 1) return

{children}

; + if (level === 2) return

{children}

; + if (level === 3) return

{children}

; + if (level === 4) return

{children}

; + if (level === 5) return
{children}
; + if (level === 6) return
{children}
; + return {children}; +} + +function InlineNameField({ + value, + onChange, + size = 'sm', + headingLevel, + invalid, + placeholder, + ...inputProps +}: InlineNameFieldProps) { + // The input's value is not part of its parent's accessible name, so the + // heading would otherwise be announced as the input's label. + const headingName = headingLevel != null ? value || placeholder : undefined; + return ( + + onChange(e.target.value)} + /> + + ); +} + +export interface InlineNameInputProps + extends Omit { + value: string; + /** + * Called with the trimmed name when it changed and isn't empty. Return a + * promise so a failed save reverts the field; the typed name stays on + * screen until `value` updates or the promise rejects. + */ + onCommit: (name: string) => void | Promise; +} + +/** + * Name of an object that is already saved. Enter or blur commits, Escape + * reverts, and an empty name reverts. + */ +export function InlineNameInput({ + value, + onCommit, + onKeyDown, + onBlur, + ...fieldProps +}: InlineNameInputProps) { + // The name just committed, kept until the saved `value` catches up so the + // title doesn't flash the old name while the save is in flight. Cleared + // when `value` changes (the save landed, or something else wrote) or when + // the commit rejects. + const [pending, setPending] = useState(); + const [trackedValue, setTrackedValue] = useState(value); + if (value !== trackedValue) { + setTrackedValue(value); + setPending(undefined); + } + + // What the user is typing. Undefined means show the committed name. + const [draft, setDraft] = useState(); + const shown = draft ?? pending ?? value; + + const handleKeyDown = (e: KeyboardEvent) => { + onKeyDown?.(e); + // Enter confirms an IME candidate before it inserts text. Committing + // there would save the half-composed name. + if (e.key === 'Enter' && !e.nativeEvent.isComposing) { + e.preventDefault(); + e.currentTarget.blur(); + } else if (e.key === 'Escape') { + e.preventDefault(); + // The blur handler reads the DOM value, so reset it before blurring. + e.currentTarget.value = pending ?? value; + e.currentTarget.blur(); + } + }; + + return ( + { + const next = e.currentTarget.value.trim(); + setDraft(undefined); + if (next !== '' && next !== (pending ?? value)) { + setPending(next); + Promise.resolve(onCommit(next)).catch(() => { + setPending(current => (current === next ? undefined : current)); + }); + } else if (next === '') { + setPending(undefined); + } + onBlur?.(e); + }} + /> + ); +} + +export interface InlineNameInputControlledProps + extends Omit { + name: Path; + control: Control; + rules?: Parameters['register']>[1]; +} + +/** + * Name of a draft, such as a tile in the editor. The value is saved with the + * rest of the form. + */ +export function InlineNameInputControlled({ + name, + control, + rules, + ...fieldProps +}: InlineNameInputControlledProps) { + return ( + ( + + )} + /> + ); +} diff --git a/packages/app/src/components/InlineNameInput/__tests__/InlineNameInput.test.tsx b/packages/app/src/components/InlineNameInput/__tests__/InlineNameInput.test.tsx new file mode 100644 index 0000000000..1c6843f723 --- /dev/null +++ b/packages/app/src/components/InlineNameInput/__tests__/InlineNameInput.test.tsx @@ -0,0 +1,211 @@ +import { useForm } from 'react-hook-form'; +import { act, render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { + InlineNameInput, + InlineNameInputControlled, +} from '@/components/InlineNameInput/InlineNameInput'; + +function renderInput(value = 'My dashboard') { + const onCommit = jest.fn(); + const utils = render( + , + ); + return { ...utils, onCommit, input: screen.getByLabelText('Dashboard name') }; +} + +describe('InlineNameInput', () => { + it('commits the trimmed name on Enter', async () => { + const user = userEvent.setup(); + const { input, onCommit } = renderInput(); + + await user.clear(input); + await user.type(input, ' Checkout latency {Enter}'); + + expect(onCommit).toHaveBeenCalledWith('Checkout latency'); + expect(input).not.toHaveFocus(); + }); + + it('keeps the typed name until the saved value arrives', async () => { + const user = userEvent.setup(); + let resolveSave: () => void = () => {}; + const onCommit = jest.fn( + () => + new Promise(resolve => { + resolveSave = resolve; + }), + ); + const { rerender } = render( + , + ); + const input = screen.getByLabelText('Dashboard name'); + + await user.type(input, ' v2{Enter}'); + expect(input).toHaveValue('My dashboard v2'); + + await act(async () => { + resolveSave(); + }); + expect(input).toHaveValue('My dashboard v2'); + + rerender( + , + ); + expect(input).toHaveValue('My dashboard v2'); + }); + + it('reverts to the saved name when the commit fails', async () => { + const user = userEvent.setup(); + const onCommit = jest.fn(() => Promise.reject(new Error('nope'))); + render( + , + ); + const input = screen.getByLabelText('Dashboard name'); + + await user.type(input, ' v2{Enter}'); + + await waitFor(() => expect(input).toHaveValue('My dashboard')); + }); + + it('shows a newer saved value that arrives while a rename is in flight', async () => { + const user = userEvent.setup(); + const onCommit = jest.fn(() => new Promise(() => {})); + const { rerender } = render( + , + ); + const input = screen.getByLabelText('Dashboard name'); + + await user.type(input, ' v2{Enter}'); + expect(input).toHaveValue('My dashboard v2'); + + rerender( + , + ); + expect(input).toHaveValue('Renamed elsewhere'); + }); + + it('commits on blur', async () => { + const user = userEvent.setup(); + const { input, onCommit } = renderInput(); + + await user.type(input, ' v2'); + await user.tab(); + + expect(onCommit).toHaveBeenCalledWith('My dashboard v2'); + }); + + it('reverts on Escape without committing', async () => { + const user = userEvent.setup(); + const { input, onCommit } = renderInput(); + + await user.type(input, ' changed{Escape}'); + + expect(onCommit).not.toHaveBeenCalled(); + expect(input).toHaveValue('My dashboard'); + }); + + it('reverts an empty or unchanged name without committing', async () => { + const user = userEvent.setup(); + const { input, onCommit } = renderInput(); + + await user.clear(input); + await user.tab(); + expect(input).toHaveValue('My dashboard'); + + await user.click(input); + await user.tab(); + expect(onCommit).not.toHaveBeenCalled(); + }); + + it('picks up a new saved value when not editing', () => { + const { rerender, input } = renderInput(); + + rerender( + , + ); + + expect(input).toHaveValue('Renamed elsewhere'); + }); + + it('exposes the name as a heading when headingLevel is set', () => { + render( + , + ); + + expect( + screen.getByRole('heading', { level: 3, name: 'My dashboard' }), + ).toContainElement(screen.getByLabelText('Dashboard name')); + }); +}); + +function ControlledHarness({ onSubmit }: { onSubmit: (v: unknown) => void }) { + const { control, handleSubmit } = useForm({ defaultValues: { name: '' } }); + return ( +
+ + + + ); +} + +describe('InlineNameInputControlled', () => { + it('stores the name in the form and saves it with the form', async () => { + const user = userEvent.setup(); + const onSubmit = jest.fn(); + render(); + + const input = screen.getByLabelText('Tile name'); + expect(input).toHaveAttribute('placeholder', 'Untitled tile'); + + await user.type(input, 'Error rate'); + await user.tab(); + expect(onSubmit).not.toHaveBeenCalled(); + + await user.click(screen.getByRole('button', { name: 'Save' })); + expect(onSubmit).toHaveBeenCalledWith( + { name: 'Error rate' }, + expect.anything(), + ); + }); +}); diff --git a/packages/app/src/stories/docs/AgentDoc.tsx b/packages/app/src/stories/docs/AgentDoc.tsx index a2e178155c..670b8456ed 100644 --- a/packages/app/src/stories/docs/AgentDoc.tsx +++ b/packages/app/src/stories/docs/AgentDoc.tsx @@ -12,6 +12,7 @@ const STORY_HREFS: Record = { 'code_style.md': '?path=/story/guidelines-code-style--documentation', 'themes.md': '?path=/story/guidelines-themes--documentation', 'page_layout.md': '?path=/story/guidelines-page-layout--documentation', + 'naming_objects.md': '?path=/story/guidelines-naming-objects--documentation', 'data_viz_colors.md': '?path=/story/guidelines-data-visualization-colors--documentation', }; diff --git a/packages/app/src/stories/docs/NamingObjects.stories.tsx b/packages/app/src/stories/docs/NamingObjects.stories.tsx new file mode 100644 index 0000000000..c5f6f04044 --- /dev/null +++ b/packages/app/src/stories/docs/NamingObjects.stories.tsx @@ -0,0 +1,13 @@ +import namingObjects from '@agent-docs/naming_objects.md?raw'; + +import { AgentDoc } from './AgentDoc'; + +const story = { + title: 'Guidelines/Naming objects', + parameters: { + layout: 'padded', + }, +}; +export default story; + +export const Documentation = () => ; diff --git a/packages/app/tests/e2e/components/SavedSearchModalComponent.ts b/packages/app/tests/e2e/components/SavedSearchModalComponent.ts index 8cc48fa087..cf664f2478 100644 --- a/packages/app/tests/e2e/components/SavedSearchModalComponent.ts +++ b/packages/app/tests/e2e/components/SavedSearchModalComponent.ts @@ -9,7 +9,7 @@ export class SavedSearchModalComponent { readonly page: Page; private readonly modal: Locator; private readonly nameInput: Locator; - private readonly savedSearchNameTitle: Locator; + private readonly savedSearchNameInput: Locator; private readonly submitButton: Locator; private readonly addTagButton: Locator; @@ -17,9 +17,7 @@ export class SavedSearchModalComponent { this.page = page; this.modal = page.locator('[data-testid="save-search-modal"]'); this.nameInput = page.locator('[data-testid="save-search-name-input"]'); - this.savedSearchNameTitle = page.locator( - '[data-testid="saved-search-name"]', - ); + this.savedSearchNameInput = page.getByTestId('saved-search-name'); this.submitButton = page.locator( '[data-testid="save-search-submit-button"]', ); @@ -103,8 +101,10 @@ export class SavedSearchModalComponent { // Wait for navigation to complete await urlPromise; - await expect(this.savedSearchNameTitle).toBeVisible({ timeout: 5000 }); - await expect(this.savedSearchNameTitle).toHaveText(name, { timeout: 5000 }); + await expect(this.savedSearchNameInput).toBeVisible({ timeout: 5000 }); + await expect(this.savedSearchNameInput).toHaveValue(name, { + timeout: 5000, + }); } /** diff --git a/packages/app/tests/e2e/features/dashboard.spec.ts b/packages/app/tests/e2e/features/dashboard.spec.ts index 89380bfe13..306c8efb9d 100644 --- a/packages/app/tests/e2e/features/dashboard.spec.ts +++ b/packages/app/tests/e2e/features/dashboard.spec.ts @@ -3333,7 +3333,7 @@ test.describe('Dashboard', { tag: ['@dashboard'] }, () => { // Wait for THIS dashboard's data to land before asserting absence — // otherwise the assertion races an unrendered page and passes for the // wrong reason. - await expect(dashboardPage.dashboardName).toHaveText(uniqueName); + await expect(dashboardPage.dashboardName).toHaveValue(uniqueName); // Terraform and ProvisionDashboardsTask would both claim ownership of // this dashboard, so the popover must not appear. await expect(terraformButton).toBeHidden(); @@ -3386,7 +3386,7 @@ test.describe('Dashboard', { tag: ['@dashboard'] }, () => { await test.step('Verify it is withheld after reload', async () => { await dashboardPage.gotoDashboard(dashboardId); - await expect(dashboardPage.dashboardName).toHaveText(uniqueName); + await expect(dashboardPage.dashboardName).toHaveValue(uniqueName); // Importing this dashboard would delete the PromQL tile on the next // apply, because the provider reads it back through external API v2. await expect(terraformButton).toBeHidden(); diff --git a/packages/app/tests/e2e/features/search/saved-search.spec.ts b/packages/app/tests/e2e/features/search/saved-search.spec.ts index 47c37f1b06..9201f730d3 100644 --- a/packages/app/tests/e2e/features/search/saved-search.spec.ts +++ b/packages/app/tests/e2e/features/search/saved-search.spec.ts @@ -277,8 +277,8 @@ test.describe('Saved Search Functionality', () => { // Wait for the search page to load await expect(page.getByTestId('search-page')).toBeVisible(); - await expect(searchPage.savedSearchNameTitle).toBeVisible(); - await expect(searchPage.savedSearchNameTitle).toHaveText( + await expect(searchPage.savedSearchNameInput).toBeVisible(); + await expect(searchPage.savedSearchNameInput).toHaveValue( 'Info Logs Navigation Test', ); }); diff --git a/packages/app/tests/e2e/page-objects/DashboardPage.ts b/packages/app/tests/e2e/page-objects/DashboardPage.ts index 963f4b15af..419aaf3260 100644 --- a/packages/app/tests/e2e/page-objects/DashboardPage.ts +++ b/packages/app/tests/e2e/page-objects/DashboardPage.ts @@ -93,7 +93,6 @@ export class DashboardPage { private readonly addDropdownButton: Locator; private readonly addTileMenuItem: Locator; private readonly addGroupMenuItem: Locator; - private readonly dashboardNameHeading: Locator; private readonly searchSubmitButton: Locator; private readonly liveButton: Locator; private readonly tempDashboardBanner: Locator; @@ -149,7 +148,6 @@ export class DashboardPage { '[data-testid="search-submit-button"]', ); this.liveButton = page.locator('button:has-text("Live")'); - this.dashboardNameHeading = page.getByRole('heading', { level: 3 }); this.granularityPicker = page.getByTestId('granularity-picker'); this.tempDashboardBanner = page.locator( '[data-testid="temporary-dashboard-banner"]', @@ -259,27 +257,7 @@ export class DashboardPage { * Edit dashboard name */ async editDashboardName(newName: string) { - // Wait for initial dashboard name to load - const defaultNameHeading = this.page.getByRole('heading', { - name: 'My Dashboard', - level: 3, - }); - await defaultNameHeading.waitFor({ state: 'visible', timeout: 5000 }); - - // Double-click to enter edit mode - await defaultNameHeading.dblclick(); - - // Fill in new name - const nameInput = this.page.locator('input[placeholder="Name"]'); - await nameInput.fill(newName); - await this.page.keyboard.press('Enter'); - - // Wait for the name to be saved - const updatedHeading = this.page.getByRole('heading', { - name: newName, - level: 3, - }); - await updatedHeading.waitFor({ state: 'visible', timeout: 10000 }); + await this.renameDashboard('My Dashboard', newName); } /** @@ -288,23 +266,18 @@ export class DashboardPage { * earlier in the same test). */ async renameDashboard(currentName: string, newName: string) { - const currentHeading = this.page.getByRole('heading', { - name: currentName, - level: 3, - }); - await currentHeading.waitFor({ state: 'visible', timeout: 10000 }); + const nameInput = this.page.getByTestId('dashboard-name-input'); + await expect(nameInput).toHaveValue(currentName, { timeout: 10000 }); - await currentHeading.dblclick(); - - const nameInput = this.page.locator('input[placeholder="Name"]'); await nameInput.fill(newName); - await this.page.keyboard.press('Enter'); + await nameInput.press('Enter'); - const updatedHeading = this.page.getByRole('heading', { - name: newName, - level: 3, + // The document title comes from the saved dashboard, so it only changes + // once the rename has persisted. + const escaped = newName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + await expect(this.page).toHaveTitle(new RegExp(`^${escaped} – `), { + timeout: 10000, }); - await updatedHeading.waitFor({ state: 'visible', timeout: 10000 }); } /** @@ -1991,7 +1964,7 @@ export class DashboardPage { } get dashboardName() { - return this.dashboardNameHeading; + return this.page.getByTestId('dashboard-name-input'); } get filterInput() { diff --git a/packages/app/tests/e2e/page-objects/SearchPage.ts b/packages/app/tests/e2e/page-objects/SearchPage.ts index 45d0ae9f72..75e37c25d2 100644 --- a/packages/app/tests/e2e/page-objects/SearchPage.ts +++ b/packages/app/tests/e2e/page-objects/SearchPage.ts @@ -32,7 +32,7 @@ export class SearchPage { readonly heatmap: HeatmapComponent; readonly whereInput: WhereInputComponent; readonly savedSearchModal: SavedSearchModalComponent; - readonly savedSearchNameTitle: Locator; + readonly savedSearchNameInput: Locator; readonly alertModal: SearchPageAlertModalComponent; readonly defaultTimeout: number = 3000; private readonly alertsButtonLocator: Locator; @@ -62,9 +62,7 @@ export class SearchPage { this.savedSearchModal = new SavedSearchModalComponent(page); this.alertModal = new SearchPageAlertModalComponent(page); this.alertsButtonLocator = page.getByTestId('alerts-button'); - this.savedSearchNameTitle = page.locator( - '[data-testid="saved-search-name"]', - ); + this.savedSearchNameInput = page.getByTestId('saved-search-name'); // Define page-specific locators this.searchForm = page.getByTestId('search-form');