An open source design system that's fully customizable and agent ready
TypeScript
fix(ChatMessage): the avatar's name-row spacing is parent-relative, so WebKit stays linear (#9438)
Cindy Zhang644a601acbc3
diff --git a/.changeset/chatmessage-avatar-rule-linear.md b/.changeset/chatmessage-avatar-rule-linear.mdnew file mode 100644index 0000000000..4b9304f2d7--- /dev/null+++ b/.changeset/chatmessage-avatar-rule-linear.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Safari no longer slows down as a page fills a container with many children because of ChatMessage's avatar-spacing rule. The avatar's top spacing beside a named bubble is now judged from the message itself instead of from its siblings. It looks exactly as before.++@cixzhangdiff --git a/packages/core/src/Chat/ChatMessage.test.tsx b/packages/core/src/Chat/ChatMessage.test.tsxindex 393585a696..d849199688 100644--- a/packages/core/src/Chat/ChatMessage.test.tsx+++ b/packages/core/src/Chat/ChatMessage.test.tsx@@ -1,5 +1,10 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import {readFileSync} from 'node:fs';+import {createRequire} from 'node:module';+import * as path from 'node:path';+import {transformSync} from '@babel/core';+import stylexBabelPlugin from '@stylexjs/babel-plugin';import {createElement, createRef, Fragment, type ReactNode} from 'react';import {describe, it, expect} from 'vitest';import {render, screen} from '@testing-library/react';@@ -342,3 +347,59 @@ describe('ChatMessage', () => {expect(message.style.order).toBe('2');});});++// A sibling-relative :has(~ …) in Core's global stylesheet makes WebKit+// re-check every earlier sibling on each insertion into any container. The+// avatar's top spacing is judged from the message article instead.+describe('ChatMessage compiled avatar rule', () => {+ function compiledSelectors(): {selector: string; declaration: string}[] {+ const repoRoot = path.resolve(__dirname, '../../../..');+ const source = path.resolve(__dirname, 'ChatMessage.tsx');+ const require = createRequire(__filename);+ const result = transformSync(readFileSync(source, 'utf8'), {+ babelrc: false,+ configFile: false,+ filename: source,+ presets: [+ [+ require.resolve('@babel/preset-typescript'),+ {isTSX: true, allExtensions: true},+ ],+ [require.resolve('@babel/preset-react'), {runtime: 'automatic'}],+ ],+ plugins: [+ [+ stylexBabelPlugin,+ {+ dev: false,+ runtimeInjection: false,+ genConditionalClasses: true,+ treeshakeCompensation: true,+ unstable_moduleResolution: {type: 'commonJS', rootDir: repoRoot},+ },+ ],+ ],+ });+ const rules =+ (result?.metadata as {stylex?: [string, {ltr: string}, number][]})+ ?.stylex ?? [];+ return rules.map(([, {ltr}]) => {+ const brace = ltr.indexOf('{');+ return {selector: ltr.slice(0, brace), declaration: ltr.slice(brace)};+ });+ }++ it('compiles no sibling-relative :has() and judges the name from the article', () => {+ const rules = compiledSelectors();+ expect(rules.filter(rule => rule.selector.includes(':has(~'))).toEqual([]);+ // The article sets the avatar offset from its own :has(), and the+ // avatar wrapper reads it.+ const offset = rules.filter(+ rule =>+ rule.selector.includes(':has([data-chat-name])') &&+ rule.declaration.includes('var(--spacing-5)'),+ );+ expect(offset).toHaveLength(1);+ expect(offset[0].selector).not.toContain(' ');+ });+});diff --git a/packages/core/src/Chat/ChatMessage.tsx b/packages/core/src/Chat/ChatMessage.tsxindex 35dea7d4aa..06c76a1b43 100644--- a/packages/core/src/Chat/ChatMessage.tsx+++ b/packages/core/src/Chat/ChatMessage.tsx@@ -37,6 +37,7 @@ import {import {isRenderable, mergeProps} from '../utils';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';+import {chatMessageVars} from './chatMessage.vars.stylex';import {useTranslator} from '../i18n';export interface ChatMessageProps extends BaseProps<HTMLElement> {@@ -108,12 +109,20 @@ const styles = stylex.create({// Slot wrappers collapse when the caller's content renders nothing, so an// empty Fragment or a component that returns null leaves no gap. Content is// never inspected to decide this.+ // Judged from this article (parent-relative), never from siblings, so the+ // global stylesheet keeps no sibling-relative :has().+ avatarOffset: {+ [chatMessageVars.avatarOffset]: {+ default: '0px',+ ':has([data-chat-name])': spacingVars['--spacing-5'],+ },+ },avatarWrap: {display: {default: null, ':empty': 'none'},flexShrink: 0,- ':has(~ * [data-chat-name])': {- marginBlockStart: spacingVars['--spacing-5'],- },+ // The avatar lines up with a bubble's name row when the message holds+ // one; the article sets the offset (see chatMessageVars).+ marginBlockStart: chatMessageVars.avatarOffset,},contentColumn: {display: 'flex',@@ -257,6 +266,7 @@ export function ChatMessage({{...mergeProps(themeProps('chat-message', {sender, density}),stylex.props(+ styles.avatarOffset,styles.root,rootAlignment,hasAvatar && rootGap,diff --git a/packages/core/src/Chat/__tests__/ChatMessageAvatar.interaction.browser.spec.ts b/packages/core/src/Chat/__tests__/ChatMessageAvatar.interaction.browser.spec.tsnew file mode 100644index 0000000000..fa89373ea6--- /dev/null+++ b/packages/core/src/Chat/__tests__/ChatMessageAvatar.interaction.browser.spec.ts@@ -0,0 +1,79 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ChatMessageAvatar.interaction.browser.spec.ts+ * @input Storybook story core-chat--chat-conversation+ * @output ChatMessage's avatar spacing in a real browser: a message whose+ * bubble renders a name gives its avatar the name row's top spacing, and a+ * message without one does not. The rule is judged from the message article+ * (parent-relative), so the stylesheet keeps no sibling-relative :has().+ * @position ChatMessage avatar-alignment evidence, run in the Chromium+ * interaction lane; jsdom checks only the compiled selector's shape.+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});++test.afterAll(async () => {+ await storybook?.close();+});++interface AvatarSpacing {+ story: string;+ hasName: boolean;+ marginTop: string;+}++async function avatarSpacing(+ page: Page,+ story: string,+): Promise<AvatarSpacing[]> {+ await page.goto(`${storybook.origin}/iframe.html?id=${story}&viewMode=story`);+ await page.locator('article.astryx-chat-message').first().waitFor();+ const rows = await page.evaluate(() =>+ Array.from(+ document.querySelectorAll<HTMLElement>('article.astryx-chat-message'),+ )+ // The avatar wrapper is the article's first child when an avatar renders.+ .filter(article =>+ article.firstElementChild?.querySelector('.astryx-avatar'),+ )+ .map(article => ({+ hasName: article.querySelector('[data-chat-name]') != null,+ marginTop: getComputedStyle(article.firstElementChild as HTMLElement)+ .marginTop,+ })),+ );+ return rows.map(row => ({story, ...row}));+}++test('an avatar takes the name row spacing only when a bubble has a name', async ({+ page,+}) => {+ const rows = [+ ...(await avatarSpacing(page, 'core-chat--chat-conversation')),+ ...(await avatarSpacing(page, 'core-chatmessage--default')),+ ];+ const named = rows.filter(row => row.hasName);+ const unnamed = rows.filter(row => !row.hasName);+ expect(named.length).toBeGreaterThan(0);+ expect(unnamed.length).toBeGreaterThan(0);+ for (const row of named) {+ expect(parseFloat(row.marginTop), row.story).toBeGreaterThan(0);+ }+ for (const row of unnamed) {+ expect(row.marginTop, row.story).toBe('0px');+ }+});diff --git a/packages/core/src/Chat/chatMessage.vars.stylex.ts b/packages/core/src/Chat/chatMessage.vars.stylex.tsnew file mode 100644index 0000000000..7c05af1a65--- /dev/null+++ b/packages/core/src/Chat/chatMessage.vars.stylex.ts@@ -0,0 +1,18 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import * as stylex from '@stylexjs/stylex';++/**+ * Per-message values ChatMessage sets on its article for its own slots.+ *+ * `avatarOffset` is the avatar's top spacing: the name row's spacing when a+ * bubble in this message renders a name, else none. Each article sets it from+ * its own `:has([data-chat-name])`, a parent-relative rule: a sibling-relative+ * `:has(~ …)` in the global stylesheet makes WebKit re-check every earlier+ * sibling on each insertion into any container, so filling one grows+ * quadratically. A message nested in another sets its own value, so it never+ * inherits the outer message's.+ */+export const chatMessageVars = stylex.defineVars({+ avatarOffset: '0px',+});