diff --git a/docs/buzz-help.md b/docs/buzz-help.md index cf390f28d6..233f3eb76d 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -523,6 +523,8 @@ and are asked to sign in again in Buzz. not change. Chats reorder by recent activity with the same short slides and fades as Team channels. Reduced motion applies the new order immediately. + A Solo chat name you save here changes immediately. Title changes that arrive + from an agent or another device animate unless reduced motion is enabled. Deleting or archiving the open chat keeps you in Solo and opens another chat or a new draft. **Start Solo chat**, in the menu of any delivered message (and in a channel's diff --git a/src/app/shell/PrimarySidebar.test.tsx b/src/app/shell/PrimarySidebar.test.tsx index 8ccc9f3a52..166ca8fb5d 100644 --- a/src/app/shell/PrimarySidebar.test.tsx +++ b/src/app/shell/PrimarySidebar.test.tsx @@ -92,6 +92,8 @@ it("double-clicks a Solo row to edit its selected name, retaining a failed save base, expect.objectContaining({ name: "New plan", labels: [SOLO_LABEL] }), expect.any(AbortSignal), + undefined, + f.session.channels, ); await user.dblClick(screen.getByRole("button", { name: /^Planning/ })); await screen.findByRole("textbox", { name: "Chat name" }); diff --git a/src/bundled/channels/ChannelHeaderIdentity.tsx b/src/bundled/channels/ChannelHeaderIdentity.tsx index f9b9418263..6e066ba562 100644 --- a/src/bundled/channels/ChannelHeaderIdentity.tsx +++ b/src/bundled/channels/ChannelHeaderIdentity.tsx @@ -2,6 +2,7 @@ import type { ComponentProps } from "react"; import type { ChannelSummary } from "../../features/relay/contracts"; import type { RelaySession } from "../../features/relay/session"; import { SurfaceButton } from "../../shared/design-system/ui/SurfaceButton"; +import { SoloChatTitle } from "../../features/solo/SoloChatTitle"; import { ChannelMemberAvatars } from "./ChannelMemberAvatars"; import styles from "./ChannelHeaderIdentity.module.css"; @@ -73,7 +74,18 @@ export function ChannelHeaderIdentity({ - {name} + + {access === soloAccess || access === soloReadOnlyAccess ? ( + + ) : ( + name + )} + ); diff --git a/src/bundled/channels/SoloChatName.test.tsx b/src/bundled/channels/SoloChatName.test.tsx index 6c874fb57e..bdd67ecd83 100644 --- a/src/bundled/channels/SoloChatName.test.tsx +++ b/src/bundled/channels/SoloChatName.test.tsx @@ -15,6 +15,7 @@ afterEach(cleanup); function setup(overrides: Partial = {}) { const save = vi.fn(async () => {}); const close = vi.fn(); + const channels = { subscribeList: () => () => {} }; const details: ChannelDetailsCapability = { available: true, load: vi.fn(async () => ({ @@ -36,7 +37,9 @@ function setup(overrides: Partial = {}) { render( <> = {}) { , ); - return { save, close, details, user: userEvent.setup() }; + return { save, close, details, channels, user: userEvent.setup() }; } it.each(["", "Plan"])( @@ -78,6 +81,8 @@ it("saves on click-away without taking focus back from the destination", async ( labels: ["buzz.solo"], }), expect.any(AbortSignal), + undefined, + f.channels, ); expect(screen.getByRole("button", { name: "Elsewhere" })).toHaveFocus(); }); diff --git a/src/bundled/channels/SoloInventory.tsx b/src/bundled/channels/SoloInventory.tsx index 92994db610..0de3740568 100644 --- a/src/bundled/channels/SoloInventory.tsx +++ b/src/bundled/channels/SoloInventory.tsx @@ -1,5 +1,6 @@ import { useSoloRowActivation } from "../../features/channel-navigation/useSoloRowActivation"; import { useIsPresent } from "motion/react"; +import { SoloChatTitle } from "../../features/solo/SoloChatTitle"; import type { ComposeWorkspaces } from "../../features/channel-navigation/WorkspaceComposition"; import { useSoloNavigation } from "../../features/channel-navigation/solo-navigation-react"; import { soloNavigationFor } from "../../features/channel-navigation/solo-navigation"; @@ -625,7 +626,14 @@ function SoloConversationRow({ + } labelUnread="all" /> diff --git a/src/features/channel-navigation/SoloDestination.tsx b/src/features/channel-navigation/SoloDestination.tsx index 7aaf4f13da..0abb42a8ce 100644 --- a/src/features/channel-navigation/SoloDestination.tsx +++ b/src/features/channel-navigation/SoloDestination.tsx @@ -1,4 +1,5 @@ import { useSoloRowActivation } from "./useSoloRowActivation"; +import { SoloChatTitle } from "../solo/SoloChatTitle"; import { type ReactNode, type RefObject, @@ -302,7 +303,18 @@ function ConversationLink(props: SoloConversationLinkProps) { {...(primary ? { "data-solo-destination-id": state.channel.id } : {})} aria-label={props["aria-label"]} aria-describedby={props["aria-describedby"]} - label={props.label} + label={ + !props.multiline && props.label === state.channel.name ? ( + + ) : ( + props.label + ) + } icon={props.icon} trailing={props.trailing} multiline={!!props.multiline} diff --git a/src/features/relay/channel-details.test.ts b/src/features/relay/channel-details.test.ts index 88edc4fe65..cd23f8ed95 100644 --- a/src/features/relay/channel-details.test.ts +++ b/src/features/relay/channel-details.test.ts @@ -1081,6 +1081,62 @@ it.each([undefined, 600])( }, ); +it.each(["away and back", "rejection", "disposal"] as const)( + "retires the local Solo rename marker after %s", + async (ending) => { + const h = harness("owner", true); + const details = h.owner.capability; + h.set([ + h.metadata("First prompt", "", "private", "stream", [SOLO_LABEL]), + ...h.events().slice(1), + ]); + const base = await details.load(id); + const next = { ...base, name: "Release notes" }; + let name = base.name; + const listeners = new Set<() => void>(); + const channels = { + get: () => ({ id, name }), + subscribeList(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + }; + const observe = (title: string) => { + name = title; + for (const listener of listeners) listener(); + }; + const marker = () => details.localRename?.(id, next.name); + h.publish.mockImplementationOnce(async () => { + expect(marker()).toBeDefined(); + if (ending === "rejection") throw new PublishRejected("Not permitted"); + h.set([ + h.metadata(next.name, "", "private", "stream", [ + SOLO_LABEL, + SOLO_NAMED_LABEL, + ]), + ...h.events().slice(1), + ]); + observe(next.name); + }); + const save = details.save(base, next, undefined, undefined, channels); + if (ending === "rejection") { + await expect(save).rejects.toThrow("Not permitted"); + } else { + await save; + expect(marker()).toBeDefined(); + if (ending === "disposal") h.owner.dispose(); + else { + observe(base.name); + observe(next.name); + } + } + expect(marker()).toBeUndefined(); + expect(listeners.size).toBe(0); + }, +); + it("refuses chosen-name label overflow before signing and retains the existing label set", async () => { const h = harness("owner", true); const labels = [ diff --git a/src/features/relay/channel-details.ts b/src/features/relay/channel-details.ts index 21c0a56735..0572777685 100644 --- a/src/features/relay/channel-details.ts +++ b/src/features/relay/channel-details.ts @@ -1,6 +1,7 @@ import { regionLabels } from "../solo/region-labels"; import { getEventHash, verifyEvent } from "nostr-tools"; import type { RelayReader } from "./reader"; +import type { ChannelQueries } from "./contracts"; import { retryRead } from "./read-retry"; import type { RelayWriter } from "./transport"; import type { RelayEvent } from "./events"; @@ -21,6 +22,8 @@ export type DetailsAttempt = Readonly<{ draft: ChannelDetailsDraft; status: "saving" | "unconfirmed"; }>; +type ChannelNames = Pick; + export interface ChannelDetailsCapability { readonly available: boolean; load(id: string, signal?: AbortSignal): Promise; @@ -30,7 +33,11 @@ export interface ChannelDetailsCapability { signal?: AbortSignal, /** Checked synchronously right before publishing; false publishes nothing. */ active?: () => boolean, + /** Present only for name edits initiated by this app's Solo editor. */ + manualRename?: ChannelNames, ): Promise; + /** An in-memory revision of a matching title change initiated here. */ + localRename?(id: string, name: string): number | undefined; check(id: string, signal?: AbortSignal): Promise; snapshot(id: string): DetailsAttempt | undefined; subscribe(listener: () => void): () => void; @@ -59,11 +66,41 @@ export function createChannelDetails({ }) { let closed = false; const attempts = new Map(); + const manualNames = new Map< + string, + { name: string; previous?: string | undefined; revision: number } + >(); + let renameRevision = 0; + let unsubscribeNames: (() => void) | undefined; const controllers = new Set(); const listeners = new Set<() => void>(); function emit() { for (const listener of listeners) listener(); } + function forgetManualName(id: string) { + manualNames.delete(id); + if (!manualNames.size) { + unsubscribeNames?.(); + unsubscribeNames = undefined; + } + } + function rememberManualName( + channels: ChannelNames, + id: string, + previous: string, + name: string, + ) { + if (channels.get?.(id)?.name !== previous) return; + manualNames.set(id, { name, previous, revision: ++renameRevision }); + unsubscribeNames ??= channels.subscribeList(() => { + for (const [id, rename] of manualNames) { + const current = channels.get?.(id)?.name; + if (current === rename.name) rename.previous = undefined; + else if (current === undefined || current !== rename.previous) + forgetManualName(id); + } + }); + } function assertAccess(id: string) { if (closed || !canAccess(id)) throw new Error("Channel access changed. Reopen channel settings."); @@ -134,6 +171,10 @@ export function createChannelDetails({ } const capability: ChannelDetailsCapability = Object.freeze({ available: !!reader && !!writer, + localRename(id: string, name: string) { + const rename = manualNames.get(id); + return rename?.name === name ? rename.revision : undefined; + }, snapshot: (id: string) => attempts.get(id), subscribe(listener: () => void) { listeners.add(listener); @@ -173,6 +214,7 @@ export function createChannelDetails({ input: ChannelDetailsDraft, caller?: AbortSignal, active?: () => boolean, + manualRename?: ChannelNames, ) { const id = lifecycleChannelId(base.channelId); if (!writer || !reader) @@ -253,6 +295,8 @@ export function createChannelDetails({ signal.throwIfAborted(); if (active?.() === false) throw new DOMException("Channel edit cancelled", "AbortError"); + if (manualRename && chosenName) + rememberManualName(manualRename, id, base.name, draft.name); publicationStarted = true; await writer.publish(signed, signal); await confirm(id, draft, signal); @@ -265,6 +309,8 @@ export function createChannelDetails({ attempts.set(id, Object.freeze({ draft, status: "unconfirmed" })); throw new Error(uncertain); } + if (publicationStarted && manualRename && chosenName) + forgetManualName(id); attempts.delete(id); if (error instanceof Error && error.name === "AbortError") throw error; if (!publicationStarted) @@ -290,6 +336,8 @@ export function createChannelDetails({ closed = true; cancel(); attempts.clear(); + unsubscribeNames?.(); + manualNames.clear(); listeners.clear(); }, }; diff --git a/src/features/solo/Lifetime.tsx b/src/features/solo/Lifetime.tsx index f9ec1d91ee..5b2f4d167e 100644 --- a/src/features/solo/Lifetime.tsx +++ b/src/features/solo/Lifetime.tsx @@ -167,6 +167,8 @@ export function useLifetime({ ttlSeconds: ttl, }, active, + undefined, + nameChanged ? session.channels : undefined, ); } } diff --git a/src/features/solo/SoloChatTitle.module.css b/src/features/solo/SoloChatTitle.module.css new file mode 100644 index 0000000000..27dc587849 --- /dev/null +++ b/src/features/solo/SoloChatTitle.module.css @@ -0,0 +1,18 @@ +.title { + position: relative; + display: block; + min-width: 0; + overflow: hidden; +} + +.value { + display: block; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.character { + display: inline-block; + white-space: pre; +} diff --git a/src/features/solo/SoloChatTitle.reduced-motion.test.tsx b/src/features/solo/SoloChatTitle.reduced-motion.test.tsx new file mode 100644 index 0000000000..08fa527326 --- /dev/null +++ b/src/features/solo/SoloChatTitle.reduced-motion.test.tsx @@ -0,0 +1,25 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { SoloChatTitle } from "./SoloChatTitle"; + +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +it("replaces the visible and accessible title immediately with reduced motion", () => { + const media = Object.assign(new EventTarget(), { matches: true }); + vi.stubGlobal("matchMedia", () => media); + const { rerender } = render(, { + wrapper: ({ children }) => , + }); + rerender(); + + expect(screen.queryByText("First")).toBeNull(); + expect( + screen.getByText("Renamed", { selector: '[aria-hidden="true"]' }), + ).toBeVisible(); + expect(screen.getByRole("button")).toHaveAccessibleName("Renamed"); +}); diff --git a/src/features/solo/SoloChatTitle.test.tsx b/src/features/solo/SoloChatTitle.test.tsx new file mode 100644 index 0000000000..59e8230824 --- /dev/null +++ b/src/features/solo/SoloChatTitle.test.tsx @@ -0,0 +1,71 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, expect, it } from "vitest"; +import { SoloChatTitle } from "./SoloChatTitle"; + +afterEach(cleanup); + +function setup() { + const first = "First title"; + const { container, rerender } = render(, { + wrapper: ({ children }) => , + }); + const value = () => container.querySelector('[aria-hidden="true"]'); + const characters = () => + [...(value()?.children ?? [])].map((node) => node.textContent); + const rename = (title: string) => { + rerender(); + expect(screen.getByRole("button")).toHaveAccessibleName(title); + }; + const expectSettled = (title: string) => + waitFor(() => { + expect(value()?.textContent).toBe(title); + expect(characters()).toEqual([]); + }); + return { first, value, characters, rename, expectSettled }; +} + +it("keeps the latest rename during exit and reveals whole graphemes", async () => { + const { first, value, characters, rename, expectSettled } = setup(); + rename("Intermediate title"); + expect(value()).toHaveTextContent(first); + const title = "A 👩🏽‍💻 e\u0301"; + rename(title); + expect(characters()).toEqual([]); + + await waitFor(() => + expect(characters()).toEqual(["A", " ", "👩🏽‍💻", " ", "e\u0301"]), + ); + await expectSettled(title); +}); + +it("settles on the original title when renamed back during the reveal", async () => { + const { first, characters, rename, expectSettled } = setup(); + const title = "Second ΩЯ漢かなカナ한"; + rename(title); + await waitFor(() => expect(characters().join("")).toBe(title)); + + rename(first); + await waitFor(() => expect(characters().join("")).toBe(first)); + await expectSettled(first); +}); + +it.each([ + ["Hebrew", "שלום"], + ["Arabic", "خطة الإصدار"], + ["right-to-left mark", "Plan \u200f2026"], + ["right-to-left override", "Plan \u202eABC"], + ["right-to-left isolate", "Plan \u2067ABC"], + ["Phoenician", "Plan \u{10900}"], + ["Adlam", "Plan \u{1e900}"], + ["Myanmar", "မြန်မာ"], + ["Kannada", "ಕನ್ನಡ"], + ["Mongolian mixed with Latin", "Plan ᠮᠣᠩᠭᠣᠯ"], +])("keeps %s in one text run as the new title appears", async (_, title) => { + const { value, rename } = setup(); + rename(title); + // Check the first appearance so a split reveal cannot pass by settling. + await waitFor(() => expect(value()?.textContent).toBe(title)); + expect(value()?.childElementCount).toBe(0); +}); diff --git a/src/features/solo/SoloChatTitle.tsx b/src/features/solo/SoloChatTitle.tsx new file mode 100644 index 0000000000..ab9aab991f --- /dev/null +++ b/src/features/solo/SoloChatTitle.tsx @@ -0,0 +1,128 @@ +import { + AnimatePresence, + motion, + stagger, + useIsPresent, + useReducedMotion, +} from "motion/react"; +import { useEffect, useRef, useState } from "react"; +import type { ChannelDetailsCapability } from "../relay/channel-details"; +import styles from "./SoloChatTitle.module.css"; + +const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" }); +const ease = [0.25, 0.1, 0.25, 1] as const; +// Keep RTL blocks, including shared punctuation and numerals, in one text run. +const bidiText = + /[\p{Bidi_Control}\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufeff\u{10800}-\u{10fff}\u{1e800}-\u{1efff}]/u; +// Other scripts can also need shaping across grapheme boundaries. Only split +// familiar scripts, plus shared punctuation, symbols, and combining marks. +const splitSafeScripts = + /^[\p{Script=Latin}\p{Script=Greek}\p{Script=Cyrillic}\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Common}\p{Script=Inherited}]*$/u; +const revealTransition = { duration: 0.18, ease }; +const character = { + hidden: { opacity: 0, filter: "blur(3px)", transform: "translateX(-3px)" }, + visible: { + opacity: 1, + filter: "blur(0px)", + transform: "translateX(0px)", + transition: revealTransition, + }, +}; + +/** Key by chat id at the call site: renames animate, navigation starts at rest. */ +export function SoloChatTitle({ + title, + channelId, + details, +}: { + title: string; + channelId?: string; + details?: Pick | undefined; +}) { + const reducedMotion = useReducedMotion(); + const localRename = channelId + ? details?.localRename?.(channelId, title) + : undefined; + const [presenceKey, setPresenceKey] = useState(localRename); + // Start a new presence group at rest for this editor's save. Keep its key + // for the next incoming title so that title can still animate. + if (localRename !== undefined && localRename !== presenceKey) + setPresenceKey(localRename); + const mounted = useRef(false); + useEffect(() => { + mounted.current = true; + }, []); + return ( + + {title} + {reducedMotion ? ( + + ) : ( + + + + )} + + ); +} + +function TitleValue({ title, reveal }: { title: string; reveal: boolean }) { + const present = useIsPresent(); + const [revealing, setRevealing] = useState(reveal); + const wholeTitle = bidiText.test(title) || !splitSafeScripts.test(title); + const characters = + revealing && !wholeTitle ? [...graphemes.segment(title)] : []; + return ( + + ); +} diff --git a/tests/browser/navigation-selection.spec.mjs b/tests/browser/navigation-selection.spec.mjs index 2ac3060871..d58c6d26a5 100644 --- a/tests/browser/navigation-selection.spec.mjs +++ b/tests/browser/navigation-selection.spec.mjs @@ -4,6 +4,7 @@ import { virtuaIdle } from "./timeline.mjs"; import { holdMenuExit, opened } from "./menu-motion.mjs"; const chatId = "33333333-3333-4333-8333-333333333333"; +const visibleSoloTitle = "[data-solo-chat-title] > [aria-hidden=true]"; test.use({ productionBroker: true, channelIds: ["alpha", "beta", chatId], @@ -106,7 +107,8 @@ test("navigation menus do not highlight labels while message text and editors re name: "Solo conversations", }); const chat = conversations.locator(`[data-solo-channel-id="${chatId}"]`); - const chatLabel = chat.getByText("Solo conversation", { exact: true }); + const chatLabel = chat.locator(visibleSoloTitle); + await expect(chat).toHaveAccessibleName("Solo conversation"); // Leaving the draft retires its "New chat" row; let the list settle first. await chatLabel.click(); await expect( @@ -222,7 +224,14 @@ test("context menus appear immediately and retain their source highlight through subtree: true, }); }, `Actions for ${name}`); - await source.getByText(name, { exact: true }).click({ button: "right" }); + const label = + surface === "channel" + ? source.getByText(name, { exact: true }) + : source.locator(visibleSoloTitle); + await label.click({ + button: "right", + position: await textPosition(label), + }); await opened(menu); const samples = await page.evaluate(() => { window.__contextObserver.disconnect(); diff --git a/tests/browser/solo-chats.spec.mjs b/tests/browser/solo-chats.spec.mjs index 1b08881bb9..721d6ee1e5 100644 --- a/tests/browser/solo-chats.spec.mjs +++ b/tests/browser/solo-chats.spec.mjs @@ -224,7 +224,7 @@ test.describe("Berd-style Solo project organization", () => { await expect(row).toBeVisible(); await expect(beta).toBeVisible(); - await sidebar.getByText("Alpha", { exact: true }).click(); + await row.click(); await expect( page.getByRole("button", { name: "Workspace: Work", exact: true }), ).toBeVisible(); @@ -271,7 +271,7 @@ test.describe("Berd-style Solo project organization", () => { await page.keyboard.insertText("Keep this follow-up draft"); await beta.click(); await expect(composer).not.toContainText("Keep this follow-up draft"); - await sidebar.getByText("Alpha", { exact: true }).click(); + await row.click(); await expect(composer).toContainText("Keep this follow-up draft"); await expect(tag).toBeVisible(); await page.reload(); diff --git a/tests/browser/solo-title-motion.spec.mjs b/tests/browser/solo-title-motion.spec.mjs new file mode 100644 index 0000000000..45d769946c --- /dev/null +++ b/tests/browser/solo-title-motion.spec.mjs @@ -0,0 +1,271 @@ +import { test, expect } from "./fixture.mjs"; +import { newChat } from "./navigation.mjs"; + +const chat = "33333333-3333-4333-8333-333333333333"; +const other = "44444444-4444-8444-4444-444444444444"; +const title = + "Release planning and follow-up for the next workspace review and the upcoming project launch checklist"; +const titleSelector = "[data-solo-chat-title] > [aria-hidden]"; + +test.use({ + reducedMotion: "no-preference", + pluginFixtures: true, + productionBroker: true, + channelIds: [chat, other], + channelNames: { [chat]: "Alpha", [other]: "Beta" }, + soloChannels: [chat, other], + ownSoloChannels: [chat, other], + historyCounts: { [chat]: 0, [other]: 0 }, +}); + +test("Solo rename animates both titles without interrupting typing or overflowing", async ({ + page, + app, +}) => { + await page.goto(app.origin); + await newChat(page); + const sidebar = page.getByRole("navigation", { name: "Solo conversations" }); + const row = sidebar.locator(`[data-solo-channel-id="${chat}"]`); + await row.click(); + const composer = page.getByRole("textbox", { name: "Message your agents" }); + await expect(composer).toBeFocused(); + const header = (name) => + page.locator("header").getByRole("button", { + name: `Share access to ${name}`, + exact: true, + }); + // Hold only the title's real browser animations, then release one phase at a time. + await page.evaluate(() => { + window.titleAnimations = new WeakMap(); + const animate = Element.prototype.animate; + Element.prototype.animate = function (...args) { + const animation = animate.apply(this, args); + if (this.closest("[data-solo-chat-title]")) { + // Motion sets startTime after animate() returns, which resumes a + // synchronous pause. Hold the track after Motion has initialized it. + queueMicrotask(() => { + animation.pause(); + animation.currentTime = 0; + const animations = window.titleAnimations.get(this) ?? []; + animations.push(animation); + window.titleAnimations.set(this, animations); + }); + } + return animation; + }; + }); + const rename = (name) => + app.setChannelMetadata(chat, [ + ["name", name], + ["private"], + ["t", "stream"], + ["t", "buzz.solo"], + ["t", "buzz.session.named"], + ]); + const titlesFor = (name) => + row.locator(titleSelector).or(header(name).locator(titleSelector)); + const localTitle = "Local planning"; + await page.getByRole("button", { name: "Chat actions", exact: true }).click(); + await page + .getByRole("menuitem", { name: "Chat settings", exact: true }) + .click(); + const settings = page.getByRole("dialog", { name: "Edit chat", exact: true }); + await settings.getByRole("textbox", { name: /^Chat name/ }).fill(localTitle); + await settings + .getByRole("button", { name: "Save changes", exact: true }) + .click(); + await expect(settings).toBeHidden(); + // A title animation would be held indefinitely on the previous name. + await expect(titlesFor(localTitle)).toHaveText([localTitle, localTitle]); + const oldHeader = await header(localTitle).elementHandle(); + + rename(title); + const renamedHeader = header(title); + await expect(row).toHaveAccessibleName(title); + expect( + await renamedHeader.evaluate((node, old) => node === old, oldHeader), + ).toBe(true); + await expect(composer).toBeFocused(); + + const titles = titlesFor(title); + await expect(titles).toHaveText([localTitle, localTitle]); + await expect + .poll(() => + titles.evaluateAll((nodes) => + nodes.map((node) => { + const tracks = window.titleAnimations.get(node) ?? []; + return { + ...Object.assign( + {}, + ...tracks.map(({ effect }) => effect.getKeyframes().at(-1)), + ), + held: tracks.every( + (track) => + track.playState === "paused" && track.currentTime === 0, + ), + }; + }), + ), + ) + .toEqual( + Array(2).fill( + expect.objectContaining({ + held: true, + opacity: "0", + filter: "blur(3px)", + transform: expect.stringMatching(/^translateX\(-/), + }), + ), + ); + await page.keyboard.type("Still typing"); + await expect(composer).toHaveText("Still typing"); + const finishPhase = (values) => + values.evaluateAll((nodes) => { + for (const node of nodes.flatMap((node) => [node, ...node.children])) + for (const animation of window.titleAnimations.get(node) ?? []) + animation.finish(); + }); + await finishPhase(titles); + + const characters = titles.locator("> span"); + await expect(characters).toHaveCount(title.length * 2); + await expect + .poll(() => + titles.evaluateAll((nodes) => + nodes.map((node) => { + const delays = [...node.children].map( + (character) => + (window.titleAnimations.get(character) ?? []) + .find((track) => { + const frames = track.effect.getKeyframes(); + return ( + track.playState === "paused" && + track.currentTime === 0 && + frames[0]?.filter === "blur(3px)" && + frames.at(-1)?.filter === "blur(0px)" + ); + }) + ?.effect.getTiming().delay, + ); + return delays.every( + (delay, index) => + delay !== undefined && (index === 0 || delay > delays[index - 1]), + ); + }), + ), + ) + .toEqual([true, true]); + await page.keyboard.type(" through the rename"); + await finishPhase(titles); + await expect(characters).toHaveCount(0); + await expect(titles).toHaveText([title, title]); + await expect(composer).toBeFocused(); + await expect(composer).toHaveText("Still typing through the rename"); + + for (const [mode, width, scale] of [ + ["light", 1440, 1], + ["dark", 760, 1.5], + ]) { + await page.setViewportSize({ width, height: 950 }); + await page.evaluate( + ({ mode, scale }) => { + document.documentElement.setAttribute("data-color-mode", mode); + document.documentElement.style.setProperty("--buzz-text-scale", scale); + }, + { mode, scale }, + ); + for (const control of [row, renamedHeader]) { + await expect(control).toBeVisible(); + const value = control.locator(titleSelector); + await expect(value).toHaveCSS("text-overflow", "ellipsis"); + await expect(value).toHaveCSS("overflow-x", "hidden"); + if (scale > 1) + expect( + await value.evaluate((node) => node.scrollWidth > node.clientWidth), + ).toBe(true); + expect( + await value.evaluate( + (node, owner) => { + const text = node.getBoundingClientRect(); + const bounds = owner.getBoundingClientRect(); + return text.width > 0 && text.right <= bounds.right + 1; + }, + await control.elementHandle(), + ), + ).toBe(true); + } + } + // Compare glyph positions without clipping the mixed-direction sample. + await page.setViewportSize({ width: 1440, height: 950 }); + await page.evaluate(() => + document.documentElement.style.removeProperty("--buzz-text-scale"), + ); + const mixed = "Release שלום 2026"; + rename(mixed); + const mixedTitles = titlesFor(mixed); + const expectOpacityPhase = (from, to) => + expect + .poll(() => + mixedTitles.evaluateAll( + (nodes, { from, to }) => + nodes.filter((node) => + (window.titleAnimations.get(node) ?? []).some((track) => { + const frames = track.effect.getKeyframes(); + return ( + track.playState === "paused" && + frames[0]?.opacity === from && + frames.at(-1)?.opacity === to + ); + }), + ).length, + { from, to }, + ), + ) + .toBe(2); + await expect(mixedTitles).toHaveText([title, title]); + await expectOpacityPhase("1", "0"); + await finishPhase(mixedTitles); + await expect(mixedTitles).toHaveText([mixed, mixed]); + await expectOpacityPhase("0", "1"); + const hebrewRunIsRTL = () => + mixedTitles.evaluateAll((nodes) => + nodes.map((node) => { + const text = node.firstChild; + const range = document.createRange(); + const left = (character) => { + const offset = text.textContent.indexOf(character); + range.setStart(text, offset); + range.setEnd(text, offset + 1); + return range.getBoundingClientRect().left; + }; + return left("ו") < left("ל"); + }), + ); + expect(await hebrewRunIsRTL()).toEqual([true, true]); + await finishPhase(mixedTitles); + expect(await hebrewRunIsRTL()).toEqual([true, true]); + + // The old local save must not suppress an incoming return to the same name. + rename(localTitle); + await expect( + titlesFor(localTitle).and(page.locator("[data-exiting]")), + ).toHaveText([mixed, mixed]); + await row.dblclick(); + const inlineName = sidebar.getByRole("textbox", { name: "Chat name" }); + await inlineName.fill("Handoff notes"); + await inlineName.press("Enter"); + await expect(inlineName).toBeHidden(); + await expect(titlesFor("Handoff notes")).toHaveText([ + "Handoff notes", + "Handoff notes", + ]); + + await sidebar.locator(`[data-solo-channel-id="${other}"]`).click(); + const nextTitle = header("Beta").locator(titleSelector); + await expect(nextTitle).toHaveText("Beta"); + expect( + await nextTitle.evaluate( + (node) => node.getAnimations({ subtree: true }).length, + ), + ).toBe(0); +});