-
Notifications
You must be signed in to change notification settings - Fork 14
fix(stabilization): fix loadImageSrcset plugin #264
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
132 changes: 102 additions & 30 deletions
132
packages/browser/src/global/stabilization/plugins/loadImageSrcset.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,60 +1,132 @@ | ||
| import type { Plugin } from ".."; | ||
|
|
||
| /** | ||
| * Force the reload of srcset on resize. | ||
| * To ensure that if the viewport changes, it's the same behaviour | ||
| * as if the page was reloaded. | ||
| * Force srcset to resolve to the biggest candidate for the current run. | ||
| * This collapses srcset to a single candidate while staying consistent with | ||
| * descriptor rules from the spec. | ||
| */ | ||
| export const plugin = { | ||
| name: "loadImageSrcset" as const, | ||
| beforeEach(options) { | ||
| // If the user is not using viewports, do nothing. | ||
| if (!options.viewports || options.viewports.length === 0) { | ||
| return undefined; | ||
| } | ||
|
|
||
| function getLargestSrcFromSrcset(srcset: string) { | ||
| // Parse srcset into array of {url, width} | ||
| const sources = srcset | ||
| type ParsedCandidate = | ||
| | { url: string; kind: "w"; value: number } | ||
| | { url: string; kind: "x"; value: number } | ||
| | { url: string; kind: "none"; value: 1 }; | ||
|
|
||
| function parseSrcset(srcset: string): ParsedCandidate[] { | ||
| return srcset | ||
| .split(",") | ||
| .map((item) => { | ||
| const [url, size] = item.trim().split(/\s+/); | ||
| if (!url) { | ||
| return null; | ||
| .reduce<ParsedCandidate[]>((candidates, rawPart) => { | ||
| const part = rawPart.trim(); | ||
| if (!part) { | ||
| return candidates; | ||
| } | ||
|
|
||
| const tokens = part.split(/\s+/); | ||
| const maybeDescriptor = | ||
| tokens.length > 1 ? tokens[tokens.length - 1] : null; | ||
|
|
||
| if (maybeDescriptor && /^\d+w$/.test(maybeDescriptor)) { | ||
| const url = tokens.slice(0, -1).join(" "); | ||
| if (url) { | ||
| candidates.push({ | ||
| url, | ||
| kind: "w", | ||
| value: Number.parseInt(maybeDescriptor.slice(0, -1), 10), | ||
| }); | ||
| } | ||
| return candidates; | ||
| } | ||
| // Only handle width descriptors (e.g., 800w) | ||
| const widthMatch = size && size.match(/^(\d+)w$/); | ||
| if (!widthMatch) { | ||
| return { url, width: 0 }; | ||
|
|
||
| if (maybeDescriptor && /^\d+\.?\d*x$/.test(maybeDescriptor)) { | ||
| const url = tokens.slice(0, -1).join(" "); | ||
| if (url) { | ||
| candidates.push({ | ||
| url, | ||
| kind: "x", | ||
| value: Number.parseFloat(maybeDescriptor.slice(0, -1)), | ||
| }); | ||
| } | ||
| return candidates; | ||
| } | ||
|
|
||
| const url = tokens[0] ?? ""; | ||
| if (url) { | ||
| candidates.push({ url, kind: "none", value: 1 }); | ||
| } | ||
| const width = parseInt(widthMatch[1]!, 10); | ||
| return { url, width }; | ||
| }) | ||
| .filter((x) => x !== null); | ||
|
|
||
| if (sources.length === 0) { | ||
| return srcset; | ||
| return candidates; | ||
| }, []); | ||
| } | ||
|
|
||
| function pickLargestCandidate( | ||
| candidates: ParsedCandidate[], | ||
| ): ParsedCandidate | null { | ||
| let winner: ParsedCandidate | null = null; | ||
| let kind: ParsedCandidate["kind"] | null = null; | ||
|
|
||
| for (const candidate of candidates) { | ||
| if (kind !== null && candidate.kind !== kind) { | ||
| return null; | ||
| } | ||
|
|
||
| kind ??= candidate.kind; | ||
|
|
||
| if (winner === null || candidate.value > winner.value) { | ||
| winner = candidate; | ||
| } | ||
| } | ||
|
|
||
| // Find the source with the largest width | ||
| const largest = sources.reduce((max, curr) => | ||
| curr.width > max.width ? curr : max, | ||
| ); | ||
| return winner; | ||
| } | ||
|
|
||
| // Return only the largest source as srcset | ||
| return largest.url; | ||
| function candidateToSingleSrcset( | ||
| candidate: ParsedCandidate, | ||
| requireW: boolean, | ||
| ): string { | ||
| if (candidate.kind === "none") { | ||
| return requireW ? `${candidate.url} 1w` : candidate.url; | ||
| } | ||
|
|
||
| return `${candidate.url} ${candidate.value}${candidate.kind}`; | ||
| } | ||
|
|
||
| function forceSrcsetReload(img: Element) { | ||
| const srcset = img.getAttribute("srcset"); | ||
| function forceSrcsetReload(el: Element): void { | ||
| const srcset = el.getAttribute("srcset"); | ||
| if (!srcset) { | ||
| return; | ||
| } | ||
| img.setAttribute("srcset", getLargestSrcFromSrcset(srcset)); | ||
|
|
||
| const candidates = parseSrcset(srcset); | ||
| const chosen = pickLargestCandidate(candidates); | ||
| if (!chosen) { | ||
| return; | ||
| } | ||
|
|
||
| const requireW = | ||
| el.hasAttribute("sizes") || | ||
| chosen.kind === "w" || | ||
| candidates.some((c) => c.kind === "w"); | ||
|
|
||
| el.setAttribute("srcset", ""); | ||
|
|
||
| if (el instanceof HTMLImageElement) { | ||
| el.src = chosen.url; | ||
| } | ||
|
|
||
| void el.clientWidth; | ||
|
|
||
| el.setAttribute("srcset", candidateToSingleSrcset(chosen, requireW)); | ||
| } | ||
|
|
||
| Array.from(document.querySelectorAll("img,source")).forEach( | ||
| forceSrcsetReload, | ||
| ); | ||
|
|
||
| return undefined; | ||
| }, | ||
| } satisfies Plugin; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.