Prepare 4.0.5 Firefox update and Shorts fixes

Add Firefox data consent, repair contributor sign-in, and introduce optional Hide clutter buttons. Harden video navigation, voting, and action layouts with shared browser regression coverage and reproducible release packaging.
This commit is contained in:
Anarios committed 2026-09-06 12:51:12 +02:00
1 parent 3657de9b2c
commit e500088e65
196 files changed
+39706 -2694

No files matched your search

@@ -0,0 +1,73 @@
function defaultGetActivationTarget(control) {
if (control?.matches?.("button, tp-yt-paper-button#button")) {
return control;
}
return control?.querySelector?.("button, tp-yt-paper-button#button") ?? control ?? null;
}
function isHiddenWithinButtons(activationTarget, buttons) {
let current = activationTarget;
while (current) {
if (
current.hidden === true ||
current.getAttribute?.("aria-hidden") === "true" ||
current.hasAttribute?.("inert") ||
current.style?.display === "none" ||
current.style?.visibility === "hidden"
) {
return true;
}
if (current === buttons) {
return false;
}
current = current.parentElement;
}
return true;
}
function eventActivatesTarget(event, activationTarget) {
const eventPath = typeof event?.composedPath === "function" ? event.composedPath() : [];
if (eventPath.includes(activationTarget)) {
return true;
}
const eventTarget = event?.target;
return Boolean(eventTarget && activationTarget?.contains?.(eventTarget));
}
function resolveDelegatedVoteActivation({
buttons,
dislikeButton,
event,
getActivationTarget = defaultGetActivationTarget,
likeButton,
}) {
if (!event || !buttons?.isConnected) {
return null;
}
for (const [action, control] of [
["dislike", dislikeButton],
["like", likeButton],
]) {
if (!control?.isConnected || !buttons.contains(control)) {
continue;
}
const activationTarget = getActivationTarget(control);
if (
!activationTarget?.isConnected ||
!control.contains(activationTarget) ||
isHiddenWithinButtons(activationTarget, buttons) ||
activationTarget.disabled === true ||
activationTarget.getAttribute?.("aria-disabled") === "true"
) {
continue;
}
if (eventActivatesTarget(event, activationTarget)) {
return { action, activationTarget };
}
}
return null;
}
export { resolveDelegatedVoteActivation };
@@ -0,0 +1,99 @@
/** @jest-environment jsdom */
import { resolveDelegatedVoteActivation } from "./delegated-vote-activation";
function createReactionTree() {
const buttons = document.createElement("div");
const likeButton = document.createElement("like-button-view-model");
const dislikeButton = document.createElement("dislike-button-view-model");
likeButton.innerHTML = '<button type="button"><span data-target="like"></span></button>';
dislikeButton.innerHTML = '<button type="button"><span data-target="dislike"></span></button>';
buttons.append(likeButton, dislikeButton);
document.body.append(buttons);
return { buttons, dislikeButton, likeButton };
}
function clickEventFor(target) {
return {
composedPath: () => [target, target.parentElement],
target,
};
}
describe("delegated vote activation", () => {
test.each([
["like", "likeButton"],
["dislike", "dislikeButton"],
])("resolves the current %s activation target", (action, controlName) => {
const tree = createReactionTree();
const activationTarget = tree[controlName].querySelector("button");
expect(resolveDelegatedVoteActivation({ ...tree, event: clickEventFor(activationTarget) })).toEqual({
action,
activationTarget,
});
});
test("accepts a synchronously cloned current control without prior binding", () => {
const tree = createReactionTree();
const replacement = tree.dislikeButton.cloneNode(true);
tree.dislikeButton.replaceWith(replacement);
tree.dislikeButton = replacement;
const activationTarget = replacement.querySelector("button");
expect(resolveDelegatedVoteActivation({ ...tree, event: clickEventFor(activationTarget) })).toEqual({
action: "dislike",
activationTarget,
});
});
test.each([
["like", "likeButton", "dislikeButton"],
["dislike", "dislikeButton", "likeButton"],
])("accepts the current %s while its counterpart is temporarily absent", (action, controlName, missingName) => {
const tree = createReactionTree();
tree[missingName].remove();
tree[missingName] = null;
const activationTarget = tree[controlName].querySelector("button");
expect(resolveDelegatedVoteActivation({ ...tree, event: clickEventFor(activationTarget) })).toEqual({
action,
activationTarget,
});
});
test("ignores an activation from a detached stale control", () => {
const tree = createReactionTree();
const staleDislike = tree.dislikeButton;
const replacement = staleDislike.cloneNode(true);
staleDislike.replaceWith(replacement);
tree.dislikeButton = replacement;
expect(
resolveDelegatedVoteActivation({
...tree,
event: clickEventFor(staleDislike.querySelector("button")),
}),
).toBeNull();
});
test.each([
["hidden attribute", (control) => (control.hidden = true)],
["aria-hidden", (control) => control.setAttribute("aria-hidden", "true")],
["display none", (control) => (control.style.display = "none")],
])("ignores a current control hidden by %s", (_label, hide) => {
const tree = createReactionTree();
hide(tree.dislikeButton);
const activationTarget = tree.dislikeButton.querySelector("button");
expect(resolveDelegatedVoteActivation({ ...tree, event: clickEventFor(activationTarget) })).toBeNull();
});
test("ignores a current control whose nested activation target is hidden", () => {
const tree = createReactionTree();
const activationTarget = tree.dislikeButton.querySelector("button");
activationTarget.hidden = true;
expect(resolveDelegatedVoteActivation({ ...tree, event: clickEventFor(activationTarget) })).toBeNull();
});
});
@@ -0,0 +1,163 @@
const SHORTS_HYDRATED_SURFACE_STABILITY_MS = 250;
const SHORTS_UNHYDRATED_SURFACE_STABILITY_MS = 1500;
const SHORTS_LINK_SELECTOR = "a[href*='/shorts/']";
const SHORTS_CANONICAL_PLAYER_LINK_SELECTOR = "a.ytp-title-link[href*='/shorts/']";
const SHORTS_ICON_GRAPHIC_SELECTOR = "path, circle, ellipse, line, polygon, polyline, rect";
function getShortsIdentityLinkVideoIds(root, baseUrl = "https://www.youtube.com/") {
const identities = new Set();
if (!root?.querySelectorAll) {
return identities;
}
const links = Array.from(root.querySelectorAll(SHORTS_LINK_SELECTOR));
const canonicalPlayerLinks = links.filter((link) => link.matches(SHORTS_CANONICAL_PLAYER_LINK_SELECTOR));
// The player title link identifies the reel. Other /shorts/ links can be
// unrelated calls to action in the current Short's description/metapanel.
// Choose the canonical subset before parsing so malformed player metadata
// cannot make an unrelated description link look authoritative.
const identityLinks = canonicalPlayerLinks.length > 0 ? canonicalPlayerLinks : links;
for (const link of identityLinks) {
try {
const href = link.getAttribute("href");
if (!href) continue;
const videoId = new URL(href, baseUrl).pathname.match(/^\/shorts\/([^/]+)\/?$/)?.[1];
if (videoId) identities.add(videoId);
} catch {
// Ignore malformed or incomplete links while YouTube hydrates the reel.
}
}
return identities;
}
function getShortsControlSurfaceStabilityMs(isHydrated) {
return isHydrated ? SHORTS_HYDRATED_SURFACE_STABILITY_MS : SHORTS_UNHYDRATED_SURFACE_STABILITY_MS;
}
function isShortsControlSurfaceReadyForMutation({
allowUnhydratedFallback = false,
candidateVideoIds = [],
currentVideoId,
isConnected,
isHydrated,
isRendered,
isStable,
isViewportIntersecting,
visibleCandidateCount,
}) {
const uniqueCandidateVideoIds = new Set(Array.from(candidateVideoIds).filter(Boolean));
const hasExactIdentity = uniqueCandidateVideoIds.size === 1 && uniqueCandidateVideoIds.has(currentVideoId);
const isUnambiguousIdentitylessSurface = uniqueCandidateVideoIds.size === 0 && visibleCandidateCount === 1;
return Boolean(
currentVideoId &&
isConnected &&
(isHydrated || allowUnhydratedFallback) &&
isRendered &&
isStable &&
isViewportIntersecting &&
(hasExactIdentity || isUnambiguousIdentitylessSurface),
);
}
function actionBarHasHydratedData(actionBar) {
return Boolean(actionBar) && (!("data" in actionBar) || Boolean(actionBar.data));
}
function capturePaintedShortsIcon(button) {
const svg = button?.querySelector("svg") ?? null;
if (!svg?.isConnected) return null;
const graphic = Array.from(svg.querySelectorAll(SHORTS_ICON_GRAPHIC_SELECTOR)).find(
(candidate) => candidate.tagName.toLowerCase() !== "path" || (candidate.getAttribute("d") ?? "").trim().length > 0,
);
if (!graphic?.isConnected) return null;
const rect = svg.getBoundingClientRect();
if (!(rect.width > 0 && rect.height > 0)) return null;
return { graphic, svg };
}
function captureShortsNativeControlInventory(
actionBar,
{ syntheticSelector = "[data-ryd-synthetic-shorts-dislike]" } = {},
) {
const nativeChildren = Array.from(actionBar?.children ?? []).filter((child) => !child.matches(syntheticSelector));
const likeButton = actionBar?.querySelector("like-button-view-model") ?? null;
const nativeLikeButton = likeButton?.querySelector("button") ?? null;
const nativeLikeIcon = capturePaintedShortsIcon(nativeLikeButton);
const activationTargets = nativeChildren.map((child) =>
child.querySelector("button, a[href], a[role='button'][tabindex='0'], tp-yt-paper-button#button"),
);
if (
!likeButton?.isConnected ||
!nativeLikeButton?.isConnected ||
!nativeLikeIcon ||
nativeChildren.length < 4 ||
!nativeChildren.includes(likeButton) ||
activationTargets.some((target) => !target?.isConnected)
) {
return null;
}
return {
activationTargets,
likeButton,
nativeChildren,
nativeLikeButton,
nativeLikeGraphic: nativeLikeIcon.graphic,
nativeLikeSvg: nativeLikeIcon.svg,
};
}
function shortsNativeControlInventoryMatches(left, right) {
return Boolean(
left &&
right &&
left.likeButton === right.likeButton &&
left.nativeLikeButton === right.nativeLikeButton &&
left.nativeLikeGraphic === right.nativeLikeGraphic &&
left.nativeLikeSvg === right.nativeLikeSvg &&
left.nativeChildren.length === right.nativeChildren.length &&
left.nativeChildren.every((child, index) => child === right.nativeChildren[index]) &&
left.activationTargets.every((target, index) => target === right.activationTargets[index]),
);
}
function shortsNativeControlInventoryIsReadyForFallback(
inventory,
{ getTopmostElement, isMeaningfullyInViewport, isRendered },
) {
if (
!inventory?.activationTargets?.length ||
typeof getTopmostElement !== "function" ||
typeof isMeaningfullyInViewport !== "function" ||
typeof isRendered !== "function"
) {
return false;
}
return inventory.activationTargets.every((target) => {
if (!target?.isConnected || !isRendered(target) || !isMeaningfullyInViewport(target)) {
return false;
}
const rect = target.getBoundingClientRect();
const topmostElement = getTopmostElement(rect.left + rect.width / 2, rect.top + rect.height / 2);
return Boolean(topmostElement && (topmostElement === target || target.contains(topmostElement)));
});
}
export {
SHORTS_HYDRATED_SURFACE_STABILITY_MS,
SHORTS_UNHYDRATED_SURFACE_STABILITY_MS,
actionBarHasHydratedData,
captureShortsNativeControlInventory,
getShortsControlSurfaceStabilityMs,
getShortsIdentityLinkVideoIds,
isShortsControlSurfaceReadyForMutation,
shortsNativeControlInventoryIsReadyForFallback,
shortsNativeControlInventoryMatches,
};
@@ -0,0 +1,290 @@
/** @jest-environment jsdom */
import {
SHORTS_HYDRATED_SURFACE_STABILITY_MS,
SHORTS_UNHYDRATED_SURFACE_STABILITY_MS,
actionBarHasHydratedData,
captureShortsNativeControlInventory,
getShortsControlSurfaceStabilityMs,
getShortsIdentityLinkVideoIds,
isShortsControlSurfaceReadyForMutation,
shortsNativeControlInventoryIsReadyForFallback,
shortsNativeControlInventoryMatches,
} from "./shorts-control-readiness";
const readySurface = {
candidateVideoIds: ["BBBBBBBBBBB"],
currentVideoId: "BBBBBBBBBBB",
isConnected: true,
isHydrated: true,
isRendered: true,
isStable: true,
isViewportIntersecting: true,
visibleCandidateCount: 1,
};
function appendNativeLikeSvg(actionBar, { height = 24, path = "M3 12h18", width = 24 } = {}) {
const button = actionBar.querySelector("like-button-view-model button");
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.getBoundingClientRect = () => ({ bottom: height, height, left: 0, right: width, top: 0, width });
if (path !== null) {
const graphic = document.createElementNS("http://www.w3.org/2000/svg", "path");
graphic.setAttribute("d", path);
svg.appendChild(graphic);
}
button.appendChild(svg);
return svg;
}
describe("Shorts control mutation readiness", () => {
describe("renderer link identity", () => {
test("prefers the hidden player-title permalink over a visible description cross-link", () => {
const renderer = document.createElement("ytd-reel-video-renderer");
renderer.innerHTML = `
<div id="shorts-player">
<a class="ytp-title-link yt-uix-sessionlink" href="/shorts/BBBBBBBBBBB?feature=share"></a>
</div>
<button-view-model>
<a href="/shorts/AAAAAAAAAAA">This knot is very useful</a>
</button-view-model>`;
expect(Array.from(getShortsIdentityLinkVideoIds(renderer, "https://www.youtube.com/shorts/BBBBBBBBBBB"))).toEqual(
["BBBBBBBBBBB"],
);
});
test("keeps conflicting canonical player and renderer identities ambiguous", () => {
const renderer = document.createElement("ytd-reel-video-renderer");
renderer.setAttribute("video-id", "BBBBBBBBBBB");
renderer.innerHTML = '<a class="ytp-title-link" href="/shorts/AAAAAAAAAAA"></a>';
const identities = new Set([renderer.getAttribute("video-id"), ...getShortsIdentityLinkVideoIds(renderer)]);
expect(Array.from(identities).sort()).toEqual(["AAAAAAAAAAA", "BBBBBBBBBBB"]);
});
test("keeps multiple canonical player identities ambiguous", () => {
const renderer = document.createElement("ytd-reel-video-renderer");
renderer.innerHTML = `
<a class="ytp-title-link" href="/shorts/AAAAAAAAAAA"></a>
<a class="ytp-title-link" href="/shorts/BBBBBBBBBBB"></a>
<a href="/shorts/CCCCCCCCCCC"></a>`;
expect(Array.from(getShortsIdentityLinkVideoIds(renderer)).sort()).toEqual(["AAAAAAAAAAA", "BBBBBBBBBBB"]);
});
test("retains the generic exact-link fallback when no player-title permalink exists", () => {
const renderer = document.createElement("ytm-reel-video-renderer");
renderer.innerHTML = '<a href="/shorts/BBBBBBBBBBB"></a>';
expect(Array.from(getShortsIdentityLinkVideoIds(renderer))).toEqual(["BBBBBBBBBBB"]);
});
test("does not fall through to description links when canonical player metadata is malformed", () => {
const renderer = document.createElement("ytd-reel-video-renderer");
renderer.innerHTML = `
<a class="ytp-title-link" href="/shorts/"></a>
<a href="/shorts/AAAAAAAAAAA"></a>`;
expect(Array.from(getShortsIdentityLinkVideoIds(renderer))).toEqual([]);
});
});
test("uses the shared hydrated and persistent-unhydrated stability windows", () => {
expect(getShortsControlSurfaceStabilityMs(true)).toBe(SHORTS_HYDRATED_SURFACE_STABILITY_MS);
expect(getShortsControlSurfaceStabilityMs(false)).toBe(SHORTS_UNHYDRATED_SURFACE_STABILITY_MS);
expect(SHORTS_HYDRATED_SURFACE_STABILITY_MS).toBe(250);
expect(SHORTS_UNHYDRATED_SURFACE_STABILITY_MS).toBe(1500);
});
test("accepts the current rendered action surface only after it intersects the viewport", () => {
expect(isShortsControlSurfaceReadyForMutation(readySurface)).toBe(true);
expect(
isShortsControlSurfaceReadyForMutation({
...readySurface,
isViewportIntersecting: false,
}),
).toBe(false);
});
test.each([
["detached", { isConnected: false }],
["not hydrated", { isHydrated: false }],
["not rendered", { isRendered: false }],
["not stable", { isStable: false }],
["owned by another video", { candidateVideoIds: ["AAAAAAAAAAA"] }],
["missing route identity", { currentVideoId: null }],
])("rejects a %s action surface", (_label, override) => {
expect(isShortsControlSurfaceReadyForMutation({ ...readySurface, ...override })).toBe(false);
});
test("accepts one visible current surface while YouTube is still hydrating its own identity", () => {
expect(
isShortsControlSurfaceReadyForMutation({
...readySurface,
candidateVideoIds: [],
}),
).toBe(true);
});
test("accepts a data-null surface only through the explicit fallback without bypassing other guards", () => {
const unhydratedSurface = { ...readySurface, isHydrated: false };
expect(isShortsControlSurfaceReadyForMutation(unhydratedSurface)).toBe(false);
expect(
isShortsControlSurfaceReadyForMutation({
...unhydratedSurface,
allowUnhydratedFallback: true,
}),
).toBe(true);
expect(
isShortsControlSurfaceReadyForMutation({
...unhydratedSurface,
allowUnhydratedFallback: true,
isStable: false,
}),
).toBe(false);
});
test("rejects ambiguous and non-unique identity-less surfaces", () => {
expect(
isShortsControlSurfaceReadyForMutation({
...readySurface,
candidateVideoIds: ["BBBBBBBBBBB", "AAAAAAAAAAA"],
}),
).toBe(false);
expect(
isShortsControlSurfaceReadyForMutation({
...readySurface,
candidateVideoIds: [],
visibleCandidateCount: 2,
}),
).toBe(false);
});
test("requires truthy action-bar data only when YouTube exposes the property", () => {
const actionBar = document.createElement("reel-action-bar-view-model");
expect(actionBarHasHydratedData(actionBar)).toBe(true);
actionBar.data = null;
expect(actionBarHasHydratedData(actionBar)).toBe(false);
actionBar.data = { likeButtonViewModel: {} };
expect(actionBarHasHydratedData(actionBar)).toBe(true);
});
test("requires a complete interactive inventory and detects native reconciliation", () => {
const actionBar = document.createElement("reel-action-bar-view-model");
actionBar.innerHTML = `
<like-button-view-model><button></button></like-button-view-model>
<button-view-model><button></button></button-view-model>`;
document.body.appendChild(actionBar);
expect(captureShortsNativeControlInventory(actionBar)).toBeNull();
actionBar.insertAdjacentHTML(
"beforeend",
"<button-view-model><button></button></button-view-model>" +
'<pivot-button-view-model><a role="button" tabindex="0"></a></pivot-button-view-model>',
);
appendNativeLikeSvg(actionBar);
const before = captureShortsNativeControlInventory(actionBar);
expect(before).not.toBeNull();
expect(before.activationTargets.at(-1)).toBe(actionBar.querySelector("pivot-button-view-model > a"));
expect(shortsNativeControlInventoryMatches(before, captureShortsNativeControlInventory(actionBar))).toBe(true);
actionBar.children[1].replaceWith(actionBar.children[1].cloneNode(true));
expect(shortsNativeControlInventoryMatches(before, captureShortsNativeControlInventory(actionBar))).toBe(false);
});
test("requires every native activation target to be rendered, meaningfully visible, and topmost for fallback", () => {
const actionBar = document.createElement("reel-action-bar-view-model");
actionBar.innerHTML = `
<like-button-view-model><button></button></like-button-view-model>
<button-view-model><button></button></button-view-model>
<button-view-model><button></button></button-view-model>
<pivot-button-view-model><a role="button" tabindex="0"></a></pivot-button-view-model>`;
document.body.appendChild(actionBar);
appendNativeLikeSvg(actionBar);
const inventory = captureShortsNativeControlInventory(actionBar);
const targets = inventory.activationTargets;
targets.forEach((target, index) => {
target.getBoundingClientRect = () => ({ height: 40, left: index * 50, top: 10, width: 40 });
});
const getTopmostElement = jest.fn((x) => targets[Math.floor(x / 50)]);
const readyOptions = {
getTopmostElement,
isMeaningfullyInViewport: () => true,
isRendered: () => true,
};
expect(shortsNativeControlInventoryIsReadyForFallback(inventory, readyOptions)).toBe(true);
expect(getTopmostElement).toHaveBeenCalledTimes(targets.length);
expect(
shortsNativeControlInventoryIsReadyForFallback(inventory, {
...readyOptions,
isRendered: (target) => target !== targets[1],
}),
).toBe(false);
expect(
shortsNativeControlInventoryIsReadyForFallback(inventory, {
...readyOptions,
isMeaningfullyInViewport: (target) => target !== targets[2],
}),
).toBe(false);
expect(
shortsNativeControlInventoryIsReadyForFallback(inventory, {
...readyOptions,
getTopmostElement: () => document.body,
}),
).toBe(false);
});
test("accepts only the real no-href Pivot anchor button topology", () => {
const actionBar = document.createElement("reel-action-bar-view-model");
actionBar.innerHTML = `
<like-button-view-model><button></button></like-button-view-model>
<button-view-model><button></button></button-view-model>
<button-view-model><button></button></button-view-model>
<pivot-button-view-model><a role="button" tabindex="-1"></a></pivot-button-view-model>`;
document.body.appendChild(actionBar);
appendNativeLikeSvg(actionBar);
expect(captureShortsNativeControlInventory(actionBar)).toBeNull();
actionBar.querySelector("pivot-button-view-model > a").setAttribute("tabindex", "0");
expect(captureShortsNativeControlInventory(actionBar)).not.toBeNull();
});
test("waits for the exact native Like icon to progress from shell-only through empty SVG to painted", () => {
const actionBar = document.createElement("reel-action-bar-view-model");
actionBar.innerHTML = `
<like-button-view-model><button></button></like-button-view-model>
<button-view-model><button></button></button-view-model>
<button-view-model><button></button></button-view-model>
<pivot-button-view-model><a role="button" tabindex="0"></a></pivot-button-view-model>`;
document.body.appendChild(actionBar);
expect(captureShortsNativeControlInventory(actionBar)).toBeNull();
const svg = appendNativeLikeSvg(actionBar, { path: null });
expect(captureShortsNativeControlInventory(actionBar)).toBeNull();
const graphic = document.createElementNS("http://www.w3.org/2000/svg", "path");
graphic.setAttribute("d", "");
svg.appendChild(graphic);
expect(captureShortsNativeControlInventory(actionBar)).toBeNull();
graphic.setAttribute("d", "M3 12h18");
svg.getBoundingClientRect = () => ({ bottom: 0, height: 0, left: 0, right: 24, top: 0, width: 24 });
expect(captureShortsNativeControlInventory(actionBar)).toBeNull();
svg.getBoundingClientRect = () => ({ bottom: 24, height: 24, left: 0, right: 24, top: 0, width: 24 });
const painted = captureShortsNativeControlInventory(actionBar);
expect(painted).not.toBeNull();
expect(painted.nativeLikeButton).toBe(actionBar.querySelector("like-button-view-model button"));
expect(painted.nativeLikeSvg).toBe(svg);
expect(painted.nativeLikeGraphic).toBe(graphic);
graphic.replaceWith(graphic.cloneNode(true));
expect(shortsNativeControlInventoryMatches(painted, captureShortsNativeControlInventory(actionBar))).toBe(false);
});
});
+57
View File
@@ -0,0 +1,57 @@
const LIKED_STATE = "LIKED_STATE";
const DISLIKED_STATE = "DISLIKED_STATE";
const NEUTRAL_STATE = "NEUTRAL_STATE";
const LIKE_ACTION = "like";
const DISLIKE_ACTION = "dislike";
const TRANSITIONS = {
[NEUTRAL_STATE]: {
[LIKE_ACTION]: { nextState: LIKED_STATE, value: 1, likesDelta: 1, dislikesDelta: 0 },
[DISLIKE_ACTION]: { nextState: DISLIKED_STATE, value: -1, likesDelta: 0, dislikesDelta: 1 },
},
[LIKED_STATE]: {
[LIKE_ACTION]: { nextState: NEUTRAL_STATE, value: 0, likesDelta: -1, dislikesDelta: 0 },
[DISLIKE_ACTION]: { nextState: DISLIKED_STATE, value: -1, likesDelta: -1, dislikesDelta: 1 },
},
[DISLIKED_STATE]: {
[LIKE_ACTION]: { nextState: LIKED_STATE, value: 1, likesDelta: 1, dislikesDelta: -1 },
[DISLIKE_ACTION]: { nextState: NEUTRAL_STATE, value: 0, likesDelta: 0, dislikesDelta: -1 },
},
};
function resolveVoteTransition(previousState, action) {
const transition = TRANSITIONS[previousState]?.[action];
if (!transition) {
throw new TypeError(`Unsupported vote transition: ${previousState} -> ${action}`);
}
return { ...transition };
}
function applyVoteTransitionCounts(likes, dislikes, transition) {
if (!transition || !Number.isFinite(transition.likesDelta) || !Number.isFinite(transition.dislikesDelta)) {
throw new TypeError("A valid vote transition is required");
}
const normalizedLikes = Number.isFinite(likes) ? likes : 0;
const normalizedDislikes = Number.isFinite(dislikes) ? dislikes : 0;
return {
likes: Math.max(0, normalizedLikes + transition.likesDelta),
dislikes: Math.max(0, normalizedDislikes + transition.dislikesDelta),
};
}
function shouldSubmitVote({ disableVoteSubmission = false, signedOut = false } = {}) {
return disableVoteSubmission !== true && signedOut !== true;
}
module.exports = {
DISLIKED_STATE,
DISLIKE_ACTION,
LIKED_STATE,
LIKE_ACTION,
NEUTRAL_STATE,
applyVoteTransitionCounts,
resolveVoteTransition,
shouldSubmitVote,
};
+10 -46
View File
@@ -1,49 +1,13 @@
const LIKED_STATE = "LIKED_STATE";
const DISLIKED_STATE = "DISLIKED_STATE";
const NEUTRAL_STATE = "NEUTRAL_STATE";
const LIKE_ACTION = "like";
const DISLIKE_ACTION = "dislike";
const TRANSITIONS = {
[NEUTRAL_STATE]: {
[LIKE_ACTION]: { nextState: LIKED_STATE, value: 1, likesDelta: 1, dislikesDelta: 0 },
[DISLIKE_ACTION]: { nextState: DISLIKED_STATE, value: -1, likesDelta: 0, dislikesDelta: 1 },
},
[LIKED_STATE]: {
[LIKE_ACTION]: { nextState: NEUTRAL_STATE, value: 0, likesDelta: -1, dislikesDelta: 0 },
[DISLIKE_ACTION]: { nextState: DISLIKED_STATE, value: -1, likesDelta: -1, dislikesDelta: 1 },
},
[DISLIKED_STATE]: {
[LIKE_ACTION]: { nextState: LIKED_STATE, value: 1, likesDelta: 1, dislikesDelta: -1 },
[DISLIKE_ACTION]: { nextState: NEUTRAL_STATE, value: 0, likesDelta: 0, dislikesDelta: -1 },
},
};
function resolveVoteTransition(previousState, action) {
const transition = TRANSITIONS[previousState]?.[action];
if (!transition) {
throw new TypeError(`Unsupported vote transition: ${previousState} -> ${action}`);
}
return { ...transition };
}
function applyVoteTransitionCounts(likes, dislikes, transition) {
if (!transition || !Number.isFinite(transition.likesDelta) || !Number.isFinite(transition.dislikesDelta)) {
throw new TypeError("A valid vote transition is required");
}
const normalizedLikes = Number.isFinite(likes) ? likes : 0;
const normalizedDislikes = Number.isFinite(dislikes) ? dislikes : 0;
return {
likes: Math.max(0, normalizedLikes + transition.likesDelta),
dislikes: Math.max(0, normalizedDislikes + transition.dislikesDelta),
};
}
function shouldSubmitVote({ disableVoteSubmission = false, signedOut = false } = {}) {
return disableVoteSubmission !== true && signedOut !== true;
}
const {
DISLIKED_STATE,
DISLIKE_ACTION,
LIKED_STATE,
LIKE_ACTION,
NEUTRAL_STATE,
applyVoteTransitionCounts,
resolveVoteTransition,
shouldSubmitVote,
} = require("./vote-transition-core");
export {
LIKED_STATE,