Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/verse-action-label-wrap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@youversion/platform-react-ui': patch
---

Long custom verse action labels now wrap to two lines. Each button fits its text, and icons, swatches, and the divider stay on one line.
155 changes: 155 additions & 0 deletions packages/ui/src/components/verse-action-popover.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import type { Meta, StoryObj } from '@storybook/react-vite';

import { useState } from 'react';
import { expect, within } from 'storybook/test';
import { waitFor } from '../test/storybook-dom';
import { BookOpenIcon } from './icons/book-open';
import { GlobeIcon } from './icons/globe';
import { FlameIcon } from './icons/flame';
import { ClockBackIcon } from './icons/clock-back';
import { VerseActionPopover, type VerseActionPopoverItem } from './verse-action-popover';

const icon = (Icon: typeof BookOpenIcon) => <Icon className="yv:size-5" />;

/**
* Host labels arrive already localized, so a bar can mix short built-ins with
* long translated or descriptive custom actions. Each item stresses one case.
*/
const DATASETS = {
/** What most apps show: no `actionItems`. */
default: undefined,
demo: [
'highlights',
'copy',
'share',
{ id: 'custom', label: 'Custom Action', icon: icon(FlameIcon), onSelect: () => {} },
],
worstCase: [
'highlights',
'copy',
// German compound words have no break opportunity.
{
id: 'prayer-list',
label: 'Zur Gebetsanliegenliste hinzufügen',
icon: icon(BookOpenIcon),
onSelect: () => {},
},
'share',
// Stacked Vietnamese diacritics are clipped by a tight line box.
{ id: 'plan', label: 'Thêm vào kế hoạch đọc', icon: icon(ClockBackIcon), onSelect: () => {} },
// A descriptive English action longer than two short lines.
{
id: 'discussion',
label: 'Add these verses to tomorrow’s small-group discussion',
icon: icon(GlobeIcon),
onSelect: () => {},
},
{ id: 'pin', label: 'Pin', icon: icon(FlameIcon), onSelect: () => {} },
],
} satisfies Record<string, readonly VerseActionPopoverItem[] | undefined>;

type VerseActionLabelsProps = {
data: keyof typeof DATASETS;
theme?: 'light' | 'dark';
};

function VerseActionLabels({ data, theme }: VerseActionLabelsProps): React.ReactNode {
const [anchor, setAnchor] = useState<HTMLElement | null>(null);
return (
<div className="yv:pb-48 yv:text-center">
<span ref={setAnchor} className="yv-v" style={{ color: 'gray' }}>
In the beginning was the Word.
</span>
<VerseActionPopover
open={anchor !== null}
onOpenChange={() => {}}
activeHighlights={new Set()}
selectedVerses={[1]}
highlightedVerses={{}}
anchorElement={anchor}
actionItems={DATASETS[data]}
includeSave
onHighlight={() => {}}
onClearHighlight={() => {}}
onSave={() => {}}
onCopy={() => {}}
onShare={() => {}}
theme={theme}
/>
</div>
);
}

const meta = {
title: 'Components/VerseActionPopover',
component: VerseActionLabels,
parameters: { layout: 'centered' },
argTypes: {
data: {
control: 'inline-radio',
options: Object.keys(DATASETS),
description: 'Action items passed through `actionItems`.',
},
},
render: (args, { globals }) => (
<VerseActionLabels {...args} theme={globals.theme === 'dark' ? 'dark' : 'light'} />
),
} satisfies Meta<typeof VerseActionLabels>;

export default meta;
type Story = StoryObj<typeof meta>;

/** Built-in actions only, as most apps show the bar. */
export const Default: Story = { args: { data: 'default' } };

