mirror of
https://github.com/Alvin-Zilverstand/return-youtube-dislike.git
synced 2026-12-01 10:21:22 +01:00
Fix Shorts support and add userscript voting
Harden Shorts controls, reaction state, and navigation; share voting logic with the extension; improve ratio-bar rendering; and add comprehensive Jest, Playwright, artifact, and live-browser regression coverage.
This commit is contained in:
1 parent
4e6dfd1977
commit
3657de9b2c
74 files changed
+23328
-588
No files matched your search
@@ -19,7 +19,12 @@
|
||||
} */
|
||||
|
||||
#ryd-bar-container {
|
||||
background: var(--yt-spec-icon-disabled);
|
||||
background: #737373;
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--yt-spec-text-primary, #f1f1f1) 55%,
|
||||
var(--yt-spec-base-background, #0f0f0f) 45%
|
||||
);
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { config, getApiUrl, getApiEndpoint, getChangelogUrl } from "./src/config";
|
||||
import { createVoteClient } from "../common/vote-client";
|
||||
import { createBrowserCredentialStore } from "./src/vote-client-adapter";
|
||||
|
||||
const apiUrl = getApiUrl();
|
||||
const voteDisabledIconName = config.voteDisabledIconName;
|
||||
@@ -13,7 +15,15 @@ let extConfig = { ...config.defaultExtConfig };
|
||||
if (isChrome()) api = chrome;
|
||||
else if (isFirefox()) api = browser;
|
||||
|
||||
const voteClient = createVoteClient({
|
||||
apiBaseUrl: apiUrl,
|
||||
fetchImpl: (...args) => fetch(...args),
|
||||
credentialStore: createBrowserCredentialStore(api.storage.sync, () => api.runtime?.lastError),
|
||||
cryptoImpl: globalThis.crypto,
|
||||
});
|
||||
|
||||
initExtConfig();
|
||||
voteClient.ensureRegistered().catch((error) => console.error("Vote registration failed", error));
|
||||
|
||||
function broadcastPatreonStatus(authenticated, user, sessionToken) {
|
||||
chrome.tabs.query({}, (tabs) => {
|
||||
@@ -175,10 +185,16 @@ api.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
||||
toSend = [];
|
||||
}
|
||||
} else if (request.message == "register") {
|
||||
register();
|
||||
voteClient
|
||||
.ensureRegistered()
|
||||
.then(({ userId }) => sendResponse?.({ success: true, userId }))
|
||||
.catch((error) => sendResponse?.({ success: false, error: error.message }));
|
||||
return true;
|
||||
} else if (request.message == "send_vote") {
|
||||
sendVote(request.videoId, request.vote);
|
||||
voteClient
|
||||
.submitVote(request.videoId, request.vote)
|
||||
.then(() => sendResponse?.({ success: true }))
|
||||
.catch((error) => sendResponse?.({ success: false, error: error.message }));
|
||||
return true;
|
||||
} else if (request.message === "patreon_oauth_login") {
|
||||
(async () => {
|
||||
@@ -486,156 +502,9 @@ if (api?.runtime?.onStartup && typeof api.runtime.onStartup.addListener === "fun
|
||||
// }
|
||||
// });
|
||||
|
||||
async function sendVote(videoId, vote, depth = 1) {
|
||||
api.storage.sync.get(null, async (storageResult) => {
|
||||
if (!storageResult.userId || !storageResult.registrationConfirmed) {
|
||||
await register();
|
||||
}
|
||||
let voteResponse = await fetch(getApiEndpoint("/interact/vote"), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userId: storageResult.userId,
|
||||
videoId,
|
||||
value: vote,
|
||||
}),
|
||||
});
|
||||
|
||||
if (voteResponse.status == 401 && depth > 0) {
|
||||
await register();
|
||||
await sendVote(videoId, vote, depth - 1);
|
||||
return;
|
||||
} else if (voteResponse.status == 401) {
|
||||
// We have already tried registering
|
||||
return;
|
||||
}
|
||||
|
||||
const voteResponseJson = await voteResponse.json();
|
||||
const solvedPuzzle = await solvePuzzle(voteResponseJson);
|
||||
if (!solvedPuzzle.solution) {
|
||||
await sendVote(videoId, vote);
|
||||
return;
|
||||
}
|
||||
|
||||
await fetch(getApiEndpoint("/interact/confirmVote"), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
...solvedPuzzle,
|
||||
userId: storageResult.userId,
|
||||
videoId,
|
||||
}),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function register() {
|
||||
const userId = generateUserID();
|
||||
api.storage.sync.set({ userId });
|
||||
const registrationResponse = await fetch(getApiEndpoint(`/puzzle/registration?userId=${userId}`), {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
}).then((response) => response.json());
|
||||
const solvedPuzzle = await solvePuzzle(registrationResponse);
|
||||
if (!solvedPuzzle.solution) {
|
||||
await register();
|
||||
return;
|
||||
}
|
||||
const result = await fetch(getApiEndpoint(`/puzzle/registration?userId=${userId}`), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(solvedPuzzle),
|
||||
}).then((response) => response.json());
|
||||
if (result === true) {
|
||||
return api.storage.sync.set({ registrationConfirmed: true });
|
||||
}
|
||||
}
|
||||
|
||||
api.storage.sync.get(null, async (res) => {
|
||||
if (!res || !res.userId || !res.registrationConfirmed) {
|
||||
await register();
|
||||
}
|
||||
});
|
||||
|
||||
const sentIds = new Set();
|
||||
let toSend = [];
|
||||
|
||||
function countLeadingZeroes(uInt8View, limit) {
|
||||
let zeroes = 0;
|
||||
let value = 0;
|
||||
for (let i = 0; i < uInt8View.length; i++) {
|
||||
value = uInt8View[i];
|
||||
if (value === 0) {
|
||||
zeroes += 8;
|
||||
} else {
|
||||
let count = 1;
|
||||
if (value >>> 4 === 0) {
|
||||
count += 4;
|
||||
value <<= 4;
|
||||
}
|
||||
if (value >>> 6 === 0) {
|
||||
count += 2;
|
||||
value <<= 2;
|
||||
}
|
||||
zeroes += count - (value >>> 7);
|
||||
break;
|
||||
}
|
||||
if (zeroes >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return zeroes;
|
||||
}
|
||||
|
||||
async function solvePuzzle(puzzle) {
|
||||
let challenge = Uint8Array.from(atob(puzzle.challenge), (c) => c.charCodeAt(0));
|
||||
let buffer = new ArrayBuffer(20);
|
||||
let uInt8View = new Uint8Array(buffer);
|
||||
let uInt32View = new Uint32Array(buffer);
|
||||
let maxCount = Math.pow(2, puzzle.difficulty) * 3;
|
||||
for (let i = 4; i < 20; i++) {
|
||||
uInt8View[i] = challenge[i - 4];
|
||||
}
|
||||
|
||||
for (let i = 0; i < maxCount; i++) {
|
||||
uInt32View[0] = i;
|
||||
let hash = await crypto.subtle.digest("SHA-512", buffer);
|
||||
let hashUint8 = new Uint8Array(hash);
|
||||
if (countLeadingZeroes(hashUint8) >= puzzle.difficulty) {
|
||||
return {
|
||||
solution: btoa(String.fromCharCode.apply(null, uInt8View.slice(0, 4))),
|
||||
};
|
||||
}
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
function generateUserID(length = 36) {
|
||||
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
let result = "";
|
||||
if (crypto && crypto.getRandomValues) {
|
||||
const values = new Uint32Array(length);
|
||||
crypto.getRandomValues(values);
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += charset[values[i] % charset.length];
|
||||
}
|
||||
return result;
|
||||
} else {
|
||||
for (let i = 0; i < length; i++) {
|
||||
result += charset[Math.floor(Math.random() * charset.length)];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
function storageChangeHandler(changes, area) {
|
||||
if (changes.disableVoteSubmission !== undefined) {
|
||||
handleDisableVoteSubmissionChangeEvent(changes.disableVoteSubmission.newValue);
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
import { getButtons } from "./src/buttons";
|
||||
import { isShorts, setInitialState, initExtConfig } from "./src/state";
|
||||
import { getBrowser, isVideoLoaded } from "./src/utils";
|
||||
import { getButtons, getDislikeButton, getLikeButton, hasRenderedBox, markButtonsForVideo } from "./src/buttons";
|
||||
import {
|
||||
hasLoadedStateForVideo,
|
||||
initExtConfig,
|
||||
isLikesDisabled,
|
||||
isShorts,
|
||||
restoreCurrentState,
|
||||
setInitialState,
|
||||
} from "./src/state";
|
||||
import { getBrowser, getVideoId, isVideoLoaded } from "./src/utils";
|
||||
import { addLikeDislikeEventListener, createSmartimationObserver, storageChangeHandler } from "./src/events";
|
||||
import { createInitializationCycleRunner } from "./src/initialization-cycle";
|
||||
import { initPatreonFeatures } from "./src/patreon";
|
||||
|
||||
if (__RYD_LIVE_TEST_BUILD__) {
|
||||
document.documentElement.setAttribute("data-ryd-extension-version", getBrowser().runtime.getManifest().version);
|
||||
document.documentElement.setAttribute("data-ryd-extension-build", __RYD_LIVE_BUILD_ID__);
|
||||
}
|
||||
|
||||
await initExtConfig();
|
||||
initPatreonFeatures();
|
||||
|
||||
@@ -12,6 +25,11 @@ let isSetInitialStateDone = false;
|
||||
let isStorageListenerRegistered = false;
|
||||
let shortsNavigationObserver = null;
|
||||
let shortsNavigationObserverTarget = null;
|
||||
let initializedVideoId = null;
|
||||
let initializedButtons = null;
|
||||
let initializedLikeButton = null;
|
||||
let initializedDislikeButton = null;
|
||||
let initializationCheckRunning = false;
|
||||
|
||||
function ensureShortsNavigationObserver() {
|
||||
if (!isShorts()) {
|
||||
@@ -51,19 +69,44 @@ function ensureShortsNavigationObserver() {
|
||||
}
|
||||
|
||||
async function checkForInitialization() {
|
||||
if (initializationCheckRunning) return;
|
||||
initializationCheckRunning = true;
|
||||
try {
|
||||
if (isShorts()) {
|
||||
ensureShortsNavigationObserver();
|
||||
}
|
||||
|
||||
if ((isShorts() && isVideoLoaded()) || (getButtons()?.offsetParent && isVideoLoaded())) {
|
||||
const buttons = getButtons();
|
||||
const videoId = getVideoId(window.location.href);
|
||||
if ((isShorts() && isVideoLoaded()) || (hasRenderedBox(buttons) && isVideoLoaded())) {
|
||||
if (!buttons) return;
|
||||
const likeButton = getLikeButton();
|
||||
const dislikeButton = getDislikeButton();
|
||||
if (!likeButton || !dislikeButton) return;
|
||||
if (jsInitChecktimer !== null) {
|
||||
clearInterval(jsInitChecktimer);
|
||||
jsInitChecktimer = null;
|
||||
}
|
||||
markButtonsForVideo(buttons, videoId);
|
||||
createSmartimationObserver();
|
||||
addLikeDislikeEventListener();
|
||||
await setInitialState();
|
||||
if (hasLoadedStateForVideo(videoId)) {
|
||||
restoreCurrentState();
|
||||
} else {
|
||||
await setInitialState();
|
||||
}
|
||||
if (
|
||||
videoId !== getVideoId(window.location.href) ||
|
||||
buttons !== getButtons() ||
|
||||
likeButton !== getLikeButton() ||
|
||||
dislikeButton !== getDislikeButton()
|
||||
) {
|
||||
return;
|
||||
}
|
||||
initializedVideoId = videoId;
|
||||
initializedButtons = buttons;
|
||||
initializedLikeButton = likeButton;
|
||||
initializedDislikeButton = dislikeButton;
|
||||
isSetInitialStateDone = true;
|
||||
if (!isStorageListenerRegistered) {
|
||||
getBrowser().storage.onChanged.addListener(storageChangeHandler);
|
||||
@@ -71,14 +114,13 @@ async function checkForInitialization() {
|
||||
}
|
||||
}
|
||||
} catch (exception) {
|
||||
if (!isSetInitialStateDone) {
|
||||
console.log("error");
|
||||
await setInitialState();
|
||||
}
|
||||
console.warn("Initialization failed; retrying when the current controls are ready.", exception);
|
||||
} finally {
|
||||
initializationCheckRunning = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function triggerInitializationCycle() {
|
||||
const initializationCycle = createInitializationCycleRunner(async () => {
|
||||
isSetInitialStateDone = false;
|
||||
|
||||
if (jsInitChecktimer !== null) {
|
||||
@@ -99,6 +141,10 @@ async function triggerInitializationCycle() {
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
});
|
||||
|
||||
function triggerInitializationCycle() {
|
||||
return initializationCycle.request();
|
||||
}
|
||||
|
||||
async function setEventListeners() {
|
||||
@@ -111,6 +157,34 @@ document.addEventListener("yt-navigate-finish", async function (event) {
|
||||
await setEventListeners();
|
||||
});
|
||||
|
||||
function watchControlsNeedInitialization() {
|
||||
const videoId = getVideoId(window.location.href);
|
||||
if (!videoId || initializationCycle.isRunning() || jsInitChecktimer !== null) return false;
|
||||
const buttons = getButtons();
|
||||
if (!buttons) return true;
|
||||
const likeButton = getLikeButton();
|
||||
const dislikeButton = getDislikeButton();
|
||||
return (
|
||||
initializedVideoId !== videoId ||
|
||||
initializedButtons !== buttons ||
|
||||
initializedLikeButton !== likeButton ||
|
||||
initializedDislikeButton !== dislikeButton ||
|
||||
!buttons?.isConnected ||
|
||||
!likeButton?.isConnected ||
|
||||
!dislikeButton?.isConnected ||
|
||||
!buttons?.contains(likeButton) ||
|
||||
!buttons?.contains(dislikeButton) ||
|
||||
(!isShorts() &&
|
||||
hasLoadedStateForVideo(videoId) &&
|
||||
!isLikesDisabled() &&
|
||||
!buttons.querySelector("#ryd-bar-container"))
|
||||
);
|
||||
}
|
||||
|
||||
setInterval(() => {
|
||||
if (watchControlsNeedInitialization()) void triggerInitializationCycle();
|
||||
}, 500);
|
||||
|
||||
const s = document.createElement("script");
|
||||
s.src = chrome.runtime.getURL("menu-fixer.js");
|
||||
s.onload = function () {
|
||||
|
||||
@@ -2,12 +2,32 @@ import { getButtons, getDislikeButton, getLikeButton } from "./buttons";
|
||||
import { extConfig, isMobile, isLikesDisabled, isNewDesign, isRoundedDesign, isShorts } from "./state";
|
||||
import { getColorFromTheme, isInViewport, querySelector } from "./utils";
|
||||
|
||||
function closestConfigured(element, selectors) {
|
||||
for (const selector of Array.isArray(selectors) ? selectors : [selectors]) {
|
||||
const match = selector ? element?.closest(selector) : null;
|
||||
if (match) return match;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function findInCurrentWatchTree(buttons, selectors, fallbackScope = null) {
|
||||
const closest = closestConfigured(buttons, selectors);
|
||||
if (closest) return closest;
|
||||
const watchRoot = buttons?.closest("ytd-watch-flexy, ytd-watch-grid");
|
||||
const scope = fallbackScope ?? watchRoot;
|
||||
return scope ? querySelector(selectors, scope) : undefined;
|
||||
}
|
||||
|
||||
function createRateBar(likes, dislikes) {
|
||||
let rateBar = document.getElementById("ryd-bar-container");
|
||||
const buttons = getButtons();
|
||||
for (const wrapper of document.querySelectorAll(".ryd-tooltip")) {
|
||||
if (!buttons?.contains(wrapper)) wrapper.remove();
|
||||
}
|
||||
let rateBar = buttons?.querySelector("#ryd-bar-container");
|
||||
if (!isLikesDisabled()) {
|
||||
// sometimes rate bar is hidden
|
||||
if (rateBar && !isInViewport(rateBar)) {
|
||||
rateBar.remove();
|
||||
(rateBar.closest(".ryd-tooltip") ?? rateBar).remove();
|
||||
rateBar = null;
|
||||
}
|
||||
|
||||
@@ -52,10 +72,7 @@ function createRateBar(likes, dislikes) {
|
||||
colorLikeStyle = "; background-color: " + getColorFromTheme(true);
|
||||
colorDislikeStyle = "; background-color: " + getColorFromTheme(false);
|
||||
}
|
||||
let actions =
|
||||
isNewDesign() && getButtons() === querySelector(extConfig.selectors.rateBar.newDesignActions)
|
||||
? getButtons()
|
||||
: querySelector(extConfig.selectors.rateBar.oldDesignActions);
|
||||
const actions = buttons;
|
||||
(actions || querySelector(extConfig.selectors.rateBar.mobileActionBar)).insertAdjacentHTML(
|
||||
"beforeend",
|
||||
`
|
||||
@@ -80,30 +97,43 @@ function createRateBar(likes, dislikes) {
|
||||
|
||||
if (isNewDesign()) {
|
||||
// Add border between info and comments
|
||||
let descriptionAndActionsElement = querySelector(extConfig.selectors.rateBar.topRow);
|
||||
descriptionAndActionsElement.style.borderBottom = "1px solid var(--yt-spec-10-percent-layer)";
|
||||
descriptionAndActionsElement.style.paddingBottom = "10px";
|
||||
const descriptionAndActionsElement = findInCurrentWatchTree(buttons, extConfig.selectors.rateBar.topRow);
|
||||
if (descriptionAndActionsElement) {
|
||||
descriptionAndActionsElement.style.borderBottom = "1px solid var(--yt-spec-10-percent-layer)";
|
||||
descriptionAndActionsElement.style.paddingBottom = "10px";
|
||||
}
|
||||
|
||||
// Fix like/dislike ratio bar offset in new UI
|
||||
querySelector(extConfig.selectors.rateBar.actionsInner).style.width = "revert";
|
||||
const actionsInner = findInCurrentWatchTree(
|
||||
buttons,
|
||||
extConfig.selectors.rateBar.actionsInner,
|
||||
descriptionAndActionsElement,
|
||||
);
|
||||
if (actionsInner) actionsInner.style.width = "revert";
|
||||
if (isRoundedDesign()) {
|
||||
querySelector(extConfig.selectors.rateBar.actions).style.flexDirection = "row-reverse";
|
||||
const actions = findInCurrentWatchTree(
|
||||
buttons,
|
||||
extConfig.selectors.rateBar.actions,
|
||||
descriptionAndActionsElement,
|
||||
);
|
||||
if (actions) actions.style.flexDirection = "row-reverse";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
document.querySelector(`.ryd-tooltip`).style.width = widthPx + "px";
|
||||
document.getElementById("ryd-bar").style.width = widthPercent + "%";
|
||||
document.querySelector("#ryd-dislike-tooltip > #tooltip").innerHTML = tooltipInnerHTML;
|
||||
buttons.querySelector(`.ryd-tooltip`).style.width = widthPx + "px";
|
||||
buttons.querySelector("#ryd-bar").style.width = widthPercent + "%";
|
||||
const tooltip = buttons.querySelector("#ryd-dislike-tooltip > #tooltip");
|
||||
if (tooltip) tooltip.innerHTML = tooltipInnerHTML;
|
||||
if (extConfig.coloredBar) {
|
||||
document.getElementById("ryd-bar-container").style.backgroundColor = getColorFromTheme(false);
|
||||
document.getElementById("ryd-bar").style.backgroundColor = getColorFromTheme(true);
|
||||
buttons.querySelector("#ryd-bar-container").style.backgroundColor = getColorFromTheme(false);
|
||||
buttons.querySelector("#ryd-bar").style.backgroundColor = getColorFromTheme(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log("removing bar");
|
||||
if (rateBar) {
|
||||
rateBar.parentNode.removeChild(rateBar);
|
||||
(rateBar.closest(".ryd-tooltip") ?? rateBar).remove();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
/** @jest-environment jsdom */
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
jest.mock("./buttons", () => ({
|
||||
getButtons: jest.fn(),
|
||||
getDislikeButton: jest.fn(),
|
||||
getLikeButton: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("./state", () => ({
|
||||
extConfig: {
|
||||
coloredBar: false,
|
||||
rateBar: null,
|
||||
selectors: {
|
||||
rateBar: {
|
||||
actions: ["#actions"],
|
||||
actionsInner: ["#actions-inner"],
|
||||
mobileActionBar: ["ytm-slim-video-action-bar-renderer"],
|
||||
topRow: ["#top-row"],
|
||||
},
|
||||
},
|
||||
showTooltipPercentage: false,
|
||||
tooltipPercentageMode: "dash_like",
|
||||
},
|
||||
isLikesDisabled: jest.fn(() => false),
|
||||
isMobile: jest.fn(() => false),
|
||||
isNewDesign: jest.fn(() => true),
|
||||
isRoundedDesign: jest.fn(() => true),
|
||||
isShorts: jest.fn(() => false),
|
||||
}));
|
||||
|
||||
jest.mock("./utils", () => ({
|
||||
getColorFromTheme: jest.fn(() => "red"),
|
||||
isInViewport: jest.fn(() => true),
|
||||
querySelector: jest.fn((selectors, element) => {
|
||||
const scope = element ?? globalThis.document;
|
||||
for (const selector of Array.isArray(selectors) ? selectors : [selectors]) {
|
||||
const match = scope?.querySelector(selector);
|
||||
if (match) return match;
|
||||
}
|
||||
return undefined;
|
||||
}),
|
||||
}));
|
||||
|
||||
const { getButtons, getDislikeButton, getLikeButton } = require("./buttons");
|
||||
const { createRateBar } = require("./bar");
|
||||
const { isLikesDisabled, isMobile, isNewDesign, isRoundedDesign, isShorts } = require("./state");
|
||||
|
||||
describe("rate-bar stylesheet contrast", () => {
|
||||
test("uses the same high-contrast negative track recipe as the userscript", () => {
|
||||
const stylesheet = fs.readFileSync(path.join(__dirname, "../content-style.css"), "utf8");
|
||||
const rule = stylesheet.match(/#ryd-bar-container\s*{([^}]*)}/)?.[1] ?? "";
|
||||
|
||||
expect(rule).toContain("background: #737373");
|
||||
expect(rule).toContain("var(--yt-spec-text-primary, #f1f1f1) 55%");
|
||||
expect(rule).toContain("var(--yt-spec-base-background, #0f0f0f) 45%");
|
||||
expect(rule).not.toContain("--yt-spec-icon-disabled");
|
||||
});
|
||||
});
|
||||
|
||||
function watchTree(videoId) {
|
||||
return `
|
||||
<ytd-watch-flexy video-id="${videoId}">
|
||||
<div id="top-row" data-watch-row="${videoId}">
|
||||
<div id="actions-inner" data-watch-actions-inner="${videoId}" style="width: 999px">
|
||||
<div id="actions" data-watch-actions="${videoId}">
|
||||
<div id="top-level-buttons-computed" data-watch-buttons="${videoId}">
|
||||
<like-button-view-model><button style="width: 96px"></button></like-button-view-model>
|
||||
<dislike-button-view-model><button style="width: 96px"></button></dislike-button-view-model>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ytd-watch-flexy>`;
|
||||
}
|
||||
|
||||
describe("rate-bar visual ownership", () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = `${watchTree("AAAAAAAAAAA")}${watchTree("BBBBBBBBBBB")}`;
|
||||
isLikesDisabled.mockReturnValue(false);
|
||||
isMobile.mockReturnValue(false);
|
||||
isNewDesign.mockReturnValue(true);
|
||||
isRoundedDesign.mockReturnValue(true);
|
||||
isShorts.mockReturnValue(false);
|
||||
const buttons = document.querySelector('[data-watch-buttons="BBBBBBBBBBB"]');
|
||||
getButtons.mockReturnValue(buttons);
|
||||
getLikeButton.mockReturnValue(buttons.querySelector("like-button-view-model"));
|
||||
getDislikeButton.mockReturnValue(buttons.querySelector("dislike-button-view-model"));
|
||||
});
|
||||
|
||||
test("mutates only the selected current watch tree when stale duplicate IDs come first", () => {
|
||||
const currentButtons = document.querySelector('[data-watch-buttons="BBBBBBBBBBB"]');
|
||||
expect(currentButtons.closest("#top-row")).toBe(document.querySelector('[data-watch-row="BBBBBBBBBBB"]'));
|
||||
expect(isNewDesign()).toBe(true);
|
||||
createRateBar(100, 25);
|
||||
|
||||
const staleRow = document.querySelector('[data-watch-row="AAAAAAAAAAA"]');
|
||||
const staleActionsInner = document.querySelector('[data-watch-actions-inner="AAAAAAAAAAA"]');
|
||||
const staleActions = document.querySelector('[data-watch-actions="AAAAAAAAAAA"]');
|
||||
const currentRow = document.querySelector('[data-watch-row="BBBBBBBBBBB"]');
|
||||
const currentActionsInner = document.querySelector('[data-watch-actions-inner="BBBBBBBBBBB"]');
|
||||
const currentActions = document.querySelector('[data-watch-actions="BBBBBBBBBBB"]');
|
||||
|
||||
expect(staleRow.style.borderBottom).toBe("");
|
||||
expect(staleRow.style.paddingBottom).toBe("");
|
||||
expect(staleActionsInner.style.width).toBe("999px");
|
||||
expect(staleActions.style.flexDirection).toBe("");
|
||||
expect(currentRow.style.paddingBottom).toBe("10px");
|
||||
expect(currentActionsInner.style.width).toBe("revert");
|
||||
expect(currentActions.style.flexDirection).toBe("row-reverse");
|
||||
expect(document.querySelector('[data-watch-buttons="BBBBBBBBBBB"] > .ryd-tooltip')).not.toBeNull();
|
||||
expect(document.querySelector('[data-watch-buttons="AAAAAAAAAAA"] > .ryd-tooltip')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,109 @@
|
||||
import { isMobile, isShorts, extConfig } from "./state";
|
||||
import { isInViewport, querySelector, querySelectorAll } from "./utils";
|
||||
import { getVideoId, isInViewport, querySelector, querySelectorAll } from "./utils";
|
||||
|
||||
const buttonsVideoOwnership = new WeakMap();
|
||||
|
||||
function hasRenderedBox(element) {
|
||||
if (!element?.isConnected || element.closest("[hidden], [aria-hidden='true'], [inert]")) {
|
||||
return false;
|
||||
}
|
||||
for (let current = element; current; current = current.parentElement) {
|
||||
const style = window.getComputedStyle(current);
|
||||
if (
|
||||
style.display === "none" ||
|
||||
style.visibility === "hidden" ||
|
||||
style.visibility === "collapse" ||
|
||||
Number.parseFloat(style.opacity) === 0
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0;
|
||||
}
|
||||
|
||||
function intersectsViewport(element) {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const height = innerHeight || document.documentElement.clientHeight;
|
||||
const width = innerWidth || document.documentElement.clientWidth;
|
||||
return (
|
||||
rect.width > 0 && rect.height > 0 && rect.bottom > 0 && rect.right > 0 && rect.top < height && rect.left < width
|
||||
);
|
||||
}
|
||||
|
||||
function configuredMatches(selectors) {
|
||||
const matches = [];
|
||||
for (const selector of Array.isArray(selectors) ? selectors : [selectors]) {
|
||||
if (selector) matches.push(...document.querySelectorAll(selector));
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
function getDesktopWatchButtonCandidates() {
|
||||
return Array.from(
|
||||
new Set([
|
||||
...configuredMatches(extConfig.selectors.buttons.regular.desktopMenu),
|
||||
...configuredMatches(extConfig.selectors.buttons.regular.desktopNoMenu),
|
||||
]),
|
||||
).filter((candidate) => {
|
||||
const segmented = querySelector(extConfig.selectors.buttons.segmentedContainer, candidate);
|
||||
const like = querySelector(extConfig.selectors.buttons.likeButton.notSegmented, candidate);
|
||||
return segmented !== undefined || like !== undefined;
|
||||
});
|
||||
}
|
||||
|
||||
function markButtonsForVideo(buttons, videoId) {
|
||||
if (buttons && videoId) {
|
||||
buttonsVideoOwnership.set(buttons, videoId);
|
||||
}
|
||||
}
|
||||
|
||||
function getButtonsVideoOwnership(candidate) {
|
||||
return (
|
||||
buttonsVideoOwnership.get(candidate) ??
|
||||
candidate.getAttribute("video-id") ??
|
||||
candidate.getAttribute("data-video-id")
|
||||
);
|
||||
}
|
||||
|
||||
function selectCurrentWatchButtons(candidates) {
|
||||
const videoId = getVideoId(window.location.href);
|
||||
const ranked = candidates
|
||||
.map((candidate, index) => {
|
||||
const watchRoot = candidate.closest("ytd-watch-flexy, ytd-watch-grid");
|
||||
const rootVideoId = watchRoot?.getAttribute("video-id");
|
||||
const rootMatches = Boolean(videoId && rootVideoId === videoId);
|
||||
const rootConflicts = Boolean(videoId && rootVideoId && rootVideoId !== videoId);
|
||||
const controlsVideoId = getButtonsVideoOwnership(candidate);
|
||||
const controlsMatch = Boolean(videoId && controlsVideoId === videoId);
|
||||
const controlsConflict = Boolean(videoId && controlsVideoId && controlsVideoId !== videoId);
|
||||
const rendered = hasRenderedBox(candidate);
|
||||
const inViewport = rendered && intersectsViewport(candidate);
|
||||
const tier =
|
||||
controlsMatch && inViewport
|
||||
? 8
|
||||
: rootMatches && inViewport
|
||||
? 7
|
||||
: inViewport
|
||||
? 6
|
||||
: controlsMatch && rendered
|
||||
? 5
|
||||
: rootMatches && rendered
|
||||
? 4
|
||||
: rendered
|
||||
? 3
|
||||
: controlsMatch || rootMatches
|
||||
? 2
|
||||
: 1;
|
||||
return { candidate, controlsConflict, index, rootConflicts, tier };
|
||||
})
|
||||
// Do not bind outgoing controls to the destination video while YouTube is
|
||||
// switching the current watch root during an SPA navigation.
|
||||
.filter(({ rootConflicts }) => !rootConflicts);
|
||||
const ownershipCompatible = ranked.filter(({ controlsConflict }) => !controlsConflict);
|
||||
const selectionPool = ownershipCompatible.length > 0 ? ownershipCompatible : ranked;
|
||||
return selectionPool.sort((left, right) => right.tier - left.tier || left.index - right.index)[0]?.candidate;
|
||||
}
|
||||
|
||||
function getNativeButton(buttonContainer) {
|
||||
return querySelector(extConfig.selectors.buttons.nativeButton, buttonContainer);
|
||||
@@ -32,20 +136,15 @@ function getButtons() {
|
||||
if (isMobile()) {
|
||||
return document.querySelector(extConfig.selectors.buttons.regular.mobile);
|
||||
}
|
||||
//--- If Menu Element Is Displayed: ---//
|
||||
if (querySelector(extConfig.selectors.menuContainer)?.offsetParent === null) {
|
||||
return querySelector(extConfig.selectors.buttons.regular.desktopMenu);
|
||||
//--- If Menu Element Isn't Displayed: ---//
|
||||
} else {
|
||||
return querySelector(extConfig.selectors.buttons.regular.desktopNoMenu);
|
||||
}
|
||||
return selectCurrentWatchButtons(getDesktopWatchButtonCandidates());
|
||||
}
|
||||
|
||||
function getLikeButton() {
|
||||
const buttons = getButtons();
|
||||
return isSegmentedButtonLayout()
|
||||
? querySelector(extConfig.selectors.buttons.likeButton.segmented) ??
|
||||
querySelector(extConfig.selectors.buttons.likeButton.segmentedGetButtons, getButtons())
|
||||
: querySelector(extConfig.selectors.buttons.likeButton.notSegmented, getButtons());
|
||||
? querySelector(extConfig.selectors.buttons.likeButton.segmented, buttons) ??
|
||||
querySelector(extConfig.selectors.buttons.likeButton.segmentedGetButtons, buttons)
|
||||
: querySelector(extConfig.selectors.buttons.likeButton.notSegmented, buttons);
|
||||
}
|
||||
|
||||
function getLikeTextContainer() {
|
||||
@@ -53,21 +152,22 @@ function getLikeTextContainer() {
|
||||
}
|
||||
|
||||
function getDislikeButton() {
|
||||
const buttons = getButtons();
|
||||
if (isSegmentedButtonLayout()) {
|
||||
return (
|
||||
querySelector(extConfig.selectors.buttons.dislikeButton.segmented) ??
|
||||
querySelector(extConfig.selectors.buttons.dislikeButton.segmentedGetButtons, getButtons())
|
||||
querySelector(extConfig.selectors.buttons.dislikeButton.segmented, buttons) ??
|
||||
querySelector(extConfig.selectors.buttons.dislikeButton.segmentedGetButtons, buttons)
|
||||
);
|
||||
}
|
||||
|
||||
const notSegmentedMatch = querySelector(extConfig.selectors.buttons.dislikeButton.notSegmented, getButtons());
|
||||
const notSegmentedMatch = querySelector(extConfig.selectors.buttons.dislikeButton.notSegmented, buttons);
|
||||
|
||||
if (notSegmentedMatch != null) {
|
||||
return notSegmentedMatch;
|
||||
}
|
||||
|
||||
if (isShorts()) {
|
||||
return querySelector(extConfig.selectors.buttons.dislikeButton.shortsFallback, getButtons());
|
||||
return querySelector(extConfig.selectors.buttons.dislikeButton.shortsFallback, buttons);
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -141,4 +241,6 @@ export {
|
||||
getLikeTextContainer,
|
||||
getDislikeTextContainer,
|
||||
checkForSignInButton,
|
||||
hasRenderedBox,
|
||||
markButtonsForVideo,
|
||||
};
|
||||
@@ -0,0 +1,151 @@
|
||||
/** @jest-environment jsdom */
|
||||
|
||||
const { extConfig } = require("./state");
|
||||
const { getButtons, getDislikeButton, getLikeButton, hasRenderedBox, markButtonsForVideo } = require("./buttons");
|
||||
|
||||
function controls(id, videoId, attributes = "") {
|
||||
return `
|
||||
<ytd-menu-renderer class="ytd-watch-metadata" ${attributes}>
|
||||
<div id="${id}" data-video-id="${videoId}">
|
||||
<segmented-like-dislike-button-view-model>
|
||||
<like-button-view-model id="segmented-like-button"><button aria-pressed="false"></button></like-button-view-model>
|
||||
<dislike-button-view-model id="segmented-dislike-button"><button aria-pressed="false"></button></dislike-button-view-model>
|
||||
</segmented-like-dislike-button-view-model>
|
||||
</div>
|
||||
</ytd-menu-renderer>`;
|
||||
}
|
||||
|
||||
function setBox(element, { height = 48, width = 320, x = 20, y = 20 } = {}) {
|
||||
element.getBoundingClientRect = () => ({
|
||||
bottom: y + height,
|
||||
height,
|
||||
left: x,
|
||||
right: x + width,
|
||||
top: y,
|
||||
width,
|
||||
x,
|
||||
y,
|
||||
});
|
||||
}
|
||||
|
||||
describe("desktop watch button ownership", () => {
|
||||
beforeEach(() => {
|
||||
history.replaceState({}, "", "/watch?v=BBBBBBBBBBB");
|
||||
extConfig.selectors.buttons.regular.desktopMenu = ["ytd-menu-renderer.ytd-watch-metadata > div"];
|
||||
extConfig.selectors.buttons.regular.desktopNoMenu = ["#top-level-buttons-computed"];
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
test("prefers viewport-intersecting destination controls over a positive-size offscreen sibling in the same root", () => {
|
||||
document.body.innerHTML = `
|
||||
<ytd-watch-flexy video-id="BBBBBBBBBBB">
|
||||
${controls("stale", "AAAAAAAAAAA")}
|
||||
${controls("current", "BBBBBBBBBBB")}
|
||||
</ytd-watch-flexy>`;
|
||||
setBox(document.querySelector("#stale"), { x: -10_000 });
|
||||
setBox(document.querySelector("#current"), { x: 40 });
|
||||
|
||||
expect(getButtons()).toBe(document.querySelector("#current"));
|
||||
});
|
||||
|
||||
test("prefers unowned destination controls over initialized outgoing controls when both overlap in the current root", () => {
|
||||
document.body.innerHTML = `
|
||||
<ytd-watch-flexy video-id="BBBBBBBBBBB">
|
||||
${controls("stale", "AAAAAAAAAAA")}
|
||||
${controls("current", "BBBBBBBBBBB")}
|
||||
</ytd-watch-flexy>`;
|
||||
const stale = document.querySelector("#stale");
|
||||
const current = document.querySelector("#current");
|
||||
setBox(stale, { x: 40 });
|
||||
setBox(current, { x: 40 });
|
||||
markButtonsForVideo(stale, "AAAAAAAAAAA");
|
||||
|
||||
expect(getButtons()).toBe(current);
|
||||
});
|
||||
|
||||
test("falls back to a reused marked control when it is the only current-root candidate", () => {
|
||||
document.body.innerHTML = `
|
||||
<ytd-watch-flexy video-id="BBBBBBBBBBB">
|
||||
${controls("reused", "AAAAAAAAAAA")}
|
||||
</ytd-watch-flexy>`;
|
||||
const reused = document.querySelector("#reused");
|
||||
setBox(reused, { x: 40 });
|
||||
markButtonsForVideo(reused, "AAAAAAAAAAA");
|
||||
|
||||
expect(getButtons()).toBe(reused);
|
||||
});
|
||||
|
||||
test("ignores hidden, transparent, and inert stale candidates before current controls", () => {
|
||||
document.body.innerHTML = `
|
||||
<ytd-watch-flexy video-id="BBBBBBBBBBB">
|
||||
<div hidden>${controls("hidden-stale", "AAAAAAAAAAA")}</div>
|
||||
<div style="opacity: 0">${controls("transparent-stale", "AAAAAAAAAAA")}</div>
|
||||
<div inert>${controls("inert-stale", "AAAAAAAAAAA")}</div>
|
||||
${controls("current", "BBBBBBBBBBB")}
|
||||
</ytd-watch-flexy>`;
|
||||
["#hidden-stale", "#transparent-stale", "#inert-stale", "#current"].forEach((selector) =>
|
||||
setBox(document.querySelector(selector)),
|
||||
);
|
||||
|
||||
expect(getButtons()).toBe(document.querySelector("#current"));
|
||||
expect(hasRenderedBox(document.querySelector("#hidden-stale"))).toBe(false);
|
||||
expect(hasRenderedBox(document.querySelector("#transparent-stale"))).toBe(false);
|
||||
expect(hasRenderedBox(document.querySelector("#inert-stale"))).toBe(false);
|
||||
});
|
||||
|
||||
test("does not bind rendered controls owned by an explicit outgoing video root", () => {
|
||||
document.body.innerHTML = `
|
||||
<ytd-watch-flexy video-id="AAAAAAAAAAA">
|
||||
${controls("outgoing", "AAAAAAAAAAA")}
|
||||
</ytd-watch-flexy>`;
|
||||
setBox(document.querySelector("#outgoing"));
|
||||
|
||||
expect(getButtons()).toBeUndefined();
|
||||
});
|
||||
|
||||
test("accepts fixed-position current controls even though they have no offset parent", () => {
|
||||
document.body.innerHTML = `
|
||||
<ytd-watch-flexy video-id="BBBBBBBBBBB">
|
||||
${controls("current", "BBBBBBBBBBB", 'style="position: fixed"')}
|
||||
</ytd-watch-flexy>`;
|
||||
const current = document.querySelector("#current");
|
||||
setBox(current);
|
||||
|
||||
expect(current.offsetParent).toBeNull();
|
||||
expect(hasRenderedBox(current)).toBe(true);
|
||||
expect(getButtons()).toBe(current);
|
||||
});
|
||||
|
||||
test("uses an offscreen current-root candidate as a fallback when no viewport candidate exists", () => {
|
||||
document.body.innerHTML = `
|
||||
<ytd-watch-flexy video-id="BBBBBBBBBBB">
|
||||
${controls("current", "BBBBBBBBBBB")}
|
||||
</ytd-watch-flexy>`;
|
||||
const current = document.querySelector("#current");
|
||||
setBox(current, { x: -10_000 });
|
||||
|
||||
expect(hasRenderedBox(current)).toBe(true);
|
||||
expect(getButtons()).toBe(current);
|
||||
});
|
||||
|
||||
test("scopes segmented reaction controls to the selected destination container", () => {
|
||||
const originalSegmentedContainer = extConfig.selectors.buttons.segmentedContainer;
|
||||
extConfig.selectors.buttons.segmentedContainer = ["segmented-like-dislike-button-view-model"];
|
||||
try {
|
||||
document.body.innerHTML = `
|
||||
<ytd-watch-flexy video-id="BBBBBBBBBBB">
|
||||
${controls("stale", "AAAAAAAAAAA")}
|
||||
${controls("current", "BBBBBBBBBBB")}
|
||||
</ytd-watch-flexy>`;
|
||||
setBox(document.querySelector("#stale"), { x: -10_000 });
|
||||
setBox(document.querySelector("#current"), { x: 40 });
|
||||
|
||||
const current = document.querySelector("#current");
|
||||
expect(getButtons()).toBe(current);
|
||||
expect(getLikeButton()).toBe(current.querySelector("like-button-view-model"));
|
||||
expect(getDislikeButton()).toBe(current.querySelector("dislike-button-view-model"));
|
||||
} finally {
|
||||
extConfig.selectors.buttons.segmentedContainer = originalSegmentedContainer;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,24 +1,25 @@
|
||||
import { getBrowser, getVideoId, numberFormat, createObserver, querySelector } from "./utils";
|
||||
import { checkForSignInButton, getButtons, getDislikeButton, getLikeButton } from "./buttons";
|
||||
import {
|
||||
NEUTRAL_STATE,
|
||||
LIKED_STATE,
|
||||
DISLIKED_STATE,
|
||||
setDislikes,
|
||||
extConfig,
|
||||
storedData,
|
||||
setLikes,
|
||||
getLikeCountFromButton,
|
||||
} from "./state";
|
||||
import { setDislikes, extConfig, storedData, setLikes, getLikeCountFromButton } from "./state";
|
||||
import { createRateBar } from "./bar";
|
||||
import {
|
||||
LIKE_ACTION,
|
||||
DISLIKE_ACTION,
|
||||
resolveVoteTransition,
|
||||
applyVoteTransitionCounts,
|
||||
shouldSubmitVote,
|
||||
} from "../../common/vote-transition";
|
||||
|
||||
function sendVote(vote) {
|
||||
if (extConfig.disableVoteSubmission !== true) {
|
||||
getBrowser().runtime.sendMessage({
|
||||
if (shouldSubmitVote({ disableVoteSubmission: extConfig.disableVoteSubmission })) {
|
||||
const result = getBrowser().runtime.sendMessage({
|
||||
message: "send_vote",
|
||||
vote: vote,
|
||||
videoId: getVideoId(window.location.href),
|
||||
});
|
||||
if (result && typeof result.catch === "function") {
|
||||
result.catch((error) => console.error("Vote submission failed", error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -27,25 +28,16 @@ function updateDOMDislikes() {
|
||||
createRateBar(storedData.likes, storedData.dislikes);
|
||||
}
|
||||
|
||||
function likeClicked() {
|
||||
function handleVoteAction(action) {
|
||||
if (checkForSignInButton() === false) {
|
||||
if (storedData.previousState === DISLIKED_STATE) {
|
||||
sendVote(1);
|
||||
if (storedData.dislikes > 0) storedData.dislikes--;
|
||||
storedData.likes++;
|
||||
updateDOMDislikes();
|
||||
storedData.previousState = LIKED_STATE;
|
||||
} else if (storedData.previousState === NEUTRAL_STATE) {
|
||||
sendVote(1);
|
||||
storedData.likes++;
|
||||
updateDOMDislikes();
|
||||
storedData.previousState = LIKED_STATE;
|
||||
} else if ((storedData.previousState = LIKED_STATE)) {
|
||||
sendVote(0);
|
||||
if (storedData.likes > 0) storedData.likes--;
|
||||
updateDOMDislikes();
|
||||
storedData.previousState = NEUTRAL_STATE;
|
||||
}
|
||||
const transition = resolveVoteTransition(storedData.previousState, action);
|
||||
const counts = applyVoteTransitionCounts(storedData.likes, storedData.dislikes, transition);
|
||||
sendVote(transition.value);
|
||||
storedData.likes = counts.likes;
|
||||
storedData.dislikes = counts.dislikes;
|
||||
storedData.previousState = transition.nextState;
|
||||
updateDOMDislikes();
|
||||
|
||||
if (extConfig.numberDisplayReformatLikes === true) {
|
||||
const nativeLikes = getLikeCountFromButton();
|
||||
if (nativeLikes !== false) {
|
||||
@@ -55,45 +47,29 @@ function likeClicked() {
|
||||
}
|
||||
}
|
||||
|
||||
function dislikeClicked() {
|
||||
if (checkForSignInButton() == false) {
|
||||
if (storedData.previousState === NEUTRAL_STATE) {
|
||||
sendVote(-1);
|
||||
storedData.dislikes++;
|
||||
updateDOMDislikes();
|
||||
storedData.previousState = DISLIKED_STATE;
|
||||
} else if (storedData.previousState === DISLIKED_STATE) {
|
||||
sendVote(0);
|
||||
if (storedData.dislikes > 0) storedData.dislikes--;
|
||||
updateDOMDislikes();
|
||||
storedData.previousState = NEUTRAL_STATE;
|
||||
} else if (storedData.previousState === LIKED_STATE) {
|
||||
sendVote(-1);
|
||||
if (storedData.likes > 0) storedData.likes--;
|
||||
storedData.dislikes++;
|
||||
updateDOMDislikes();
|
||||
storedData.previousState = DISLIKED_STATE;
|
||||
if (extConfig.numberDisplayReformatLikes === true) {
|
||||
const nativeLikes = getLikeCountFromButton();
|
||||
if (nativeLikes !== false) {
|
||||
setLikes(numberFormat(nativeLikes));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function likeClicked() {
|
||||
handleVoteAction(LIKE_ACTION);
|
||||
}
|
||||
|
||||
function dislikeClicked() {
|
||||
handleVoteAction(DISLIKE_ACTION);
|
||||
}
|
||||
|
||||
const boundLikeButtons = new WeakSet();
|
||||
const boundDislikeButtons = new WeakSet();
|
||||
|
||||
function addLikeDislikeEventListener() {
|
||||
if (window.rydPreNavigateLikeButton !== getLikeButton()) {
|
||||
getLikeButton().addEventListener("click", likeClicked);
|
||||
getLikeButton().addEventListener("touchstart", likeClicked);
|
||||
if (getDislikeButton()) {
|
||||
getDislikeButton().addEventListener("click", dislikeClicked);
|
||||
getDislikeButton().addEventListener("touchstart", dislikeClicked);
|
||||
getDislikeButton().addEventListener("focusin", updateDOMDislikes);
|
||||
getDislikeButton().addEventListener("focusout", updateDOMDislikes);
|
||||
}
|
||||
window.rydPreNavigateLikeButton = getLikeButton();
|
||||
const likeButton = getLikeButton();
|
||||
const dislikeButton = getDislikeButton();
|
||||
if (likeButton && !boundLikeButtons.has(likeButton)) {
|
||||
likeButton.addEventListener("click", likeClicked);
|
||||
boundLikeButtons.add(likeButton);
|
||||
}
|
||||
if (dislikeButton && !boundDislikeButtons.has(dislikeButton)) {
|
||||
dislikeButton.addEventListener("click", dislikeClicked);
|
||||
dislikeButton.addEventListener("focusin", updateDOMDislikes);
|
||||
dislikeButton.addEventListener("focusout", updateDOMDislikes);
|
||||
boundDislikeButtons.add(dislikeButton);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
function createInitializationCycleRunner(runCycle) {
|
||||
if (typeof runCycle !== "function") {
|
||||
throw new TypeError("An initialization cycle function is required.");
|
||||
}
|
||||
|
||||
let activePromise = null;
|
||||
let rerunRequested = false;
|
||||
|
||||
async function request() {
|
||||
if (activePromise) {
|
||||
rerunRequested = true;
|
||||
return activePromise;
|
||||
}
|
||||
|
||||
activePromise = (async () => {
|
||||
do {
|
||||
rerunRequested = false;
|
||||
await runCycle();
|
||||
} while (rerunRequested);
|
||||
})();
|
||||
|
||||
try {
|
||||
return await activePromise;
|
||||
} finally {
|
||||
activePromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isRunning: () => activePromise !== null,
|
||||
request,
|
||||
};
|
||||
}
|
||||
|
||||
export { createInitializationCycleRunner };
|
||||
@@ -0,0 +1,58 @@
|
||||
import { createInitializationCycleRunner } from "./initialization-cycle";
|
||||
|
||||
function deferred() {
|
||||
let resolve;
|
||||
const promise = new Promise((resolvePromise) => {
|
||||
resolve = resolvePromise;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
test("queues a fresh initialization when navigation arrives during an in-flight cycle", async () => {
|
||||
const outgoing = deferred();
|
||||
const calls = [];
|
||||
const runner = createInitializationCycleRunner(async () => {
|
||||
calls.push(calls.length === 0 ? "A" : "B");
|
||||
if (calls.length === 1) await outgoing.promise;
|
||||
});
|
||||
|
||||
const first = runner.request();
|
||||
const navigation = runner.request();
|
||||
|
||||
expect(runner.isRunning()).toBe(true);
|
||||
expect(calls).toEqual(["A"]);
|
||||
|
||||
outgoing.resolve();
|
||||
await Promise.all([first, navigation]);
|
||||
|
||||
expect(calls).toEqual(["A", "B"]);
|
||||
expect(runner.isRunning()).toBe(false);
|
||||
});
|
||||
|
||||
test("coalesces repeated navigation signals into one pending cycle", async () => {
|
||||
const outgoing = deferred();
|
||||
const runCycle = jest.fn(async () => {
|
||||
if (runCycle.mock.calls.length === 1) await outgoing.promise;
|
||||
});
|
||||
const runner = createInitializationCycleRunner(runCycle);
|
||||
|
||||
const first = runner.request();
|
||||
const queued = [runner.request(), runner.request(), runner.request()];
|
||||
outgoing.resolve();
|
||||
await Promise.all([first, ...queued]);
|
||||
|
||||
expect(runCycle).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("continues accepting independent cycles after a queued rerun", async () => {
|
||||
const runner = createInitializationCycleRunner(jest.fn(async () => {}));
|
||||
|
||||
await runner.request();
|
||||
await runner.request();
|
||||
|
||||
expect(runner.isRunning()).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects invalid cycle callbacks", () => {
|
||||
expect(() => createInitializationCycleRunner()).toThrow(TypeError);
|
||||
});
|
||||
@@ -11,9 +11,7 @@ import {
|
||||
createObserver,
|
||||
} from "./utils";
|
||||
import { config, getApiEndpoint, DEV_API_URL, PROD_API_URL, isDevelopment } from "./config";
|
||||
const LIKED_STATE = "LIKED_STATE";
|
||||
const DISLIKED_STATE = "DISLIKED_STATE";
|
||||
const NEUTRAL_STATE = "NEUTRAL_STATE";
|
||||
import { LIKED_STATE, DISLIKED_STATE, NEUTRAL_STATE } from "../../common/vote-transition";
|
||||
|
||||
const DEFAULT_SELECTORS = {
|
||||
dislikeTextContainer: [
|
||||
@@ -140,6 +138,7 @@ let storedData = {
|
||||
likes: 0,
|
||||
dislikes: 0,
|
||||
previousState: NEUTRAL_STATE,
|
||||
videoId: null,
|
||||
};
|
||||
|
||||
function isMobile() {
|
||||
@@ -317,7 +316,10 @@ function processResponse(response, storedData) {
|
||||
}
|
||||
|
||||
// Tells the user if the API is down
|
||||
function displayError(error) {
|
||||
function displayError(error, videoId = getVideoId(window.location.href)) {
|
||||
if (getVideoId(window.location.href) !== videoId) {
|
||||
return;
|
||||
}
|
||||
getDislikeTextContainer().innerText = localize("textTempUnavailable");
|
||||
}
|
||||
|
||||
@@ -326,35 +328,54 @@ async function setState(storedData) {
|
||||
window.__rydSetStateCalls = (window.__rydSetStateCalls || 0) + 1;
|
||||
}
|
||||
storedData.previousState = isVideoDisliked() ? DISLIKED_STATE : isVideoLiked() ? LIKED_STATE : NEUTRAL_STATE;
|
||||
let statsSet = false;
|
||||
console.log("Video is loaded. Adding buttons...");
|
||||
|
||||
let videoId = getVideoId(window.location.href);
|
||||
let likeCount = getLikeCountFromButton() || null;
|
||||
|
||||
let response = await fetch(getApiEndpoint(`/votes?videoId=${videoId}&likeCount=${likeCount || ""}`), {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok) displayError(response.error);
|
||||
return response;
|
||||
})
|
||||
.then((response) => response.json())
|
||||
.catch(displayError);
|
||||
const videoId = getVideoId(window.location.href);
|
||||
const likeCount = getLikeCountFromButton() || null;
|
||||
let response;
|
||||
try {
|
||||
const request = await fetch(getApiEndpoint(`/votes?videoId=${videoId}&likeCount=${likeCount || ""}`), {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
if (!request.ok) {
|
||||
displayError(request.error, videoId);
|
||||
return;
|
||||
}
|
||||
response = await request.json();
|
||||
} catch (error) {
|
||||
displayError(error, videoId);
|
||||
return;
|
||||
}
|
||||
console.log("response from api:");
|
||||
console.log(JSON.stringify(response));
|
||||
if (response !== undefined && !("traceId" in response) && !statsSet) {
|
||||
processResponse(response, storedData);
|
||||
if (getVideoId(window.location.href) !== videoId) {
|
||||
return;
|
||||
}
|
||||
if (!response || typeof response !== "object" || "traceId" in response) {
|
||||
displayError(response, videoId);
|
||||
return;
|
||||
}
|
||||
processResponse(response, storedData);
|
||||
storedData.videoId = videoId;
|
||||
}
|
||||
|
||||
async function setInitialState() {
|
||||
await setState(storedData);
|
||||
}
|
||||
|
||||
function hasLoadedStateForVideo(videoId) {
|
||||
return storedData.videoId === videoId;
|
||||
}
|
||||
|
||||
function restoreCurrentState() {
|
||||
storedData.previousState = isVideoDisliked() ? DISLIKED_STATE : isVideoLiked() ? LIKED_STATE : NEUTRAL_STATE;
|
||||
setDislikes(numberFormat(storedData.dislikes));
|
||||
createRateBar(storedData.likes, storedData.dislikes);
|
||||
}
|
||||
|
||||
async function initExtConfig() {
|
||||
initializeDisableVoteSubmission();
|
||||
initializeDisableLogging();
|
||||
@@ -508,4 +529,6 @@ export {
|
||||
initExtConfig,
|
||||
storedData,
|
||||
isLikesDisabled,
|
||||
hasLoadedStateForVideo,
|
||||
restoreCurrentState,
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
|
||||
jest.mock("./buttons", () => {
|
||||
const dislikeTextContainer = {
|
||||
innerText: "native dislike",
|
||||
removeAttribute: jest.fn(),
|
||||
};
|
||||
const likeButton = {
|
||||
classList: { contains: () => false },
|
||||
native: { getAttribute: (name) => (name === "aria-label" ? "35 likes" : "false") },
|
||||
};
|
||||
const dislikeButton = {
|
||||
classList: { contains: () => false },
|
||||
native: { getAttribute: () => "false" },
|
||||
};
|
||||
return {
|
||||
getButtons: () => ({ children: [] }),
|
||||
getDislikeButton: () => dislikeButton,
|
||||
getDislikeTextContainer: () => dislikeTextContainer,
|
||||
getLikeButton: () => likeButton,
|
||||
getLikeTextContainer: () => ({ innerText: "35" }),
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock("./bar", () => ({
|
||||
createRateBar: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("./config", () => ({
|
||||
DEV_API_URL: "https://example.test",
|
||||
PROD_API_URL: "https://example.test",
|
||||
config: {},
|
||||
getApiEndpoint: (pathname) => `https://example.test${pathname}`,
|
||||
isDevelopment: () => false,
|
||||
}));
|
||||
|
||||
jest.mock("./utils", () => ({
|
||||
createObserver: () => ({ observe: jest.fn() }),
|
||||
getBrowser: () => undefined,
|
||||
getColorFromTheme: () => undefined,
|
||||
getVideoId: (url) => new URL(url).searchParams.get("v"),
|
||||
initializeLogging: () => undefined,
|
||||
localize: (key) => key,
|
||||
numberFormat: (value) => String(value),
|
||||
querySelector: (selectors, root) => root?.native ?? null,
|
||||
}));
|
||||
|
||||
import { createRateBar } from "./bar";
|
||||
import { getDislikeTextContainer } from "./buttons";
|
||||
import { setState } from "./state";
|
||||
|
||||
const dislikeTextContainer = getDislikeTextContainer();
|
||||
|
||||
function deferred() {
|
||||
let resolve;
|
||||
let reject;
|
||||
const promise = new Promise((resolvePromise, rejectPromise) => {
|
||||
resolve = resolvePromise;
|
||||
reject = rejectPromise;
|
||||
});
|
||||
return { promise, reject, resolve };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
dislikeTextContainer.innerText = "native dislike";
|
||||
dislikeTextContainer.removeAttribute.mockClear();
|
||||
createRateBar.mockClear();
|
||||
global.fetch = jest.fn();
|
||||
window.history.replaceState(null, "", "/watch?v=abcdefghijk");
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
delete global.fetch;
|
||||
});
|
||||
|
||||
test("a delayed outgoing request failure cannot overwrite the destination before its successful initialization", async () => {
|
||||
const outgoing = deferred();
|
||||
const destinationResponse = {
|
||||
ok: true,
|
||||
json: jest.fn(async () => ({ dislikes: 65, likes: 35, rating: 3.5 })),
|
||||
};
|
||||
fetch.mockReturnValueOnce(outgoing.promise).mockResolvedValueOnce(destinationResponse);
|
||||
const testState = { dislikes: 0, likes: 0, previousState: "neutral", videoId: null };
|
||||
|
||||
const outgoingInitialization = setState(testState);
|
||||
await Promise.resolve();
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
window.history.replaceState(null, "", "/watch?v=zyxwvutsrqp");
|
||||
outgoing.reject(new TypeError("outgoing request failed"));
|
||||
await outgoingInitialization;
|
||||
|
||||
expect(dislikeTextContainer.innerText).toBe("native dislike");
|
||||
expect(createRateBar).not.toHaveBeenCalled();
|
||||
|
||||
await setState(testState);
|
||||
|
||||
expect(dislikeTextContainer.innerText).toBe("65");
|
||||
expect(createRateBar).toHaveBeenCalledWith(35, 65);
|
||||
expect(testState.videoId).toBe("zyxwvutsrqp");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["non-2xx", { ok: false, error: new Error("unavailable") }],
|
||||
[
|
||||
"malformed JSON",
|
||||
{
|
||||
ok: true,
|
||||
json: async () => {
|
||||
throw new SyntaxError("invalid JSON");
|
||||
},
|
||||
},
|
||||
],
|
||||
])("a delayed outgoing %s response cannot write an error into the destination controls", async (name, response) => {
|
||||
const outgoing = deferred();
|
||||
fetch.mockReturnValueOnce(outgoing.promise);
|
||||
const testState = { dislikes: 0, likes: 0, previousState: "neutral", videoId: null };
|
||||
|
||||
const initialization = setState(testState);
|
||||
await Promise.resolve();
|
||||
window.history.replaceState(null, "", "/watch?v=zyxwvutsrqp");
|
||||
// Resolve the request only after navigation so every failure path exercises the stale-video guard.
|
||||
outgoing.resolve(response);
|
||||
await initialization;
|
||||
|
||||
expect(dislikeTextContainer.innerText).toBe("native dislike");
|
||||
expect(createRateBar).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
function createStorageCaller(storageArea, getLastError = () => undefined) {
|
||||
return function call(methodName, ...args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
const finish = (callback) => (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
callback(value);
|
||||
};
|
||||
const resolveOnce = finish(resolve);
|
||||
const rejectOnce = finish(reject);
|
||||
const callback = (result) => {
|
||||
const lastError = getLastError();
|
||||
if (lastError) {
|
||||
rejectOnce(new Error(lastError.message || String(lastError)));
|
||||
} else {
|
||||
resolveOnce(result);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const maybePromise = storageArea[methodName](...args, callback);
|
||||
if (maybePromise && typeof maybePromise.then === "function") {
|
||||
maybePromise.then(resolveOnce, rejectOnce);
|
||||
}
|
||||
} catch (callbackError) {
|
||||
try {
|
||||
const maybePromise = storageArea[methodName](...args);
|
||||
Promise.resolve(maybePromise).then(resolveOnce, rejectOnce);
|
||||
} catch (promiseError) {
|
||||
rejectOnce(promiseError ?? callbackError);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
function createBrowserCredentialStore(storageArea, getLastError) {
|
||||
if (!storageArea?.get || !storageArea?.set) {
|
||||
throw new TypeError("A browser storage area is required");
|
||||
}
|
||||
|
||||
const call = createStorageCaller(storageArea, getLastError);
|
||||
return {
|
||||
async load() {
|
||||
const result = await call("get", ["userId", "registrationConfirmed"]);
|
||||
if (!result?.userId || result.registrationConfirmed !== true) return null;
|
||||
return { userId: result.userId, registrationConfirmed: true };
|
||||
},
|
||||
|
||||
async save(credentials) {
|
||||
await call("set", {
|
||||
userId: credentials.userId,
|
||||
registrationConfirmed: credentials.registrationConfirmed === true,
|
||||
});
|
||||
},
|
||||
|
||||
async clear() {
|
||||
if (typeof storageArea.remove === "function") {
|
||||
await call("remove", ["userId", "registrationConfirmed"]);
|
||||
} else {
|
||||
await call("set", { userId: null, registrationConfirmed: false });
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export { createBrowserCredentialStore };
|
||||
@@ -0,0 +1,80 @@
|
||||
import { createBrowserCredentialStore } from "./vote-client-adapter";
|
||||
|
||||
describe("createBrowserCredentialStore", () => {
|
||||
it("implements the credential contract with callback-based Chrome storage", async () => {
|
||||
const values = {};
|
||||
const storageArea = {
|
||||
get: jest.fn((keys, callback) => {
|
||||
callback(Object.fromEntries(keys.filter((key) => key in values).map((key) => [key, values[key]])));
|
||||
}),
|
||||
set: jest.fn((nextValues, callback) => {
|
||||
Object.assign(values, nextValues);
|
||||
callback();
|
||||
}),
|
||||
remove: jest.fn((keys, callback) => {
|
||||
keys.forEach((key) => delete values[key]);
|
||||
callback();
|
||||
}),
|
||||
};
|
||||
const store = createBrowserCredentialStore(storageArea, () => undefined);
|
||||
|
||||
expect(await store.load()).toBeNull();
|
||||
await store.save({ userId: "callback-user", registrationConfirmed: true });
|
||||
expect(await store.load()).toEqual({ userId: "callback-user", registrationConfirmed: true });
|
||||
expect(values).toEqual({ userId: "callback-user", registrationConfirmed: true });
|
||||
|
||||
await store.clear();
|
||||
expect(values).toEqual({});
|
||||
expect(storageArea.remove).toHaveBeenCalledWith(["userId", "registrationConfirmed"], expect.any(Function));
|
||||
});
|
||||
|
||||
it("implements the same contract with Promise-based browser storage", async () => {
|
||||
const values = { userId: "promise-user", registrationConfirmed: true };
|
||||
const storageArea = {
|
||||
get: jest.fn(async (keys) => Object.fromEntries(keys.map((key) => [key, values[key]]))),
|
||||
set: jest.fn(async (nextValues) => Object.assign(values, nextValues)),
|
||||
remove: jest.fn(async (keys) => keys.forEach((key) => delete values[key])),
|
||||
};
|
||||
const store = createBrowserCredentialStore(storageArea);
|
||||
|
||||
expect(await store.load()).toEqual({ userId: "promise-user", registrationConfirmed: true });
|
||||
await store.save({ userId: "replacement-user", registrationConfirmed: true });
|
||||
expect(values).toEqual({ userId: "replacement-user", registrationConfirmed: true });
|
||||
await store.clear();
|
||||
expect(await store.load()).toBeNull();
|
||||
});
|
||||
|
||||
it("does not expose a partially confirmed legacy identity", async () => {
|
||||
const storageArea = {
|
||||
get: jest.fn(async () => ({ userId: "unconfirmed-user", registrationConfirmed: false })),
|
||||
set: jest.fn(async () => undefined),
|
||||
};
|
||||
|
||||
expect(await createBrowserCredentialStore(storageArea).load()).toBeNull();
|
||||
});
|
||||
|
||||
it("clears through set when remove is unavailable", async () => {
|
||||
const storageArea = {
|
||||
get: jest.fn(async () => ({})),
|
||||
set: jest.fn(async () => undefined),
|
||||
};
|
||||
|
||||
await createBrowserCredentialStore(storageArea).clear();
|
||||
expect(storageArea.set).toHaveBeenCalledWith({ userId: null, registrationConfirmed: false }, expect.any(Function));
|
||||
});
|
||||
|
||||
it("propagates callback storage failures", async () => {
|
||||
const storageArea = {
|
||||
get: jest.fn((_keys, callback) => callback({})),
|
||||
set: jest.fn((_values, callback) => callback()),
|
||||
};
|
||||
const store = createBrowserCredentialStore(storageArea, () => ({ message: "storage unavailable" }));
|
||||
|
||||
await expect(store.load()).rejects.toThrow("storage unavailable");
|
||||
});
|
||||
|
||||
it("rejects an invalid storage adapter", () => {
|
||||
expect(() => createBrowserCredentialStore()).toThrow(TypeError);
|
||||
expect(() => createBrowserCredentialStore({ get() {} })).toThrow(TypeError);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user