Skip to content

Commit 4fdc68f

Browse files
wesbillmanBrainPinky
authored
fix(desktop): stabilize channel-timeline scrollback with per-row height reserves (#1413)
Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co> Co-authored-by: Pinky <44b8e82baa6e0e254e0208d68f335c283c94e7b78dd1fa10d5a49d3f13dd0435@sprout-oss.stage.blox.sqprod.co>
1 parent 697f63d commit 4fdc68f

6 files changed

Lines changed: 620 additions & 23 deletions

File tree

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
import assert from "node:assert/strict";
2+
import { test } from "node:test";
3+
4+
import {
5+
estimateRowHeight,
6+
timelineRowReserveStyle,
7+
} from "./rowHeightEstimate.ts";
8+
9+
function msg(over = {}) {
10+
return {
11+
id: "m1",
12+
createdAt: 0,
13+
author: "a",
14+
time: "now",
15+
body: "",
16+
depth: 0,
17+
...over,
18+
};
19+
}
20+
21+
test("estimateRowHeight: short text is near the floor", () => {
22+
const h = estimateRowHeight(msg({ body: "hello" }));
23+
assert.ok(h >= 60 && h < 120, `expected small, got ${h}`);
24+
});
25+
26+
test("estimateRowHeight: many lines reserve more", () => {
27+
const tall = estimateRowHeight(
28+
msg({ body: Array.from({ length: 20 }, (_, i) => `line ${i}`).join("\n") }),
29+
);
30+
const short = estimateRowHeight(msg({ body: "one line" }));
31+
assert.ok(tall > short + 200, `tall ${tall} vs short ${short}`);
32+
});
33+
34+
test("estimateRowHeight: fenced code adds height by line", () => {
35+
const withCode = estimateRowHeight(
36+
msg({ body: "see:\n```\na\nb\nc\nd\ne\n```" }),
37+
);
38+
const withoutCode = estimateRowHeight(msg({ body: "see:" }));
39+
assert.ok(withCode > withoutCode + 80, `code ${withCode} vs ${withoutCode}`);
40+
});
41+
42+
test("estimateRowHeight: imeta image with dim reserves bounded media height", () => {
43+
const tagged = estimateRowHeight(
44+
msg({
45+
body: "shot",
46+
tags: [["imeta", "url http://x/a.png", "m image/png", "dim 320x240"]],
47+
}),
48+
);
49+
// 320x240 -> 4:3, width-bound 384/(4/3)=288 capped at 256, plus chrome+text.
50+
assert.ok(tagged >= 256 && tagged <= 360, `got ${tagged}`);
51+
});
52+
53+
test("estimateRowHeight: dim-less imeta reserves the full media box", () => {
54+
const noDim = estimateRowHeight(
55+
msg({
56+
body: "shot",
57+
tags: [["imeta", "url http://x/a.png", "m image/png"]],
58+
}),
59+
);
60+
assert.ok(noDim >= 256, `got ${noDim}`);
61+
});
62+
63+
test("estimateRowHeight: markdown image with NO imeta reserves media box", () => {
64+
const h = estimateRowHeight(
65+
msg({ body: "look\n![](https://example.com/pic.png)" }),
66+
);
67+
assert.ok(h >= 256, `expected full media reserve, got ${h}`);
68+
});
69+
70+
test("estimateRowHeight: bare media URL line reserves media box, not a card", () => {
71+
const h = estimateRowHeight(msg({ body: "https://example.com/clip.mp4" }));
72+
assert.ok(h >= 256, `expected media reserve, got ${h}`);
73+
});
74+
75+
test("estimateRowHeight: imeta dim is not double-counted with its body url", () => {
76+
const url = "https://x/a.png";
77+
const both = estimateRowHeight(
78+
msg({
79+
body: `![](${url})`,
80+
tags: [["imeta", `url ${url}`, "m image/png", "dim 320x240"]],
81+
}),
82+
);
83+
// One media reserve (~256 capped) + chrome, not two.
84+
assert.ok(both < 400, `expected single media reserve, got ${both}`);
85+
});
86+
87+
test("estimateRowHeight: bare URL line adds a preview card", () => {
88+
const withUrl = estimateRowHeight(msg({ body: "https://example.com/x" }));
89+
const withoutUrl = estimateRowHeight(msg({ body: "example" }));
90+
assert.ok(withUrl > withoutUrl + 80, `url ${withUrl} vs ${withoutUrl}`);
91+
});
92+
93+
test("timelineRowReserveStyle: message item yields containIntrinsicSize", () => {
94+
const style = timelineRowReserveStyle({
95+
kind: "message",
96+
key: "k",
97+
entry: { message: msg({ body: "hi" }), summary: null },
98+
});
99+
assert.match(String(style.containIntrinsicSize), /^auto \d+px$/);
100+
});
101+
102+
test("timelineRowReserveStyle: divider is short fixed height", () => {
103+
const style = timelineRowReserveStyle({
104+
kind: "day-divider",
105+
key: "k",
106+
headingTimestamp: 0,
107+
});
108+
assert.equal(style.containIntrinsicSize, "auto 32px");
109+
});
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
import type * as React from "react";
2+
3+
import { aspectRatioFromDim } from "@/shared/ui/markdown/utils";
4+
import type { TimelineItem } from "./timelineItems";
5+
import type { TimelineMessage } from "../types";
6+
import { parseImetaTags } from "./parseImeta";
7+
8+
/**
9+
* Estimate a timeline row's rendered height so its `content-visibility`
10+
* placeholder reserves credible space BEFORE first paint. A flat placeholder
11+
* makes a never-painted media/code row snap from the floor to its true height
12+
* as it realizes on scroll-up — the teleport. The browser's `auto` keyword
13+
* still refines the size once the row paints; this only has to make that first
14+
* realization land near-correct, not exact.
15+
*
16+
* Deliberately conservative and cheap (no DOM, no markdown parse): row chrome
17+
* + a line-count estimate for text/code + known media `dim`s. Over-reserving a
18+
* little is harmless (a small downward settle); under-reserving by a lot is the
19+
* jump we're killing.
20+
*/
21+
22+
// Visual caps mirror the inline image/markdown styles.
23+
const MEDIA_MAX_WIDTH = 384; // max-w-[min(24rem,100%)]
24+
const MEDIA_MAX_HEIGHT = 256; // max-h-64
25+
const TEXT_LINE_HEIGHT = 22;
26+
const CODE_LINE_HEIGHT = 19;
27+
const CHARS_PER_LINE = 64; // rough wrap width at the timeline column
28+
const ROW_CHROME = 34; // author/time header + row padding
29+
const REACTION_ROW = 28;
30+
const PREVIEW_CARD = 96;
31+
const MIN_ESTIMATE = 60; // never reserve less than the old flat floor
32+
33+
function mediaHeightFromDim(dim: string | undefined): number {
34+
const ratio = aspectRatioFromDim(dim);
35+
if (!ratio || ratio <= 0) return MEDIA_MAX_HEIGHT; // unknown shape: reserve full box
36+
const widthBoundHeight = MEDIA_MAX_WIDTH / ratio;
37+
return Math.round(Math.min(MEDIA_MAX_HEIGHT, widthBoundHeight));
38+
}
39+
40+
function wrappedLineCount(text: string): number {
41+
let lines = 0;
42+
for (const raw of text.split("\n")) {
43+
lines += Math.max(1, Math.ceil(raw.length / CHARS_PER_LINE));
44+
}
45+
return lines;
46+
}
47+
48+
/**
49+
* Strip fenced code blocks from the body, returning the prose remainder and the
50+
* total number of code lines (for separate mono line-height accounting).
51+
*/
52+
function splitFencedCode(body: string): { prose: string; codeLines: number } {
53+
const parts = body.split(/```/);
54+
// Even indices are prose, odd indices are inside a fence.
55+
let prose = "";
56+
let codeLines = 0;
57+
for (let i = 0; i < parts.length; i += 1) {
58+
if (i % 2 === 1) {
59+
codeLines += parts[i].split("\n").length;
60+
} else {
61+
prose += parts[i];
62+
}
63+
}
64+
return { prose, codeLines };
65+
}
66+
67+
// Image/video file extensions the markdown renderer turns into inline media.
68+
const MEDIA_URL_RE =
69+
/https?:\/\/\S+\.(?:png|jpe?g|gif|webp|avif|svg|mp4|webm|mov)(?:\?\S*)?$/i;
70+
71+
/**
72+
* URLs in the body that the markdown renderer shows as inline `<img>`/`<video>`:
73+
* `![alt](url)` markdown images and bare media URLs on their own line. Used to
74+
* reserve media height for dim-less inline media (no imeta tag).
75+
*/
76+
function mediaUrlsInBody(body: string): string[] {
77+
const urls: string[] = [];
78+
for (const match of body.matchAll(/!\[[^\]]*\]\(([^)\s]+)\)/g)) {
79+
urls.push(match[1]);
80+
}
81+
for (const line of body.split("\n")) {
82+
const trimmed = line.trim();
83+
if (MEDIA_URL_RE.test(trimmed)) urls.push(trimmed);
84+
}
85+
return urls;
86+
}
87+
88+
export function estimateRowHeight(message: TimelineMessage): number {
89+
const body = message.body ?? "";
90+
const { prose, codeLines } = splitFencedCode(body);
91+
92+
let height = ROW_CHROME;
93+
height +=
94+
wrappedLineCount(prose.trim() === "" ? "" : prose) * TEXT_LINE_HEIGHT;
95+
height += codeLines * CODE_LINE_HEIGHT;
96+
97+
const imetaUrls = new Set<string>();
98+
if (message.tags && message.tags.length > 0) {
99+
const imeta = parseImetaTags(message.tags);
100+
for (const entry of imeta.values()) {
101+
if (!entry.url) continue;
102+
imetaUrls.add(entry.url);
103+
height += mediaHeightFromDim(entry.dim);
104+
}
105+
}
106+
for (const url of mediaUrlsInBody(body)) {
107+
if (imetaUrls.has(url)) continue; // already counted via its imeta dim
108+
height += MEDIA_MAX_HEIGHT; // dim-less inline media: reserve the full box
109+
}
110+
111+
// A bare non-media URL on its own line usually renders a link-preview card.
112+
const hasPreviewUrlLine = body
113+
.split("\n")
114+
.some(
115+
(line) =>
116+
/^\s*https?:\/\/\S+\s*$/.test(line) && !MEDIA_URL_RE.test(line.trim()),
117+
);
118+
if (hasPreviewUrlLine) height += PREVIEW_CARD;
119+
120+
if (message.reactions && message.reactions.length > 0) height += REACTION_ROW;
121+
122+
return Math.max(MIN_ESTIMATE, Math.round(height));
123+
}
124+
125+
// Dividers are short, fixed-height rows; reserving their true height keeps the
126+
// estimate honest without a content scan.
127+
const DIVIDER_HEIGHT = 32;
128+
129+
/**
130+
* `contain-intrinsic-size` for a `timeline-row-cv` wrapper. A credible per-row
131+
* reserve replaces the flat 60px placeholder so a never-painted row realizes
132+
* near its true height instead of snapping the scroll position. `auto` keeps
133+
* refining once the row paints.
134+
*/
135+
export function timelineRowReserveStyle(
136+
item: TimelineItem,
137+
): React.CSSProperties {
138+
const height =
139+
item.kind === "message" || item.kind === "system"
140+
? estimateRowHeight(item.entry.message)
141+
: DIVIDER_HEIGHT;
142+
return { containIntrinsicSize: `auto ${height}px` };
143+
}

‎desktop/src/features/messages/ui/TimelineMessageList.tsx‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as React from "react";
22

33
import { formatDayHeading } from "@/features/messages/lib/dateFormatters";
4+
import { timelineRowReserveStyle } from "@/features/messages/lib/rowHeightEstimate";
45
import {
56
buildTimelineItems,
67
getTimelineItemKey,
@@ -245,7 +246,11 @@ export const TimelineMessageList = React.memo(function TimelineMessageList({
245246
return (
246247
<div className="flex flex-col">
247248
{itemsResult.items.map((item) => (
248-
<div className="timeline-row-cv" key={getTimelineItemKey(item)}>
249+
<div
250+
className="timeline-row-cv"
251+
key={getTimelineItemKey(item)}
252+
style={timelineRowReserveStyle(item)}
253+
>
249254
{renderItem(item)}
250255
</div>
251256
))}

‎desktop/src/shared/ui/markdown.tsx‎

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -78,9 +78,13 @@ import { SpoilerInline } from "./markdown/SpoilerInline";
7878
import {
7979
aspectRatioFromDim,
8080
dimensionsFromDim,
81+
getDecodedImageDimensions,
82+
imageReserveStyle,
8183
isInsideHiddenSpoiler,
8284
getReactNodeText,
8385
messageLinkUrlTransform,
86+
rememberDecodedImageDimensions,
87+
useFrozenImageReserve,
8488
useStableArray,
8589
} from "./markdown/utils";
8690
import { VideoPlayer, type VideoReviewContext } from "./VideoPlayer";
@@ -293,7 +297,8 @@ function imageLightboxBasisBoxForItem(
293297
item: ImageGalleryItem,
294298
fallbackBox: ImageLightboxBox,
295299
): ImageLightboxBox {
296-
const dimensions = dimensionsFromDim(item.dim);
300+
const dimensions =
301+
dimensionsFromDim(item.dim) ?? getDecodedImageDimensions(item.resolvedSrc);
297302
if (!dimensions) {
298303
return item.thumbnailBox ?? fallbackBox;
299304
}
@@ -1330,12 +1335,29 @@ function ImageBlock({ alt, dim, resolvedSrc, src }: ImageBlockProps) {
13301335
[resolvedSrc],
13311336
);
13321337

1338+
const handleImageLoad = React.useCallback(
1339+
(image: HTMLImageElement) => {
1340+
rememberDecodedImageDimensions(
1341+
resolvedSrc,
1342+
image.naturalWidth,
1343+
image.naturalHeight,
1344+
);
1345+
updateSpoilerMediaSize(image);
1346+
},
1347+
[resolvedSrc, updateSpoilerMediaSize],
1348+
);
1349+
13331350
const imageRef = React.useCallback(
13341351
(image: HTMLImageElement | null) => {
13351352
inlineImageRef.current = image;
1336-
if (image?.complete) updateSpoilerMediaSize(image);
1353+
if (image?.complete) handleImageLoad(image);
13371354
},
1338-
[updateSpoilerMediaSize],
1355+
[handleImageLoad],
1356+
);
1357+
1358+
const { intrinsicDimensions, useFixedReserveBox } = useFrozenImageReserve(
1359+
dim,
1360+
resolvedSrc,
13391361
);
13401362

13411363
const currentSpoilerMediaSize =
@@ -1344,15 +1366,11 @@ function ImageBlock({ alt, dim, resolvedSrc, src }: ImageBlockProps) {
13441366
? currentSpoilerMediaSize
13451367
: null;
13461368

1347-
const spoilerMediaStyle = hiddenSpoilerMediaSize
1348-
? ({
1349-
"--buzz-spoiler-media-aspect-ratio": `${hiddenSpoilerMediaSize.width} / ${hiddenSpoilerMediaSize.height}`,
1350-
"--buzz-spoiler-media-width": `${hiddenSpoilerMediaSize.width}px`,
1351-
aspectRatio: `${hiddenSpoilerMediaSize.width} / ${hiddenSpoilerMediaSize.height}`,
1352-
height: "auto",
1353-
width: `${hiddenSpoilerMediaSize.width}px`,
1354-
} as React.CSSProperties)
1355-
: undefined;
1369+
const spoilerMediaStyle = imageReserveStyle({
1370+
hiddenSpoilerMediaSize,
1371+
intrinsicDimensions,
1372+
useFixedReserveBox,
1373+
});
13561374

13571375
React.useLayoutEffect(() => {
13581376
const trigger = triggerRef.current;
@@ -1379,12 +1397,6 @@ function ImageBlock({ alt, dim, resolvedSrc, src }: ImageBlockProps) {
13791397
const closeMenu = React.useCallback(() => setMenu(null), []);
13801398
useDismissImageContextMenu(Boolean(menu), closeMenu);
13811399

1382-
// Intrinsic dimensions from the NIP-92 `dim` tag, stamped as width/height
1383-
// attributes so the browser reserves aspect-ratio space before the image
1384-
// decodes. Without this the row grows from ~0 on load and shoves the
1385-
// timeline — the exact reflow the anchored-scroll restore then has to fight.
1386-
const intrinsicDimensions = dimensionsFromDim(dim);
1387-
13881400
const handleContextMenu = (e: React.MouseEvent) => {
13891401
e.preventDefault();
13901402
if (isInsideHiddenSpoiler(e.currentTarget)) return;
@@ -1471,12 +1483,12 @@ function ImageBlock({ alt, dim, resolvedSrc, src }: ImageBlockProps) {
14711483
alt={alt}
14721484
className="block h-auto max-h-64 max-w-[min(24rem,100%)] rounded-xl object-contain"
14731485
data-spoiler-media-size={hiddenSpoilerMediaSize ? "" : undefined}
1474-
height={intrinsicDimensions?.height}
1486+
height={intrinsicDimensions.height}
14751487
ref={imageRef}
14761488
src={resolvedSrc}
14771489
style={spoilerMediaStyle}
1478-
width={intrinsicDimensions?.width}
1479-
onLoad={(event) => updateSpoilerMediaSize(event.currentTarget)}
1490+
width={intrinsicDimensions.width}
1491+
onLoad={(event) => handleImageLoad(event.currentTarget)}
14801492
/>
14811493
</button>
14821494
{menu && src ? (

0 commit comments

Comments
 (0)