/** Long, translated, and very short host labels side by side. */
export const LongCustomLabels: Story = {
tags: ['integration'],
args: { data: 'worstCase' },
play: async ({ canvasElement }) => {
const dialog = await within(canvasElement.ownerDocument.body).findByRole('dialog', {
name: 'Verse actions',
});
await Promise.all(dialog.getAnimations().map((animation) => animation.finished));
const actions = within(dialog);
const centerY = (element: Element) => {
const { top, height } = element.getBoundingClientRect();
return top + height / 2;
};
const copy = actions.getByRole('button', { name: 'Copy' });
const discussion = actions.getByRole('button', {
name: 'Add these verses to tomorrow’s small-group discussion',
});
const label = discussion.lastElementChild;
if (!copy.firstElementChild || !label) throw new Error('Action button parts missing');
const lineHeight = Number.parseFloat(getComputedStyle(label).lineHeight);

await waitFor(async () => {
// The long label wraps to two clamped lines instead of widening the bar.
await expect(label.getBoundingClientRect().height).toBe(lineHeight * 2);
// Its box hugs its longest visible line, so the gaps beside it match the others.
const range = label.ownerDocument.createRange();
range.selectNodeContents(label);
const visibleLines = Array.from(range.getClientRects()).filter(
(line) => line.top < label.getBoundingClientRect().bottom,
);
const widest = Math.max(...visibleLines.map((line) => line.width));
await expect(label.getBoundingClientRect().width - widest).toBeLessThan(1);

Check failure on line 137 in packages/ui/src/components/verse-action-popover.stories.tsx

View workflow job for this annotation

GitHub Actions / Integration Tests

src/components/verse-action-popover.stories.tsx > Long Custom Labels

AssertionError: Click to debug the error directly in Storybook: ***/?path=/story/components-verseactionpopover--long-custom-labels&addonPanel=storybook/interactions/panel expected 1 to be less than 1 Ignored nodes: comments, script, style <html lang="en" > <head> <link href="https://***/v1/fonts/1/stylesheet?app_key=***" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&family=Source+Serif+4:wght@400;700&display=swap" rel="stylesheet" /> <meta charset="UTF-8" /> <link href="/__vitest__/favicon.svg" rel="icon" type="image/svg+xml" /> <meta content="width=device-width, initial-scale=1.0" name="viewport" /> <title> Vitest Browser Tester </title> <link crossorigin="" href="/__vitest_browser__/utils-uxqdqUz8.js" rel="modulepreload" /> <base target="_parent" /> </head> <body style="background-color: rgb(255, 255, 255);" > <span data-radix-focus-guard="" style="outline: none; opacity: 0; position: fixed; pointer-events: none;" tabindex="0" /> <div class="sb-preparing-story sb-wrapper" > <div class="sb-loader" /> </div> <div class="sb-preparing-docs sb-wrapper" > <div class="sb-previewBlock" > <div class="sb-previewBlock_header" > <div class="sb-previewBlock_icon" /> <div class="sb-previewBlock_icon" /> <div class="sb-previewBlock_icon" /> <div class="sb-previewBlock_icon" /> </div> <div class="sb-previewBlock_body" > <div class="sb-loader" /> </div> </div> <table aria-hidden="true" class="sb-argstableBlock" > <thead class="sb-argstableBlock-head" > <tr> <th> <span> Name </span> </th> <th> <span> Description </span> </th> <th> <span> Default </span> </th> <th> <span> Control </span> </th> </tr> </thead> <tbody class="sb-argstableBlock-body" > <tr> <td> <span> propertyName </span> <span title="Required" > * </span> </td> <td> <div> <span> This is a short description </span> </div> <div class="sb-argstableBlock-summary" > <div> <span class="sb-argstableBlock-code" > summary </span> </div> </div> </td> <td>
});
// A taller button grows downward: icons stay level, and the swatches and divider
// stay centered on a one-line button.
for (const button of actions.getAllByRole('button').filter((b) => !b.closest('[role=group]'))) {
if (!button.firstElementChild) throw new Error('Action icon missing');
await expect(centerY(button.firstElementChild)).toBeCloseTo(
centerY(copy.firstElementChild),
0,
);
}
await expect(centerY(actions.getByRole('group', { name: 'Highlight colors' }))).toBeCloseTo(
centerY(copy),
0,
);
await expect(discussion).toHaveAttribute('title', discussion.getAttribute('aria-label'));
await expect(copy).not.toHaveAttribute('title');
},
};
72 changes: 59 additions & 13 deletions packages/ui/src/components/verse-action-popover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -201,28 +201,70 @@ function highlightSwatchLabel(t: TFunction, color: string, showRemove: boolean):
type ActionButtonProps = {
icon: ReactNode;
label: string;
/** Full text on hover, for host labels that may be clamped. */
title?: string;
onClick: () => void;
onClickCapture?: () => void;
};

