Don't show "Read more" if the read more link takes more room than showing the content
Problem
We need to include the height of the read more link in our computation for deciding whether to show "Read more"
https://github.com/user-attachments/assets/ec81c8ba-edfb-451e-8a43-ac5a5bc68397
Reproducing the bug
- Go to https://openlibrary.org/books/OL25998417M/A_Night_With_Consequences
- Expected behavior: Description should not be collapsed
- Actual behavior: Description is collapsed with read more
Context
NA
Breakdown
Implementation Details (for maintainers)
Requirements Checklist
- [ ]
Related files
Stakeholders
- @lokesh
Instructions for Contributors
- Please run these commands to ensure your repository is up to date before creating a new branch to work on this issue and each time after pushing code to Github, because the pre-commit bot may add commits to your PRs upstream.
⚠️ Contributors, this issue will be ready to work on once:
- [ ] Triage — maintainers will add
Priority: *andLead: @*to replaceNeeds: TriageandNeeds: Lead - [ ] Needs: Breakdown — implementation checklist in the issue body has not been filled in
Context
The component lives in openlibrary/components/lit/OLReadMore.js (introduced in #11666). The decision to show or hide the "Read More" button is made in _checkIfTruncationNeeded() (lines 158–168):
_checkIfTruncationNeeded() {
const content = this.shadowRoot.querySelector('.content-wrapper');
if (!content) return;
const isOverflowing = content.scrollHeight > content.clientHeight;
this._unnecessary = !isOverflowing;
...
}
This checks for any overflow against maxHeight, but does not account for the button's own rendered height (~41px for medium label, ~27px for small — noted in the component's constructor comment). When content overflows maxHeight by less than the button height, showing the button makes the total rendered height larger than simply displaying the full content.
Issue Assessment
Suggested breakdown:
- [ ] In
_checkIfTruncationNeeded(), query the.toggle-btn.moreelement'soffsetHeightafter the component renders (available infirstUpdated()) - [ ] Update the overflow check: only truncate when
content.scrollHeight > content.clientHeight + toggleBtnHeight - [ ] Verify the fix using the reproduction URL — description should no longer be collapsed after the change
Full triage checklist (maintainers / Richy)
- [x] Triage — correct labels applied or removed
- [x] Problem / opportunity — problem is clear, audience identified, actionable
- [x] Scope — issue is well-scoped; single component, single method
- [ ] Justification — quantified impact not stated (how many pages/descriptions are affected?)
- [x] Success & testing criteria — defines what "done" looks like, verifiable via the reproduction URL
- [ ] Proposal & breakdown — implementation checklist in issue body is empty
- [ ] If bug: environment & repro steps — no browser/version specified (reproduction URL and video provided)
- [ ] Risks, concerns, open questions — none surfaced (e.g. does querying
offsetHeightbefore layout settle cause issues in all browsers?) - [x] Richy context — relevant code and originating PR reviewed; no duplicate issue found
- [x] References — video and reproduction URL present
[!NOTE] This comment was automatically generated by Richy, via PAM, Open Library's Project AI Manager, on behalf of @mekarpeles. Richy is designed to provide status visibility, perform basic project management functions and relevant codebase research, and provide actionable feedback so contributors aren't left waiting.
Hi! I'd love to work on this issue. I've done a analysis of the layout math and the component's structure, and I have a clean, robust fix ready to implement.
🔍 Analysis of the Bug
The root cause is indeed that _checkIfTruncationNeeded() in OLReadMore.js does not account for the toggle button's own rendered height.
When the content overflow is less than the button's height, collapsing the content and showing the button actually consumes more vertical space than just displaying the full uncollapsed text.
Here is the exact CSS box-model layout math confirming why 41px and 27px are the precise thresholds:
- Medium Label (Default - 41px):
padding-top(--spacing-inset-lg=24px) +padding-bottom(--spacing-md=12px) +text-height(17px) -margin-topoffset (12px) =41px.
- Small Label (27px):
padding-top(--spacing-inset-md=16px) +padding-bottom(--spacing-inset-sm=8px) +text-height(15px) -margin-topoffset (12px) =27px.
🛠️ Proposed Solution
I propose updating _checkIfTruncationNeeded() in openlibrary/components/lit/OLReadMore.js to measure the button's height. To make the fix robust against edge cases (such as the component rendering inside an initially hidden container like display: none where offsetHeight is 0), I will include a safe fallback to the exact JSDoc-documented values:
_checkIfTruncationNeeded() {
const content = this.shadowRoot.querySelector('.content-wrapper');
if (!content) return;
const toggleBtn = this.shadowRoot.querySelector('.toggle-btn.more');
// Measure actual rendered height, falling back to documented values if hidden (offsetHeight === 0)
const toggleBtnHeight = toggleBtn && toggleBtn.offsetHeight > 0
? toggleBtn.offsetHeight
: (this.labelSize === 'small' ? 27 : 41);
const isOverflowing = content.scrollHeight > content.clientHeight + toggleBtnHeight;
this._unnecessary = !isOverflowing;
if (this._unnecessary) {
this._expanded = true;
}
}
This perfectly solves the reproduction case (like on /books/OL25998417M) so that short descriptions are no longer collapsed unnecessarily, while remaining fully backward-compatible and robust.
I have my local Docker environment active and can submit a self-contained PR passing all linters and tests. Please let me know if I can go ahead and be assigned this!
I have opened Pull Request #13059 with a robust and minimal fix that should resolve this issue.
The solution dynamically incorporates the toggle button's height (toggleBtn.offsetHeight) directly into the truncation threshold calculation of ol-read-more. This ensures that short descriptions slightly exceeding 80px are no longer collapsed unnecessarily, while also maintaining a reliable fallback to CSS defaults (41px / 27px) for edge-case rendering inside hidden or unmounted containers.
The PR has been fully linted and verified locally on the developer design system.
Any feedback or suggestions regarding the proposed implementation would be greatly appreciated.
Thanks @RsbhThakur. Before we go further on #13059, I'd like to rethink the approach rather than tune the math.
The direction in #13059 is right, but it's still trying to compute a precise break-even point (maxHeight + button height), and that's where I think we go wrong. Two problems:
1. It's fragile. The button's "height" isn't one number. .toggle-btn.more has a -12px negative margin-top, so its real footprint is offsetHeight - 12 (~41px), not offsetHeight (~53px). The PR uses raw offsetHeight in the live path but the documented 41 in the fallback, so the two branches disagree by 12px. Any padding or font tweak silently shifts the threshold again.
2. The UX it produces is awkward. Even with perfect math, content that's barely over the break-even gets collapsed to save almost nothing:
Current logic (break-even math):
content ≤ 80px → show all
80px < content ≤ 121px → show all (the #13059 fix)
content > 121px → collapse to 80px + "Read more"
▲
at 122px we collapse and hide a
couple lines behind a click to
save ~1px. not worth a button.
Proposal: go blunt. Drop the break-even math entirely.
Proposed (blunt rule):
content ≤ X → show all, no button
content > X → collapse substantially (~half) + "Read more"
▲
when we collapse we always hide a real chunk,
so the button always earns its place.
content taller than X:
full (e.g. 200px) collapsed (blunt rule)
┌────────────────────┐ ┌────────────────────┐
│ line 1 │ │ line 1 │
│ line 2 │ │ line 2 │
│ line 3 │ │ line 3 ░░░ fade ░░ │
│ line 4 │ ├────────────────────┤
│ line 5 │ │ Read more ⌄ │
│ line 6 │ └────────────────────┘
│ ... │
└────────────────────┘
Recommended heights. .book-description is ~18px/line (12px text, ~1.5 line-height), and the button costs ~2 lines. So:
- X (show everything) ≈ 10 lines (~180px). Most descriptions fall under this and just render in full.
- Collapsed height ≈ 5 lines (~90px), i.e. half of X (close to today's 80px).
When we do collapse, content is 10+ lines and we show 5, so we're always hiding 5+ lines, well past the ~2-line button cost. The gap between the 5-line collapsed height and the 10-line ceiling is the point: it's what stops us collapsing a 6-line description to save almost nothing. Expressing both as line-height multiples also kills the hand-measured constants that drift.
The one tradeoff is we'd show more descriptions in full than today (anything under X). I think that's the better default. Seeing the whole description beats a button that saves a few pixels.
@cdrini what do you think on direction? Happy to tweak the 10/5 split.
If I understand you correctly, you're proposing using a fixed-size "buffer" instead of computing the button size, right?
That makes sense to me. The benefit of computing the button size is that we can ensure it's always greater; it should likely always have a buffer! But if we choose a fixed number that is very likely to always be greater regardless of user fonts/sizes/etc, that should be fine and simpler.
IIRC this is the part of relevance, where we check if truncation is necessary:
https://github.com/internetarchive/openlibrary/blob/863c8336fcd2150f11dedd4ea4ab02811d6db290/openlibrary/components/lit/OLReadMore.js#L158-L168
Both approaches I believe add a buffer, right, for how many pixels are worth saving? So we'd change this to const isOverflowingEnough = content.scrollHeight > content.clientHeight + 80px; // or some buffer .
Is that what you mean?
yeah exactly. The buffer should be sized for "is a click worth it" (~4–5 lines), not "bigger than the button" (~41px). The scenario where you click the 'read more' button and it reveals one line is frustrating "why did you hide that one line, just show it to me!?" - user.
We could set the buffer to 80px or similar and keep it simple. The other route is to add some code to calculate the height of a line and multiply by the number of minimum lines we would want to have hidden...
// Number of lines worth hiding before a "Read more" button earns its place.
// Expressed in lines (not px) so font/spacing tweaks don't silently shift the threshold.
static BUFFER_LINES = 5;
/**
* Resolve an element's line-height to px, approximating `normal` from font-size.
*/
_getLineHeight(el) {
const cs = getComputedStyle(el);
const lh = parseFloat(cs.lineHeight);
// `line-height: normal` parses to NaN — fall back to a typical ratio.
return Number.isNaN(lh) ? parseFloat(cs.fontSize) * 1.5 : lh;
}
_checkIfTruncationNeeded() {
const content = this.shadowRoot.querySelector('.content-wrapper');
if (!content) return;
// Measure the real slotted text, not the shadow wrapper — the wrapper
// inherits the host's line-height, which may differ from the content's.
const slot = this.shadowRoot.querySelector('slot');
const sample = slot?.assignedElements?.()[0] ?? content;
const buffer = OLReadMore.BUFFER_LINES * this._getLineHeight(sample);
const isOverflowingEnough = content.scrollHeight > content.clientHeight + buffer;
this._unnecessary = !isOverflowingEnough;
if (this._unnecessary) {
this._expanded = true;
}
}
@lokesh @cdrini Thank you both for the incredibly thoughtful review and feedback!
I have to apologize—in my focus on making the mathematical threshold completely robust against hidden container edge-cases, I definitely overlooked the broader UX boundary perspective. You are absolutely spot-on: collapsing a 6-line description to save virtually nothing while adding a 2-line button is an awkward interaction that frustrates the reader.
The proposed approach with BUFFER_LINES is a much more elegant and robust solution.
I also did some responsive design verification on how this lines-based buffer behaves across different viewports:
- On Desktop (Wide Viewport): Short-to-medium descriptions wrap into fewer lines. Since
scrollHeightnaturally stays below the threshold, the component correctly renders them in full without showing an unnecessary toggle button. - On Mobile (Narrow Viewport): The exact same text wraps into more lines, raising the
scrollHeightand naturally triggering the truncation threshold. This is perfect because saving vertical space on mobile is highly critical, so collapsing the text and showing the button is fully justified. - Dynamic Scaling: By querying the active slotted element's computed
line-height(and fallbackfont-size), the buffer scales automatically even if the page utilizes responsive typography overrides on smaller screens.
I am completely aligned with this direction and will update the PR to implement this dynamic line-height-based buffer approach. Pushing the updated commit shortly!
I've updated the PR to implement the line-height buffer-based approach.
The component now calculates the threshold using the assigned element's computed line-height and a BUFFER_LINES = 5 threshold. The content is only collapsed if doing so saves more than 5 lines of vertical space—otherwise, it displays fully and hides the button.
Please let me know if you have any further suggestions or if anything else should be adjusted!