perf(primitives): carry the hover marquee by a CSS animation instead of a frame script
The marquee moved its text by setting the scroll position in a requestAnimationFrame callback on every frame of the travel. The text now sits in an inner span that a keyframe animation translates: the handler measures the overflow once on entry and gives the stylesheet the distance and the time it takes at 30px/s. A delayed zero-length animation lifts the end fade at the far edge, and reduced motion is a media query. Speed, the far-edge hold, the one-step return, the 8px threshold, and the touch exclusion stay.
This commit is contained in:
1 parent
0277971e87
commit
bc75e0ed84
15 files changed
+291
-402
No files matched your search
@@ -1,10 +1,10 @@
|
||||
// Web e2e scenario: hovering a sidebar session row marquees a title wider than
|
||||
// its cell. The jsdom lane pins only the positions the handler writes; the
|
||||
// assembled browser is where the title really clips, really crawls toward its
|
||||
// own hovered extent (the trailing relative-time cell yields to the row menu
|
||||
// while the pointer rests on the row, so the hovered cell is wider than the
|
||||
// resting one), really fades its moved left edge, and really returns to its
|
||||
// start when the pointer leaves.
|
||||
// its cell. The jsdom lane pins only the distance and time the handler hands
|
||||
// the stylesheet; the assembled browser is where the title really clips,
|
||||
// really travels toward its own hovered extent (the trailing relative-time
|
||||
// cell yields to the row menu while the pointer rests on the row, so the
|
||||
// hovered cell is wider than the resting one) without a frame script, really
|
||||
// fades its cut edges, and really returns to its start when the pointer leaves.
|
||||
//
|
||||
// Zero model calls: seeding one renamed session and hovering its row touches no
|
||||
// provider.
|
||||
@@ -48,60 +48,77 @@ describe('web e2e: hovering a clipped session title marquees it to its far edge'
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-title-hover-scroll'))
|
||||
const row = page.getByRole('treeitem').filter({ has: page.getByText(TITLE, { exact: true }) })
|
||||
await row.waitFor({ timeout: 20_000 })
|
||||
const title = row.getByText(TITLE, { exact: true })
|
||||
// The title text sits in the span that travels; its parent clips it.
|
||||
const travel = row.getByText(TITLE, { exact: true })
|
||||
const title = travel.locator('xpath=..')
|
||||
/** How far the text has travelled from its start, in CSS pixels. */
|
||||
const travelled = async (): Promise<number> => travel.evaluate((el) => {
|
||||
const transform = getComputedStyle(el).transform
|
||||
return transform === 'none' ? 0 : -new DOMMatrix(transform).m41
|
||||
})
|
||||
/** Top of the title's glyphs: the text keeps its line while its span becomes a box to travel. */
|
||||
const glyphTop = async (): Promise<number> => travel.evaluate((el) => {
|
||||
const glyphs = document.createRange()
|
||||
glyphs.selectNodeContents(el)
|
||||
return glyphs.getBoundingClientRect().top
|
||||
})
|
||||
/** The distance the hook measured for the hovered cell. */
|
||||
const range = async (): Promise<number> => title.evaluate(el => Number.parseFloat(el.style.getPropertyValue('--dsh-marquee-range')))
|
||||
|
||||
// At rest the row clips its title with an ellipsis and holds its start.
|
||||
expect(await title.evaluate(el => el.scrollWidth - el.clientWidth)).toBeGreaterThan(0)
|
||||
expect(await title.evaluate(el => getComputedStyle(el).textOverflow)).toBe('ellipsis')
|
||||
expect(await title.evaluate(el => el.scrollLeft)).toBe(0)
|
||||
expect(await travelled()).toBe(0)
|
||||
const restingTop = await glyphTop()
|
||||
|
||||
// The stylesheet moves the text, so the page runs no frame callback per frame while it travels.
|
||||
await page.evaluate(() => {
|
||||
const request = window.requestAnimationFrame.bind(window)
|
||||
const counter = window as unknown as { marqueeFrames: number }
|
||||
counter.marqueeFrames = 0
|
||||
window.requestAnimationFrame = (callback) => { counter.marqueeFrames += 1; return request(callback) }
|
||||
})
|
||||
await row.hover()
|
||||
// The marquee crawls instead of jumping: the title is caught mid-travel,
|
||||
// strictly between its start and its far edge, with both cut edges
|
||||
// publishing their fade-mask hooks.
|
||||
await expect.poll(
|
||||
async () => title.evaluate(el => el.scrollLeft > 0),
|
||||
{ timeout: 5_000 },
|
||||
).toBe(true)
|
||||
expect(await title.evaluate(el => el.scrollLeft < el.scrollWidth - el.clientWidth - 1)).toBe(true)
|
||||
expect(await title.evaluate(el => el.hasAttribute('data-scrolled'))).toBe(true)
|
||||
expect(await title.evaluate(el => el.hasAttribute('data-clipped'))).toBe(true)
|
||||
expect(await title.evaluate(el => getComputedStyle(el).maskImage)).toContain('linear-gradient')
|
||||
// The crawl still reaches the far edge of the hovered cell (the wider
|
||||
// The marquee travels instead of jumping: the title is caught mid-travel,
|
||||
// strictly between its start and its far edge, with both cut edges faded.
|
||||
await expect.poll(async () => await travelled() > 0, { timeout: 5_000 }).toBe(true)
|
||||
expect(await travelled()).toBeLessThan(await range() - 1)
|
||||
expect(await title.evaluate(el => el.hasAttribute('data-marquee'))).toBe(true)
|
||||
expect(await title.evaluate(el => getComputedStyle(el).maskImage)).toContain('calc(100% - 12px)')
|
||||
expect(Math.abs(await glyphTop() - restingTop)).toBeLessThan(0.5)
|
||||
// Constant 30px/s: one second of travel covers about 30px.
|
||||
const before = await travelled()
|
||||
const started = Date.now()
|
||||
await page.waitForTimeout(1_000)
|
||||
const speed = (await travelled() - before) / ((Date.now() - started) / 1_000)
|
||||
expect(speed).toBeGreaterThan(24)
|
||||
expect(speed).toBeLessThan(36)
|
||||
// The travel still reaches the far edge of the hovered cell (the wider
|
||||
// one — the relative-time label yields to the row menu) and rests there,
|
||||
// lifting the right fade so the final character reads at full strength.
|
||||
// The fade lifts on the frame that lands exactly on the far edge, one or
|
||||
// two frames after scrollLeft first rounds within a pixel of it.
|
||||
// lifting the end fade so the final character reads at full strength.
|
||||
await expect.poll(async () => await travelled() >= await range() - 1, { timeout: 20_000 }).toBe(true)
|
||||
await expect.poll(
|
||||
async () => title.evaluate(el => el.scrollLeft >= el.scrollWidth - el.clientWidth - 1),
|
||||
{ timeout: 20_000 },
|
||||
).toBe(true)
|
||||
await expect.poll(
|
||||
async () => title.evaluate(el => el.hasAttribute('data-clipped')),
|
||||
async () => title.evaluate(el => getComputedStyle(el).maskImage.includes('calc(100% - 12px)')),
|
||||
{ timeout: 5_000 },
|
||||
).toBe(false)
|
||||
expect(await title.evaluate(el => getComputedStyle(el).maskImage)).toContain('linear-gradient')
|
||||
// At its extent, the title must not paint the ellipsis over the
|
||||
// characters the marquee reached.
|
||||
expect(await title.evaluate(el => getComputedStyle(el).textOverflow)).toBe('clip')
|
||||
// A frame script would have run once per frame for the whole travel; other parts of the page may ask for a frame or two.
|
||||
expect(await page.evaluate(() => (window as unknown as { marqueeFrames: number }).marqueeFrames)).toBeLessThan(10)
|
||||
|
||||
// Leaving returns in one step: a crawl back would still be travelling
|
||||
// Leaving returns in one step: a travel back would still be under way
|
||||
// inside this window, and it would carry the resting ellipsis with it.
|
||||
await page.mouse.move(0, 0)
|
||||
await expect.poll(
|
||||
async () => title.evaluate(el => el.scrollLeft),
|
||||
{ timeout: 150, interval: 20 },
|
||||
).toBe(0)
|
||||
expect(await title.evaluate(el => el.hasAttribute('data-scrolled'))).toBe(false)
|
||||
await expect.poll(travelled, { timeout: 150, interval: 20 }).toBe(0)
|
||||
expect(await title.evaluate(el => el.hasAttribute('data-marquee'))).toBe(false)
|
||||
expect(await title.evaluate(el => getComputedStyle(el).textOverflow)).toBe('ellipsis')
|
||||
|
||||
// Reduced motion reaches the handler's matchMedia probe: the reveal jumps
|
||||
// to the far edge instead of crawling.
|
||||
// Reduced motion shows the far edge at once instead of travelling to it.
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' })
|
||||
await row.hover()
|
||||
await expect.poll(
|
||||
async () => title.evaluate(el => el.scrollLeft >= el.scrollWidth - el.clientWidth - 1),
|
||||
{ timeout: 500, interval: 20 },
|
||||
).toBe(true)
|
||||
await expect.poll(async () => await travelled() >= await range() - 1, { timeout: 500, interval: 20 }).toBe(true)
|
||||
await page.mouse.move(0, 0)
|
||||
await page.emulateMedia({ reducedMotion: null })
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
|
||||
@@ -743,10 +743,9 @@ describe('JobsSection hover', () => {
|
||||
Object.defineProperty(label, 'clientWidth', { value: 200, configurable: true })
|
||||
const row = label.closest<HTMLElement>('[data-job-row]')!
|
||||
fireEvent.pointerEnter(row)
|
||||
// The suite's matchMedia answers reduced motion, so the command jumps to its far edge.
|
||||
expect(label.scrollLeft).toBe(100)
|
||||
expect([label.hasAttribute('data-marquee'), label.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '100px'])
|
||||
fireEvent.pointerLeave(row)
|
||||
expect(label.scrollLeft).toBe(0)
|
||||
expect([label.hasAttribute('data-marquee'), label.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, ''])
|
||||
const stop = screen.getByRole('button', { name: zh['kill.stopAria'].replace('{label}', 'pnpm run build') })
|
||||
fireEvent.pointerEnter(stop, { pointerType: 'mouse' })
|
||||
act(() => { vi.advanceTimersByTime(499) })
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 33a5b39959a595c6
|
||||
zh: efd1088e9f13ed67
|
||||
/deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog:
|
||||
en: bd746373375bcd7a
|
||||
zh: f37e43b679c06229
|
||||
en: 982b43ef6d6857da
|
||||
zh: 71d5c17e5996e971
|
||||
/deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons:
|
||||
en: fd3499ef403a0594
|
||||
zh: 3a17727316d3c666
|
||||
|
||||
@@ -55,7 +55,7 @@ Check this table before writing a control in a feature package. A plugin cannot
|
||||
| `SegmentedTabs` | Controlled equal-width tabs with a sliding indicator and Left/Right, Home, and End navigation. The caller supplies labels, tab/panel ids, and panel content. Default `size="md"` is 42px tall with a 4px inset; `size="sm"` is 34px tall with a 2px inset. |
|
||||
| `Tag` | Read-only capsule badge; `tone` selects one of eight palettes. |
|
||||
| `PathLabel` | Single-line file path with subdued directories, a primary filename, and the full path on hover. Fitting paths align left; clipped paths preserve their suffix with a left-edge fade that updates on path and size changes. |
|
||||
| `MarqueeText`, `useHoverMarquee` | Single-line text that clips with an ellipsis at rest, and the row handlers that marquee it: entering the row crawls a clipped text at 30px/s to its far edge and holds it there, fading the edges that still hide text; leaving returns it to the start at once. Overflow of at most 8px, touch pointers, and text that fits stay put; reduced motion jumps to the far edge. |
|
||||
| `MarqueeText`, `useHoverMarquee` | Single-line text that clips with an ellipsis at rest, and the row handlers that marquee it: entering the row carries a clipped text at 30px/s to its far edge and holds it there, fading the edges that still hide text; leaving returns it to the start at once. The stylesheet animates the travel, and the handlers measure the overflow once per entry. Overflow of at most 8px, touch pointers, and text that fits stay put; reduced motion shows the far edge at once. |
|
||||
| `StateDot` | Solid green `done`, amber `warning`, red `error`, and neutral-grey `idle` marks in a 10px slot, plus a tertiary-grey 14px rotating `ongoing` loader whose animations pin to document time zero on mount and on every animation restart, such as a list reorder, so every visible loader rotates in phase. `aria-hidden`, so the render site owns the name. `appearance="step"` shows a filled check for completion and a hollow pending circle. |
|
||||
| `ConnectionIndicator` | Inline connection-recovery control across outage, retry, and recovered states. |
|
||||
| `DisclosureRow` | 24px compact disclosure that lays title and content side by side. The header supplies tertiary at rest and secondary on hover; text and icons inherit it regardless of expandability or open state unless the caller supplies a feature-specific override. Semantic status colors remain explicit. Collapsed rows preview a down chevron on hover, and expanded rows keep an up chevron visible. `headerAccessory` places an independent action outside the disclosure target and shimmer; with an accessory, the title row shrinks to its content width. Memoized with shallow prop comparison; keep callbacks and React-node props stable when their content is unchanged. |
|
||||
|
||||
@@ -55,7 +55,7 @@ kind: "package-library"
|
||||
| `SegmentedTabs` | 受控的等宽分段标签,支持滑动指示条及左/右方向键、Home、End 导航。调用方提供文案、标签与面板 id,以及面板内容。默认 `size="md"` 总高 42px、内边距 4px;`size="sm"` 总高 34px、内边距 2px。 |
|
||||
| `Tag` | 只读胶囊徽章;`tone` 选择八种配色之一。 |
|
||||
| `PathLabel` | 单行文件路径:目录使用弱化颜色,文件名使用主色,悬停可查看完整路径。空间足够时靠左显示;溢出时保留尾部并在左侧渐隐,路径或尺寸变化时更新。 |
|
||||
| `MarqueeText`、`useHoverMarquee` | 静止时以省略号截断的单行文字,以及让它滚动显示的行处理函数:指针进入行时,被截断的文字以 30px/s 匀速滚到末尾并停在那里,仍有文字被遮住的边缘渐隐;离开时立即回到开头。溢出不超过 8px、触摸指针以及放得下的文字都不滚动;减少动态效果时直接跳到末尾。 |
|
||||
| `MarqueeText`、`useHoverMarquee` | 静止时以省略号截断的单行文字,以及让它滚动显示的行处理函数:指针进入行时,被截断的文字以 30px/s 匀速移到末尾并停在那里,仍有文字被遮住的边缘渐隐;离开时立即回到开头。移动由样式表的动画完成,处理函数每次进入只测量一次溢出宽度。溢出不超过 8px、触摸指针以及放得下的文字都不滚动;减少动态效果时直接显示末尾。 |
|
||||
| `StateDot` | 10px 槽内的绿色 `done`、琥珀色 `warning`、红色 `error`、中性灰色 `idle` 圆点,以及 tertiary 灰色 14px 旋转 `ongoing` loading,其动画在挂载时以及每次动画重启(如列表重排)时固定到文档时间零点,所以所有可见 loading 同相旋转。它是 `aria-hidden` 的,名称由渲染点提供。 `appearance="step"` 以实心勾表示完成、空心圆表示等待。 |
|
||||
| `ConnectionIndicator` | 行内连接恢复控件,覆盖断线、重试与已恢复三种状态。 |
|
||||
| `DisclosureRow` | 24px 紧凑折叠行,标题与内容左右排列。标题行默认使用 tertiary,悬停时使用 secondary;文字与图标继承该颜色,不受能否展开及开合状态影响,调用方可提供功能专属覆盖。语义状态色保持显式指定。收起时悬停预览向下箭头,展开后持续显示向上箭头。`headerAccessory` 将独立操作放在折叠触发区域和流光之外;有此操作时,标题行收窄到内容宽度。使用浅层 prop 比较进行 memo;内容未变时,保持回调与 React 节点 prop 的引用稳定。 |
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
/* Single-line text that clips with an ellipsis at rest. While a marquee crawls
|
||||
it, the ellipsis drops and both clipping edges fade in over 12px instead of
|
||||
hard-cutting a character: the start once the text has moved off its start
|
||||
(data-scrolled), the end while text still remains beyond the cell
|
||||
(data-clipped). At the far edge the end fade lifts so the final character
|
||||
reads at full strength. */
|
||||
/* Single-line text that clips with an ellipsis at rest. While it marquees
|
||||
(data-marquee), the ellipsis drops, the inner span travels to the far edge
|
||||
over the distance and time the hook measured, and both clipping edges fade
|
||||
in over 12px instead of hard-cutting a character. */
|
||||
.text {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
@@ -12,19 +10,38 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.text[data-scrolled],
|
||||
.text[data-clipped] {
|
||||
/* At the far edge the end fade lifts so the final character reads at full
|
||||
strength: a zero-length animation, delayed by the travel's duration, swaps
|
||||
the mask and holds it. */
|
||||
.text[data-marquee] {
|
||||
text-overflow: clip;
|
||||
}
|
||||
|
||||
.text[data-scrolled] {
|
||||
mask-image: linear-gradient(to right, transparent, #000 12px);
|
||||
}
|
||||
|
||||
.text[data-clipped] {
|
||||
mask-image: linear-gradient(to left, transparent, #000 12px);
|
||||
}
|
||||
|
||||
.text[data-scrolled][data-clipped] {
|
||||
mask-image: linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent);
|
||||
animation: dsh-marquee-arrive 0s var(--dsh-marquee-duration) forwards;
|
||||
}
|
||||
|
||||
@keyframes dsh-marquee-arrive {
|
||||
to { mask-image: linear-gradient(to right, transparent, #000 12px); }
|
||||
}
|
||||
|
||||
/* Inline at rest, so the ellipsis cuts between characters; a transform needs a box. */
|
||||
.text[data-marquee] > .travel {
|
||||
display: inline-block;
|
||||
animation: dsh-marquee-travel var(--dsh-marquee-duration) linear forwards;
|
||||
}
|
||||
|
||||
@keyframes dsh-marquee-travel {
|
||||
to { transform: translateX(calc(-1 * var(--dsh-marquee-range))); }
|
||||
}
|
||||
|
||||
/* Reduced motion shows the far edge at once, so only the start edge hides text. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.text[data-marquee] {
|
||||
mask-image: linear-gradient(to right, transparent, #000 12px);
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.text[data-marquee] > .travel {
|
||||
animation: none;
|
||||
transform: translateX(calc(-1 * var(--dsh-marquee-range)));
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
// Hover marquee for single-line text that its cell clips: entering the owning
|
||||
// row crawls the text to its far edge, and leaving returns it to the start.
|
||||
// Hover marquee for single-line text that its cell clips: while the pointer is
|
||||
// on the owning row, a CSS animation carries the text to its far edge, and
|
||||
// leaving returns it to the start.
|
||||
|
||||
import { forwardRef, useEffect, useMemo, useRef } from 'react'
|
||||
import { forwardRef, useMemo } from 'react'
|
||||
import type { HTMLAttributes, PointerEvent, RefObject } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import css from './Marquee.module.css'
|
||||
|
||||
/* Overflow this small hides no meaningful tail; scrolling for it reads as an
|
||||
/* Overflow this small hides no meaningful tail; travelling for it reads as an
|
||||
accidental jitter, so the text stays put. */
|
||||
const MIN_REVEAL_PX = 8
|
||||
|
||||
@@ -15,96 +16,73 @@ const PX_PER_MS = 0.03
|
||||
|
||||
/** Row handlers that start and stop one text's marquee. */
|
||||
export interface HoverMarquee {
|
||||
/** Start the crawl; touch pointers and text that fits do nothing. */
|
||||
/** Start the travel; touch pointers and text that fits do nothing. */
|
||||
readonly enter: (event?: PointerEvent) => void
|
||||
/** Return the text to its start in one step. */
|
||||
readonly leave: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Place the text's scroll position and publish the stylesheet's fade-mask
|
||||
* hooks: `data-scrolled` while the text has left its start (left fade) and
|
||||
* `data-clipped` while text remains beyond the end edge (right fade).
|
||||
* Start the text's travel unless it already marquees: measure how far the text
|
||||
* overflows its cell, and hand the stylesheet that distance and the time it
|
||||
* takes at the constant speed.
|
||||
* @param text - the clipping text element.
|
||||
* @param left - scroll offset in CSS pixels.
|
||||
* @param range - the text's maximum scroll offset in CSS pixels.
|
||||
*/
|
||||
function place(text: HTMLElement, left: number, range: number): void {
|
||||
// jsdom implements no scrollTo; direct assignment is instant there anyway,
|
||||
// so both paths land on the same position.
|
||||
if (typeof text.scrollTo === 'function') text.scrollTo({ left, behavior: 'instant' })
|
||||
else text.scrollLeft = left
|
||||
if (left > 0) text.dataset.scrolled = ''
|
||||
else delete text.dataset.scrolled
|
||||
if (left < range) text.dataset.clipped = ''
|
||||
else delete text.dataset.clipped
|
||||
function travel(text: HTMLElement): void {
|
||||
if (text.dataset.marquee !== undefined) return
|
||||
const range = text.scrollWidth - text.clientWidth
|
||||
if (range <= MIN_REVEAL_PX) return
|
||||
text.style.setProperty('--dsh-marquee-range', `${range}px`)
|
||||
text.style.setProperty('--dsh-marquee-duration', `${Math.round(range / PX_PER_MS)}ms`)
|
||||
text.dataset.marquee = ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the text to its resting state: scrolled to the start with both fade
|
||||
* masks off, so the resting ellipsis renders at full strength.
|
||||
* Return the text to its resting state: at its start, with the ellipsis and
|
||||
* without fades.
|
||||
* @param text - the clipping text element.
|
||||
*/
|
||||
function rest(text: HTMLElement): void {
|
||||
if (typeof text.scrollTo === 'function') text.scrollTo({ left: 0, behavior: 'instant' })
|
||||
else text.scrollLeft = 0
|
||||
delete text.dataset.scrolled
|
||||
delete text.dataset.clipped
|
||||
delete text.dataset.marquee
|
||||
text.style.removeProperty('--dsh-marquee-range')
|
||||
text.style.removeProperty('--dsh-marquee-duration')
|
||||
}
|
||||
|
||||
/**
|
||||
* Marquee one-line text wider than its cell while its row is hovered: the text
|
||||
* clips itself, so entering crawls it at a constant speed until its far edge is
|
||||
* in view, then rests there under the pointer. Overflow of at most 8px stays
|
||||
* put. Leaving returns the text to the start in one step, because the resting
|
||||
* ellipsis and the narrowed cell would otherwise meet the text while it
|
||||
* travelled back. Reduced motion jumps to the far edge instead of crawling.
|
||||
* @param text - ref to the clipping text element, such as a {@link MarqueeText}.
|
||||
* Marquee one-line text wider than its cell while the pointer is on its row:
|
||||
* the text travels at 30px/s until its far edge is in view, then rests there
|
||||
* under the pointer. Overflow of at most 8px stays put. Leaving returns the
|
||||
* text to the start in one step, because the resting ellipsis and the narrowed
|
||||
* cell would otherwise meet the text while it travelled back. The stylesheet
|
||||
* animates the travel and its fades, so the script only measures the overflow
|
||||
* once per entry; reduced motion shows the far edge at once.
|
||||
* @param text - ref to the clipping text element, a {@link MarqueeText}.
|
||||
* @returns stable pointer enter and leave handlers for the row.
|
||||
*/
|
||||
export function useHoverMarquee(text: RefObject<HTMLElement | null>): HoverMarquee {
|
||||
const frame = useRef(0)
|
||||
const revealing = useRef(false)
|
||||
useEffect(() => () => { cancelAnimationFrame(frame.current) }, [])
|
||||
return useMemo(() => ({
|
||||
enter: (event?: PointerEvent): void => {
|
||||
if (event?.pointerType === 'touch') return
|
||||
const element = text.current
|
||||
if (element === null || revealing.current) return
|
||||
revealing.current = true
|
||||
const range = element.scrollWidth - element.clientWidth
|
||||
if (range <= MIN_REVEAL_PX) return
|
||||
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
||||
place(element, range, range)
|
||||
return
|
||||
}
|
||||
cancelAnimationFrame(frame.current)
|
||||
let previous: number | undefined
|
||||
let position = 0
|
||||
const step = (now: DOMHighResTimeStamp): void => {
|
||||
position += previous === undefined ? 0 : (now - previous) * PX_PER_MS
|
||||
previous = now
|
||||
place(element, Math.min(position, range), range)
|
||||
if (position < range) frame.current = requestAnimationFrame(step)
|
||||
}
|
||||
frame.current = requestAnimationFrame(step)
|
||||
if (text.current !== null) travel(text.current)
|
||||
},
|
||||
leave: (): void => {
|
||||
revealing.current = false
|
||||
cancelAnimationFrame(frame.current)
|
||||
if (text.current !== null) rest(text.current)
|
||||
},
|
||||
}), [text])
|
||||
}
|
||||
|
||||
/** Props of single-line text that a {@link useHoverMarquee} can crawl. */
|
||||
/** Props of single-line text that a {@link useHoverMarquee} can marquee. */
|
||||
export type MarqueeTextProps = HTMLAttributes<HTMLSpanElement>
|
||||
|
||||
/**
|
||||
* Render single-line text that clips with an ellipsis at rest and, while a
|
||||
* {@link useHoverMarquee} crawls it, drops the ellipsis and fades whichever
|
||||
* edge still hides text.
|
||||
* {@link useHoverMarquee} marquees it, drops the ellipsis and fades whichever
|
||||
* edge still hides text. The children sit in an inner span, which travels.
|
||||
*/
|
||||
export const MarqueeText = forwardRef<HTMLSpanElement, MarqueeTextProps>(function MarqueeText({ className, ...attributes }, ref) {
|
||||
return <span {...attributes} ref={ref} className={clsx(css.text, className)} />
|
||||
export const MarqueeText = forwardRef<HTMLSpanElement, MarqueeTextProps>(function MarqueeText({ className, children, ...attributes }, ref) {
|
||||
return (
|
||||
<span {...attributes} ref={ref} className={clsx(css.text, className)}>
|
||||
<span className={css.travel}>{children}</span>
|
||||
</span>
|
||||
)
|
||||
})
|
||||
@@ -1,17 +1,20 @@
|
||||
/**
|
||||
* MarqueeText's clipping and fade masks as CSS text: the component suite sees
|
||||
* CSS Modules as class-name maps, so only the stylesheet proves that a crawling
|
||||
* text drops its ellipsis and fades the edges that still hide text.
|
||||
* MarqueeText's clipping, travel, and fade masks as CSS text: the component
|
||||
* suite sees CSS Modules as class-name maps, so only the stylesheet proves that
|
||||
* a marqueeing text drops its ellipsis, travels by the measured distance and
|
||||
* time, and fades the edges that still hide text.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const css = readFileSync(fileURLToPath(new URL('../src/Marquee.module.css', import.meta.url)), 'utf8')
|
||||
const source = readFileSync(fileURLToPath(new URL('../src/Marquee.module.css', import.meta.url)), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ' ')
|
||||
const reduced = /@media \(prefers-reduced-motion: reduce\) \{([\s\S]*)\}\s*$/.exec(source)?.[1] ?? ''
|
||||
const base = source.replace(/@media \(prefers-reduced-motion: reduce\) \{[\s\S]*\}\s*$/, '')
|
||||
|
||||
function declarations(selector: string): Map<string, string> {
|
||||
function declarations(css: string, selector: string): Map<string, string> {
|
||||
const found = new Map<string, string>()
|
||||
for (const [, selectorList = '', body = ''] of css.replace(/\/\*[\s\S]*?\*\//g, ' ').matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
|
||||
for (const [, selectorList = '', body = ''] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
|
||||
if (!selectorList.split(',').map(value => value.trim()).includes(selector)) continue
|
||||
for (const part of body.split(';')) {
|
||||
const colon = part.indexOf(':')
|
||||
@@ -21,18 +24,34 @@ function declarations(selector: string): Map<string, string> {
|
||||
return found
|
||||
}
|
||||
|
||||
const START_FADE = 'linear-gradient(to right, transparent, #000 12px)'
|
||||
|
||||
describe('Marquee.module.css', () => {
|
||||
it('clips one line with an ellipsis at rest', () => {
|
||||
const rest = declarations('.text')
|
||||
it('clips one line with an ellipsis at rest, with the travelling span inline so the ellipsis cuts between characters', () => {
|
||||
const rest = declarations(base, '.text')
|
||||
expect([rest.get('overflow'), rest.get('text-overflow'), rest.get('white-space')]).toEqual(['hidden', 'ellipsis', 'nowrap'])
|
||||
expect(declarations(base, '.travel').size).toBe(0)
|
||||
})
|
||||
|
||||
it('drops the ellipsis and fades whichever edge still hides text while it crawls', () => {
|
||||
expect(declarations('.text[data-scrolled]').get('text-overflow')).toBe('clip')
|
||||
expect(declarations('.text[data-clipped]').get('text-overflow')).toBe('clip')
|
||||
expect(declarations('.text[data-scrolled]').get('mask-image')).toBe('linear-gradient(to right, transparent, #000 12px)')
|
||||
expect(declarations('.text[data-clipped]').get('mask-image')).toBe('linear-gradient(to left, transparent, #000 12px)')
|
||||
expect(declarations('.text[data-scrolled][data-clipped]').get('mask-image'))
|
||||
.toBe('linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent)')
|
||||
it('drops the ellipsis and fades both edges while the text travels, then only the start edge once the travel time has passed', () => {
|
||||
const travelling = declarations(base, '.text[data-marquee]')
|
||||
expect(travelling.get('text-overflow')).toBe('clip')
|
||||
expect(travelling.get('mask-image')).toBe('linear-gradient(to right, transparent, #000 12px, #000 calc(100% - 12px), transparent)')
|
||||
expect(travelling.get('animation')).toBe('dsh-marquee-arrive 0s var(--dsh-marquee-duration) forwards')
|
||||
expect(base.replace(/\s+/g, ' ')).toContain(`@keyframes dsh-marquee-arrive { to { mask-image: ${START_FADE}; } }`)
|
||||
})
|
||||
|
||||
it('carries the span over the measured distance in the measured time at a constant speed and holds the far edge', () => {
|
||||
const travel = declarations(base, '.text[data-marquee] > .travel')
|
||||
expect(travel.get('display')).toBe('inline-block')
|
||||
expect(travel.get('animation')).toBe('dsh-marquee-travel var(--dsh-marquee-duration) linear forwards')
|
||||
expect(base.replace(/\s+/g, ' ')).toContain('@keyframes dsh-marquee-travel { to { transform: translateX(calc(-1 * var(--dsh-marquee-range))); } }')
|
||||
})
|
||||
|
||||
it('shows the far edge at once under reduced motion, with the start fade alone', () => {
|
||||
const text = declarations(reduced, '.text[data-marquee]')
|
||||
expect([text.get('mask-image'), text.get('animation')]).toEqual([START_FADE, 'none'])
|
||||
const travel = declarations(reduced, '.text[data-marquee] > .travel')
|
||||
expect([travel.get('animation'), travel.get('transform')]).toEqual(['none', 'translateX(calc(-1 * var(--dsh-marquee-range)))'])
|
||||
})
|
||||
})
|
||||
@@ -1,14 +1,10 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { useRef } from 'react'
|
||||
import { MarqueeText, useHoverMarquee } from '../src/Marquee.tsx'
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
afterEach(cleanup)
|
||||
|
||||
function Row({ text }: { readonly text: string }) {
|
||||
const ref = useRef<HTMLSpanElement>(null)
|
||||
@@ -20,81 +16,55 @@ function Row({ text }: { readonly text: string }) {
|
||||
)
|
||||
}
|
||||
|
||||
/** The clipping element and the span inside it that travels. */
|
||||
function parts(): { text: HTMLElement; travel: HTMLElement } {
|
||||
const text = document.querySelector('[data-cell]') as HTMLElement
|
||||
return { text, travel: text.firstElementChild as HTMLElement }
|
||||
}
|
||||
|
||||
/** State the clipped text's geometry outright: jsdom lays out nothing. */
|
||||
function geometry(element: HTMLElement, scrollWidth: number, clientWidth: number): void {
|
||||
Object.defineProperty(element, 'scrollWidth', { value: scrollWidth, configurable: true })
|
||||
Object.defineProperty(element, 'clientWidth', { value: clientWidth, configurable: true })
|
||||
}
|
||||
|
||||
/** What the stylesheet reads: whether the text marquees, the travel distance, and its duration. */
|
||||
function marquee(text: HTMLElement): (string | undefined)[] {
|
||||
return [text.dataset.marquee, text.style.getPropertyValue('--dsh-marquee-range'), text.style.getPropertyValue('--dsh-marquee-duration')]
|
||||
}
|
||||
|
||||
describe('useHoverMarquee', () => {
|
||||
it('crawls clipped text to its far edge at 30px/s while hovered and returns at once on leave', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false })))
|
||||
it('hands the stylesheet the overflow and its time at 30px/s while hovered, and rests at once on leave', () => {
|
||||
render(<Row text="A cell long enough to clip" />)
|
||||
const row = screen.getByRole('row')
|
||||
const text = screen.getByText('A cell long enough to clip')
|
||||
const { text, travel } = parts()
|
||||
expect(text.className).toContain('cell')
|
||||
expect(text.hasAttribute('data-cell')).toBe(true)
|
||||
expect(travel.textContent).toBe('A cell long enough to clip')
|
||||
geometry(text, 320, 180)
|
||||
fireEvent.pointerEnter(row, { pointerType: 'touch' })
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(text.scrollLeft).toBe(0)
|
||||
expect(marquee(text)).toEqual([undefined, '', ''])
|
||||
fireEvent.pointerEnter(row)
|
||||
vi.advanceTimersByTime(16)
|
||||
expect([text.scrollLeft, text.hasAttribute('data-scrolled'), text.hasAttribute('data-clipped')]).toEqual([0, false, true])
|
||||
vi.advanceTimersByTime(1600)
|
||||
expect(text.scrollLeft).toBeCloseTo(48, 5)
|
||||
expect([text.hasAttribute('data-scrolled'), text.hasAttribute('data-clipped')]).toEqual([true, true])
|
||||
// A repeated entry while revealing does not restart the crawl.
|
||||
expect(marquee(text)).toEqual(['', '140px', '4667ms'])
|
||||
// A repeated entry while it marquees measures nothing again, so the travel does not restart.
|
||||
geometry(text, 400, 180)
|
||||
fireEvent.pointerEnter(row)
|
||||
vi.advanceTimersByTime(10_000)
|
||||
expect([text.scrollLeft, text.hasAttribute('data-clipped')]).toEqual([140, false])
|
||||
expect(marquee(text)).toEqual(['', '140px', '4667ms'])
|
||||
fireEvent.pointerLeave(row)
|
||||
expect([text.scrollLeft, text.hasAttribute('data-scrolled'), text.hasAttribute('data-clipped')]).toEqual([0, false, false])
|
||||
expect(marquee(text)).toEqual([undefined, '', ''])
|
||||
})
|
||||
|
||||
it('leaves text that fits or overflows by at most 8px at its start', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false })))
|
||||
it('leaves text that fits or overflows by at most 8px at rest', () => {
|
||||
render(<Row text="Short" />)
|
||||
const row = screen.getByRole('row')
|
||||
const text = screen.getByText('Short')
|
||||
for (const [scrollWidth, expected] of [[180, 0], [188, 0], [189, 9]] as const) {
|
||||
const { text } = parts()
|
||||
for (const [scrollWidth, expected] of [[180, false], [188, false], [189, true]] as const) {
|
||||
geometry(text, scrollWidth, 180)
|
||||
fireEvent.pointerEnter(row)
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(text.scrollLeft).toBe(expected)
|
||||
expect(text.hasAttribute('data-marquee')).toBe(expected)
|
||||
fireEvent.pointerLeave(row)
|
||||
}
|
||||
})
|
||||
|
||||
it('jumps to the far edge under reduced motion and uses scrollTo where the element has it', () => {
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })))
|
||||
render(<Row text="Reduced motion text" />)
|
||||
const row = screen.getByRole('row')
|
||||
const text = screen.getByText('Reduced motion text')
|
||||
const scrollTo = vi.fn()
|
||||
text.scrollTo = scrollTo as typeof text.scrollTo
|
||||
geometry(text, 300, 200)
|
||||
fireEvent.pointerEnter(row)
|
||||
expect(scrollTo).toHaveBeenLastCalledWith({ left: 100, behavior: 'instant' })
|
||||
expect([text.hasAttribute('data-scrolled'), text.hasAttribute('data-clipped')]).toEqual([true, false])
|
||||
fireEvent.pointerLeave(row)
|
||||
expect(scrollTo).toHaveBeenLastCalledWith({ left: 0, behavior: 'instant' })
|
||||
})
|
||||
|
||||
it('stops its frames when the row unmounts mid-crawl', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false })))
|
||||
const view = render(<Row text="Unmounted mid-crawl" />)
|
||||
const text = screen.getByText('Unmounted mid-crawl')
|
||||
geometry(text, 400, 200)
|
||||
fireEvent.pointerEnter(screen.getByRole('row'))
|
||||
vi.advanceTimersByTime(100)
|
||||
view.unmount()
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('ignores hover before its text element mounts', () => {
|
||||
function Detached() {
|
||||
const ref = useRef<HTMLSpanElement>(null)
|
||||
|
||||
@@ -200,11 +200,9 @@
|
||||
}
|
||||
|
||||
/* Hovering a session row marquees a title wider than its cell: the shared
|
||||
hover marquee crawls it at a constant speed to its far edge while the pointer
|
||||
rests on the row, holds it there, fades the edges that still hide text, and
|
||||
returns it to the start in one step when the pointer leaves. The motion is
|
||||
scripted frame by frame (reduced motion jumps), so no scroll-behavior applies
|
||||
here. */
|
||||
hover marquee carries it at a constant speed to its far edge while the
|
||||
pointer rests on the row, holds it there, fades the edges that still hide
|
||||
text, and returns it to the start in one step when the pointer leaves. */
|
||||
.sessionRow .title {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
@@ -184,11 +184,9 @@ describe('WorkspaceBrowser.module.css list', () => {
|
||||
})
|
||||
|
||||
it('marquees a clipped session title on row hover', () => {
|
||||
// The shared hover marquee scripts the crawl frame by frame and its
|
||||
// MarqueeText fades the clipping edges, so the title declares no
|
||||
// scroll-behavior; the stylesheet keeps the hovered cell unclipped.
|
||||
// The shared MarqueeText animates the travel and fades the clipping
|
||||
// edges; the row's stylesheet sizes the cell and keeps it unclipped on hover.
|
||||
expect(rowDeclarations('.sessionRow .title')?.get('flex')).toBe('1')
|
||||
expect(rowDeclarations('.sessionRow .title')?.get('scroll-behavior')).toBeUndefined()
|
||||
expect(rowDeclarations('.sessionRow:hover .title')?.get('text-overflow')).toBe('clip')
|
||||
})
|
||||
|
||||
|
||||
@@ -269,15 +269,15 @@ describe('workspace browser rows', () => {
|
||||
}
|
||||
const view = render(<SessionNodeItem node={idle} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
|
||||
// The cell is the row's first element and holds nothing while the row is
|
||||
// idle without an occupant; the title follows it.
|
||||
const cell = screen.getByText('Flat Session').previousElementSibling
|
||||
// idle without an occupant; the title, whose text sits in an inner span, follows it.
|
||||
const cell = screen.getByText('Flat Session').parentElement?.previousElementSibling
|
||||
expect(cell?.className).toMatch(/slot/)
|
||||
expect(cell?.children).toHaveLength(0)
|
||||
|
||||
view.rerender(<SessionNodeItem node={{ ...idle, running: true }} currentId={undefined} now={0}
|
||||
onOpen={vi.fn()} t={t} />)
|
||||
// A row that gains a state dot keeps that dot in the same cell.
|
||||
expect(screen.getByText('Flat Session').previousElementSibling?.querySelector('[data-state="ongoing"]')).toBeTruthy()
|
||||
expect(screen.getByText('Flat Session').parentElement?.previousElementSibling?.querySelector('[data-state="ongoing"]')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('renders a selected content-search row and opens only its session', () => {
|
||||
@@ -398,165 +398,72 @@ describe('workspace browser rows', () => {
|
||||
})
|
||||
|
||||
it('marquees a clipped session title at a constant speed while the row is hovered', () => {
|
||||
vi.useFakeTimers()
|
||||
// jsdom implements no matchMedia; the stub answers the reduced-motion probe.
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false })))
|
||||
try {
|
||||
const node: SessionNode = {
|
||||
id: sid('clipped'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false,
|
||||
running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0,
|
||||
pinned: false, archived: false,
|
||||
}
|
||||
render(
|
||||
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />,
|
||||
)
|
||||
const row = screen.getByRole('treeitem')
|
||||
const title = screen.getByText(node.title)
|
||||
// jsdom lays out nothing: the title's clipped geometry is stated outright.
|
||||
const geometry = (scrollWidth: number, clientWidth: number): void => {
|
||||
Object.defineProperty(title, 'scrollWidth', { value: scrollWidth, configurable: true })
|
||||
Object.defineProperty(title, 'clientWidth', { value: clientWidth, configurable: true })
|
||||
}
|
||||
|
||||
geometry(320, 180)
|
||||
const touch = new Event('pointerover', { bubbles: true })
|
||||
Object.defineProperty(touch, 'pointerType', { value: 'touch' })
|
||||
fireEvent(row, touch)
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(title.scrollLeft).toBe(0)
|
||||
fireEvent.pointerEnter(row)
|
||||
// The first frame only records the clock; travel begins on the second.
|
||||
vi.advanceTimersByTime(16)
|
||||
expect(title.scrollLeft).toBe(0)
|
||||
expect(title.hasAttribute('data-scrolled')).toBe(false)
|
||||
expect(title.hasAttribute('data-clipped')).toBe(true)
|
||||
// Constant 30px/s: 1600ms of frames crawl 48px, and the moved title
|
||||
// publishes both fade-mask hooks — off its start, short of its far edge.
|
||||
vi.advanceTimersByTime(1600)
|
||||
expect(title.scrollLeft).toBeCloseTo(48, 5)
|
||||
expect(title.hasAttribute('data-scrolled')).toBe(true)
|
||||
expect(title.hasAttribute('data-clipped')).toBe(true)
|
||||
// The crawl clamps at the far edge and rests there under the pointer;
|
||||
// the right fade lifts so the final character reads at full strength.
|
||||
vi.advanceTimersByTime(10_000)
|
||||
expect(title.scrollLeft).toBe(140)
|
||||
expect(title.hasAttribute('data-clipped')).toBe(false)
|
||||
fireEvent.pointerLeave(row)
|
||||
expect(title.scrollLeft).toBe(0)
|
||||
expect(title.hasAttribute('data-scrolled')).toBe(false)
|
||||
expect(title.hasAttribute('data-clipped')).toBe(false)
|
||||
|
||||
// A title that fits has no scroll range: hovering leaves it at its start.
|
||||
geometry(180, 180)
|
||||
fireEvent.pointerEnter(row)
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(title.scrollLeft).toBe(0)
|
||||
fireEvent.pointerLeave(row)
|
||||
|
||||
// Overflow at the 8px jitter threshold also stays put.
|
||||
geometry(188, 180)
|
||||
fireEvent.pointerEnter(row)
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(title.scrollLeft).toBe(0)
|
||||
fireEvent.pointerLeave(row)
|
||||
|
||||
// One pixel past the threshold crawls to its 9px extent.
|
||||
geometry(189, 180)
|
||||
fireEvent.pointerEnter(row)
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(title.scrollLeft).toBe(9)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
const node: SessionNode = {
|
||||
id: sid('clipped'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false,
|
||||
running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0,
|
||||
pinned: false, archived: false,
|
||||
}
|
||||
render(
|
||||
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />,
|
||||
)
|
||||
const row = screen.getByRole('treeitem')
|
||||
// The title text sits in the span that travels; its parent clips it.
|
||||
const title = screen.getByText(node.title).parentElement as HTMLElement
|
||||
// jsdom lays out nothing: the title's clipped geometry is stated outright.
|
||||
const geometry = (scrollWidth: number, clientWidth: number): void => {
|
||||
Object.defineProperty(title, 'scrollWidth', { value: scrollWidth, configurable: true })
|
||||
Object.defineProperty(title, 'clientWidth', { value: clientWidth, configurable: true })
|
||||
}
|
||||
const marquee = (): (string | undefined)[] =>
|
||||
[title.dataset.marquee, title.style.getPropertyValue('--dsh-marquee-range'), title.style.getPropertyValue('--dsh-marquee-duration')]
|
||||
|
||||
geometry(320, 180)
|
||||
const touch = new Event('pointerover', { bubbles: true })
|
||||
Object.defineProperty(touch, 'pointerType', { value: 'touch' })
|
||||
fireEvent(row, touch)
|
||||
expect(marquee()).toEqual([undefined, '', ''])
|
||||
// Constant 30px/s: the stylesheet travels the 140px overflow in 4667ms.
|
||||
fireEvent.pointerEnter(row)
|
||||
expect(marquee()).toEqual(['', '140px', '4667ms'])
|
||||
// Leaving returns the title to its start in one step.
|
||||
fireEvent.pointerLeave(row)
|
||||
expect(marquee()).toEqual([undefined, '', ''])
|
||||
|
||||
// A title that fits has nothing to travel: hovering leaves it at rest.
|
||||
geometry(180, 180)
|
||||
fireEvent.pointerEnter(row)
|
||||
expect(marquee()).toEqual([undefined, '', ''])
|
||||
fireEvent.pointerLeave(row)
|
||||
|
||||
// Overflow at the 8px jitter threshold also stays put.
|
||||
geometry(188, 180)
|
||||
fireEvent.pointerEnter(row)
|
||||
expect(marquee()).toEqual([undefined, '', ''])
|
||||
fireEvent.pointerLeave(row)
|
||||
|
||||
// One pixel past the threshold travels its 9px extent.
|
||||
geometry(189, 180)
|
||||
fireEvent.pointerEnter(row)
|
||||
expect(marquee()).toEqual(['', '9px', '300ms'])
|
||||
})
|
||||
|
||||
it('continues a title crawl while its context menu owns the hover highlight', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false })))
|
||||
try {
|
||||
const node: SessionNode = { id: sid('context-crawl'), title: 'A long Session title', blank: false,
|
||||
running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false }
|
||||
const props = { node, currentId: undefined, now: 0, onOpen: vi.fn(), t }
|
||||
const view = render(<SessionNodeItem {...props} />)
|
||||
const row = screen.getByRole('treeitem')
|
||||
const title = screen.getByText(node.title)
|
||||
Object.defineProperty(title, 'scrollWidth', { value: 400, configurable: true })
|
||||
Object.defineProperty(title, 'clientWidth', { value: 160, configurable: true })
|
||||
fireEvent.pointerEnter(row)
|
||||
vi.advanceTimersByTime(1616)
|
||||
expect(title.scrollLeft).toBeCloseTo(48)
|
||||
view.rerender(<SessionNodeItem {...props} useContextMenuTarget={select => select({ kind: 'session',
|
||||
value: { sessionId: node.id, displayTitle: node.title } })} />)
|
||||
fireEvent.pointerLeave(row)
|
||||
vi.advanceTimersByTime(1600)
|
||||
expect(title.scrollLeft).toBeCloseTo(96)
|
||||
view.rerender(<SessionNodeItem {...props} />)
|
||||
expect(title.scrollLeft).toBe(0)
|
||||
} finally { vi.useRealTimers(); vi.unstubAllGlobals() }
|
||||
})
|
||||
|
||||
it('jumps a clipped title to its far edge under reduced motion', () => {
|
||||
vi.stubGlobal('matchMedia', vi.fn((query: string) => ({ matches: query === '(prefers-reduced-motion: reduce)' })))
|
||||
try {
|
||||
const node: SessionNode = {
|
||||
id: sid('reduced-motion'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false,
|
||||
running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0,
|
||||
pinned: false, archived: false,
|
||||
}
|
||||
render(
|
||||
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />,
|
||||
)
|
||||
const row = screen.getByRole('treeitem')
|
||||
const title = screen.getByText(node.title)
|
||||
Object.defineProperty(title, 'scrollWidth', { value: 320, configurable: true })
|
||||
Object.defineProperty(title, 'clientWidth', { value: 180, configurable: true })
|
||||
|
||||
fireEvent.pointerEnter(row)
|
||||
expect(title.scrollLeft).toBe(140)
|
||||
expect(title.hasAttribute('data-scrolled')).toBe(true)
|
||||
expect(title.hasAttribute('data-clipped')).toBe(false)
|
||||
fireEvent.pointerLeave(row)
|
||||
expect(title.scrollLeft).toBe(0)
|
||||
expect(title.hasAttribute('data-scrolled')).toBe(false)
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('returns a marqueed title to its start in one step and cancels the crawl', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: false })))
|
||||
try {
|
||||
const node: SessionNode = {
|
||||
id: sid('instant-return'), title: 'A Session Title Long Enough To Be Clipped (1)', blank: false,
|
||||
running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0,
|
||||
pinned: false, archived: false,
|
||||
}
|
||||
render(
|
||||
<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />,
|
||||
)
|
||||
const row = screen.getByRole('treeitem')
|
||||
const title = screen.getByText(node.title)
|
||||
Object.defineProperty(title, 'scrollWidth', { value: 320, configurable: true })
|
||||
Object.defineProperty(title, 'clientWidth', { value: 180, configurable: true })
|
||||
const scrollTo = vi.fn()
|
||||
Object.defineProperty(title, 'scrollTo', { value: scrollTo, configurable: true })
|
||||
|
||||
fireEvent.pointerEnter(row)
|
||||
vi.advanceTimersByTime(160)
|
||||
fireEvent.pointerLeave(row)
|
||||
// Browsers receive the explicit instant behavior so mid-crawl positions
|
||||
// never ease; the return is one step.
|
||||
expect(scrollTo).toHaveBeenLastCalledWith({ left: 0, behavior: 'instant' })
|
||||
// Leaving cancels the crawl rather than letting it finish under the mask.
|
||||
const settled = scrollTo.mock.calls.length
|
||||
vi.advanceTimersByTime(1000)
|
||||
expect(scrollTo.mock.calls.length).toBe(settled)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
it('keeps a title marqueed while its context menu owns the hover highlight', () => {
|
||||
const node: SessionNode = { id: sid('context-crawl'), title: 'A long Session title', blank: false,
|
||||
running: false, runningSubagentCount: 0, completed: false, failed: false, updatedAt: 0, pinned: false, archived: false }
|
||||
const props = { node, currentId: undefined, now: 0, onOpen: vi.fn(), t }
|
||||
const view = render(<SessionNodeItem {...props} />)
|
||||
const row = screen.getByRole('treeitem')
|
||||
const title = screen.getByText(node.title).parentElement as HTMLElement
|
||||
Object.defineProperty(title, 'scrollWidth', { value: 400, configurable: true })
|
||||
Object.defineProperty(title, 'clientWidth', { value: 160, configurable: true })
|
||||
fireEvent.pointerEnter(row)
|
||||
expect(title.style.getPropertyValue('--dsh-marquee-range')).toBe('240px')
|
||||
view.rerender(<SessionNodeItem {...props} useContextMenuTarget={select => select({ kind: 'session',
|
||||
value: { sessionId: node.id, displayTitle: node.title } })} />)
|
||||
fireEvent.pointerLeave(row)
|
||||
expect(title.hasAttribute('data-marquee')).toBe(true)
|
||||
view.rerender(<SessionNodeItem {...props} />)
|
||||
expect(title.hasAttribute('data-marquee')).toBe(false)
|
||||
})
|
||||
|
||||
it('shows the green unread dot only on an unread session (live activity wins the slot)', () => {
|
||||
@@ -1152,7 +1059,7 @@ describe('workspace browser rows', () => {
|
||||
}
|
||||
const view = render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={t} />)
|
||||
const row = screen.getByRole('treeitem')
|
||||
const title = screen.getByText('Needs input')
|
||||
const title = screen.getByText('Needs input').parentElement as HTMLElement
|
||||
expect(row.querySelector('[data-state="warning"]')).toBeTruthy()
|
||||
expect(row.querySelector('[data-state="ongoing"]')).toBeNull()
|
||||
expect(row.textContent).toContain(label)
|
||||
@@ -1188,7 +1095,7 @@ describe('workspace browser rows', () => {
|
||||
}
|
||||
render(<SessionNodeItem node={node} currentId={undefined} now={0} onOpen={vi.fn()} t={tEn} />)
|
||||
const row = screen.getByRole('treeitem')
|
||||
expect(screen.getByText('Needs input').nextElementSibling?.textContent).toBe(compactLabel)
|
||||
expect(screen.getByText('Needs input').parentElement?.nextElementSibling?.textContent).toBe(compactLabel)
|
||||
expect(screen.getByText(compactLabel).getAttribute('aria-hidden')).toBe('true')
|
||||
expect(row.textContent).not.toContain('now')
|
||||
})
|
||||
|
||||
@@ -126,15 +126,10 @@ describe('ChangeRequestCard head', () => {
|
||||
expect(text.textContent).toBe('Change 7')
|
||||
Object.defineProperty(text, 'scrollWidth', { value: 240, configurable: true })
|
||||
Object.defineProperty(text, 'clientWidth', { value: 120, configurable: true })
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })))
|
||||
try {
|
||||
fireEvent.pointerEnter(b.head)
|
||||
expect([text.scrollLeft, text.hasAttribute('data-scrolled')]).toEqual([120, true])
|
||||
fireEvent.pointerLeave(b.head)
|
||||
expect([text.scrollLeft, text.hasAttribute('data-scrolled')]).toEqual([0, false])
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
fireEvent.pointerEnter(b.head)
|
||||
expect([text.hasAttribute('data-marquee'), text.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '120px'])
|
||||
fireEvent.pointerLeave(b.head)
|
||||
expect([text.hasAttribute('data-marquee'), text.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, ''])
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -549,21 +549,16 @@ describe('ChangesTab tooltips', () => {
|
||||
expect(tooltipAfterHover(tree.getByRole('button', { name: 'src/app.ts' }))).toEqual({ early: null, at500: null })
|
||||
expect(tooltipAfterHover(tree.getByRole('button', { name: 'lib/a.txt → lib/b.txt' })))
|
||||
.toEqual({ early: null, at500: 'lib/a.txt → lib/b.txt' })
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })))
|
||||
try {
|
||||
const row = tree.getByRole('button', { name: 'src/app.ts' })
|
||||
const name = row.querySelector('[data-forge-tree-name]')
|
||||
if (!(name instanceof HTMLElement)) throw new Error('no tree name')
|
||||
expect(name.textContent).toBe('app.ts')
|
||||
Object.defineProperty(name, 'scrollWidth', { value: 240, configurable: true })
|
||||
Object.defineProperty(name, 'clientWidth', { value: 120, configurable: true })
|
||||
fireEvent.pointerEnter(row)
|
||||
expect([name.scrollLeft, name.hasAttribute('data-scrolled')]).toEqual([120, true])
|
||||
fireEvent.pointerLeave(row)
|
||||
expect([name.scrollLeft, name.hasAttribute('data-scrolled')]).toEqual([0, false])
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
const row = tree.getByRole('button', { name: 'src/app.ts' })
|
||||
const name = row.querySelector('[data-forge-tree-name]')
|
||||
if (!(name instanceof HTMLElement)) throw new Error('no tree name')
|
||||
expect(name.textContent).toBe('app.ts')
|
||||
Object.defineProperty(name, 'scrollWidth', { value: 240, configurable: true })
|
||||
Object.defineProperty(name, 'clientWidth', { value: 120, configurable: true })
|
||||
fireEvent.pointerEnter(row)
|
||||
expect([name.hasAttribute('data-marquee'), name.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '120px'])
|
||||
fireEvent.pointerLeave(row)
|
||||
expect([name.hasAttribute('data-marquee'), name.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, ''])
|
||||
})
|
||||
|
||||
it('shows toolbar and viewed hints after 500ms of hover and at once on keyboard focus, with no native titles', async () => {
|
||||
|
||||
@@ -409,18 +409,14 @@ describe('CheckoutRow', () => {
|
||||
it('crawls a branch name the row clips while the pointer rests on the row', () => {
|
||||
const b = row(ready(), '/work')
|
||||
const element = b.element() as HTMLElement
|
||||
const name = within(element).getByText('main')
|
||||
// The name's text sits in the span that travels; its parent clips it.
|
||||
const name = within(element).getByText('main').parentElement as HTMLElement
|
||||
Object.defineProperty(name, 'scrollWidth', { value: 240, configurable: true })
|
||||
Object.defineProperty(name, 'clientWidth', { value: 120, configurable: true })
|
||||
vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true })))
|
||||
try {
|
||||
fireEvent.pointerEnter(element)
|
||||
expect(name.scrollLeft).toBe(120)
|
||||
fireEvent.pointerLeave(element)
|
||||
expect(name.scrollLeft).toBe(0)
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
fireEvent.pointerEnter(element)
|
||||
expect([name.hasAttribute('data-marquee'), name.style.getPropertyValue('--dsh-marquee-range')]).toEqual([true, '120px'])
|
||||
fireEvent.pointerLeave(element)
|
||||
expect([name.hasAttribute('data-marquee'), name.style.getPropertyValue('--dsh-marquee-range')]).toEqual([false, ''])
|
||||
})
|
||||
|
||||
it('names a detached HEAD with its commit and a linked worktree', () => {
|
||||
|
||||
Reference in new issue
Block a user