function ActionButton({ icon, label, onClick, onClickCapture }: ActionButtonProps) {
function ActionButton({ icon, label, title, onClick, onClickCapture }: ActionButtonProps) {
// CSS sizes a wrapped label to the 8rem cap rather than to its longest line, which
// leaves wider gaps beside it than between one-line actions. Shrink the label to its
// longest line, in em so zoom and text size keep the fit.
const labelRef = useRef<HTMLSpanElement>(null);
useLayoutEffect(() => {
const element = labelRef.current;
// Skip an element without layout, such as one rendered in jsdom.
if (!element?.offsetWidth) return;
const fit = (): void => {
element.style.inlineSize = '';
const range = element.ownerDocument.createRange();
range.selectNodeContents(element);
// Lines hidden by the two-line clamp still report rects; skip them. Rects include
// the bar's zoom-in transform, so divide it out.
const { bottom, width } = element.getBoundingClientRect();
const lines = Array.from(range.getClientRects())
.filter((line) => line.top < bottom)
.map((line) => line.width);
if (lines.length < 2) return;
const widest = (Math.max(...lines) * element.offsetWidth) / width;
const fontSize = Number.parseFloat(getComputedStyle(element).fontSize);
element.style.inlineSize = `${Math.ceil(widest) / fontSize}em`;
Comment on lines +226 to +232

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Mixed-direction labels shrink too far

Range.getClientRects() can return several text fragments for one line when a custom label mixes Arabic or Hebrew with Latin text. Taking the widest fragment makes inlineSize smaller than the complete line. Even a short label such as “حفظ في Notes” can then wrap unnecessarily or lose text to the two-line clamp.

Group fragments by their vertical position and measure each complete line before shrinking the label. Add a mixed-direction label to the story.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/ui/src/components/verse-action-popover.tsx
Line: 226-232

Comment:
**Mixed-direction labels shrink too far**

`Range.getClientRects()` can return several text fragments for one line when a custom label mixes Arabic or Hebrew with Latin text. Taking the widest fragment makes `inlineSize` smaller than the complete line. Even a short label such as “حفظ في Notes” can then wrap unnecessarily or lose text to the two-line clamp.

Group fragments by their vertical position and measure each complete line before shrinking the label. Add a mixed-direction label to the story.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Cursor Fix in Codex

};
fit();
// A web font that finishes loading changes the line widths.
const { fonts } = element.ownerDocument;
fonts.addEventListener('loadingdone', fit);
return () => fonts.removeEventListener('loadingdone', fit);
}, [label]);

return (
<button
type="button"
aria-label={label}
title={title}
onClick={onClick}
onClickCapture={onClickCapture}
className={cn(
'yv:flex yv:max-w-full yv:shrink-0 yv:flex-col yv:items-center yv:gap-1 yv:px-2 yv:py-1',
'yv:text-xs yv:text-foreground',
// A long host label wraps to two lines inside the 8rem cap; the bar top-aligns its
// items, so a taller button grows downward and every icon stays on one line.
'yv:flex yv:min-w-11 yv:max-w-32 yv:shrink-0 yv:flex-col yv:items-center yv:gap-1 yv:px-2 yv:py-1',
'yv:text-xs yv:text-foreground yv:text-center',
'yv:rounded-md yv:transition-colors yv:hover:bg-muted',
'yv:focus-visible:outline-none yv:focus-visible:ring-2 yv:focus-visible:ring-ring',
)}
>
<span aria-hidden="true" className="yv:inline-flex">
{icon}
</span>
<span className="yv:max-w-full yv:[overflow-wrap:anywhere]">{label}</span>
{/* A host label keeps its own direction, so its ellipsis follows its script. */}
<span
ref={labelRef}
dir="auto"
className="yv:line-clamp-2 yv:max-w-full yv:text-balance yv:[overflow-wrap:anywhere]"
>
{label}
</span>
</button>
);
}
Expand Down Expand Up @@ -572,7 +614,7 @@ export const VerseActionPopover: FC<VerseActionPopoverProps> = ({
'yv:bg-card yv:text-popover-foreground',
'yv:rounded-full yv:drop-shadow-[0px_4.8432px_20px_rgba(0,0,0,0.19)]',
'yv:px-4 yv:py-2',
'yv:flex yv:items-center yv:gap-1',
'yv:flex yv:items-start yv:gap-1',
// Never wider than the viewport (minus collision padding). When the
// swatch row can't fit, it scrolls inside instead of overflowing the
// screen. Radix sets `--radix-popover-content-available-width`, but
Expand Down Expand Up @@ -614,7 +656,7 @@ export const VerseActionPopover: FC<VerseActionPopoverProps> = ({
inert={!portal.open}
className={
view.scrollAllActions
? 'yv:flex yv:min-w-0 yv:items-center yv:gap-1 yv:overflow-x-auto yv:p-1 yv:-m-1'
? 'yv:flex yv:min-w-0 yv:items-start yv:gap-1 yv:overflow-x-auto yv:p-1 yv:-m-1'
: 'yv:contents'
}
>
Expand Down Expand Up @@ -652,16 +694,20 @@ export const VerseActionPopover: FC<VerseActionPopoverProps> = ({
key={`custom:${item.id}`}
icon={item.icon}
label={item.label}
title={item.label}
onClick={item.onSelect}
onClickCapture={markOverlayAction}
/>
);
}
if (!highlightsEnabled) return null;

// The row top-aligns, so the divider and swatches center on a
// one-line action button (3rem) and keep their place when a host
// label wraps.
const divider = (
<div
className="yv:mx-2 yv:w-px yv:h-8 yv:shrink-0 yv:bg-border"
className="yv:m-2 yv:w-px yv:h-8 yv:shrink-0 yv:bg-border"
aria-hidden="true"
/>
);
Expand All @@ -673,15 +719,15 @@ export const VerseActionPopover: FC<VerseActionPopoverProps> = ({
ref={view.scrollAllActions ? undefined : setSwatchRow}
// `min-w-0` lets this flex child actually shrink below its
// content size so `overflow-x-auto` engages instead of widening
// the pill. `py-1 -my-1` gives the hover:scale-110 swatches
// vertical breathing room inside the (now-clipping) scroll box
// without shifting the row's resting position. Scrollbar hidden;
// the edge fade signals there's more to scroll.
// the pill. `py-1` gives the hover:scale-110 swatches vertical
// breathing room inside the (now-clipping) scroll box, and `my-1`
// completes the 3rem band. Scrollbar hidden; the edge fade signals
// there's more to scroll.
className={cn(
'yv:flex yv:items-center yv:gap-2',
view.scrollAllActions
? 'yv:shrink-0'
: 'yv:min-w-0 yv:overflow-x-auto yv:scrollbar-hide yv:py-1 yv:-my-1',
? 'yv:my-2 yv:shrink-0'
: 'yv:min-w-0 yv:overflow-x-auto yv:scrollbar-hide yv:py-1 yv:my-1',
)}
style={view.scrollAllActions ? undefined : scrollFadeMask(scrollFade)}
role="group"
Expand Down
Loading