Compare commits

...

86 Commits

Author SHA1 Message Date
joshpatra edd997037a v5.1.1-beta.1 2026-04-02 13:11:47 -04:00
joshpatra f85a1f9f29 Bump version to 5.1.1 2026-04-02 13:11:46 -04:00
joshpatra 97366b76b6 chore: open options in tab 2026-04-02 13:09:09 -04:00
joshpatra 8269875bb1 fix: removed divider 2026-04-02 13:01:14 -04:00
joshpatra e34ec17f33 v5.1.0-beta.1 2026-04-02 12:53:10 -04:00
joshpatra 8d3905b654 Bump version to 5.1.0 2026-04-02 12:53:09 -04:00
joshpatra 7fd8a931d8 deploy: squash beta→main for stable; beta script pushes dev then pulls 2026-04-02 12:52:27 -04:00
joshpatra 17319c1e25 Re-run site rules on DOM media attach; extract refreshAllControllerGeometry 2026-04-02 12:52:27 -04:00
joshpatra 841c1a246e fix: nudge flash layout, Lucide icons, hover bar spacing 2026-04-02 12:52:27 -04:00
joshpatra ed0f63e8bc feat: user-customizable Lucide controller button icons 2026-04-02 12:52:27 -04:00
joshpatra 53f66f1eeb v5.0.4-beta.1 2026-04-01 16:31:49 -04:00
joshpatra f106ab490a Bump version to 5.0.4 2026-04-01 16:31:48 -04:00
joshpatra 5a38121e09 refactor: scripts update 2026-04-01 16:31:29 -04:00
joshpatra 36ed922b5c Add interactive deploy scripts for beta and AMO stable releases 2026-04-01 16:29:19 -04:00
joshpatra 3275d1f322 v5.0.2-beta.1 2026-04-01 16:24:24 -04:00
joshpatra f6d706f096 chore: version bump, deployment update 2026-04-01 16:21:44 -04:00
joshpatra 04292a8018 refactor: update settings, feat: change reset speed indicator to show speed it changes to/from 2026-04-01 16:18:36 -04:00
joshpatra 8eb3901121 v5.0.2-beta.1 2026-04-01 15:32:37 -04:00
joshpatra 0bcca24241 fix: switch from url based video diffing to dom based 2026-04-01 15:20:22 -04:00
joshpatra 6bf48fa479 v5.0.1-beta.1 2026-04-01 11:28:47 -04:00
joshpatra 9b4f338ebb fix: remember playback speed site switching behavior 2026-04-01 11:28:11 -04:00
joshpatra 3a583ce3b8 v5.0.1-beta.1 2026-04-01 11:19:06 -04:00
joshpatra 06f40b3d6d feat: top/bottom margin setting, fix: site-specific rule overrides, refactor: wording for settings 2026-04-01 11:18:30 -04:00
joshpatra 5c20d7ae0b v5.0.0-beta.1 2026-03-31 15:03:56 -04:00
joshpatra 068e65f62f chore: update manifest.json 2026-03-31 15:03:23 -04:00
joshpatra b0498cd1d7 Merge dev 2026-03-31 15:01:17 -04:00
joshpatra 52080a4185 Add .vscode to .gitignore 2026-03-31 15:01:16 -04:00
joshpatra 85215ae54b Merge main: update beta install instructions 2026-03-31 14:53:41 -04:00
joshpatra 9f8c235cea Merge dev: update beta install instructions 2026-03-31 14:53:41 -04:00
joshpatra 30c5a7dbe3 Update beta release install instructions for Firefox XPI auto-install 2026-03-31 14:53:30 -04:00
joshpatra 597c7a8af5 Merge main: fix beta signing via AMO unlisted 2026-03-31 14:48:47 -04:00
joshpatra d215ad4224 Merge dev: fix beta signing via AMO unlisted 2026-03-31 14:48:46 -04:00
joshpatra 705667b532 Fix beta signing: use AMO unlisted channel instead of unsigned build
Unsigned XPIs are blocked by Firefox. Beta releases must be signed via
AMO --channel unlisted to allow manual installation.
2026-03-31 14:48:37 -04:00
joshpatra df18e638c2 Merge main: fix XPI rename glob 2026-03-31 14:44:46 -04:00
joshpatra 9ff3ce4f74 Merge dev: fix XPI rename glob 2026-03-31 14:44:39 -04:00
joshpatra 11e3518902 Fix XPI rename: web-ext build outputs .zip not .xpi 2026-03-31 14:44:24 -04:00
joshpatra 91dc47f5a8 Merge main: restructure CI/CD workflow 2026-03-31 14:39:11 -04:00
joshpatra 36a60bbe34 Merge dev: restructure CI/CD workflow 2026-03-31 14:39:04 -04:00
joshpatra ea48170e11 Restructure CI/CD: tag-based releases, branch-based routing
- v* tags without -beta → sign & submit to AMO (listed/public)
- v*-beta tags → GitHub prerelease XPI for self-hosting
- dev branch pushes → lint-only CI, no release artifacts
2026-03-31 14:38:46 -04:00
joshpatra 3bcb36f6d0 Merge branch 'dev' into beta 2026-03-31 14:22:24 -04:00
joshpatra f2cf8b6205 Fix workflow: use system jq, tag-based builds 2026-03-31 14:22:14 -04:00
joshpatra 2747c15924 Test beta prerelease 2026-03-31 14:18:49 -04:00
joshpatra 5e7d5d6d21 Merge branch 'dev' into beta 2026-03-31 14:18:32 -04:00
joshpatra 6045ac5688 Fix GitHub Actions jq error 2026-03-31 14:18:30 -04:00
joshpatra 38174a2a76 Test beta prerelease 2026-03-31 14:15:17 -04:00
joshpatra 8569fa6e33 ci: add Firefox AMO + GitHub release workflow 2026-03-31 14:11:05 -04:00
joshpatra 30ba6585b0 fix: import/export 2026-03-31 14:06:17 -04:00
joshpatra 8d48dcccca fix: dragging from middle positions 2026-03-31 01:08:57 -04:00
joshpatra 75acaada8d feat: uniform spacing between controls 2026-03-31 01:02:43 -04:00
joshpatra 6d993edf50 feat(ui): configurable control bar, popup controls, and settings overhaul 2026-03-31 00:48:47 -04:00
joshpatra b4030f91dd feat: settings update 2026-03-30 16:25:03 -04:00
joshpatra 44c9c576ed Add donation footer to options page 2026-03-30 15:46:54 -04:00
joshpatra 72f590cd02 fix: mouseover behavior 2026-03-29 18:18:02 -04:00
joshpatra caf75b3e54 fix: closes #17 for real this time 2026-03-29 16:22:43 -04:00
joshpatra 37d1831b8b feat: a minimal fix to try and close #17 2026-03-29 15:28:10 -04:00
joshpatra 14e37c62d5 feat: hide with controls timer for non-youtube websites, site-specific rules for it too 2026-03-29 15:13:59 -04:00
joshpatra 03f5dbaa96 fix: import/export, and saving settings fixed 2026-03-29 14:43:25 -04:00
joshpatra 8b30005fb2 chore: swap versioning for Github and Firefox 2026-03-29 12:03:01 -04:00
joshpatra f385074905 chore: replace the default disabled websites with example domains 2026-03-28 19:15:37 -04:00
joshpatra a51801e7c3 fix: made hide with controls site-specific accidentally 2026-03-28 19:08:14 -04:00
joshpatra cd5e4bee9f feat: add setting to hide controller with YouTube controls, restoring a bug from before lol 2026-03-28 18:57:48 -04:00
joshpatra 4d34c8754d fix: expand from right for middle positions 2026-03-28 17:31:18 -04:00
joshpatra 194acacab4 fix: z-index regression, fullscreen top padding 2026-03-28 17:25:34 -04:00
joshpatra 6cf4ef3f93 feat: add import/export settings with modular architecture 2026-03-28 16:30:37 -04:00
joshpatra 104b828d47 feat: improve removal button visibility and standardize site rules 2026-03-28 16:03:06 -04:00
joshpatra 318598b8cf fix: restore default keybinding population in options 2026-03-28 16:02:50 -04:00
joshpatra 5616778421 feat: Site-Specific Rules stash pop, cleaned up some settings 2026-03-28 11:38:13 -04:00
joshpatra bec32b4c0e Video controller: adjust bottom padding for controller locations 2026-03-28 11:31:06 -04:00
joshpatra 2832598881 feat: add the 'Preferences' pane to the Addon Menu 2026-03-28 10:00:53 -04:00
joshpatra 079834ca72 fix: bring back blocklisted websites, must've accidentally removed them 2026-03-28 03:31:48 -04:00
joshpatra d44010f7a3 feat: Default controller location, easy moving of Controller with new shortcut 2026-03-28 03:21:50 -04:00
joshpatra b02cdb14b3 feat: Hijack Youtube's native playback speed controller for some performance gain, at least up to 2.0, and afterwards, use the nudging mechanism 2026-03-28 02:54:33 -04:00
joshpatra be8342fa18 fix: nudge now works on YouTube embeds on sites like KhanAcademy, refactor: use querySelectorAll instead of recursively calling scanNodeForMedia on every element in the DOM 2026-03-28 01:57:14 -04:00
joshpatra f96fd4ac14 feat: flash indicator, alongisde the hover control indicator, autohides one when the other appears 2026-03-28 01:33:14 -04:00
joshpatra b96d1a62ec Fix YouTube hover controls & improve nudge indicator UX 2026-03-28 01:21:35 -04:00
joshpatra ab85de0a0f fix: separate Speeder from yt autohide, ignore temp folder with magnus fork to reduce size, update build.py 2026-03-26 18:43:34 -04:00
joshpatra 64f30a04c0 chore: version bump 2026-03-26 13:53:43 -04:00
joshpatra 303864e37b feat(nudge): add per-tab toggle, status badge, and cpu tuning 2026-03-26 13:53:13 -04:00
joshpatra b1c7cb6741 fix(controller): reveal hover controls from the visible pill 2026-03-26 13:11:01 -04:00
joshpatra f8e846ab0c chore: remove __pycache__ from index and gitignore it 2026-03-23 19:44:03 -04:00
joshpatra c6bb82894e Merge pull request #4 from Gitoffthelawn/patch-11
Improve usability, improve accuracy, fix links
2026-03-23 19:39:49 -04:00
Gitoffthelawn 1fc6ab278b Improve usability, improve accuracy, fix links 2026-03-23 12:41:13 -07:00
joshpatra f2c128094e Merge branch 'firefox-port' of github.com:SoPat712/videospeed into firefox-port 2026-03-23 13:23:04 -04:00
joshpatra f34ad12b88 feat: Changed name to Speeder 2026-03-23 13:23:00 -04:00
joshpatra c309fbb743 Update funding sources in FUNDING.yml 2026-03-23 12:57:32 -04:00
joshpatra 6765a6e131 fix(z-index): accidentally left the z-index at 99999, meaning it was showing above all elements on the page 2026-03-23 02:24:44 -04:00
23 changed files with 6037 additions and 824 deletions
+15
View File
@@ -0,0 +1,15 @@
# These are supported funding model platforms
github: [SoPat712]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: joshpatra
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
+73
View File
@@ -0,0 +1,73 @@
name: Build & Release Firefox Addon
on:
push:
tags:
- "v*"
branches:
- dev
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install deps
run: npm install -g web-ext
- name: Lint
run: web-ext lint
# Beta tag (v*-beta) → Sign as unlisted on AMO, attach signed XPI to GitHub Prerelease
# Firefox blocks all unsigned XPIs, even for self-hosted installs — unlisted signing is required
- name: Sign XPI via AMO (unlisted, beta)
if: contains(github.ref_name, '-beta')
run: |
web-ext sign \
--api-key ${{ secrets.FIREFOX_API_KEY }} \
--api-secret ${{ secrets.FIREFOX_API_SECRET }} \
--source-dir . \
--artifacts-dir web-ext-artifacts \
--channel unlisted
- name: Get signed XPI path (beta)
if: contains(github.ref_name, '-beta')
id: xpi
run: |
FILE=$(ls web-ext-artifacts/*.xpi | head -n 1)
XPI="web-ext-artifacts/speeder-${{ github.ref_name }}.xpi"
mv "$FILE" "$XPI"
echo "file=$XPI" >> $GITHUB_OUTPUT
- name: Create GitHub Prerelease (beta)
if: contains(github.ref_name, '-beta')
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ github.ref_name }}
name: ${{ github.ref_name }}
files: ${{ steps.xpi.outputs.file }}
prerelease: true
body: |
Beta build — signed for self-hosted manual installation.
### Installation Instructions
1. Click the `.xpi` file below
2. Click "Continue to Installation"
3. Click "Add"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Stable tag (v* without -beta) → Sign & submit to public AMO listing
- name: Sign & Submit to AMO (stable)
if:
startsWith(github.ref, 'refs/tags/') && !contains(github.ref_name,
'-beta')
run: |
web-ext sign \
--api-key ${{ secrets.FIREFOX_API_KEY }} \
--api-secret ${{ secrets.FIREFOX_API_SECRET }} \
--source-dir . \
--artifacts-dir web-ext-artifacts \
--channel listed
+3
View File
@@ -1,7 +1,10 @@
.DS_Store
.vscode/
local
# IntelliJ IDEA
*.xpi
.idea/
node_modules
__pycache__/
temp/
+3
View File
@@ -0,0 +1,3 @@
{
"kiroAgent.configureMCP": "Disabled"
}
+12 -14
View File
@@ -1,5 +1,5 @@
[![Add to Firefox](https://img.shields.io/badge/Add%20to-Firefox-orange?logo=firefox&logoColor=white)](https://addons.mozilla.org/en-US/firefox/addon/video-speed-controller-v1/)
# Available for Firefox
[![Add to Firefox](https://img.shields.io/badge/Add%20to-Firefox-orange?logo=firefox&logoColor=white)](https://addons.mozilla.org//firefox/addon/speeder/)
# The science of accelerated playback
@@ -7,19 +7,19 @@
**TL;DR: faster playback translates to better engagement and retention.**
Average adult reads prose text at
[250 to 300 words per minute](http://www.paperbecause.com/PIOP/files/f7/f7bb6bc5-2c4a-466f-9ae7-b483a2c0dca4.pdf)
[250 to 300 words per minute](https://web.archive.org/web/20220325065025/https://www.domtar.com/en/resources/paper-advocacy/paperbecause)
(wpm). By contrast, the average rate of speech for English speakers is ~150 wpm,
with slide presentations often closer to 100 wpm. As a result, when given the
choice, many viewers
[speed up video playback to ~1.3\~1.5 its recorded rate](http://research.microsoft.com/en-us/um/redmond/groups/coet/compression/chi99/paper.pdf)
[speed up video playback to ~1.3\~1.5 its recorded rate](https://research.microsoft.com/en-us/um/redmond/groups/coet/compression/chi99/paper.pdf)
to compensate for the difference.
Many viewers report that
[accelerated viewing keeps their attention longer](http://www.enounce.com/docs/BYUPaper020319.pdf):
[accelerated viewing keeps their attention longer](https://www.enounce.com/docs/BYUPaper020319.pdf):
faster delivery keeps the viewer more engaged with the content. In fact, with a
little training many end up watching videos at 2x+ the recorded speed. Some
studies report that after being exposed to accelerated playback,
[listeners become uncomfortable](http://alumni.media.mit.edu/~barons/html/avios92.html#beasleyalteredspeech)
[listeners become uncomfortable](https://web.archive.org/web/20230912173120/http://alumni.media.mit.edu/~barons/html/avios92.html)
if they are forced to return to normal rate of presentation.
## Faster HTML5 Video
@@ -36,7 +36,7 @@ last point to listen to it a few more times.
#### *Install [Chrome](https://chrome.google.com/webstore/detail/video-speed-controller/nffaoalbilbmmfgbnbgppjihopabppdk) or [Firefox](https://addons.mozilla.org/en-us/firefox/addon/videospeed/) Extension*
\*\* Once the extension is installed simply navigate to any page that offers
HTML5 video ([example](http://www.youtube.com/watch?v=E9FxNzv1Tr8)), and you'll
HTML5 video ([example](https://www.youtube.com/watch?v=E9FxNzv1Tr8)), and you'll
see a speed indicator in top left corner. Hover over the indicator to reveal the
controls to accelerate, slowdown, and quickly rewind or advance the video. Or,
even better, simply use your keyboard:
@@ -74,13 +74,11 @@ and inspect the menu: if it mentions flash, then that's the issue. That said,
most sites will fallback to HTML5 if they detect that Flash is not available.
You can try manually disabling Flash from the browser.
**What is this fork of `igrigorik/videospeed` all about?** This fork of the
[`igrigorik/videospeed`](https://github.com/igrigorik/videospeed) repository
is a port of [`igrigorik`](https://github.com/igrigorik)'s videospeed Chrome
add-on for Firefox. This fork modifies the Chrome add-on code so that it works
in Firefox. This repo is the code behind the [Firefox Extension](https://addons.mozilla.org/en-US/firefox/addon/video-speed-controller-v1/)
whereas the [`igrigorik/videospeed`](https://github.com/igrigorik/videospeed)
repository contains the code behind the [Chrome Extension](https://chrome.google.com/webstore/detail/video-speed-controller/nffaoalbilbmmfgbnbgppjihopabppdk).
**What is this fork all about?** This is a fork of
[CodeBicycle's Video Speed Controller extension for Firefox](https://github.com/codebicycle/videospeed)
which is a fork of [Igrigorik's Video Speed Controller extension for Chromium](https://github.com/igrigorik/videospeed).
The goal of this fork is fix bugs in the upstream code as well as add new features.
### License
+5
View File
@@ -0,0 +1,5 @@
chrome.runtime.onMessage.addListener(function (request) {
if (request.action === "openOptions") {
chrome.tabs.create({ url: chrome.runtime.getURL("options.html") });
}
});
+45 -18
View File
@@ -1,4 +1,5 @@
import glob
import fnmatch
import os
import re
import shutil
@@ -7,6 +8,32 @@ import zipfile
SCRIPT_NAME = os.path.basename(__file__)
TARGET_FILE = "manifest.json"
DEFAULT_EXCLUDE_FILES = {".DS_Store"}
DEFAULT_EXCLUDE_DIRS = {"__pycache__", "temp"}
DEFAULT_EXCLUDE_PATTERNS = {"._*", "*.pyc"}
def should_exclude(rel_path, exclude_files, exclude_dirs):
rel_path = os.path.normpath(rel_path)
path_parts = rel_path.split(os.sep)
file_name = path_parts[-1]
if file_name in DEFAULT_EXCLUDE_FILES or rel_path in DEFAULT_EXCLUDE_FILES:
return True
if any(part in DEFAULT_EXCLUDE_DIRS for part in path_parts):
return True
if file_name in exclude_files or rel_path in exclude_files:
return True
if any(part in exclude_dirs for part in path_parts):
return True
if any(fnmatch.fnmatch(file_name, pattern) for pattern in DEFAULT_EXCLUDE_PATTERNS):
return True
return False
def zip_folder(output_name, folder, exclude_files, exclude_dirs):
@@ -15,15 +42,15 @@ def zip_folder(output_name, folder, exclude_files, exclude_dirs):
dirs[:] = [
d
for d in dirs
if os.path.relpath(os.path.join(root, d), folder) not in exclude_dirs
if not should_exclude(
os.path.relpath(os.path.join(root, d), folder),
exclude_files,
exclude_dirs,
)
]
for file in files:
rel_path = os.path.relpath(os.path.join(root, file), folder)
if (
file in exclude_files
or rel_path in exclude_files
or any(rel_path.startswith(ed + os.sep) for ed in exclude_dirs)
):
if should_exclude(rel_path, exclude_files, exclude_dirs):
continue
zipf.write(os.path.join(root, file), arcname=rel_path)
@@ -82,30 +109,30 @@ def main():
print("❌ No version entered. Exiting.")
return
firefox_version = f"{base_version}.0"
github_version = f"{base_version}.0"
# Step 1: Update manifest.json on disk to base_version
# Step 1: Update manifest.json on disk to base_version (for Firefox)
if os.path.exists(manifest_path):
update_version_line(manifest_path, base_version)
else:
print(f"{TARGET_FILE} not found. Aborting.")
return
# Step 2: Create videospeed-github.xpi (exclude script, .git, AND videospeed-github.xpi itself)
exclude_files = [SCRIPT_NAME, "videospeed-github.xpi"]
# Step 2: Create videospeed-firefox.xpi (exclude script, .git, AND videospeed-firefox.xpi itself)
exclude_files = [SCRIPT_NAME, "videospeed-firefox.xpi"]
exclude_dirs = [".git"]
zip_folder("videospeed-github.xpi", current_dir, exclude_files, exclude_dirs)
print("✅ Created videospeed-github.xpi")
zip_folder("videospeed-firefox.xpi", current_dir, exclude_files, exclude_dirs)
print("✅ Created videospeed-firefox.xpi")
# Step 3: Re-scan for .xpi files after GitHub archive creation, exclude them for Firefox zip
# Step 3: Re-scan for .xpi files after Firefox archive creation, exclude them for GitHub zip
current_xpi_files = set(glob.glob("*.xpi"))
exclude_temp_files = current_xpi_files.union({SCRIPT_NAME})
exclude_temp_dirs = set(exclude_dirs)
# Step 4: Create videospeed-firefox.xpi from temp folder with version bumped to .0
# Step 4: Create videospeed-github.xpi from temp folder with version bumped to .0
with tempfile.TemporaryDirectory() as temp_dir:
for item in os.listdir(current_dir):
if item in exclude_temp_files or item in exclude_temp_dirs:
if should_exclude(item, exclude_temp_files, exclude_temp_dirs):
continue
src = os.path.join(current_dir, item)
dst = os.path.join(temp_dir, item)
@@ -116,14 +143,14 @@ def main():
temp_manifest = os.path.join(temp_dir, TARGET_FILE)
if os.path.exists(temp_manifest):
update_version_line(temp_manifest, firefox_version)
update_version_line(temp_manifest, github_version)
else:
print(f"⚠️ {TARGET_FILE} not found in temp folder.")
zip_folder(
"videospeed-firefox.xpi", temp_dir, exclude_files=[], exclude_dirs=[]
"videospeed-github.xpi", temp_dir, exclude_files=[], exclude_dirs=[]
)
print("✅ Created videospeed-firefox.xpi")
print("✅ Created videospeed-github.xpi")
if __name__ == "__main__":
+16
View File
@@ -0,0 +1,16 @@
/* Runs via chrome.tabs.executeScript(allFrames) in the same isolated world as inject.js */
(function () {
try {
if (typeof getPrimaryVideoElement !== "function") {
return null;
}
var v = getPrimaryVideoElement();
if (!v) return null;
return {
speed: v.playbackRate,
preferred: !v.paused
};
} catch (e) {
return null;
}
})();
+156
View File
@@ -0,0 +1,156 @@
// Import/Export functionality for Video Speed Controller settings
function generateBackupFilename() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hours = String(now.getHours()).padStart(2, "0");
const minutes = String(now.getMinutes()).padStart(2, "0");
const seconds = String(now.getSeconds()).padStart(2, "0");
return `speeder-backup_${year}-${month}-${day}_${hours}.${minutes}.${seconds}.json`;
}
function exportSettings() {
chrome.storage.sync.get(null, function (storage) {
chrome.storage.local.get(null, function (localStorage) {
const backup = {
version: "1.1",
exportDate: new Date().toISOString(),
settings: storage,
localSettings: localStorage || {}
};
const dataStr = JSON.stringify(backup, null, 2);
const blob = new Blob([dataStr], { type: "application/json" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = generateBackupFilename();
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
showStatus("Settings exported successfully");
});
});
}
function importSettings() {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json";
input.onchange = function (event) {
const file = event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function (e) {
try {
const backup = JSON.parse(e.target.result);
let settingsToImport = null;
// Detect backup format: check for 'settings' wrapper or raw storage keys
if (backup.settings && typeof backup.settings === "object") {
settingsToImport = backup.settings;
} else if (typeof backup === "object" && (backup.keyBindings || backup.rememberSpeed !== undefined)) {
settingsToImport = backup; // Raw storage object
}
if (!settingsToImport) {
showStatus("Error: Invalid backup file format", true);
return;
}
var localToImport =
backup.localSettings && typeof backup.localSettings === "object"
? backup.localSettings
: null;
function afterLocalImport() {
chrome.storage.sync.clear(function () {
chrome.storage.sync.set(settingsToImport, function () {
if (chrome.runtime.lastError) {
showStatus(
"Error: Failed to save imported settings - " +
chrome.runtime.lastError.message,
true
);
return;
}
showStatus("Settings imported successfully. Reloading...");
setTimeout(function () {
if (typeof restore_options === "function") {
restore_options();
} else {
location.reload();
}
}, 500);
});
});
}
if (localToImport && Object.keys(localToImport).length > 0) {
chrome.storage.local.set(localToImport, function () {
if (chrome.runtime.lastError) {
showStatus(
"Error: Failed to save local extension data - " +
chrome.runtime.lastError.message,
true
);
return;
}
afterLocalImport();
});
} else {
afterLocalImport();
}
} catch (err) {
showStatus("Error: Failed to parse backup file - " + err.message, true);
}
};
reader.onerror = function () {
showStatus("Error: Failed to read file", true);
};
reader.readAsText(file);
};
input.click();
}
function showStatus(message, isError = false) {
const status = document.getElementById("status");
if (status) {
status.textContent = message;
status.style.color = isError ? "#d32f2f" : "";
setTimeout(function () {
status.textContent = "";
status.style.color = "";
}, 3000);
}
}
// Initialize import/export buttons when DOM is ready
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initImportExport);
} else {
initImportExport();
}
function initImportExport() {
const exportBtn = document.getElementById("exportSettings");
const importBtn = document.getElementById("importSettings");
if (exportBtn) {
exportBtn.addEventListener("click", exportSettings);
}
if (importBtn) {
importBtn.addEventListener("click", importSettings);
}
}
+31 -66
View File
@@ -1,83 +1,48 @@
/* Base styles for the controller wrapper (the shadow host) */
.vsc-controller {
position: absolute !important;
top: 0 !important;
left: 0 !important;
width: 100% !important;
height: 100% !important;
pointer-events: none !important;
z-index: 2147483646 !important;
white-space: normal;
overflow: visible !important;
}
/* Use minimal z-index for non-YouTube sites to avoid overlapping modals */
.vsc-controller.vsc-non-youtube {
z-index: 1 !important;
}
.vsc-nosource {
display: none !important;
}
.vsc-hidden {
display: none !important;
}
.vsc-manual {
visibility: visible !important;
opacity: 1 !important;
}
.vsc-controller {
/* In case of pages using `white-space: pre-line` (eg Discord), don't render vsc's whitespace */
white-space: normal;
}
/* Origin specific overrides */
/* YouTube player */
.ytp-hide-info-bar .vsc-controller {
position: relative;
top: 10px;
}
.ytp-autohide .vsc-controller {
/* YouTube auto-hide feature: fade controller with YouTube's controls */
/* When the wrapper has ytp-autohide class, hide it (unless vsc-hidden overrides) */
.vsc-controller.ytp-autohide:not(.vsc-hidden),
.vsc-controller.vsc-idle-hidden:not(.vsc-hidden) {
visibility: hidden;
transition: opacity 0.25s cubic-bezier(0.4, 0, 0.2, 1);
opacity: 0;
}
.ytp-autohide .vsc-show {
visibility: visible;
opacity: 1;
/* Show it temporarily when it has vsc-show class */
.vsc-controller.ytp-autohide.vsc-show:not(.vsc-hidden),
.vsc-controller.vsc-idle-hidden.vsc-show:not(.vsc-hidden),
.vsc-controller.vsc-forced-show:not(.vsc-hidden) {
visibility: visible !important;
opacity: 1 !important;
}
/* YouTube embedded player */
/* e.g. https://www.igvita.com/2012/09/12/web-fonts-performance-making-pretty-fast/ */
.html5-video-player:not(.ytp-hide-info-bar) .vsc-controller {
position: relative;
top: 60px;
}
/* Facebook player */
#facebook .vsc-controller {
position: relative;
top: 40px;
}
/* Google Photos player */
/* Inline preview doesn't have any additional hooks, relying on Aria label */
a[aria-label^="Video"] .vsc-controller {
position: relative;
top: 35px;
}
/* Google Photos full-screen view */
#player .house-brand .vsc-controller {
position: relative;
top: 50px;
}
/* Netflix player */
#netflix-player:not(.player-cinema-mode) .vsc-controller {
position: relative;
top: 85px;
}
/* shift controller on vine.co */
/* e.g. https://vine.co/v/OrJj39YlL57 */
.video-container .vine-video-container .vsc-controller {
margin-left: 40px;
}
/* shift YT 3D controller down */
/* e.g. https://www.youtube.com/watch?v=erftYPflJzQ */
.ytp-webgl-spherical-control {
top: 60px !important;
}
.ytp-fullscreen .ytp-webgl-spherical-control {
top: 100px !important;
}
/* Original overrides removed to avoid interference with the new anchoring system.
The .vsc-controller wrapper now fills the player container exactly,
allowing #controller (inside shadow root) to anchor correctly to all 8 positions. */
/* disable Vimeo video overlay */
div.video-wrapper + div.target {
+1423 -133
View File
@@ -1,8 +1,15 @@
var regStrip = /^[\r\t\f\v ]+|[\r\t\f\v ]+$/gm;
var isUserSeek = false; // Track if seek was user-initiated
var lastToggleSpeed = {}; // Store last toggle speeds per video
function getPrimaryVideoElement() {
if (!tc.mediaElements || tc.mediaElements.length === 0) return null;
for (var i = 0; i < tc.mediaElements.length; i++) {
var el = tc.mediaElements[i];
if (el && !el.paused) return el;
}
return tc.mediaElements[0];
}
var tc = {
settings: {
lastSpeed: 1.0,
@@ -13,34 +20,115 @@ var tc = {
forceLastSavedSpeed: false,
audioBoolean: false,
startHidden: false,
hideWithYouTubeControls: false,
hideWithControls: false,
hideWithControlsTimer: 2.0,
controllerLocation: "top-left",
controllerOpacity: 0.3,
controllerMarginTop: 0,
controllerMarginRight: 0,
controllerMarginBottom: 65,
controllerMarginLeft: 0,
keyBindings: [],
blacklist: `\
www.instagram.com
twitter.com
vine.co
imgur.com
teams.microsoft.com
`.replace(regStrip, ""),
defaultLogLevel: 4,
logLevel: 5, // Set to 5 to see your debug logs
siteRules: [],
controllerButtons: ["rewind", "slower", "faster", "advance", "display"],
defaultLogLevel: 3,
logLevel: 3,
enableSubtitleNudge: true, // Enabled by default, but only activates on YouTube
subtitleNudgeInterval: 100, // Reduced from 25ms to 100ms (10x/sec instead of 40x/sec)
subtitleNudgeAmount: 0.001
subtitleNudgeInterval: 50, // Default 50ms balances subtitle tracking with CPU cost
subtitleNudgeAmount: 0.001,
customButtonIcons: {}
},
mediaElements: [],
isNudging: false
isNudging: false,
pendingLastSpeedSave: null,
pendingLastSpeedValue: null,
persistedLastSpeed: 1.0,
activeSiteRule: null,
siteRuleBase: null
};
var MIN_SPEED = 0.0625;
var MAX_SPEED = 16;
var YT_NATIVE_MIN = 0.25;
var YT_NATIVE_MAX = 2.0;
var YT_NATIVE_STEP = 0.05;
var vscObservedRoots = new WeakSet();
var requestIdle =
typeof window.requestIdleCallback === "function"
? window.requestIdleCallback.bind(window)
: function (callback, options) {
return setTimeout(callback, (options && options.timeout) || 1);
};
return setTimeout(callback, (options && options.timeout) || 1);
};
var controllerLocations = [
"top-left",
"top-center",
"top-right",
"middle-right",
"bottom-right",
"bottom-center",
"bottom-left",
"middle-left"
];
var defaultControllerLocation = controllerLocations[0];
var controllerLocationStyles = {
"top-left": {
top: "10px",
left: "15px",
transform: "translate(0, 0)"
},
"top-center": {
top: "10px",
left: "50%",
transform: "translate(-50%, 0)"
},
"top-right": {
top: "10px",
left: "calc(100% - 10px)",
transform: "translate(-100%, 0)"
},
"middle-right": {
top: "50%",
left: "calc(100% - 10px)",
transform: "translate(-100%, -50%)"
},
"bottom-right": {
top: "calc(100% - 0px)",
left: "calc(100% - 10px)",
transform: "translate(-100%, -100%)"
},
"bottom-center": {
top: "calc(100% - 0px)",
left: "50%",
transform: "translate(-50%, -100%)"
},
"bottom-left": {
top: "calc(100% - 0px)",
left: "15px",
transform: "translate(0, -100%)"
},
"middle-left": {
top: "50%",
left: "15px",
transform: "translate(0, -50%)"
}
};
/* `label` fallback only when ui-icons has no path for the action. */
var controllerButtonDefs = {
rewind: { label: "", className: "rw" },
slower: { label: "", className: "" },
faster: { label: "", className: "" },
advance: { label: "", className: "rw" },
display: { label: "", className: "hideButton" },
reset: { label: "", className: "" },
fast: { label: "", className: "" },
settings: { label: "", className: "" },
pause: { label: "", className: "" },
muted: { label: "", className: "" },
mark: { label: "", className: "" },
jump: { label: "", className: "" }
};
var keyCodeToEventKey = {
32: " ",
@@ -139,10 +227,33 @@ function defaultKeyBindings(storage) {
"G",
Number(storage.fastKeyCode) || 71,
Number(storage.fastSpeed) || 1.8
),
createDefaultBinding(
"move",
"P",
80,
0
),
createDefaultBinding(
"toggleSubtitleNudge",
"N",
78,
0
)
];
}
function ensureDefaultKeyBinding(action, key, keyCode, value) {
if (tc.settings.keyBindings.some((binding) => binding.action === action)) {
return false;
}
tc.settings.keyBindings.push(
createDefaultBinding(action, key, keyCode, value)
);
return true;
}
function getLegacyKeyCode(binding) {
if (!binding) return null;
if (Number.isInteger(binding.keyCode)) return binding.keyCode;
@@ -152,6 +263,279 @@ function getLegacyKeyCode(binding) {
return null;
}
function normalizeControllerLocation(location) {
if (controllerLocations.includes(location)) return location;
return defaultControllerLocation;
}
var CONTROLLER_MARGIN_MAX_PX = 200;
function normalizeControllerMarginPx(value, fallback) {
var n = Number(value);
if (!Number.isFinite(n)) return fallback;
return Math.min(
CONTROLLER_MARGIN_MAX_PX,
Math.max(0, Math.round(n))
);
}
function applyControllerMargins(controller) {
if (!controller) return;
var d = tc.settings;
var loc = controller.dataset.location;
var manual = controller.dataset.positionMode === "manual";
var isTopAnchored =
!manual &&
(loc === "top-left" ||
loc === "top-center" ||
loc === "top-right");
var isBottomAnchored =
!manual &&
(loc === "bottom-right" ||
loc === "bottom-center" ||
loc === "bottom-left");
var isMiddleRow =
!manual && (loc === "middle-left" || loc === "middle-right");
var mt = normalizeControllerMarginPx(d.controllerMarginTop, 0);
var mb = normalizeControllerMarginPx(d.controllerMarginBottom, 65);
if (isTopAnchored || isBottomAnchored || isMiddleRow) {
mt = 0;
mb = 0;
}
controller.style.marginTop = mt + "px";
var ml = normalizeControllerMarginPx(d.controllerMarginLeft, 0);
var mr = normalizeControllerMarginPx(d.controllerMarginRight, 0);
if (!manual) {
ml = 0;
mr = 0;
}
controller.style.marginRight = mr + "px";
controller.style.marginBottom = mb + "px";
controller.style.marginLeft = ml + "px";
}
function getNextControllerLocation(location) {
var normalizedLocation = normalizeControllerLocation(location);
var currentIndex = controllerLocations.indexOf(normalizedLocation);
return controllerLocations[(currentIndex + 1) % controllerLocations.length];
}
function getControllerElement(videoOrController) {
if (!videoOrController) return null;
if (
videoOrController.shadowRoot &&
typeof videoOrController.shadowRoot.querySelector === "function"
) {
return videoOrController.shadowRoot.querySelector("#controller");
}
if (
videoOrController.div &&
videoOrController.div.shadowRoot &&
typeof videoOrController.div.shadowRoot.querySelector === "function"
) {
return videoOrController.div.shadowRoot.querySelector("#controller");
}
return null;
}
function applyControllerLocationToElement(controller, location) {
if (!controller) return defaultControllerLocation;
var normalizedLocation = normalizeControllerLocation(location);
var styles = controllerLocationStyles[normalizedLocation];
controller.dataset.location = normalizedLocation;
controller.dataset.positionMode = "anchored";
var top = styles.top;
if (
normalizedLocation === "top-left" ||
normalizedLocation === "top-center" ||
normalizedLocation === "top-right"
) {
var insetTop = normalizeControllerMarginPx(
tc.settings.controllerMarginTop,
0
);
top = "calc(10px + " + insetTop + "px)";
}
if (
normalizedLocation === "bottom-right" ||
normalizedLocation === "bottom-center" ||
normalizedLocation === "bottom-left"
) {
var lift = normalizeControllerMarginPx(
tc.settings.controllerMarginBottom,
65
);
top = "calc(100% - " + lift + "px)";
}
// If in fullscreen, move the controller down to avoid overlapping video titles
if (
document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement
) {
if (normalizedLocation.startsWith("top-")) {
var insetTopFs = normalizeControllerMarginPx(
tc.settings.controllerMarginTop,
0
);
top = "calc(63px + " + insetTopFs + "px)";
}
}
controller.style.top = top;
var left = styles.left;
switch (normalizedLocation) {
case "top-left":
case "middle-left":
case "bottom-left":
left = "15px";
break;
case "top-right":
case "middle-right":
case "bottom-right":
left = "calc(100% - 10px)";
break;
case "top-center":
case "bottom-center":
left = "50%";
break;
default:
break;
}
controller.style.left = left;
controller.style.transform = styles.transform;
applyControllerMargins(controller);
return normalizedLocation;
}
function applyControllerLocation(videoController, location) {
if (!videoController) return;
var controller = getControllerElement(videoController);
if (!controller) return;
videoController.controllerLocation = applyControllerLocationToElement(
controller,
location
);
}
function captureSiteRuleBase() {
tc.siteRuleBase = {
startHidden: tc.settings.startHidden,
hideWithControls: tc.settings.hideWithControls,
hideWithControlsTimer: tc.settings.hideWithControlsTimer,
controllerLocation: tc.settings.controllerLocation,
rememberSpeed: tc.settings.rememberSpeed,
forceLastSavedSpeed: tc.settings.forceLastSavedSpeed,
audioBoolean: tc.settings.audioBoolean,
controllerOpacity: tc.settings.controllerOpacity,
controllerMarginTop: tc.settings.controllerMarginTop,
controllerMarginBottom: tc.settings.controllerMarginBottom,
enableSubtitleNudge: tc.settings.enableSubtitleNudge,
subtitleNudgeInterval: tc.settings.subtitleNudgeInterval,
controllerButtons: Array.isArray(tc.settings.controllerButtons)
? tc.settings.controllerButtons.slice()
: tc.settings.controllerButtons,
keyBindings: Array.isArray(tc.settings.keyBindings)
? tc.settings.keyBindings.map(function (binding) {
return Object.assign({}, binding);
})
: tc.settings.keyBindings
};
}
function resetSettingsFromSiteRuleBase() {
if (!tc.siteRuleBase) return;
var base = tc.siteRuleBase;
tc.settings.startHidden = base.startHidden;
tc.settings.hideWithControls = base.hideWithControls;
tc.settings.hideWithControlsTimer = base.hideWithControlsTimer;
tc.settings.controllerLocation = base.controllerLocation;
tc.settings.rememberSpeed = base.rememberSpeed;
tc.settings.forceLastSavedSpeed = base.forceLastSavedSpeed;
tc.settings.audioBoolean = base.audioBoolean;
tc.settings.controllerOpacity = base.controllerOpacity;
tc.settings.controllerMarginTop = base.controllerMarginTop;
tc.settings.controllerMarginBottom = base.controllerMarginBottom;
tc.settings.enableSubtitleNudge = base.enableSubtitleNudge;
tc.settings.subtitleNudgeInterval = base.subtitleNudgeInterval;
tc.settings.controllerButtons = Array.isArray(base.controllerButtons)
? base.controllerButtons.slice()
: base.controllerButtons;
tc.settings.keyBindings = Array.isArray(base.keyBindings)
? base.keyBindings.map(function (binding) {
return Object.assign({}, binding);
})
: base.keyBindings;
}
function clearManualControllerPosition(videoController) {
if (!videoController) return;
applyControllerLocation(
videoController,
videoController.controllerLocation || tc.settings.controllerLocation
);
}
function convertControllerToManualPosition(videoController) {
if (!videoController) return null;
var controller = getControllerElement(videoController);
if (!controller) return null;
controller.dataset.positionMode = "manual";
var offsetParent = controller.offsetParent;
if (offsetParent) {
var controllerRect = controller.getBoundingClientRect();
var offsetParentRect = offsetParent.getBoundingClientRect();
controller.style.setProperty(
"left",
controllerRect.left - offsetParentRect.left + "px",
"important"
);
controller.style.setProperty(
"top",
controllerRect.top - offsetParentRect.top + "px",
"important"
);
} else {
controller.style.setProperty(
"left",
controller.offsetLeft + "px",
"important"
);
controller.style.setProperty(
"top",
controller.offsetTop + "px",
"important"
);
}
controller.style.setProperty("transform", "none", "important");
return controller;
}
function cycleControllerLocation(video) {
if (!video || !video.vsc) return;
video.vsc.controllerLocation = getNextControllerLocation(
video.vsc.controllerLocation || tc.settings.controllerLocation
);
clearManualControllerPosition(video.vsc);
}
function normalizeBindingKey(key) {
if (typeof key !== "string" || key.length === 0) return null;
if (key === "Spacebar") return " ";
@@ -257,10 +641,36 @@ function getVideoSourceKey(video) {
function getControllerTargetSpeed(video) {
if (!video || !video.vsc) return null;
return isValidSpeed(video.vsc.targetSpeed) ? video.vsc.targetSpeed : null;
if (!isValidSpeed(video.vsc.targetSpeed)) return null;
var currentSourceKey = getVideoSourceKey(video);
var targetSourceKey = video.vsc.targetSpeedSourceKey;
// SPA sites (e.g. YouTube) can reuse the same <video> element.
// Don't carry controller target speed across a source swap.
if (
targetSourceKey &&
currentSourceKey === "unknown_src" &&
targetSourceKey !== "unknown_src"
) {
return null;
}
if (
targetSourceKey &&
currentSourceKey !== "unknown_src" &&
targetSourceKey !== currentSourceKey
) {
return null;
}
return video.vsc.targetSpeed;
}
function getRememberedSpeed(video) {
if (!tc.settings.rememberSpeed && !tc.settings.forceLastSavedSpeed) {
return null;
}
var sourceKey = getVideoSourceKey(video);
if (sourceKey !== "unknown_src") {
var videoSpeed = tc.settings.speeds[sourceKey];
@@ -279,10 +689,211 @@ function getDesiredSpeed(video) {
return getControllerTargetSpeed(video) || getRememberedSpeed(video) || 1.0;
}
function isOnYouTube() {
return (
location.hostname.includes("youtube.com") ||
location.hostname.includes("youtube-nocookie.com")
);
}
function isYouTubeNativeSpeedRange(speed) {
if (speed < YT_NATIVE_MIN || speed > YT_NATIVE_MAX) return false;
// Check if speed is a multiple of 0.05 (with floating point tolerance)
var remainder = Math.abs((speed * 100) % (YT_NATIVE_STEP * 100));
return remainder < 0.01 || remainder > (YT_NATIVE_STEP * 100 - 0.01);
}
function tryYouTubeNativeSpeed(video, speed) {
if (!isOnYouTube() || !isYouTubeNativeSpeedRange(speed)) return false;
try {
// YouTube's movie_player element exposes setPlaybackRate() but it's a
// page-level JS method, not a native DOM method. Content scripts can't
// see it directly. In Firefox, wrappedJSObject gives access to the
// page's JS context.
var playerEl =
video.closest(".html5-video-player") ||
document.getElementById("movie_player");
if (!playerEl) return false;
// Try wrappedJSObject first (Firefox content script → page context)
var player = playerEl.wrappedJSObject || playerEl;
if (typeof player.setPlaybackRate === "function") {
player.setPlaybackRate(speed);
// Verify YouTube actually accepted the speed (it may silently clamp)
var actualSpeed = video.playbackRate;
if (Math.abs(actualSpeed - speed) > 0.01) {
log("YouTube clamped speed to " + actualSpeed + ", falling back", 4);
return false;
}
log("Used YouTube native setPlaybackRate: " + speed, 4);
return true;
}
} catch (e) {
log("YouTube native speed failed: " + e.message, 3);
}
return false;
}
function isSubtitleNudgeSupported(video) {
return Boolean(video);
}
function isSubtitleNudgeEnabledForVideo(video) {
if (!video || !video.vsc) return tc.settings.enableSubtitleNudge;
if (typeof video.vsc.subtitleNudgeEnabledOverride === "boolean") {
return video.vsc.subtitleNudgeEnabledOverride;
}
return tc.settings.enableSubtitleNudge;
}
function setSubtitleNudgeEnabledForVideo(video, enabled) {
if (!video || !video.vsc) return false;
var normalizedEnabled = Boolean(enabled);
video.vsc.subtitleNudgeEnabledOverride = normalizedEnabled;
if (!normalizedEnabled) {
video.vsc.stopSubtitleNudge();
} else if (!video.paused && video.playbackRate !== 1.0) {
video.vsc.startSubtitleNudge();
}
updateSubtitleNudgeIndicator(video);
// Briefly flash the standalone indicator next to the speed text
var flashEl = video.vsc.nudgeFlashIndicator;
if (flashEl) {
flashEl.classList.add("visible");
clearTimeout(flashEl._flashTimer);
flashEl._flashTimer = setTimeout(function () {
flashEl.classList.remove("visible");
}, 1500);
}
return normalizedEnabled;
}
function subtitleNudgeIconMarkup(isEnabled) {
var action = isEnabled ? "subtitleNudgeOn" : "subtitleNudgeOff";
if (typeof vscIconSvgString !== "function") {
return isEnabled ? "✓" : "×";
}
var svg = vscIconSvgString(action, 14);
if (!svg) {
return isEnabled ? "✓" : "×";
}
return (
'<span class="vsc-btn-icon" aria-hidden="true">' + svg + "</span>"
);
}
function updateSubtitleNudgeIndicator(video) {
if (!video || !video.vsc) return;
var isEnabled = isSubtitleNudgeEnabledForVideo(video);
var title = isEnabled ? "Subtitle nudge enabled" : "Subtitle nudge disabled";
var mark = subtitleNudgeIconMarkup(isEnabled);
var indicator = video.vsc.subtitleNudgeIndicator;
if (indicator) {
indicator.innerHTML = mark;
indicator.dataset.enabled = isEnabled ? "true" : "false";
indicator.dataset.supported = "true";
indicator.title = title;
indicator.setAttribute("aria-label", title);
}
var flashEl = video.vsc.nudgeFlashIndicator;
if (flashEl) {
flashEl.innerHTML = mark;
flashEl.dataset.enabled = isEnabled ? "true" : "false";
flashEl.dataset.supported = "true";
flashEl.setAttribute("aria-label", title);
}
}
function schedulePersistLastSpeed(speed) {
if (!isValidSpeed(speed)) return;
tc.pendingLastSpeedValue = speed;
if (tc.pendingLastSpeedSave !== null) return;
tc.pendingLastSpeedSave = setTimeout(function () {
var speedToPersist = tc.pendingLastSpeedValue;
tc.pendingLastSpeedSave = null;
if (!isValidSpeed(speedToPersist) || tc.persistedLastSpeed === speedToPersist) {
return;
}
chrome.storage.sync.set({ lastSpeed: speedToPersist }, function () { });
tc.persistedLastSpeed = speedToPersist;
}, 250);
}
function suppressNextNudgeRateChanges(controller, count) {
if (!controller) return;
controller.suppressedRateChangeCount =
(controller.suppressedRateChangeCount || 0) + (count || 2);
controller.suppressedRateChangeUntil =
Date.now() + Math.max(250, tc.settings.subtitleNudgeInterval * 4);
}
function shouldIgnoreSuppressedRateChange(video) {
if (!video || !video.vsc) return false;
var controller = video.vsc;
if (
controller.suppressedRateChangeCount > 0 &&
controller.suppressedRateChangeUntil >= Date.now()
) {
controller.suppressedRateChangeCount -= 1;
return true;
}
if (controller.suppressedRateChangeUntil < Date.now()) {
controller.suppressedRateChangeCount = 0;
}
return false;
}
function resolveTargetSpeed(video) {
return getDesiredSpeed(video);
}
function applySourceTransitionPolicy(video, forceUpdate) {
if (!video || !video.vsc) return;
var sourceKey = getVideoSourceKey(video);
if (!forceUpdate && video.vsc.mediaSourceKey === sourceKey) return;
video.vsc.mediaSourceKey = sourceKey;
var desiredSpeed =
tc.settings.rememberSpeed || tc.settings.forceLastSavedSpeed
? sanitizeSpeed(tc.settings.lastSpeed, 1.0)
: 1.0;
video.vsc.targetSpeed = desiredSpeed;
video.vsc.targetSpeedSourceKey = sourceKey;
if (video.vsc.speedIndicator) {
video.vsc.speedIndicator.textContent = desiredSpeed.toFixed(2);
}
if (Math.abs(video.playbackRate - desiredSpeed) > 0.01) {
setSpeed(video, desiredSpeed, false, false);
}
// Same-tab SPA (e.g. YouTube watch → Shorts): URL can change while remember-speed
// already ran on src mutation — re-apply margins / location / opacity for new rules.
reapplySiteRulesAndControllerGeometry();
}
function extendSpeedRestoreWindow(video, duration) {
if (!video || !video.vsc) return;
@@ -409,6 +1020,14 @@ function ensureController(node, parent) {
);
return null;
}
// href selects site rules; re-run on every new/usable media so margins/opacity match current URL.
var siteDisabled = applySiteRuleOverrides();
if (!tc.settings.enabled || siteDisabled) {
return null;
}
refreshAllControllerGeometry();
log(
`Creating controller for ${node.tagName}: ${node.src || node.currentSrc || "no src"}`,
4
@@ -442,20 +1061,31 @@ function scanNodeForMedia(node, parent, added) {
var ownerDocument = node.ownerDocument || document;
if (!added && ownerDocument.body && ownerDocument.body.contains(node)) return;
// Check if the node itself is a media element
if (isMediaElement(node)) {
if (added) ensureController(node, parent);
else removeController(node);
}
if (node.children) {
Array.from(node.children).forEach(function (child) {
scanNodeForMedia(child, child.parentNode || parent, added);
});
// Use querySelectorAll instead of recursive child walking — the browser's
// native selector engine is orders of magnitude faster than JS recursion.
if (typeof node.querySelectorAll === "function") {
var selector = mediaSelector();
try {
var mediaElements = node.querySelectorAll(selector);
for (var i = 0; i < mediaElements.length; i++) {
var el = mediaElements[i];
if (added) ensureController(el, el.parentNode || parent);
else removeController(el);
}
} catch (e) {
// querySelectorAll may throw on detached or unusual nodes
}
}
// Still need to observe shadow roots for media inside web components
if (node.shadowRoot) {
observeRoot(node.shadowRoot);
scanNodeForMedia(node.shadowRoot, node, added);
}
}
@@ -467,6 +1097,18 @@ function getScanNodeForRoot(root) {
return root;
}
function rootMayContainMedia(root) {
if (!root) return false;
if (root.nodeType === Node.DOCUMENT_NODE) return true;
if (typeof root.querySelector !== "function") return true;
try {
return Boolean(root.querySelector(mediaSelector()));
} catch (error) {
return true;
}
}
function scanRootForMedia(root) {
var scanRoot = getScanNodeForRoot(root);
if (!scanRoot) return;
@@ -482,7 +1124,9 @@ function observeRoot(root) {
setupListener(root);
attachMutationObserver(root);
attachMediaDetectionListeners(root);
scanRootForMedia(root);
if (rootMayContainMedia(root)) {
scanRootForMedia(root);
}
}
function patchAttachShadow() {
@@ -547,70 +1191,188 @@ chrome.storage.sync.get(tc.settings, function (storage) {
audioBoolean: tc.settings.audioBoolean,
startHidden: tc.settings.startHidden,
enabled: tc.settings.enabled,
controllerOpacity: tc.settings.controllerOpacity,
blacklist: tc.settings.blacklist.replace(regStrip, "")
controllerLocation: tc.settings.controllerLocation,
controllerOpacity: tc.settings.controllerOpacity
});
}
tc.settings.lastSpeed = Number(storage.lastSpeed);
if (!isValidSpeed(tc.settings.lastSpeed) && tc.settings.lastSpeed !== 1.0) {
log(`Invalid lastSpeed detected: ${storage.lastSpeed}, resetting to 1.0`, 3);
tc.settings.lastSpeed = 1.0;
tc.persistedLastSpeed = 1.0;
chrome.storage.sync.set({ lastSpeed: 1.0 });
} else if (!isValidSpeed(tc.settings.lastSpeed)) {
tc.settings.lastSpeed = 1.0;
}
tc.persistedLastSpeed = tc.settings.lastSpeed;
tc.settings.displayKeyCode = Number(storage.displayKeyCode);
tc.settings.rememberSpeed = Boolean(storage.rememberSpeed);
tc.settings.forceLastSavedSpeed = Boolean(storage.forceLastSavedSpeed);
tc.settings.audioBoolean = Boolean(storage.audioBoolean);
tc.settings.enabled = Boolean(storage.enabled);
tc.settings.startHidden = Boolean(storage.startHidden);
tc.settings.hideWithControls =
typeof storage.hideWithControls !== "undefined"
? Boolean(storage.hideWithControls)
: Boolean(storage.hideWithYouTubeControls);
tc.settings.hideWithControlsTimer =
Math.min(15, Math.max(0.1, Number(storage.hideWithControlsTimer) || 2.0));
tc.settings.hideWithYouTubeControls = tc.settings.hideWithControls;
tc.settings.controllerLocation = normalizeControllerLocation(
storage.controllerLocation
);
tc.settings.controllerOpacity = Number(storage.controllerOpacity);
tc.settings.blacklist = String(storage.blacklist);
tc.settings.controllerMarginTop = normalizeControllerMarginPx(
storage.controllerMarginTop,
0
);
tc.settings.controllerMarginRight = normalizeControllerMarginPx(
0,
0
);
tc.settings.controllerMarginBottom = normalizeControllerMarginPx(
storage.controllerMarginBottom,
typeof storage.controllerMarginBottom !== "undefined" ? 0 : 65
);
tc.settings.controllerMarginLeft = normalizeControllerMarginPx(
0,
0
);
tc.settings.siteRules = Array.isArray(storage.siteRules)
? storage.siteRules
: [];
tc.settings.controllerButtons = Array.isArray(storage.controllerButtons)
? storage.controllerButtons
: tc.settings.controllerButtons;
tc.settings.enableSubtitleNudge =
typeof storage.enableSubtitleNudge !== "undefined"
? Boolean(storage.enableSubtitleNudge)
: tc.settings.enableSubtitleNudge;
tc.settings.subtitleNudgeInterval =
Number(storage.subtitleNudgeInterval) || 100; // Default 100ms for better performance
tc.settings.subtitleNudgeInterval = Math.min(
1000,
Math.max(10, Number(storage.subtitleNudgeInterval) || 50)
);
tc.settings.subtitleNudgeAmount =
Number(storage.subtitleNudgeAmount) || tc.settings.subtitleNudgeAmount;
if (
tc.settings.keyBindings.filter((x) => x.action == "display").length == 0
) {
tc.settings.keyBindings.push(
createDefaultBinding(
"display",
"V",
Number(storage.displayKeyCode) || 86,
0
)
);
var addedDefaultBinding = false;
addedDefaultBinding =
ensureDefaultKeyBinding(
"display",
"V",
Number(storage.displayKeyCode) || 86,
0
) || addedDefaultBinding;
addedDefaultBinding =
ensureDefaultKeyBinding("move", "P", 80, 0) || addedDefaultBinding;
addedDefaultBinding =
ensureDefaultKeyBinding("toggleSubtitleNudge", "N", 78, 0) ||
addedDefaultBinding;
if (addedDefaultBinding) {
chrome.storage.sync.set({ keyBindings: tc.settings.keyBindings });
}
captureSiteRuleBase();
patchAttachShadow();
// Add a listener for messages from the popup.
// We use a global flag to ensure the listener is only attached once.
if (!window.vscMessageListener) {
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
// Check if the message is a request to re-scan the page.
if (request.action === "rescan_page") {
log("Re-scan command received from popup.", 4);
initializeWhenReady(document, true);
sendResponse({ status: "complete" });
return false;
}
// Required to allow for asynchronous responses.
return true;
if (request.action === "get_speed") {
// Do not sendResponse in frames with no media — only one response is
// accepted tab-wide, and the top frame often wins before an iframe.
var videoGs = getPrimaryVideoElement();
if (!videoGs) return false;
sendResponse({
speed: videoGs.playbackRate
});
return false;
}
if (request.action === "get_page_context") {
sendResponse({ url: location.href });
return false;
}
if (request.action === "run_action") {
var value = request.value;
if (value === undefined || value === null) {
value = getKeyBindings(request.actionName, "value");
}
runAction(request.actionName, value);
var videoAfter = getPrimaryVideoElement();
if (!videoAfter) return false;
sendResponse({
speed: videoAfter.playbackRate
});
return false;
}
return false;
}
);
// Set the flag to prevent adding the listener again.
window.vscMessageListener = true;
}
initializeWhenReady(document);
chrome.storage.local.get(["customButtonIcons"], function (loc) {
tc.settings.customButtonIcons =
loc &&
loc.customButtonIcons &&
typeof loc.customButtonIcons === "object"
? loc.customButtonIcons
: {};
if (!window.vscCustomIconListener) {
window.vscCustomIconListener = true;
chrome.storage.onChanged.addListener(function (changes, area) {
if (area !== "local" || !changes.customButtonIcons) return;
var nv = changes.customButtonIcons.newValue;
tc.settings.customButtonIcons =
nv && typeof nv === "object" ? nv : {};
if (tc.mediaElements && tc.mediaElements.length) {
tc.mediaElements.forEach(function (video) {
if (!video.vsc || !video.vsc.div) return;
var doc = video.ownerDocument;
var shadow = video.vsc.div.shadowRoot;
if (!shadow) return;
shadow.querySelectorAll("button[data-action]").forEach(function (btn) {
var act = btn.dataset.action;
if (!act) return;
var svg =
tc.settings.customButtonIcons &&
tc.settings.customButtonIcons[act] &&
tc.settings.customButtonIcons[act].svg;
btn.innerHTML = "";
if (svg) {
var cw = doc.createElement("span");
cw.className = "vsc-btn-icon";
cw.innerHTML = svg;
btn.appendChild(cw);
} else if (typeof vscIconWrap === "function") {
var wrap = vscIconWrap(doc, act, 14);
if (wrap) {
btn.appendChild(wrap);
} else {
var cdf = controllerButtonDefs[act];
btn.textContent = (cdf && cdf.label) || "?";
}
} else {
var cdf2 = controllerButtonDefs[act];
btn.textContent = (cdf2 && cdf2.label) || "?";
}
});
});
}
});
}
initializeWhenReady(document);
});
});
function getKeyBindings(action, what = "value") {
@@ -625,6 +1387,34 @@ function setKeyBindings(action, value) {
value;
}
function createControllerButton(doc, action, label, className) {
var button = doc.createElement("button");
button.dataset.action = action;
var custom =
tc.settings.customButtonIcons &&
tc.settings.customButtonIcons[action] &&
tc.settings.customButtonIcons[action].svg;
if (custom) {
var customWrap = doc.createElement("span");
customWrap.className = "vsc-btn-icon";
customWrap.innerHTML = custom;
button.appendChild(customWrap);
} else if (typeof vscIconWrap === "function") {
var wrap = vscIconWrap(doc, action, 14);
if (wrap) {
button.appendChild(wrap);
} else {
button.textContent = label || "?";
}
} else {
button.textContent = label || "?";
}
if (className) {
button.className = className;
}
return button;
}
function defineVideoController() {
tc.videoController = function (target, parent) {
if (target.vsc) return target.vsc;
@@ -636,11 +1426,22 @@ function defineVideoController() {
this.restoreSpeedTimer = null;
this.pendingRateChange = null;
this.speedRestoreUntil = 0;
this.subtitleNudgeEnabledOverride = null;
this.suppressedRateChangeCount = 0;
this.suppressedRateChangeUntil = 0;
this.visibilityResumeHandler = null;
this.resetToggleArmed = false;
this.resetButtonEl = null;
this.controllerLocation = normalizeControllerLocation(
tc.settings.controllerLocation
);
log(`Creating video controller for ${target.tagName} with src: ${target.src || target.currentSrc || 'none'}`, 4);
let storedSpeed = sanitizeSpeed(resolveTargetSpeed(target), 1.0);
this.targetSpeed = storedSpeed;
this.targetSpeedSourceKey = getVideoSourceKey(target);
this.mediaSourceKey = getVideoSourceKey(target);
if (!tc.settings.rememberSpeed && !tc.settings.forceLastSavedSpeed) {
setKeyBindings("reset", getKeyBindings("fast"));
}
@@ -658,7 +1459,16 @@ function defineVideoController() {
log(`Controller created and attached to DOM. Hidden: ${this.div.classList.contains('vsc-hidden')}`, 4);
var mediaEventAction = function (event) {
if (
event.type === "loadedmetadata" ||
event.type === "loadeddata" ||
event.type === "canplay"
) {
applySourceTransitionPolicy(event.target, false);
}
if (event.type === "play") {
applySourceTransitionPolicy(event.target, false);
extendSpeedRestoreWindow(event.target);
if (!tc.settings.rememberSpeed && !tc.settings.forceLastSavedSpeed) {
@@ -705,6 +1515,18 @@ function defineVideoController() {
}
};
target.addEventListener(
"loadedmetadata",
(this.handleLoadedMetadata = mediaEventAction.bind(this))
);
target.addEventListener(
"loadeddata",
(this.handleLoadedData = mediaEventAction.bind(this))
);
target.addEventListener(
"canplay",
(this.handleCanPlay = mediaEventAction.bind(this))
);
target.addEventListener(
"play",
(this.handlePlay = mediaEventAction.bind(this))
@@ -740,8 +1562,10 @@ function defineVideoController() {
this.div.classList.add("vsc-nosource");
} else {
this.div.classList.remove("vsc-nosource");
applySourceTransitionPolicy(this.video, true);
if (!mutation.target.paused) this.startSubtitleNudge();
}
updateSubtitleNudgeIndicator(this.video);
}
}
});
@@ -754,9 +1578,24 @@ function defineVideoController() {
tc.videoController.prototype.remove = function () {
this.stopSubtitleNudge();
if (this.youTubeAutoHideObserver) {
this.youTubeAutoHideObserver.disconnect();
this.youTubeAutoHideObserver = null;
}
if (this.youTubeAutoHideCleanup) {
this.youTubeAutoHideCleanup();
this.youTubeAutoHideCleanup = null;
}
if (this.genericAutoHideCleanup) {
this.genericAutoHideCleanup();
this.genericAutoHideCleanup = null;
}
if (this.div) this.div.remove();
if (this.restoreSpeedTimer) clearTimeout(this.restoreSpeedTimer);
if (this.video) {
this.video.removeEventListener("loadedmetadata", this.handleLoadedMetadata);
this.video.removeEventListener("loadeddata", this.handleLoadedData);
this.video.removeEventListener("canplay", this.handleCanPlay);
this.video.removeEventListener("play", this.handlePlay);
this.video.removeEventListener("pause", this.handlePause);
this.video.removeEventListener("seeking", this.handleSeeking);
@@ -770,14 +1609,9 @@ function defineVideoController() {
};
tc.videoController.prototype.startSubtitleNudge = function () {
const isYouTube =
(this.video &&
this.video.currentSrc &&
this.video.currentSrc.includes("googlevideo.com")) ||
location.hostname.includes("youtube.com");
if (
!isYouTube ||
!tc.settings.enableSubtitleNudge ||
!isSubtitleNudgeSupported(this.video) ||
!isSubtitleNudgeEnabledForVideo(this.video) ||
this.nudgeAnimationId !== null ||
!this.video ||
this.video.paused ||
@@ -798,12 +1632,30 @@ function defineVideoController() {
// CRITICAL: Don't nudge if tab is hidden - prevents speed drift
if (document.hidden) {
this.nudgeAnimationId = setTimeout(performNudge, tc.settings.subtitleNudgeInterval);
if (!this.visibilityResumeHandler && this.video && this.video.ownerDocument) {
this.visibilityResumeHandler = () => {
if (this.video.ownerDocument.hidden) return;
this.video.ownerDocument.removeEventListener(
"visibilitychange",
this.visibilityResumeHandler,
true
);
this.visibilityResumeHandler = null;
this.startSubtitleNudge();
};
this.video.ownerDocument.addEventListener(
"visibilitychange",
this.visibilityResumeHandler,
true
);
}
this.nudgeAnimationId = null;
return;
}
// Set flag to prevent ratechange listener from interfering
tc.isNudging = true;
suppressNextNudgeRateChanges(this, 2);
// Cache values to avoid repeated property access
const targetSpeed = this.targetSpeed;
@@ -835,20 +1687,22 @@ function defineVideoController() {
this.nudgeAnimationId = null;
log(`Nudge: Stopping.`, 5);
}
// Clear the target speed when stopping
this.targetSpeed = null;
if (this.visibilityResumeHandler && this.video && this.video.ownerDocument) {
this.video.ownerDocument.removeEventListener(
"visibilitychange",
this.visibilityResumeHandler,
true
);
this.visibilityResumeHandler = null;
}
// Clear the animation state, but PRESERVE targetSpeed so getDesiredSpeed
// doesn't lose the user's intended speed if the site hijacks it.
};
tc.videoController.prototype.performImmediateNudge = function () {
const isYouTube =
(this.video &&
this.video.currentSrc &&
this.video.currentSrc.includes("googlevideo.com")) ||
location.hostname.includes("youtube.com");
if (
!isYouTube ||
!tc.settings.enableSubtitleNudge ||
!isSubtitleNudgeSupported(this.video) ||
!isSubtitleNudgeEnabledForVideo(this.video) ||
!this.video ||
this.video.paused ||
this.video.playbackRate === 1.0 ||
@@ -861,6 +1715,7 @@ function defineVideoController() {
const nudgeAmount = tc.settings.subtitleNudgeAmount;
tc.isNudging = true;
suppressNextNudgeRateChanges(this, 2);
this.video.playbackRate = targetRate + nudgeAmount;
// Revert synchronously via microtask
@@ -874,20 +1729,217 @@ function defineVideoController() {
log(`Immediate nudge performed at rate ${targetRate.toFixed(2)}`, 5);
};
tc.videoController.prototype.setupYouTubeAutoHide = function (wrapper) {
if (!wrapper || !isOnYouTube()) return;
const video = this.video;
const ytPlayer = video.closest(".html5-video-player");
if (!ytPlayer) {
log("YouTube player not found for auto-hide setup", 4);
return;
}
const syncControllerVisibility = () => {
// YouTube adds ytp-autohide class to the player when controls should be hidden
// We mirror this class state to enable CSS-based hiding
// The vsc-hidden class (from V key) takes precedence via CSS specificity
if (ytPlayer.classList.contains("ytp-autohide")) {
wrapper.classList.add("ytp-autohide");
// Immediately end any temporary "vsc-show" state to hide with YouTube
// UNLESS it was forced by a shortcut (vsc-forced-show)
if (!wrapper.classList.contains("vsc-forced-show")) {
wrapper.classList.remove("vsc-show");
if (wrapper.showTimeOut) {
clearTimeout(wrapper.showTimeOut);
wrapper.showTimeOut = undefined;
}
}
log("YouTube controls hidden, hiding controller", 5);
} else {
wrapper.classList.remove("ytp-autohide");
log("YouTube controls visible, showing controller", 5);
}
};
// Initial sync
syncControllerVisibility();
// Observe YouTube player class changes
this.youTubeAutoHideObserver = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === "attributes" && mutation.attributeName === "class") {
syncControllerVisibility();
}
});
});
this.youTubeAutoHideObserver.observe(ytPlayer, {
attributes: true,
attributeFilter: ["class"]
});
log("YouTube auto-hide observer setup complete", 4);
// Also reveal on hover/activity independently of YouTube's own controls
// for immediate responsiveness, UNLESS Speeder is actually toggled hidden (vsc-hidden)
const resetTimer = () => {
showController(wrapper, tc.settings.hideWithControlsTimer * 1000);
};
const activityEvents = ["mousemove", "mousedown", "touchstart"];
activityEvents.forEach((type) => {
video.addEventListener(type, resetTimer, { passive: true });
wrapper.addEventListener(type, resetTimer, { passive: true });
ytPlayer.addEventListener(type, resetTimer, { passive: true });
});
// Store a cleanup function
this.youTubeAutoHideCleanup = () => {
activityEvents.forEach((type) => {
video.removeEventListener(type, resetTimer);
wrapper.removeEventListener(type, resetTimer);
ytPlayer.removeEventListener(type, resetTimer);
});
};
};
tc.videoController.prototype.setupGenericAutoHide = function (wrapper) {
if (!wrapper) return;
const video = this.video;
let timer = null;
const resetTimer = () => {
wrapper.classList.remove("vsc-idle-hidden");
showController(wrapper, tc.settings.hideWithControlsTimer * 1000);
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
// Only hide if the video is not paused
// (Many players keep controls visible while paused)
// However, the user said "Reveal on every mouse and keyboard input"
// and "auto-hidden after timespan".
// We'll follow the timer strictly.
wrapper.classList.add("vsc-idle-hidden");
log("Generic hide: controller hidden due to inactivity", 5);
}, tc.settings.hideWithControlsTimer * 1000);
};
// Initial show/timer
resetTimer();
// The wrapper covers the player area on most sites due to inject.css styles,
// but we listen on both the video and the wrapper for maximum coverage.
const activityEvents = ["mousemove", "mousedown", "keydown", "touchstart"];
const parentEl = video.parentElement;
activityEvents.forEach((type) => {
video.addEventListener(type, resetTimer, { passive: true });
wrapper.addEventListener(type, resetTimer, { passive: true });
if (parentEl) {
parentEl.addEventListener(type, resetTimer, { passive: true });
}
});
// Also reset timer on play/pause events to ensure sync when player state changes
video.addEventListener("play", resetTimer, { passive: true });
video.addEventListener("pause", resetTimer, { passive: true });
// Store a cleanup function
this.genericAutoHideCleanup = () => {
if (timer) clearTimeout(timer);
activityEvents.forEach((type) => {
video.removeEventListener(type, resetTimer);
wrapper.removeEventListener(type, resetTimer);
if (parentEl) {
parentEl.removeEventListener(type, resetTimer);
}
});
video.removeEventListener("play", resetTimer);
video.removeEventListener("pause", resetTimer);
};
log(`Generic auto-hide setup complete with ${tc.settings.hideWithControlsTimer}s timer`, 4);
};
tc.videoController.prototype.initializeControls = function () {
const doc = this.video.ownerDocument;
const speed = this.video.playbackRate.toFixed(2);
var top = "0px",
left = "0px";
var wrapper = doc.createElement("div");
wrapper.classList.add("vsc-controller");
if (!this.video.src && !this.video.currentSrc)
wrapper.classList.add("vsc-nosource");
if (tc.settings.startHidden) wrapper.classList.add("vsc-hidden");
// Use lower z-index for non-YouTube sites to avoid overlapping modals
if (!isOnYouTube()) wrapper.classList.add("vsc-non-youtube");
var shadow = wrapper.attachShadow({ mode: "open" });
shadow.innerHTML = `<style> @import "${chrome.runtime.getURL("shadow.css")}"; </style><div id="controller" style="top:${top}; left:${left}; opacity:${tc.settings.controllerOpacity}"><span data-action="drag" class="draggable">${speed}</span><span id="controls"><button data-action="rewind" class="rw">«</button><button data-action="slower"></button><button data-action="faster">+</button><button data-action="advance" class="rw">»</button><button data-action="display" class="hideButton">×</button></span></div>`;
this.speedIndicator = shadow.querySelector(".draggable");
shadow.querySelector(".draggable").addEventListener(
var shadowStylesheet = doc.createElement("link");
shadowStylesheet.rel = "stylesheet";
shadowStylesheet.href = chrome.runtime.getURL("shadow.css");
shadow.appendChild(shadowStylesheet);
var controller = doc.createElement("div");
controller.id = "controller";
controller.style.opacity = String(tc.settings.controllerOpacity);
this.controllerLocation = applyControllerLocationToElement(
controller,
this.controllerLocation
);
var dragHandle = doc.createElement("span");
dragHandle.dataset.action = "drag";
dragHandle.className = "draggable";
dragHandle.textContent = speed;
var controls = doc.createElement("span");
controls.id = "controls";
var buttonConfig = Array.isArray(tc.settings.controllerButtons)
? tc.settings.controllerButtons
: ["rewind", "slower", "faster", "advance", "display"];
var subtitleNudgeIndicator = null;
buttonConfig.forEach(function (btnId) {
if (btnId === "nudge") {
subtitleNudgeIndicator = doc.createElement("span");
subtitleNudgeIndicator.id = "nudge-indicator";
subtitleNudgeIndicator.setAttribute("role", "button");
subtitleNudgeIndicator.setAttribute("aria-live", "polite");
subtitleNudgeIndicator.setAttribute("tabindex", "0");
controls.appendChild(subtitleNudgeIndicator);
} else {
var def = controllerButtonDefs[btnId];
if (def) {
controls.appendChild(
createControllerButton(doc, btnId, def.label, def.className)
);
}
}
});
var nudgeFlashIndicator = doc.createElement("span");
nudgeFlashIndicator.id = "nudge-flash-indicator";
nudgeFlashIndicator.setAttribute("aria-hidden", "true");
controller.appendChild(dragHandle);
controller.appendChild(controls);
/* Flash sits after #controls so it never inserts space between speed and buttons. */
controller.appendChild(nudgeFlashIndicator);
shadow.appendChild(controller);
this.speedIndicator = dragHandle;
this.subtitleNudgeIndicator = subtitleNudgeIndicator;
this.nudgeFlashIndicator = nudgeFlashIndicator;
this.resetButtonEl =
shadow.querySelector('button[data-action="reset"]') || null;
this.resetToggleArmed = false;
if (subtitleNudgeIndicator) {
updateSubtitleNudgeIndicator(this.video);
}
dragHandle.addEventListener(
"mousedown",
(e) => {
runAction(
@@ -913,12 +1965,32 @@ function defineVideoController() {
true
);
});
shadow
.querySelector("#controller")
.addEventListener("click", (e) => e.stopPropagation(), false);
shadow
.querySelector("#controller")
.addEventListener("mousedown", (e) => e.stopPropagation(), false);
if (subtitleNudgeIndicator) {
subtitleNudgeIndicator.addEventListener(
"click",
(e) => {
var video = this.video;
if (video) {
var newState = !isSubtitleNudgeEnabledForVideo(video);
setSubtitleNudgeEnabledForVideo(video, newState);
}
e.stopPropagation();
},
true
);
}
controller.addEventListener("click", (e) => e.stopPropagation(), false);
controller.addEventListener("mousedown", (e) => e.stopPropagation(), false);
// Setup auto-hide observers if enabled
if (tc.settings.hideWithControls) {
if (isOnYouTube()) {
this.setupYouTubeAutoHide(wrapper);
} else {
this.setupGenericAutoHide(wrapper);
}
}
var fragment = doc.createDocumentFragment();
fragment.appendChild(wrapper);
const parentEl = this.parent || this.video.parentElement;
@@ -954,6 +2026,21 @@ function defineVideoController() {
if (s) s.prepend(fragment);
else parentEl.insertBefore(fragment, parentEl.firstChild);
break;
case location.hostname == "www.youtube.com":
case location.hostname == "m.youtube.com":
case location.hostname == "music.youtube.com":
// YouTube's player DOM has .html5-video-container (video's parent) as a
// low layer with overlay siblings (.ytp-player-content, etc.) on top that
// intercept mouse events. Insert into .html5-video-player (the player
// root) so the controller sits above all overlay layers.
log("Using YouTube-specific insertion", 5);
var ytPlayer = parentEl.closest(".html5-video-player");
if (ytPlayer) {
ytPlayer.insertBefore(fragment, ytPlayer.firstChild);
} else {
parentEl.insertBefore(fragment, parentEl.firstChild);
}
break;
default:
log("Using default insertion method", 5);
parentEl.insertBefore(fragment, parentEl.firstChild);
@@ -973,27 +2060,130 @@ function escapeStringRegExp(str) {
const m = /[|\\{}()[\]^$+*?.]/g;
return str.replace(m, "\\$&");
}
function isBlacklisted() {
let b = false;
const l = tc.settings.blacklist ? tc.settings.blacklist.split("\n") : [];
l.forEach((m) => {
if (b) return;
m = m.replace(regStrip, "");
if (m.length == 0) return;
let r;
if (m.startsWith("/") && m.lastIndexOf("/") > 0) {
function applySiteRuleOverrides() {
resetSettingsFromSiteRuleBase();
if (!Array.isArray(tc.settings.siteRules) || tc.settings.siteRules.length === 0) {
return false;
}
var currentUrl = location.href;
var matchedRule = null;
for (var i = 0; i < tc.settings.siteRules.length; i++) {
var rule = tc.settings.siteRules[i];
var pattern = rule.pattern;
if (!pattern || pattern.length === 0) continue;
var regex;
if (pattern.startsWith("/") && pattern.lastIndexOf("/") > 0) {
try {
const ls = m.lastIndexOf("/");
r = new RegExp(m.substring(1, ls), m.substring(ls + 1));
var lastSlash = pattern.lastIndexOf("/");
regex = new RegExp(
pattern.substring(1, lastSlash),
pattern.substring(lastSlash + 1)
);
} catch (e) {
log(`Invalid regex: ${m}. ${e.message}`, 2);
return;
log(`Invalid site rule regex: ${pattern}. ${e.message}`, 2);
continue;
}
} else r = new RegExp(escapeStringRegExp(m));
if (r && r.test(location.href)) b = true;
} else {
regex = new RegExp(escapeStringRegExp(pattern));
}
if (regex && regex.test(currentUrl)) {
matchedRule = rule;
break;
}
}
if (!matchedRule) return false;
tc.activeSiteRule = matchedRule;
log(`Matched site rule: ${matchedRule.pattern}`, 4);
// Check if extension should be enabled/disabled on this site
if (matchedRule.enabled === false) {
log(`Extension disabled for site: ${currentUrl}`, 4);
return true;
} else if (matchedRule.disableExtension === true) {
// Handle old format
log(`Extension disabled (legacy) for site: ${currentUrl}`, 4);
return true;
}
// Override general settings with site-specific overrides
const siteSettings = [
"startHidden",
"hideWithControls",
"hideWithControlsTimer",
"controllerLocation",
"rememberSpeed",
"forceLastSavedSpeed",
"audioBoolean",
"controllerOpacity",
"controllerMarginTop",
"controllerMarginBottom",
"enableSubtitleNudge",
"subtitleNudgeInterval"
];
siteSettings.forEach((key) => {
if (matchedRule[key] !== undefined) {
log(`Overriding ${key} for site: ${matchedRule[key]}`, 4);
tc.settings[key] = matchedRule[key];
}
});
if (b) log(`Page ${location.href} blacklisted.`, 4);
return b;
[
"controllerMarginTop",
"controllerMarginBottom"
].forEach(function (key) {
tc.settings[key] = normalizeControllerMarginPx(tc.settings[key], 0);
});
if (Array.isArray(matchedRule.controllerButtons)) {
log(`Overriding controllerButtons for site`, 4);
tc.settings.controllerButtons = matchedRule.controllerButtons;
}
// Override key bindings with site-specific shortcuts
if (Array.isArray(matchedRule.shortcuts) && matchedRule.shortcuts.length > 0) {
var overriddenActions = new Set();
matchedRule.shortcuts.forEach((shortcut) => {
overriddenActions.add(shortcut.action);
});
// Keep global bindings that aren't overridden, add site-specific ones
tc.settings.keyBindings = tc.settings.keyBindings
.filter((binding) => !overriddenActions.has(binding.action))
.concat(
matchedRule.shortcuts.map((shortcut) =>
normalizeStoredBinding(shortcut)
).filter(Boolean)
);
}
return false;
}
/** Apply current tc.settings controller layout/opacity to every attached controller (after site rules). */
function refreshAllControllerGeometry() {
tc.mediaElements.forEach(function (video) {
if (!video || !video.vsc) return;
applyControllerLocation(video.vsc, tc.settings.controllerLocation);
var controllerEl = getControllerElement(video.vsc);
if (controllerEl) {
controllerEl.style.opacity = String(tc.settings.controllerOpacity);
}
});
}
/** Re-match site rules for current URL and refresh controller position/opacity on every video. */
function reapplySiteRulesAndControllerGeometry() {
var siteDisabled = applySiteRuleOverrides();
if (!tc.settings.enabled || siteDisabled) return;
refreshAllControllerGeometry();
}
function shouldPreserveDesiredSpeed(video, speed) {
@@ -1013,17 +2203,21 @@ function shouldPreserveDesiredSpeed(video, speed) {
function setupListener(root) {
root = root || document;
if (root.vscRateListenerAttached) return;
function updateSpeedFromEvent(video) {
function updateSpeedFromEvent(video, skipResetDisarm) {
if (!video.vsc || !video.vsc.speedIndicator) return;
var speed = Number(video.playbackRate.toFixed(2));
if (!skipResetDisarm) {
video.vsc.resetToggleArmed = false;
}
var speed = video.playbackRate; // Preserve full precision (e.g. 0.0625)
video.vsc.speedIndicator.textContent = speed.toFixed(2);
video.vsc.targetSpeed = speed;
video.vsc.targetSpeedSourceKey = getVideoSourceKey(video);
var sourceKey = getVideoSourceKey(video);
if (sourceKey !== "unknown_src") {
tc.settings.speeds[sourceKey] = speed;
}
tc.settings.lastSpeed = speed;
chrome.storage.sync.set({ lastSpeed: speed }, () => { });
schedulePersistLastSpeed(speed);
if (video.vsc) {
if (speed === 1.0 || video.paused) video.vsc.stopSubtitleNudge();
else video.vsc.startSubtitleNudge();
@@ -1036,29 +2230,31 @@ function setupListener(root) {
var video = event.target;
if (!video || typeof video.playbackRate === "undefined" || !video.vsc)
return;
if (shouldIgnoreSuppressedRateChange(video)) return;
if (tc.settings.forceLastSavedSpeed) {
if (event.detail && event.detail.origin === "videoSpeed") {
video.playbackRate = event.detail.speed;
updateSpeedFromEvent(video);
updateSpeedFromEvent(video, true);
} else {
video.playbackRate = sanitizeSpeed(tc.settings.lastSpeed, 1.0);
}
event.stopImmediatePropagation();
} else {
var currentSpeed = Number(video.playbackRate.toFixed(2));
var currentSpeed = video.playbackRate; // Preserve full precision (e.g. 0.0625)
var desiredSpeed = getDesiredSpeed(video);
var pendingRateChange = takePendingRateChange(video, currentSpeed);
if (pendingRateChange) {
updateSpeedFromEvent(video);
updateSpeedFromEvent(video, true);
return;
}
if (shouldPreserveDesiredSpeed(video, currentSpeed)) {
log(
`Ignoring external rate change to ${currentSpeed.toFixed(2)} while preserving ${desiredSpeed.toFixed(2)}`,
`Ignoring external rate change to ${currentSpeed.toFixed(4)} while preserving ${desiredSpeed.toFixed(4)}`,
4
);
video.vsc.resetToggleArmed = false;
video.vsc.speedIndicator.textContent = desiredSpeed.toFixed(2);
scheduleSpeedRestore(video, desiredSpeed, "pause/play or seek");
return;
@@ -1136,7 +2332,7 @@ function attachKeydownListeners(doc) {
var docs = [doc];
try {
if (inIframe() && window.top.document !== doc) docs.push(window.top.document);
} catch (e) {}
} catch (e) { }
docs.forEach(function (keyDoc) {
if (keyDoc.vscKeydownListenerAttached) return;
@@ -1171,10 +2367,11 @@ function attachKeydownListeners(doc) {
if (item) {
runAction(item.action, item.value, event);
if (item.force === "true") {
event.preventDefault();
event.stopPropagation();
}
// Always prevent default and stop propagation for Speeder shortcuts
// to prevent the website (e.g. YouTube) from reacting to these keys.
event.preventDefault();
event.stopPropagation();
}
},
true
@@ -1201,9 +2398,12 @@ function attachMutationObserver(root) {
mutationsToProcess.forEach(function (mutation) {
if (mutation.type === "childList") {
mutation.addedNodes.forEach(function (node) {
// Skip text nodes, comments, etc. — only elements can contain media
if (node.nodeType !== Node.ELEMENT_NODE) return;
scanNodeForMedia(node, node.parentNode || mutation.target, true);
});
mutation.removedNodes.forEach(function (node) {
if (node.nodeType !== Node.ELEMENT_NODE) return;
scanNodeForMedia(node, node.parentNode || mutation.target, false);
});
return;
@@ -1226,7 +2426,11 @@ function attachMutationObserver(root) {
target.attributes["aria-hidden"] &&
target.attributes["aria-hidden"].value === "false"
) {
scanRootForMedia(root);
scanNodeForMedia(
target,
target.parentNode || root.host || mutation.target,
true
);
}
});
},
@@ -1274,7 +2478,7 @@ function attachIframeListeners(doc) {
if (frame.contentDocument) {
initializeWhenReady(frame.contentDocument, true);
}
} catch (e) {}
} catch (e) { }
});
frame.vscLoadListenerAttached = true;
}
@@ -1283,7 +2487,7 @@ function attachIframeListeners(doc) {
if (frame.contentDocument) {
initializeWhenReady(frame.contentDocument);
}
} catch (e) {}
} catch (e) { }
});
}
@@ -1309,12 +2513,18 @@ function attachNavigationListeners() {
window.addEventListener("popstate", scheduleRescan);
window.addEventListener("hashchange", scheduleRescan);
/* YouTube often navigates without a history API call the extension can see first */
if (typeof document !== "undefined" && isOnYouTube()) {
document.addEventListener("yt-navigate-finish", scheduleRescan);
}
window.vscNavigationListenersAttached = true;
}
function initializeNow(doc, forceReinit = false) {
if ((!forceReinit && vscInitializedDocuments.has(doc)) || !doc.body) return;
if (!tc.settings.enabled) return;
var siteDisabled = applySiteRuleOverrides();
if (!tc.settings.enabled || siteDisabled) return;
if (!doc.body.classList.contains("vsc-initialized")) {
doc.body.classList.add("vsc-initialized");
@@ -1326,14 +2536,21 @@ function initializeNow(doc, forceReinit = false) {
if (forceReinit) {
log("Force re-initialization requested", 4);
refreshAllControllerGeometry();
}
vscInitializedDocuments.add(doc);
}
function setSpeed(video, speed, isInitialCall = false, isUserKeyPress = false) {
function setSpeed(
video,
speed,
isInitialCall = false,
isUserKeyPress = false,
fromResetSpeedToggle = false
) {
const numericSpeed = Number(speed);
if (!isValidSpeed(numericSpeed)) {
log(
`Invalid speed rejected: ${speed}, must be between ${MIN_SPEED} and ${MAX_SPEED}`,
@@ -1341,9 +2558,13 @@ function setSpeed(video, speed, isInitialCall = false, isUserKeyPress = false) {
);
return;
}
if (!video || !video.vsc || !video.vsc.speedIndicator) return;
if (isUserKeyPress && !fromResetSpeedToggle) {
video.vsc.resetToggleArmed = false;
}
log(
`setSpeed: Target ${numericSpeed.toFixed(2)}. Initial: ${isInitialCall}. UserKeyPress: ${isUserKeyPress}`,
4
@@ -1353,11 +2574,15 @@ function setSpeed(video, speed, isInitialCall = false, isUserKeyPress = false) {
// Update the target speed for nudge so it knows what to revert to
video.vsc.targetSpeed = numericSpeed;
video.vsc.targetSpeedSourceKey = getVideoSourceKey(video);
if (isUserKeyPress && !isInitialCall && video.vsc && video.vsc.div) {
runAction("blink", 1000, null, video); // Pass video to blink
extendSpeedRestoreWindow(video); // Protect against immediate site-driven resets
}
// Try YouTube's native speed API first — keeps subtitles in sync without nudge
var usedNativeSpeed = false;
if (tc.settings.forceLastSavedSpeed) {
video.dispatchEvent(
new CustomEvent("ratechange", {
@@ -1371,12 +2596,21 @@ function setSpeed(video, speed, isInitialCall = false, isUserKeyPress = false) {
} else {
if (Math.abs(video.playbackRate - numericSpeed) > 0.001) {
rememberPendingRateChange(video, numericSpeed);
video.playbackRate = numericSpeed;
usedNativeSpeed = tryYouTubeNativeSpeed(video, numericSpeed);
if (!usedNativeSpeed) {
video.playbackRate = numericSpeed;
}
}
}
if (video.vsc) {
if (numericSpeed === 1.0 || video.paused) video.vsc.stopSubtitleNudge();
else video.vsc.startSubtitleNudge();
if (numericSpeed === 1.0 || video.paused) {
video.vsc.stopSubtitleNudge();
} else if (usedNativeSpeed) {
// YouTube's native API handles subtitle sync — no nudge needed
video.vsc.stopSubtitleNudge();
} else {
video.vsc.startSubtitleNudge();
}
}
}
@@ -1384,6 +2618,7 @@ function runAction(action, value, e) {
log("runAction Begin", 5);
var mediaTagsToProcess;
const specificVideo = arguments[3] || null;
var subtitleNudgeToggleValue = null;
if (specificVideo) {
mediaTagsToProcess = [specificVideo];
@@ -1404,8 +2639,18 @@ function runAction(action, value, e) {
} else {
mediaTagsToProcess = tc.mediaElements;
}
if (action === "settings") {
chrome.runtime.sendMessage({ action: "openOptions" });
return;
}
if (mediaTagsToProcess.length === 0 && action !== "display") return;
if (action === "toggleSubtitleNudge" && mediaTagsToProcess.length > 0) {
subtitleNudgeToggleValue = !isSubtitleNudgeEnabledForVideo(
mediaTagsToProcess[0]
);
}
mediaTagsToProcess.forEach(function (v) {
if (!v.vsc) return; // Don't process videos without a controller
var controller = v.vsc.div;
@@ -1416,14 +2661,17 @@ function runAction(action, value, e) {
"slower",
"reset",
"fast",
"move",
"pause",
"muted",
"mark",
"jump",
"drag"
"drag",
"toggleSubtitleNudge",
"display"
];
if (userDrivenActionsThatShowController.includes(action)) {
showController(controller);
if (userDrivenActionsThatShowController.includes(action) && action !== "display") {
showController(controller, 2000, true);
}
if (v.classList.contains("vsc-cancelled")) return;
const numValue = parseFloat(value);
@@ -1439,33 +2687,47 @@ function runAction(action, value, e) {
v.currentTime += numValue;
break;
case "faster":
// Round to the step precision to avoid floating-point issues (e.g., 1.80 + 0.1 = 1.9000000000000001)
var fasterStep = numValue;
var fasterPrecision = Math.round(1 / fasterStep); // e.g., 0.1 -> 10, 0.05 -> 20, 0.25 -> 4
var newFasterSpeed = (v.playbackRate < MIN_SPEED ? MIN_SPEED : v.playbackRate) + fasterStep;
newFasterSpeed = Math.round(newFasterSpeed * fasterPrecision) / fasterPrecision;
// Use grid-snapping: always move to the next multiple of fasterStep
// Add a tiny epsilon (1% of step) to jump clear of the current point
var newFasterSpeed = Math.ceil((v.playbackRate + (fasterStep * 0.01)) / fasterStep) * fasterStep;
// Clean up JS floating point math (e.g. 0.30000000000000004 -> 0.30)
newFasterSpeed = Math.round(newFasterSpeed * 1000) / 1000;
setSpeed(v, Math.min(newFasterSpeed, MAX_SPEED), false, true);
break;
case "slower":
var slowerStep = numValue;
var slowerPrecision = Math.round(1 / slowerStep);
var newSlowerSpeed = v.playbackRate - slowerStep;
newSlowerSpeed = Math.round(newSlowerSpeed * slowerPrecision) / slowerPrecision;
// Use grid-snapping: always move to the previous multiple of slowerStep
// Subtract a tiny epsilon (1% of step) to jump clear of the current point
var newSlowerSpeed = Math.floor((v.playbackRate - (slowerStep * 0.01)) / slowerStep) * slowerStep;
// Clean up JS floating point math
newSlowerSpeed = Math.round(newSlowerSpeed * 1000) / 1000;
setSpeed(v, Math.max(newSlowerSpeed, MIN_SPEED), false, true);
break;
case "reset":
resetSpeed(v, 1.0, false); // Use enhanced resetSpeed
break;
case "fast":
resetSpeed(v, numValue, true); // Use enhanced resetSpeed
var preferredSpeed = numValue;
// Apply site-specific preferred speed override if available
if (tc.activeSiteRule && typeof tc.activeSiteRule.preferredSpeed === "number") {
preferredSpeed = tc.activeSiteRule.preferredSpeed;
}
resetSpeed(v, preferredSpeed, true);
break;
case "display":
if (controller.classList.contains("vsc-hidden")) {
controller.classList.remove("vsc-hidden");
controller.classList.add("vsc-manual");
showController(controller, 2000, true);
} else {
controller.classList.add("vsc-hidden");
controller.classList.remove("vsc-manual");
// Clear any show state when explicitly hiding
controller.classList.remove("vsc-show");
controller.classList.remove("vsc-forced-show");
if (controller.showTimeOut) {
clearTimeout(controller.showTimeOut);
controller.showTimeOut = undefined;
}
}
break;
case "blink":
@@ -1502,6 +2764,9 @@ function runAction(action, value, e) {
case "drag":
if (e) handleDrag(v, e);
break;
case "move":
cycleControllerLocation(v);
break;
case "pause":
pause(v);
break;
@@ -1514,6 +2779,9 @@ function runAction(action, value, e) {
case "jump":
jumpToMark(v);
break;
case "toggleSubtitleNudge":
setSubtitleNudgeEnabledForVideo(v, subtitleNudgeToggleValue);
break;
}
});
log("runAction End", 5);
@@ -1552,11 +2820,12 @@ function resetSpeed(v, target, isFastKey = false) {
Math.abs(lastToggle - 1.0) < 0.01
? getKeyBindings("fast") || 1.8
: lastToggle;
setSpeed(v, speedToRestore, false, true);
setSpeed(v, speedToRestore, false, true, true);
} else {
// Not at 1.0, save current as toggle speed and go to 1.0
lastToggleSpeed[videoId] = currentSpeed;
setSpeed(v, resetSpeedValue, false, true);
v.vsc.resetToggleArmed = true;
setSpeed(v, resetSpeedValue, false, true, true);
}
}
}
@@ -1575,7 +2844,8 @@ function jumpToMark(v) {
}
function handleDrag(video, e) {
const c = video.vsc.div;
const sC = c.shadowRoot.querySelector("#controller");
const sC = convertControllerToManualPosition(video.vsc);
if (!sC) return;
var pE = c.parentElement;
while (
pE.parentNode &&
@@ -1588,9 +2858,16 @@ function handleDrag(video, e) {
const iXY = [e.clientX, e.clientY],
iCXY = [parseInt(sC.style.left), parseInt(sC.style.top)];
const sD = (e) => {
let s = sC.style;
s.left = iCXY[0] + e.clientX - iXY[0] + "px";
s.top = iCXY[1] + e.clientY - iXY[1] + "px";
sC.style.setProperty(
"left",
iCXY[0] + e.clientX - iXY[0] + "px",
"important"
);
sC.style.setProperty(
"top",
iCXY[1] + e.clientY - iXY[1] + "px",
"important"
);
};
const eD = () => {
pE.removeEventListener("mousemove", sD);
@@ -1603,7 +2880,7 @@ function handleDrag(video, e) {
pE.addEventListener("mouseleave", eD);
pE.addEventListener("mousemove", sD);
}
function showController(controller, duration = 2000) {
function showController(controller, duration = 2000, forced = false) {
if (!controller || typeof controller.classList === "undefined") return;
var restoreHidden =
controller.restoreHiddenAfterShow === true ||
@@ -1612,6 +2889,9 @@ function showController(controller, duration = 2000) {
controller.restoreHiddenAfterShow = restoreHidden;
controller.classList.remove("vsc-hidden");
controller.classList.add("vsc-show");
if (forced) {
controller.classList.add("vsc-forced-show");
}
if (controller.showTimeOut !== undefined) {
clearTimeout(controller.showTimeOut);
@@ -1619,6 +2899,7 @@ function showController(controller, duration = 2000) {
controller.showTimeOut = setTimeout(function () {
controller.classList.remove("vsc-show");
controller.classList.remove("vsc-forced-show");
if (controller.restoreHiddenAfterShow === true) {
controller.classList.add("vsc-hidden");
}
@@ -1626,3 +2907,12 @@ function showController(controller, duration = 2000) {
controller.showTimeOut = undefined;
}, duration);
}
// Add global listener to handle fullscreen transitions and adjust controller positions
document.addEventListener("fullscreenchange", () => {
tc.mediaElements.forEach((video) => {
if (video.vsc) {
applyControllerLocation(video.vsc, video.vsc.controllerLocation);
}
});
});
+173
View File
@@ -0,0 +1,173 @@
/**
* Lucide static icons via jsDelivr (same registry as lucide.dev).
* ISC License — https://lucide.dev
*/
var LUCIDE_STATIC_VERSION = "1.7.0";
var LUCIDE_CDN_BASE =
"https://cdn.jsdelivr.net/npm/lucide-static@" +
LUCIDE_STATIC_VERSION;
var LUCIDE_TAGS_CACHE_KEY = "lucideTagsCacheV1";
var LUCIDE_TAGS_MAX_AGE_MS = 1000 * 60 * 60 * 24 * 7; /* 7 days */
function lucideIconSvgUrl(slug) {
if (!slug || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/i.test(slug)) {
return "";
}
return LUCIDE_CDN_BASE + "/icons/" + slug.toLowerCase() + ".svg";
}
function lucideTagsJsonUrl() {
return LUCIDE_CDN_BASE + "/tags.json";
}
/** Collapse whitespace for smaller storage. */
function lucideMinifySvg(s) {
return String(s).replace(/\s+/g, " ").trim();
}
function sanitizeLucideSvg(svgText) {
if (!svgText || typeof svgText !== "string") return null;
var t = String(svgText).replace(/\0/g, "").trim();
if (!/<svg[\s>]/i.test(t)) return null;
var doc = new DOMParser().parseFromString(t, "image/svg+xml");
var svg = doc.querySelector("svg");
if (!svg) return null;
svg.querySelectorAll("script").forEach(function (n) {
n.remove();
});
svg.querySelectorAll("style").forEach(function (n) {
n.remove();
});
svg.querySelectorAll("*").forEach(function (el) {
for (var i = el.attributes.length - 1; i >= 0; i--) {
var attr = el.attributes[i];
var name = attr.name.toLowerCase();
var val = attr.value;
if (name.indexOf("on") === 0) {
el.removeAttribute(attr.name);
continue;
}
if (
(name === "href" || name === "xlink:href") &&
/^javascript:/i.test(val)
) {
el.removeAttribute(attr.name);
}
}
});
svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
svg.removeAttribute("width");
svg.removeAttribute("height");
svg.setAttribute("width", "100%");
svg.setAttribute("height", "100%");
svg.setAttribute("aria-hidden", "true");
return lucideMinifySvg(svg.outerHTML);
}
function fetchLucideSvg(slug) {
var url = lucideIconSvgUrl(slug);
if (!url) {
return Promise.reject(new Error("Invalid icon name"));
}
return fetch(url, { cache: "force-cache" }).then(function (r) {
if (!r.ok) {
throw new Error("Icon not found: " + slug);
}
return r.text();
});
}
function fetchAndCacheLucideTags(chromeLocal, resolve, reject) {
fetch(lucideTagsJsonUrl(), { cache: "force-cache" })
.then(function (r) {
if (!r.ok) throw new Error("tags.json HTTP " + r.status);
return r.json();
})
.then(function (obj) {
var payload = {};
payload[LUCIDE_TAGS_CACHE_KEY] = obj;
payload[LUCIDE_TAGS_CACHE_KEY + "At"] = Date.now();
if (chromeLocal && chromeLocal.set) {
chromeLocal.set(payload, function () {
resolve(obj);
});
} else {
resolve(obj);
}
})
.catch(reject);
}
/** @returns {Promise<Object<string, string[]>>} slug -> tags */
function getLucideTagsMap(chromeLocal, bypassCache) {
return new Promise(function (resolve, reject) {
if (!chromeLocal || !chromeLocal.get) {
fetch(lucideTagsJsonUrl(), { cache: "force-cache" })
.then(function (r) {
return r.json();
})
.then(resolve)
.catch(reject);
return;
}
if (bypassCache) {
fetchAndCacheLucideTags(chromeLocal, resolve, reject);
return;
}
chromeLocal.get(
[LUCIDE_TAGS_CACHE_KEY, LUCIDE_TAGS_CACHE_KEY + "At"],
function (stored) {
if (chrome.runtime.lastError) {
fetchAndCacheLucideTags(chromeLocal, resolve, reject);
return;
}
var data = stored[LUCIDE_TAGS_CACHE_KEY];
var at = stored[LUCIDE_TAGS_CACHE_KEY + "At"];
if (
data &&
typeof data === "object" &&
at &&
Date.now() - at < LUCIDE_TAGS_MAX_AGE_MS
) {
resolve(data);
return;
}
fetchAndCacheLucideTags(chromeLocal, resolve, reject);
}
);
});
}
/**
* @param {Object<string,string[]>} tagsMap
* @param {string} query
* @param {number} limit
* @returns {string[]} slugs
*/
function searchLucideSlugs(tagsMap, query, limit) {
var lim = limit != null ? limit : 60;
var q = String(query || "")
.toLowerCase()
.trim();
if (!tagsMap || !q) return [];
var matches = [];
for (var slug in tagsMap) {
if (!Object.prototype.hasOwnProperty.call(tagsMap, slug)) continue;
var hay =
slug +
" " +
(Array.isArray(tagsMap[slug]) ? tagsMap[slug].join(" ") : "");
if (hay.toLowerCase().indexOf(q) === -1) continue;
matches.push(slug);
}
matches.sort(function (a, b) {
var al = a.toLowerCase();
var bl = b.toLowerCase();
var ap = al.indexOf(q) === 0 ? 0 : 1;
var bp = bl.indexOf(q) === 0 ? 0 : 1;
if (ap !== bp) return ap - bp;
return al.localeCompare(bl);
});
return matches.slice(0, lim);
}
+36 -11
View File
@@ -1,13 +1,18 @@
{
"name": "Video Speed Controller",
"short_name": "videospeed",
"version": "2.1.1",
"name": "Speeder",
"short_name": "Speeder",
"version": "5.1.1",
"manifest_version": 2,
"description": "Speed up, slow down, advance and rewind HTML5 audio/video with shortcuts",
"homepage_url": "https://github.com/SoPat712/videospeed",
"description": "Speed up, slow down, advance and rewind HTML5 audio/video with shortcuts (New and improved version of \"Video Speed Controller\")",
"homepage_url": "https://github.com/SoPat712/speeder",
"browser_specific_settings": {
"gecko": {
"id": "{ed860648-f54f-4dc9-9a0d-501aec4313f5}"
"id": "{ed860648-f54f-4dc9-9a0d-501aec4313f5}",
"data_collection_permissions": {
"required": [
"none"
]
}
}
},
"icons": {
@@ -15,7 +20,15 @@
"48": "icons/icon48.png",
"128": "icons/icon128.png"
},
"permissions": ["storage"],
"background": {
"scripts": [
"background.js"
]
},
"permissions": [
"storage",
"https://cdn.jsdelivr.net/*"
],
"options_ui": {
"page": "options.html",
"open_in_tab": true
@@ -31,16 +44,28 @@
"content_scripts": [
{
"all_frames": true,
"matches": ["http://*/*", "https://*/*", "file:///*"],
"matches": [
"http://*/*",
"https://*/*",
"file:///*"
],
"match_about_blank": true,
"exclude_matches": [
"https://plus.google.com/hangouts/*",
"https://hangouts.google.com/*",
"https://meet.google.com/*"
],
"css": ["inject.css"],
"js": ["inject.js"]
"css": [
"inject.css"
],
"js": [
"ui-icons.js",
"inject.js"
]
}
],
"web_accessible_resources": ["inject.css", "shadow.css"]
"web_accessible_resources": [
"inject.css",
"shadow.css"
]
}
+958 -136
View File
@@ -1,195 +1,1017 @@
:root {
--bg: #f4f5f7;
--panel: #ffffff;
--panel-subtle: #fafbfc;
--border: #e2e5e9;
--border-strong: #d4d9e0;
--text: #17191c;
--muted: #626b76;
--accent: #111827;
--danger: #b42318;
}
* {
box-sizing: border-box;
}
html {
/* Avoid coupling to the browser viewport: embedded options (e.g. Add-ons
* Manager iframe) must size to content, not 100vh, or a large empty band
* appears below the page. */
height: auto;
min-height: 0;
}
body {
margin: 0;
padding-left: 15px;
padding-top: 53px;
font-family: sans-serif;
font-size: 12px;
color: rgb(48, 57, 66);
background-color: white;
min-height: 0;
padding: 24px 16px 40px;
background: var(--bg);
color: var(--text);
font: 14px/1.45 "Avenir Next", "SF Pro Text", "Segoe UI", sans-serif;
}
.page-shell {
width: min(880px, 100%);
margin: 0 auto;
}
.page-header {
margin-bottom: 10px;
}
.title-row {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.title-block {
max-width: 560px;
}
h1,
h2,
h3 {
font-weight: normal;
line-height: 1;
user-select: none;
cursor: default;
}
h1 {
font-size: 1.5em;
margin: 21px 0 13px;
}
.version {
margin: 0 0 12px;
color: #6b6b6b;
font-size: 0.95em;
}
h3 {
font-size: 1.2em;
margin-bottom: 0.8em;
color: black;
}
p {
margin: 0.65em 0;
h3,
h4 {
margin: 0;
font-family: "Avenir Next", "SF Pro Display", "Segoe UI", sans-serif;
font-weight: 600;
letter-spacing: -0.01em;
}
header {
position: fixed;
top: 0;
left: 15px;
right: 0;
border-bottom: 1px solid #eee;
background: linear-gradient(white, white 40%, rgba(255, 255, 255, 0.92));
h1 {
font-size: 28px;
line-height: 1.1;
}
header,
section {
min-width: 600px;
max-width: 738px;
h3 {
font-size: 16px;
line-height: 1.25;
}
section {
padding-left: 18px;
margin-top: 8px;
margin-bottom: 24px;
h4 {
font-size: 15px;
line-height: 1.3;
}
section h3 {
margin-left: -18px;
.page-subtitle,
.section-intro {
margin: 6px 0 0;
color: var(--muted);
font-size: 13px;
}
.version {
display: inline-flex;
align-items: center;
min-height: 26px;
padding: 0 9px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--panel);
color: var(--muted);
font-size: 12px;
font-weight: 600;
}
.settings-stack {
display: grid;
gap: 10px;
}
.settings-card {
padding: 18px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel);
}
.control-bars-group {
padding: 20px;
}
.control-bars-inner {
display: grid;
gap: 10px;
}
.settings-card-nested {
background: var(--panel-subtle);
border-radius: 10px;
}
.section-heading-major {
margin-bottom: 14px;
}
.section-heading-major h2 {
margin: 0 0 6px;
font-size: 18px;
font-weight: 650;
letter-spacing: -0.02em;
}
.section-heading-major .section-intro {
margin-top: 0;
}
.section-heading {
margin-bottom: 10px;
}
.defaults-divider {
height: 1px;
background: var(--border);
margin: 14px 0 10px;
}
.defaults-sub-heading {
font-size: 13px;
font-weight: 600;
color: var(--muted);
margin-bottom: 8px;
}
p {
margin: 0.75em 0;
}
a,
a:visited {
color: var(--text);
text-decoration-color: #c6ccd5;
text-underline-offset: 0.14em;
}
a:hover,
a:focus {
color: #000;
}
code {
padding: 0.08em 0.38em;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--panel-subtle);
font-family: "SFMono-Regular", Menlo, Consolas, monospace;
font-size: 0.92em;
}
button,
input,
select,
textarea {
font: inherit;
}
button {
-webkit-appearance: none;
position: relative;
margin: 0 1px 0 0;
padding: 0 10px;
min-width: 4em;
min-height: 2em;
background-image: linear-gradient(#ededed, #ededed 38%, #dedede);
border: 1px solid rgba(0, 0, 0, 0.25);
border-radius: 2px;
outline: none;
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.08),
inset 0 1px 2px rgba(255, 255, 255, 0.75);
color: #444;
text-shadow: 0 1px 0 rgb(240, 240, 240);
font: inherit;
user-select: none;
appearance: none;
min-height: 36px;
padding: 0 14px;
border: 1px solid var(--border-strong);
border-radius: 10px;
background: var(--panel);
color: var(--text);
font-weight: 500;
cursor: pointer;
transition: background-color 120ms ease, border-color 120ms ease;
}
input[type="text"] {
width: 75px;
text-align: center;
button:hover {
background: #f8f9fb;
border-color: #c5ccd5;
}
.row {
margin: 5px 0px;
button:active {
background: #f1f3f5;
}
button:focus-visible,
input[type="text"]:focus,
select:focus,
textarea:focus {
outline: 2px solid rgba(17, 24, 39, 0.14);
outline-offset: 2px;
}
#save {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
#save:hover {
background: #1f2937;
border-color: #1f2937;
}
input[type="text"],
select,
textarea {
width: 100%;
min-height: 36px;
padding: 8px 10px;
border: 1px solid var(--border-strong);
border-radius: 10px;
background: var(--panel);
color: var(--text);
}
input[type="text"]:focus,
select:focus,
textarea:focus {
border-color: #9ca3af;
}
input[type="checkbox"] {
width: 16px;
height: 16px;
margin: 2px 0 0;
accent-color: var(--accent);
}
label {
display: inline-block;
width: 170px;
vertical-align: top;
display: block;
}
label em {
display: block;
margin-top: 4px;
color: var(--muted);
font-style: normal;
}
.shortcuts-grid {
display: flex;
flex-direction: column;
}
.shortcut-row {
display: grid;
grid-template-columns: minmax(0, 1fr) 120px 120px;
gap: 12px;
align-items: center;
padding: 10px 0;
border-top: 1px solid var(--border);
}
.shortcuts-grid .shortcut-row:first-child {
padding-top: 0;
border-top: 0;
}
.shortcut-row.customs {
grid-template-columns: minmax(0, 1fr) 120px 120px 38px;
}
.shortcut-label {
color: var(--text);
font-weight: 500;
}
.customKey,
.customValue {
text-align: center;
}
#addShortcutSelector {
width: min(220px, 100%);
margin-top: 12px;
}
.removeParent,
.toggle-site-rule {
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
min-width: 36px;
height: 36px;
padding: 0;
font-size: 18px;
line-height: 1;
}
.removeParent {
color: var(--danger);
font-weight: 500;
}
.toggle-site-rule {
font-weight: 400;
}
.row {
display: grid;
grid-template-columns: minmax(0, 1fr) 160px;
gap: 16px;
align-items: start;
padding: 10px 0;
border-top: 1px solid var(--border);
}
.row input[type="text"],
.row select {
justify-self: end;
}
.row.row-checkbox {
grid-template-columns: minmax(0, 1fr) 24px;
}
.row.row-checkbox input[type="checkbox"] {
justify-self: end;
}
.settings-card .row:first-of-type {
padding-top: 0;
border-top: 0;
}
.row.row-controller-margin {
grid-template-columns: minmax(0, 1fr) minmax(0, 260px);
}
.controller-margin-inputs {
display: grid;
grid-template-columns: repeat(2, minmax(0, 116px));
gap: 8px;
width: max-content;
justify-self: end;
}
.margin-pad-cell {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 116px;
}
.margin-pad-mini {
font-size: 10px;
font-weight: 600;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.controller-margin-inputs input[type="text"] {
width: 100%;
min-width: 116px;
box-sizing: border-box;
text-align: right;
}
.site-rule-option.site-rule-margin-option {
grid-template-columns: minmax(0, 1fr) minmax(0, 260px);
}
.site-rule-override-section {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.site-rule-content > .site-rule-override-section:first-of-type {
margin-top: 0;
padding-top: 0;
border-top: 0;
}
.site-override-lead {
display: grid;
grid-template-columns: minmax(0, 1fr) 24px;
gap: 16px;
align-items: flex-start;
font-weight: 600;
margin-bottom: 8px;
cursor: pointer;
width: 100%;
}
.site-override-lead input[type="checkbox"] {
justify-self: end;
margin-top: 3px;
}
.site-override-lead span {
margin: 0;
}
.site-rule-override-section .site-override-fields,
.site-rule-override-section .site-placement-container,
.site-rule-override-section .site-visibility-container,
.site-rule-override-section .site-autohide-container,
.site-rule-override-section .site-playback-container,
.site-rule-override-section .site-opacity-container,
.site-rule-override-section .site-subtitleNudge-container {
padding-left: 4px;
}
.cb-editor {
display: flex;
flex-direction: column;
gap: 16px;
}
.cb-editor-disabled {
opacity: 0.4;
pointer-events: none;
user-select: none;
}
.cb-zone-label {
font-size: 11px;
font-weight: 600;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 8px;
}
.cb-dropzone {
display: flex;
flex-wrap: wrap;
gap: 8px;
min-height: 52px;
padding: 10px;
border: 2px dashed var(--border);
border-radius: 10px;
background: var(--panel-subtle);
transition: border-color 150ms ease, background 150ms ease;
}
.cb-dropzone.cb-over {
border-color: var(--accent);
background: rgba(17, 24, 39, 0.03);
}
.cb-active-zone:empty::after {
content: "Drag buttons here";
display: flex;
align-items: center;
width: 100%;
justify-content: center;
color: var(--muted);
font-size: 13px;
font-style: italic;
}
.cb-available-zone:empty::after {
content: "All buttons active";
display: flex;
align-items: center;
width: 100%;
justify-content: center;
color: var(--muted);
font-size: 13px;
font-style: italic;
}
.cb-block {
display: flex;
align-items: center;
gap: 8px;
padding: 7px 12px 7px 8px;
border: 1px solid var(--border-strong);
border-radius: 8px;
background: var(--panel);
cursor: grab;
user-select: none;
transition: box-shadow 150ms ease, opacity 150ms ease;
}
.cb-block:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}
.cb-block:active {
cursor: grabbing;
}
.cb-block.cb-dragging {
opacity: 0.35;
}
.cb-grip {
width: 6px;
min-width: 6px;
height: 14px;
background-image: radial-gradient(circle, currentColor 1px, transparent 1px);
background-size: 3px 3px;
opacity: 0.35;
}
.cb-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 22px;
height: 22px;
border-radius: 4px;
background: var(--panel-subtle);
border: 1px solid var(--border);
font-size: 12px;
line-height: 1;
color: var(--text);
}
.cb-icon svg {
width: 16px;
height: 16px;
flex-shrink: 0;
}
.row-lucide-pair select {
justify-self: end;
}
.row-lucide-search-row {
grid-template-columns: minmax(0, 1fr);
gap: 8px;
padding: 12px 0;
}
.row-lucide-search-row .lucide-search-label {
font-weight: 600;
font-size: 13px;
color: var(--text);
}
.lucide-search-field {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
max-width: 100%;
min-height: 44px;
padding: 0 14px 0 12px;
border: 1px solid var(--border-strong);
border-radius: 12px;
background: var(--panel);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
transition: border-color 150ms ease, box-shadow 150ms ease;
}
.lucide-search-field:focus-within {
border-color: #9ca3af;
box-shadow: 0 0 0 3px rgba(17, 24, 39, 0.08);
}
.lucide-search-icon {
display: flex;
color: var(--muted);
flex-shrink: 0;
}
.lucide-search-input {
flex: 1;
min-width: 0;
min-height: 40px;
padding: 8px 0;
border: 0 !important;
border-radius: 0 !important;
background: transparent !important;
box-shadow: none !important;
font-size: 14px;
}
.lucide-search-input::placeholder {
color: var(--muted);
opacity: 0.85;
}
.lucide-search-input:focus {
outline: none;
}
.lucide-icon-results {
display: flex;
flex-wrap: wrap;
gap: 8px;
max-height: 220px;
overflow-y: auto;
padding: 12px 0;
border-top: 1px solid var(--border);
border-bottom: 1px solid var(--border);
}
button.lucide-result-tile {
width: 44px;
height: 44px;
min-height: 44px;
padding: 0;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 10px;
background: var(--panel-subtle);
border: 1px solid var(--border-strong);
cursor: pointer;
}
button.lucide-result-tile:hover {
background: var(--panel);
border-color: #9ca3af;
}
button.lucide-result-tile .lucide-result-thumb {
width: 22px;
height: 22px;
object-fit: contain;
pointer-events: none;
}
button.lucide-result-tile.lucide-picked {
border-color: var(--accent);
box-shadow: 0 0 0 2px rgba(17, 24, 39, 0.12);
background: var(--panel);
}
.lucide-icon-status {
margin: 8px 0 0;
font-size: 12px;
color: var(--muted);
min-height: 1.2em;
}
.lucide-icon-preview-row {
display: grid;
grid-template-columns: 72px 1fr;
gap: 16px;
align-items: start;
margin-top: 14px;
}
.lucide-icon-preview {
width: 56px;
height: 56px;
display: flex;
align-items: center;
justify-content: center;
border: 1px solid var(--border-strong);
border-radius: 10px;
background: var(--panel-subtle);
color: var(--text);
}
.lucide-icon-preview svg {
width: 36px;
height: 36px;
}
.lucide-icon-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.lucide-icon-actions .lucide-apply {
background: #ffffff !important;
color: #111827 !important;
border: 1px solid var(--border-strong) !important;
font-weight: 600;
}
.lucide-icon-actions .lucide-apply:hover {
background: #f3f4f6 !important;
border-color: #9ca3af !important;
}
.lucide-icon-actions .secondary {
background: var(--panel-subtle);
color: var(--text);
border-color: var(--border-strong);
}
.cb-label {
font-size: 13px;
font-weight: 500;
white-space: nowrap;
}
#siteRulesContainer {
display: grid;
gap: 12px;
margin-bottom: 12px;
}
.site-rule {
padding: 12px;
border: 1px solid var(--border);
border-radius: 12px;
background: var(--panel-subtle);
}
.site-rule-header {
display: grid;
grid-template-columns: 36px minmax(0, 1fr) auto;
gap: 10px;
align-items: center;
}
.site-pattern {
min-width: 0;
font-family: "SFMono-Regular", Menlo, Consolas, monospace;
}
.site-rule-body {
margin-top: 12px;
}
.site-rule-content.disabled-rule {
opacity: 0.55;
pointer-events: none;
}
.site-rule-option {
display: grid;
grid-template-columns: minmax(0, 1fr) 160px;
gap: 16px;
align-items: start;
padding: 8px 0;
border-top: 1px solid var(--border);
}
.site-rule-option-checkbox {
grid-template-columns: minmax(0, 1fr) 24px;
}
.site-rule-option-checkbox > input[type="checkbox"] {
justify-self: end;
}
.site-rule-option > input[type="text"],
.site-rule-option > select {
justify-self: end;
text-align: right;
}
.site-rule-option.site-rule-margin-option .controller-margin-inputs {
justify-self: end;
}
.site-rule-body > .site-rule-option:first-child,
.site-rule-content > .site-rule-option:first-child {
padding-top: 0;
border-top: 0;
}
.site-rule-option > label:not(.site-rule-split-label) {
display: block;
margin: 0;
}
.site-rule-split-label {
display: grid;
grid-template-columns: minmax(0, 1fr) 24px;
gap: 16px;
align-items: flex-start;
width: 100%;
margin: 0;
cursor: pointer;
font-weight: 500;
color: var(--text);
}
.site-rule-split-label input[type="checkbox"] {
justify-self: end;
margin-top: 3px;
}
.site-rule-option-checkbox > .site-rule-split-label {
grid-column: 1 / -1;
}
.site-rule-controlbar,
.site-rule-shortcuts {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.site-rule-controlbar > label.site-override-lead,
.site-rule-shortcuts > label.site-override-lead {
margin: 0;
}
.site-controlbar-container,
.site-popup-controlbar-container {
margin-top: 12px;
}
.site-shortcuts-container {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 12px;
}
.site-shortcuts-container .shortcut-row {
grid-template-columns: minmax(0, 1fr) 110px 110px minmax(0, 1fr);
padding: 8px 0;
border-top: 1px solid var(--border);
}
.site-shortcuts-container .shortcut-row:first-child {
padding-top: 0;
border-top: 0;
}
.force-label {
display: flex;
align-items: flex-start;
gap: 8px;
width: auto;
margin: 0;
color: var(--muted);
font-size: 12px;
}
.force-label input {
margin-top: 2px;
}
.action-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
#status {
color: #9d9d9d;
display: inline-block;
margin-left: 50px;
min-height: 1.3em;
margin-top: 10px;
color: var(--muted);
font-weight: 500;
}
#faq {
margin-top: 2em;
}
select {
width: 170px;
}
.customForce {
#status:empty {
display: none;
width: 250px;
}
.customKey {
color: transparent;
text-shadow: 0 0 0 #000000;
.support-footer {
padding: 16px 20px;
color: var(--muted);
}
/* Dark mode styles */
@media (prefers-color-scheme: dark) {
.support-footer p {
margin: 0;
}
.support-footer a {
font-weight: 600;
}
@media (max-width: 720px) {
.lucide-icon-preview-row {
grid-template-columns: 1fr;
}
.shortcut-row,
.shortcut-row.customs,
.row,
.row.row-checkbox,
.site-rule-option,
.site-shortcuts-container .shortcut-row {
grid-template-columns: 1fr;
}
.row input[type="text"],
.row select {
justify-self: stretch;
}
.site-rule-option > input[type="text"],
.site-rule-option > select {
justify-self: stretch;
}
.site-override-lead {
grid-template-columns: minmax(0, 1fr) 24px;
}
.action-row button,
#addShortcutSelector {
width: 100%;
}
.site-rule-header {
grid-template-columns: 36px minmax(0, 1fr);
}
.remove-site-rule {
grid-column: 1 / -1;
}
}
@media (max-width: 520px) {
body {
background-color: #1a1a1a;
color: #e0e0e0;
padding: 16px 12px 28px;
}
h3 {
color: #ffffff;
h1 {
font-size: 24px;
}
.version {
color: #a8a8a8;
.settings-card {
padding: 16px;
}
header {
border-bottom: 1px solid #333;
background: linear-gradient(#1a1a1a, #1a1a1a 40%, rgba(26, 26, 26, 0.92));
.control-bars-group {
padding: 16px;
}
button {
background-image: linear-gradient(#404040, #404040 38%, #353535);
border: 1px solid rgba(255, 255, 255, 0.25);
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.08),
inset 0 1px 2px rgba(0, 0, 0, 0.75);
color: #e0e0e0;
text-shadow: 0 1px 0 rgb(20, 20, 20);
.site-rule-header {
grid-template-columns: 1fr;
}
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #111315;
--panel: #171a1d;
--panel-subtle: #1b1f23;
--border: #2b3138;
--border-strong: #3a414a;
--text: #f2f4f6;
--muted: #a0a8b2;
--accent: #f2f4f6;
--danger: #ff8a80;
}
button:hover {
background-image: linear-gradient(#4a4a4a, #4a4a4a 38%, #3f3f3f);
body {
color-scheme: dark;
}
input[type="text"],
input[type="checkbox"],
select,
textarea {
background-color: #2a2a2a;
color: #e0e0e0;
border: 1px solid #555;
a,
a:visited {
color: #f2f4f6;
text-decoration-color: #4b5563;
}
#save {
background: #f2f4f6;
border-color: #f2f4f6;
color: #111315;
}
#save:hover {
background: #dfe3e8;
border-color: #dfe3e8;
}
.cb-dropzone.cb-over {
background: rgba(255, 255, 255, 0.04);
}
input[type="text"]:focus,
select:focus,
textarea:focus {
background-color: #333;
border-color: #777;
outline: none;
border-color: #6b7280;
}
select option {
background-color: #2a2a2a;
color: #e0e0e0;
.lucide-search-field:focus-within {
border-color: #6b7280;
box-shadow: 0 0 0 3px rgba(242, 244, 246, 0.12);
}
.customKey {
color: transparent;
text-shadow: 0 0 0 #e0e0e0;
.lucide-icon-actions .lucide-apply {
background: #ffffff !important;
color: #111315 !important;
border-color: #e5e7eb !important;
}
#status {
color: #888;
.lucide-icon-actions .lucide-apply:hover {
background: #f3f4f6 !important;
border-color: #d1d5db !important;
}
a {
color: #66b3ff;
}
a:visited {
color: #cc99ff;
}
hr {
border-color: #333;
button.lucide-result-tile .lucide-result-thumb {
filter: brightness(0) invert(1);
opacity: 0.92;
}
}
+693 -226
View File
@@ -1,245 +1,712 @@
<!doctype html>
<html>
<head>
<title>Video Speed Controller: Options</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Speeder Settings</title>
<link rel="stylesheet" href="options.css" />
<script src="ui-icons.js"></script>
<script src="lucide-client.js"></script>
<script src="options.js"></script>
<script src="importExport.js"></script>
</head>
<body>
<header>
<h1>Video Speed Controller</h1>
<div class="version">Version <span id="app-version"></span></div>
</header>
<div class="page-shell">
<header class="page-header">
<div class="title-row">
<div class="title-block">
<h1>Speeder settings</h1>
<p class="page-subtitle">Shortcuts, defaults, and site rules.</p>
</div>
<div class="version">v<span id="app-version"></span></div>
</div>
</header>
<section id="customs">
<h3>Shortcuts</h3>
<div class="row customs" id="display">
<select class="customDo">
<option value="display">Show/hide controller</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (0.10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="slower">
<select class="customDo">
<option value="slower">Decrease speed</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (0.10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="faster">
<select class="customDo">
<option value="faster">Increase speed</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (0.10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="rewind">
<select class="customDo">
<option value="rewind">Rewind</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="advance">
<select class="customDo">
<option value="advance">Advance</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (10)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="reset">
<select class="customDo">
<option value="reset">Reset speed</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (1.00)"
disabled
/>
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<div class="row customs" id="fast">
<select class="customDo">
<option value="fast">Preferred speed</option>
</select>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input class="customValue" type="text" placeholder="value (1.80)" />
<select class="customForce">
<option value="false">Do not disable website key bindings</option>
<option value="true">Disable website key bindings</option>
</select>
</div>
<main class="settings-stack">
<section id="customs" class="settings-card">
<div class="section-heading">
<h3>Shortcuts</h3>
<p class="section-intro">Backspace clears a shortcut. Escape disables it.</p>
</div>
<div class="shortcuts-grid">
<div class="shortcut-row" id="display" data-action="display">
<div class="shortcut-label">Show/hide controller</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value"
value="N/A"
disabled
/>
</div>
<div class="shortcut-row" id="move" data-action="move">
<div class="shortcut-label">Move controller</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value"
value="N/A"
disabled
/>
</div>
<div class="shortcut-row" id="slower" data-action="slower">
<div class="shortcut-label">Decrease speed</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (0.10)"
/>
</div>
<div class="shortcut-row" id="faster" data-action="faster">
<div class="shortcut-label">Increase speed</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (0.10)"
/>
</div>
<div class="shortcut-row" id="rewind" data-action="rewind">
<div class="shortcut-label">Rewind</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (10)"
/>
</div>
<div class="shortcut-row" id="advance" data-action="advance">
<div class="shortcut-label">Advance</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (10)"
/>
</div>
<div class="shortcut-row" id="reset" data-action="reset">
<div class="shortcut-label">Reset speed</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value"
value="N/A"
disabled
/>
</div>
<div class="shortcut-row" id="fast" data-action="fast">
<div class="shortcut-label">Preferred speed</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value (1.80)"
/>
</div>
<div
class="shortcut-row"
id="toggleSubtitleNudge"
data-action="toggleSubtitleNudge"
>
<div class="shortcut-label">Toggle subtitle nudge</div>
<input
class="customKey"
type="text"
value=""
placeholder="press a key"
/>
<input
class="customValue"
type="text"
placeholder="value"
value="N/A"
disabled
/>
</div>
</div>
<button id="add">Add New</button>
</section>
<select id="addShortcutSelector">
<option value="">Add shortcut&hellip;</option>
</select>
</section>
<section>
<h3>Other</h3>
<div class="row">
<label for="enabled">Enable</label>
<input id="enabled" type="checkbox" />
</div>
<div class="row">
<label for="startHidden">Hide controller by default</label>
<input id="startHidden" type="checkbox" />
</div>
<div class="row">
<label for="rememberSpeed">Remember playback speed</label>
<input id="rememberSpeed" type="checkbox" />
</div>
<div class="row">
<label for="forceLastSavedSpeed"
>Force last saved speed<br />
<em
>Useful for video players that override the speeds set by
VideoSpeed</em
></label
<section id="generalSettings" class="settings-card">
<div class="section-heading">
<h3>Defaults</h3>
<p class="section-intro">Used unless a site rule overrides it.</p>
</div>
<h4 class="defaults-sub-heading">General</h4>
<div class="row row-checkbox">
<label for="enabled">Enable</label>
<input id="enabled" type="checkbox" />
</div>
<div class="row row-checkbox">
<label for="audioBoolean">Work on audio</label>
<input id="audioBoolean" type="checkbox" />
</div>
<div class="defaults-divider"></div>
<h4 class="defaults-sub-heading">Playback</h4>
<div class="row row-checkbox">
<label for="rememberSpeed">Remember playback speed</label>
<input id="rememberSpeed" type="checkbox" />
</div>
<div class="row row-checkbox">
<label for="forceLastSavedSpeed"
>Force last saved speed<br />
<em
>Useful when a video player tries to override the speed you set
in Speeder.</em
>
</label>
<input id="forceLastSavedSpeed" type="checkbox" />
</div>
<div class="defaults-divider"></div>
<h4 class="defaults-sub-heading">Controller</h4>
<div class="row row-checkbox">
<label for="startHidden">Hide controller by default</label>
<input id="startHidden" type="checkbox" />
</div>
<div class="row">
<label for="controllerLocation">Default controller location</label>
<select id="controllerLocation">
<option value="top-left">Top left</option>
<option value="top-center">Top center</option>
<option value="top-right">Top right</option>
<option value="middle-right">Middle right</option>
<option value="bottom-right">Bottom right</option>
<option value="bottom-center">Bottom center</option>
<option value="bottom-left">Bottom left</option>
<option value="middle-left">Middle left</option>
</select>
</div>
<div class="row">
<label for="controllerOpacity">Controller opacity</label>
<input id="controllerOpacity" type="text" value="" />
</div>
<div class="row row-controller-margin">
<label for="controllerMarginTop"
>Controller margin (px)<br />
<em
>Shifts the whole control from its preset position (CSS
margins). Top and bottom. 0&ndash;200.</em
>
</label>
<div class="controller-margin-inputs" aria-label="Controller margin in pixels">
<div class="margin-pad-cell">
<span class="margin-pad-mini">Top</span>
<input id="controllerMarginTop" type="text" inputmode="numeric" placeholder="0" />
</div>
<div class="margin-pad-cell">
<span class="margin-pad-mini">Bottom</span>
<input id="controllerMarginBottom" type="text" inputmode="numeric" placeholder="0" />
</div>
</div>
</div>
<div class="row row-checkbox">
<label for="hideWithControls"
>Hide with controls<br />
<em
>Fade the controller in and out with the video interface:
perfect sync on YouTube, idle-based elsewhere.</em
>
</label>
<input id="hideWithControls" type="checkbox" />
</div>
<div class="row">
<label for="hideWithControlsTimer"
>Auto-hide timer (seconds)<br />
<em
>Seconds of inactivity before hiding: 0.1&ndash;15 for
non-YouTube sites.</em
>
</label>
<input id="hideWithControlsTimer" type="text" placeholder="2" />
</div>
<div class="row row-checkbox">
<label for="showPopupControlBar">Show popup control bar</label>
<input id="showPopupControlBar" type="checkbox" />
</div>
<div class="defaults-divider"></div>
<h4 class="defaults-sub-heading">Subtitle sync</h4>
<div class="row row-checkbox">
<label for="enableSubtitleNudge"
>Enable subtitle nudge<br /><em
>Makes tiny playback changes to help keep subtitles aligned.</em
>
</label>
<input id="enableSubtitleNudge" type="checkbox" />
</div>
<div class="row">
<label for="subtitleNudgeInterval"
>Nudge interval (milliseconds)<br /><em
>How often to nudge: 10&ndash;1000. Smaller values are more
frequent. Default: 50.</em
>
</label>
<input
id="subtitleNudgeInterval"
type="text"
value=""
placeholder="50"
/>
</div>
</section>
<section
id="controlBarsGroup"
class="settings-card control-bars-group"
aria-labelledby="controlBarsGroupHeading"
>
<input id="forceLastSavedSpeed" type="checkbox" />
</div>
<div class="row">
<label for="audioBoolean">Work on audio</label>
<input id="audioBoolean" type="checkbox" />
</div>
<div class="row">
<label for="controllerOpacity">Controller opacity</label>
<input id="controllerOpacity" type="text" value="" />
</div>
<div class="row">
<label for="blacklist"
>Sites on which extension is disabled<br />
(one per line)<br />
<br />
<em>
<a href="https://www.regexpal.com/">Regex</a> is supported.<br />
Be sure it is in "//g" format.<br />
ie: /(.+)youtube\.com(\/*)$/gi
</em>
</label>
<textarea id="blacklist" rows="10" cols="50"></textarea>
</div>
</section>
<div class="section-heading section-heading-major">
<h2 id="controlBarsGroupHeading">Control bars</h2>
<p class="section-intro">
In-page hover bar, extension popup bar, and Lucide icons for
buttons.
</p>
</div>
<div class="control-bars-inner">
<section id="controlBarSettings" class="settings-card settings-card-nested">
<div class="section-heading">
<h3>Hover control bar</h3>
<p class="section-intro">
Drag blocks to reorder. Move between Active and Available to
show or hide buttons.
</p>
</div>
<div class="cb-editor">
<div class="cb-zone">
<div class="cb-zone-label">Active</div>
<div
id="controlBarActive"
class="cb-dropzone cb-active-zone"
></div>
</div>
<div class="cb-zone">
<div class="cb-zone-label">Available</div>
<div
id="controlBarAvailable"
class="cb-dropzone cb-available-zone"
></div>
</div>
</div>
</section>
<section id="nudgeSettings">
<h3>Subtitle Nudge Settings (Experimental - YouTube Only)</h3>
<div class="row">
<label for="enableSubtitleNudge"
>Enable Subtitle Nudge <br /><em
>Periodically 'nudges' video speed by a tiny amount to help keep
subtitles in sync on some sites (e.g. YouTube).</em
>
</label>
<input id="enableSubtitleNudge" type="checkbox" />
</div>
<div class="row">
<label for="subtitleNudgeInterval"
>Nudge Interval (milliseconds) <br /><em
>How often to nudge (e.g., 25-1000). Smaller values are more
frequent. Default: 25.</em
>
</label>
<input
id="subtitleNudgeInterval"
type="text"
value=""
placeholder="25"
/>
</div>
<div class="row">
<label for="subtitleNudgeAmount"
>Nudge Amount (decimal) <br /><em
>How much to change speed by (e.g., 0.001). Very small values
recommended. Default: 0.001.</em
>
</label>
<input
id="subtitleNudgeAmount"
type="text"
value=""
placeholder="0.001"
/>
</div>
</section>
<section id="popupControlBarSettings" class="settings-card settings-card-nested">
<div class="section-heading">
<h3>Popup control bar</h3>
<p class="section-intro">
Configure which buttons appear in the browser popup control bar.
</p>
</div>
<div class="row">
<label for="popupMatchHoverControls">Match hover controls</label>
<input id="popupMatchHoverControls" type="checkbox" />
</div>
<div id="popupCbEditorWrap" class="cb-editor cb-editor-disabled">
<div class="cb-zone">
<div class="cb-zone-label">Active</div>
<div
id="popupControlBarActive"
class="cb-dropzone cb-active-zone"
></div>
</div>
<div class="cb-zone">
<div class="cb-zone-label">Available</div>
<div
id="popupControlBarAvailable"
class="cb-dropzone cb-available-zone"
></div>
</div>
</div>
</section>
<button id="save">Save</button>
<button id="restore">Restore Defaults</button>
<button id="experimental">Show Experimental Features</button>
<section id="lucideIconSettings" class="settings-card settings-card-nested">
<div class="section-heading">
<h3>Button icons (Lucide)</h3>
<p class="section-intro">
Search icons from the
<a
href="https://lucide.dev"
target="_blank"
rel="noopener noreferrer"
>Lucide</a
>
set (fetched from jsDelivr). Chosen SVGs are cached in local
storage and included in settings export.
<strong>Reset speed</strong> stays numeric text only.
</p>
</div>
<div class="row row-lucide-pair">
<label for="lucideIconActionSelect">Controller action</label>
<select id="lucideIconActionSelect"></select>
</div>
<div class="row row-lucide-search-row">
<label for="lucideIconSearch" class="lucide-search-label"
>Search icons</label
>
<div class="lucide-search-field">
<span class="lucide-search-icon" aria-hidden="true">
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</svg>
</span>
<input
type="search"
id="lucideIconSearch"
class="lucide-search-input"
placeholder="Search by name or tag (e.g. star, arrow, media)…"
autocomplete="off"
spellcheck="false"
/>
</div>
</div>
<div
id="lucideIconResults"
class="lucide-icon-results"
role="listbox"
aria-label="Matching Lucide icons"
></div>
<p id="lucideIconStatus" class="lucide-icon-status" aria-live="polite"></p>
<div class="lucide-icon-preview-row">
<div
id="lucideIconPreview"
class="lucide-icon-preview"
aria-live="polite"
></div>
<div class="lucide-icon-actions">
<button type="button" id="lucideIconApply" class="lucide-apply">
Apply to action
</button>
<button type="button" id="lucideIconClearAction" class="secondary">
Clear this action
</button>
<button type="button" id="lucideIconClearAll" class="secondary">
Clear all custom icons
</button>
<button type="button" id="lucideIconReloadTags" class="secondary">
Refresh icon list from network
</button>
</div>
</div>
</section>
</div>
</section>
<div id="status"></div>
<section id="siteRules" class="settings-card">
<div class="section-heading">
<h3>Site rules</h3>
<p class="section-intro">
Use plain domains or
<a
href="https://www.regexpal.com/"
target="_blank"
rel="noopener noreferrer"
>Regex</a
>
patterns like <code>/(.+)youtube\.com(\/*)$/gi</code>. Turn on a
row only when you want that group to override the general defaults
above.
</p>
</div>
<div id="siteRulesContainer"></div>
<button id="addSiteRule" type="button">Add Site Rule</button>
</section>
<div id="faq">
<hr />
<template id="siteRuleTemplate">
<div class="site-rule">
<div class="site-rule-header">
<button type="button" class="toggle-site-rule" title="Expand/Collapse">&plus;</button>
<input
type="text"
class="site-pattern"
placeholder="e.g., youtube.com or /regex/gi"
/>
<button type="button" class="remove-site-rule">Remove</button>
</div>
<div class="site-rule-body">
<div class="site-rule-option site-rule-option-checkbox">
<label class="site-rule-split-label">
<span>Enable Speeder on this site</span>
<input type="checkbox" class="site-enabled" />
</label>
</div>
<div class="site-rule-content">
<div class="site-rule-override-section">
<label class="site-override-lead">
<span>Override placement for this site</span>
<input type="checkbox" class="override-placement" />
</label>
<div class="site-placement-container" style="display: none">
<div class="site-rule-option site-rule-option-field">
<label>Default controller location:</label>
<select class="site-controllerLocation">
<option value="top-left">Top left</option>
<option value="top-center">Top center</option>
<option value="top-right">Top right</option>
<option value="middle-right">Middle right</option>
<option value="bottom-right">Bottom right</option>
<option value="bottom-center">Bottom center</option>
<option value="bottom-left">Bottom left</option>
<option value="middle-left">Middle left</option>
</select>
</div>
<div class="site-rule-option site-rule-margin-option">
<label
>Controller margin (px):<br /><em
>Shifts the whole control. 0&ndash;200.</em
></label
>
<div class="controller-margin-inputs">
<div class="margin-pad-cell">
<span class="margin-pad-mini">T</span>
<input type="text" class="site-controllerMarginTop" inputmode="numeric" placeholder="0" />
</div>
<div class="margin-pad-cell">
<span class="margin-pad-mini">B</span>
<input type="text" class="site-controllerMarginBottom" inputmode="numeric" placeholder="0" />
</div>
</div>
</div>
</div>
</div>
<div class="site-rule-override-section">
<label class="site-override-lead">
<span>Override hide-by-default for this site</span>
<input type="checkbox" class="override-visibility" />
</label>
<div class="site-visibility-container" style="display: none">
<div class="site-rule-option site-rule-option-checkbox">
<label>Hide controller by default:</label>
<input type="checkbox" class="site-startHidden" />
</div>
</div>
</div>
<div class="site-rule-override-section">
<label class="site-override-lead">
<span>Override auto-hide for this site</span>
<input type="checkbox" class="override-autohide" />
</label>
<div class="site-autohide-container" style="display: none">
<div class="site-rule-option site-rule-option-checkbox">
<label class="site-rule-split-label">
<span>Hide with controls (idle-based)</span>
<input type="checkbox" class="site-hideWithControls" />
</label>
</div>
<div class="site-rule-option site-rule-option-field">
<label>Auto-hide timer (0.1&ndash;15s):</label>
<input type="text" class="site-hideWithControlsTimer" />
</div>
</div>
</div>
<div class="site-rule-override-section">
<label class="site-override-lead">
<span>Override playback for this site</span>
<input type="checkbox" class="override-playback" />
</label>
<div class="site-playback-container" style="display: none">
<div class="site-rule-option site-rule-option-checkbox">
<label>Remember playback speed:</label>
<input type="checkbox" class="site-rememberSpeed" />
</div>
<div class="site-rule-option site-rule-option-checkbox">
<label>Force last saved speed:</label>
<input type="checkbox" class="site-forceLastSavedSpeed" />
</div>
<div class="site-rule-option site-rule-option-checkbox">
<label>Work on audio:</label>
<input type="checkbox" class="site-audioBoolean" />
</div>
</div>
</div>
<div class="site-rule-override-section">
<label class="site-override-lead">
<span>Override opacity for this site</span>
<input type="checkbox" class="override-opacity" />
</label>
<div class="site-opacity-container" style="display: none">
<div class="site-rule-option site-rule-option-field">
<label>Controller opacity:</label>
<input type="text" class="site-controllerOpacity" />
</div>
</div>
</div>
<div class="site-rule-override-section">
<label class="site-override-lead">
<span>Override subtitle nudge for this site</span>
<input type="checkbox" class="override-subtitleNudge" />
</label>
<div class="site-subtitleNudge-container" style="display: none">
<div class="site-rule-option site-rule-option-checkbox">
<label>Enable subtitle nudge:</label>
<input type="checkbox" class="site-enableSubtitleNudge" />
</div>
<div class="site-rule-option site-rule-option-field">
<label>Nudge interval (10&ndash;1000ms):</label>
<input type="text" class="site-subtitleNudgeInterval" placeholder="50" />
</div>
</div>
</div>
<div class="site-rule-controlbar">
<label class="site-override-lead">
<span>Override in-player control bar for this site</span>
<input type="checkbox" class="override-controlbar" />
</label>
<div class="site-controlbar-container" style="display: none">
<div class="cb-editor">
<div class="cb-zone">
<div class="cb-zone-label">Active</div>
<div class="cb-dropzone cb-active-zone site-cb-active"></div>
</div>
<div class="cb-zone">
<div class="cb-zone-label">Available</div>
<div class="cb-dropzone cb-available-zone site-cb-available"></div>
</div>
</div>
</div>
</div>
<div class="site-rule-controlbar">
<label class="site-override-lead">
<span>Override extension popup for this site</span>
<input type="checkbox" class="override-popup-controlbar" />
</label>
<div class="site-popup-controlbar-container" style="display: none">
<div class="site-rule-option site-rule-option-checkbox">
<label>Show popup control bar</label>
<input type="checkbox" class="site-showPopupControlBar" />
</div>
<div class="cb-editor">
<div class="cb-zone">
<div class="cb-zone-label">Active</div>
<div class="cb-dropzone cb-active-zone site-popup-cb-active"></div>
</div>
<div class="cb-zone">
<div class="cb-zone-label">Available</div>
<div class="cb-dropzone cb-available-zone site-popup-cb-available"></div>
</div>
</div>
</div>
</div>
<div class="site-rule-shortcuts">
<label class="site-override-lead">
<span>Override shortcuts for this site</span>
<input type="checkbox" class="override-shortcuts" />
</label>
<div class="site-shortcuts-container" style="display: none"></div>
</div>
</div>
</div>
</div>
</template>
<h4>Extension controls not appearing?</h4>
<p>
This extension is only compatible with HTML5 audio and video. If you
don't see the controls showing up, chances are you are viewing a Flash
content. If you want to confirm, try right-clicking on the content and
inspect the menu: if it mentions flash, then that's the issue. That
said, <b>most sites will fallback to HTML5</b> if they detect that Flash
is not available. You can try manually disabling Flash from the browser.
</p>
<section class="settings-card action-card">
<div class="section-heading">
<h3>Actions</h3>
<p class="section-intro">Save, restore, export, or import settings.</p>
</div>
<div class="action-row">
<button id="save">Save Changes</button>
<button id="restore">Restore Defaults</button>
<button id="exportSettings">Export Settings</button>
<button id="importSettings">Import Settings</button>
</div>
<div id="status" role="status" aria-live="polite"></div>
</section>
<footer class="support-footer settings-card">
<p>
If Speeder has been useful, consider supporting its development via
<a
href="https://github.com/sponsors/SoPat712"
target="_blank"
rel="noopener noreferrer"
>GitHub Sponsor</a
>
or
<a
href="https://ko-fi.com/joshpatra"
target="_blank"
rel="noopener noreferrer"
>Ko-Fi</a
>.
</p>
</footer>
<section id="faq" class="settings-card info-card">
<h4>Extension controls not appearing?</h4>
<p>
This extension only works with HTML5 audio and video. If the
controls never appear, you may be looking at Flash content instead.
Right-click the player to check: if the menu mentions Flash, that
is the issue. Most sites will fall back to HTML5 when Flash is not
available, so disabling Flash in the browser can help.
</p>
</section>
</main>
</div>
</body>
</html>
+1264 -115
View File
@@ -121,6 +121,53 @@ var displayKeyAliases = {
ArrowRight: "Right",
ArrowDown: "Down"
};
var controllerLocations = [
"top-left",
"top-center",
"top-right",
"middle-right",
"bottom-right",
"bottom-center",
"bottom-left",
"middle-left"
];
var controllerButtonDefs = {
rewind: { icon: "\u00AB", name: "Rewind" },
slower: { icon: "\u2212", name: "Decrease speed" },
faster: { icon: "+", name: "Increase speed" },
advance: { icon: "\u00BB", name: "Advance" },
display: { icon: "\u00D7", name: "Close controller" },
reset: { icon: "", name: "Reset speed" },
fast: { icon: "\u2605", name: "Preferred speed" },
nudge: { icon: "\u2713", name: "Subtitle nudge" },
settings: { icon: "\u2699", name: "Settings" },
pause: { icon: "\u23EF", name: "Pause / Play" },
muted: { icon: "M", name: "Mute / Unmute" },
mark: { icon: "\u2691", name: "Set marker" },
jump: { icon: "\u21E5", name: "Jump to marker" }
};
/** Cached custom Lucide SVGs (mirrors chrome.storage.local customButtonIcons). */
var customButtonIconsLive = {};
function fillControlBarIconElement(icon, buttonId) {
if (!icon || !buttonId) return;
var custom = customButtonIconsLive[buttonId];
if (custom && custom.svg) {
icon.innerHTML = custom.svg;
return;
}
if (typeof vscIconSvgString === "function") {
var svgHtml = vscIconSvgString(buttonId, 16);
if (svgHtml) {
icon.innerHTML = svgHtml;
return;
}
}
var def = controllerButtonDefs[buttonId];
icon.textContent = (def && def.icon) || "?";
}
function createDefaultBinding(action, key, keyCode, value) {
return {
@@ -140,29 +187,162 @@ var tcDefaults = {
rememberSpeed: false,
audioBoolean: false,
startHidden: false,
hideWithYouTubeControls: false,
hideWithControls: false,
hideWithControlsTimer: 2.0,
controllerLocation: "top-left",
forceLastSavedSpeed: false,
enabled: true,
controllerOpacity: 0.3,
controllerMarginTop: 0,
controllerMarginRight: 0,
controllerMarginBottom: 65,
controllerMarginLeft: 0,
keyBindings: [
createDefaultBinding("display", "V", 86, 0),
createDefaultBinding("move", "P", 80, 0),
createDefaultBinding("slower", "S", 83, 0.1),
createDefaultBinding("faster", "D", 68, 0.1),
createDefaultBinding("rewind", "Z", 90, 10),
createDefaultBinding("advance", "X", 88, 10),
createDefaultBinding("reset", "R", 82, 1),
createDefaultBinding("fast", "G", 71, 1.8)
createDefaultBinding("fast", "G", 71, 1.8),
createDefaultBinding("toggleSubtitleNudge", "N", 78, 0)
],
blacklist: `www.instagram.com
twitter.com
imgur.com
teams.microsoft.com
`.replace(regStrip, ""),
enableSubtitleNudge: true,
subtitleNudgeInterval: 25,
siteRules: [
{
pattern: "/^https:\\/\\/(www\\.)?youtube\\.com\\/(?!shorts\\/).*/",
enabled: true,
enableSubtitleNudge: true,
subtitleNudgeInterval: 50
},
{
pattern: "/^https:\\/\\/(www\\.)?youtube\\.com\\/shorts\\/.*/",
enabled: true,
rememberSpeed: true,
controllerMarginTop: 60,
controllerMarginBottom: 85
}
],
controllerButtons: ["rewind", "slower", "faster", "advance", "display"],
showPopupControlBar: true,
popupMatchHoverControls: true,
popupControllerButtons: ["rewind", "slower", "faster", "advance", "display"],
enableSubtitleNudge: false,
subtitleNudgeInterval: 50,
subtitleNudgeAmount: 0.001
};
var customActionsNoValues = ["pause", "muted", "mark", "jump", "display"];
const actionLabels = {
display: "Show/hide controller",
move: "Move controller",
slower: "Decrease speed",
faster: "Increase speed",
rewind: "Rewind",
advance: "Advance",
reset: "Reset speed",
fast: "Preferred speed",
muted: "Mute",
pause: "Pause",
mark: "Set marker",
jump: "Jump to marker",
toggleSubtitleNudge: "Toggle subtitle nudge"
};
const speedBindingActions = ["slower", "faster", "fast"];
function formatSpeedBindingDisplay(action, value) {
if (!speedBindingActions.includes(action)) {
return value;
}
var n = Number(value);
if (!isFinite(n)) {
return value;
}
return n.toFixed(2);
}
const customActionsNoValues = [
"reset",
"display",
"move",
"muted",
"pause",
"mark",
"jump",
"toggleSubtitleNudge"
];
function refreshAddShortcutSelector() {
const selector = document.getElementById("addShortcutSelector");
if (!selector) return;
// Clear existing options except the first one
while (selector.options.length > 1) {
selector.remove(1);
}
// Find all currently used actions
const usedActions = new Set();
document.querySelectorAll(".shortcut-row").forEach((row) => {
const action = row.dataset.action;
if (action) {
usedActions.add(action);
}
});
// Add all unused actions
Object.keys(actionLabels).forEach((action) => {
if (!usedActions.has(action)) {
const option = document.createElement("option");
option.value = action;
option.text = actionLabels[action];
selector.appendChild(option);
}
});
// If no available actions, hide or disable the selector
if (selector.options.length === 1) {
selector.disabled = true;
selector.options[0].text = "All shortcuts added";
} else {
selector.disabled = false;
selector.options[0].text = "Add shortcut\u2026";
}
}
function ensureDefaultBinding(storage, action, key, keyCode, value) {
if (storage.keyBindings.some((item) => item.action === action)) return;
storage.keyBindings.push(createDefaultBinding(action, key, keyCode, value));
}
function normalizeControllerLocation(location) {
if (controllerLocations.includes(location)) return location;
return tcDefaults.controllerLocation;
}
function clampMarginPxInput(el, fallback) {
var n = parseInt(el && el.value, 10);
if (!Number.isFinite(n)) return fallback;
return Math.min(200, Math.max(0, n));
}
function syncSiteRuleField(ruleEl, rule, key, isCheckbox) {
var input = ruleEl.querySelector(".site-" + key);
if (!input) return;
var globalEl = document.getElementById(key);
var value;
if (rule && rule[key] !== undefined) {
value = rule[key];
} else if (globalEl) {
value = isCheckbox ? globalEl.checked : globalEl.value;
} else {
return;
}
if (isCheckbox) input.checked = Boolean(value);
else input.value = value;
}
function normalizeBindingKey(key) {
if (typeof key !== "string" || key.length === 0) return null;
@@ -263,7 +443,7 @@ function normalizeStoredBinding(binding, fallbackKeyCode) {
function getBindingLabel(binding) {
if (!binding) return "";
if (binding.disabled) return "null";
if (binding.disabled) return "";
if (binding.key) {
return displayKeyAliases[binding.key] || binding.key;
}
@@ -348,20 +528,60 @@ function updateCustomShortcutInputText(inputItem, bindingOrKeyCode) {
setShortcutInputBinding(inputItem, legacyKeyCodeToBinding(bindingOrKeyCode));
}
function add_shortcut() {
var html = `<select class="customDo"><option value="slower">Decrease speed</option><option value="faster">Increase speed</option><option value="rewind">Rewind</option><option value="advance">Advance</option><option value="reset">Reset speed</option><option value="fast">Preferred speed</option><option value="muted">Mute</option><option value="pause">Pause</option><option value="mark">Set marker</option><option value="jump">Jump to marker</option><option value="display">Show/hide controller</option></select><input class="customKey" type="text" placeholder="press a key"/><input class="customValue" type="text" placeholder="value (0.10)"/><select class="customForce"><option value="false">Do not disable website key bindings</option><option value="true">Disable website key bindings</option></select><button class="removeParent">X</button>`;
function appendSelectOptions(select, options) {
options.forEach(function (optionData) {
var option = document.createElement("option");
option.value = optionData.value;
option.textContent = optionData.label;
select.appendChild(option);
});
}
function add_shortcut(action, value) {
if (!action) return;
var div = document.createElement("div");
div.setAttribute("class", "row customs");
div.innerHTML = html;
var customsElement = document.getElementById("customs");
customsElement.insertBefore(
div,
customsElement.children[customsElement.childElementCount - 1]
);
div.setAttribute("class", "shortcut-row customs");
div.dataset.action = action;
var actionLabel = document.createElement("div");
actionLabel.className = "shortcut-label";
actionLabel.textContent = actionLabels[action] || action;
var keyInput = document.createElement("input");
keyInput.className = "customKey";
keyInput.type = "text";
keyInput.placeholder = "press a key";
var valueInput = document.createElement("input");
valueInput.className = "customValue";
valueInput.type = "text";
valueInput.placeholder = "value";
if (customActionsNoValues.includes(action)) {
valueInput.value = "N/A";
valueInput.disabled = true;
} else {
valueInput.value = formatSpeedBindingDisplay(action, value || 0);
}
var removeButton = document.createElement("button");
removeButton.className = "removeParent";
removeButton.type = "button";
removeButton.textContent = "\u00d7";
div.appendChild(actionLabel);
div.appendChild(keyInput);
div.appendChild(valueInput);
div.appendChild(removeButton);
var customsElement = document.querySelector(".shortcuts-grid");
customsElement.appendChild(div);
refreshAddShortcutSelector();
}
function createKeyBindings(item) {
var action = item.querySelector(".customDo").value;
var action = item.dataset.action || item.querySelector(".customDo").value;
var input = item.querySelector(".customKey");
var valueInput = item.querySelector(".customValue");
var predefined = !!item.id;
@@ -387,7 +607,7 @@ function createKeyBindings(item) {
value: customActionsNoValues.includes(action)
? 0
: Number(valueInput.value),
force: item.querySelector(".customForce").value,
force: false,
predefined: predefined
});
@@ -397,22 +617,27 @@ function createKeyBindings(item) {
function validate() {
var valid = true;
var status = document.getElementById("status");
document
.getElementById("blacklist")
.value.split("\n")
.forEach((match) => {
match = match.replace(regStrip, "");
if (match.startsWith("/")) {
try {
new RegExp(match);
} catch (err) {
status.textContent =
"Error: Invalid blacklist regex: " + match + ". Unable to save";
valid = false;
return;
// Validate site rules patterns
document.querySelectorAll(".site-rule").forEach((ruleEl) => {
var pattern = ruleEl.querySelector(".site-pattern").value.trim();
if (pattern.length === 0) return;
if (pattern.startsWith("/")) {
try {
var lastSlash = pattern.lastIndexOf("/");
if (lastSlash > 0) {
new RegExp(pattern.substring(1, lastSlash), pattern.substring(lastSlash + 1));
}
} catch (err) {
status.textContent =
"Error: Invalid site rule regex: " + pattern + ". Unable to save";
valid = false;
return;
}
});
}
});
return valid;
}
@@ -423,7 +648,8 @@ function save_options() {
var status = document.getElementById("status");
var saveError = null;
Array.from(document.querySelectorAll(".customs")).forEach((item) => {
// Collect shortcuts from the main shortcuts section (both default and custom)
Array.from(document.querySelectorAll("#customs .shortcut-row")).forEach((item) => {
if (saveError) return;
var result = createKeyBindings(item);
if (!result.valid) saveError = result.message;
@@ -441,120 +667,919 @@ function save_options() {
settings.audioBoolean = document.getElementById("audioBoolean").checked;
settings.enabled = document.getElementById("enabled").checked;
settings.startHidden = document.getElementById("startHidden").checked;
settings.hideWithControls = document.getElementById("hideWithControls").checked;
settings.hideWithControlsTimer =
Math.min(15, Math.max(0.1, parseFloat(document.getElementById("hideWithControlsTimer").value) || tcDefaults.hideWithControlsTimer));
// Sync back to the legacy key if it exists, for backward compatibility
settings.hideWithYouTubeControls = settings.hideWithControls;
if (settings.hideWithControlsTimer < 0.1) settings.hideWithControlsTimer = 0.1;
if (settings.hideWithControlsTimer > 15) settings.hideWithControlsTimer = 15;
settings.controllerLocation = normalizeControllerLocation(
document.getElementById("controllerLocation").value
);
settings.controllerOpacity =
document.getElementById("controllerOpacity").value;
settings.blacklist = document
.getElementById("blacklist")
.value.replace(regStrip, "");
parseFloat(document.getElementById("controllerOpacity").value) ||
tcDefaults.controllerOpacity;
settings.controllerMarginTop = clampMarginPxInput(
document.getElementById("controllerMarginTop"),
tcDefaults.controllerMarginTop
);
settings.controllerMarginBottom = clampMarginPxInput(
document.getElementById("controllerMarginBottom"),
tcDefaults.controllerMarginBottom
);
settings.keyBindings = keyBindings;
settings.enableSubtitleNudge =
document.getElementById("enableSubtitleNudge").checked;
settings.subtitleNudgeInterval =
parseInt(document.getElementById("subtitleNudgeInterval").value, 10) ||
tcDefaults.subtitleNudgeInterval;
settings.subtitleNudgeAmount =
parseFloat(document.getElementById("subtitleNudgeAmount").value) ||
tcDefaults.subtitleNudgeAmount;
settings.subtitleNudgeAmount = tcDefaults.subtitleNudgeAmount;
if (settings.subtitleNudgeInterval < 10) {
settings.subtitleNudgeInterval = 10;
}
if (
settings.subtitleNudgeAmount <= 0 ||
settings.subtitleNudgeAmount > 0.1
) {
settings.subtitleNudgeAmount = tcDefaults.subtitleNudgeAmount;
if (settings.subtitleNudgeInterval > 1000) {
settings.subtitleNudgeInterval = 1000;
}
chrome.storage.sync.remove([
"resetSpeed",
"speedStep",
"fastSpeed",
"rewindTime",
"advanceTime",
"resetKeyCode",
"slowerKeyCode",
"fasterKeyCode",
"rewindKeyCode",
"advanceKeyCode",
"fastKeyCode"
]);
settings.controllerButtons = getControlBarOrder();
settings.showPopupControlBar =
document.getElementById("showPopupControlBar").checked;
settings.popupMatchHoverControls =
document.getElementById("popupMatchHoverControls").checked;
settings.popupControllerButtons = getPopupControlBarOrder();
chrome.storage.sync.set(settings, function () {
status.textContent = "Options saved";
setTimeout(function () {
status.textContent = "";
}, 1000);
// Collect site rules
settings.siteRules = [];
document.querySelectorAll(".site-rule").forEach((ruleEl) => {
var pattern = ruleEl.querySelector(".site-pattern").value.trim();
if (pattern.length === 0) return;
var rule = { pattern: pattern };
// Handle Enable toggle
rule.enabled = ruleEl.querySelector(".site-enabled").checked;
if (ruleEl.querySelector(".override-placement").checked) {
rule.controllerLocation = normalizeControllerLocation(
ruleEl.querySelector(".site-controllerLocation").value
);
rule.controllerMarginTop = clampMarginPxInput(
ruleEl.querySelector(".site-controllerMarginTop"),
clampMarginPxInput(
document.getElementById("controllerMarginTop"),
tcDefaults.controllerMarginTop
)
);
rule.controllerMarginBottom = clampMarginPxInput(
ruleEl.querySelector(".site-controllerMarginBottom"),
clampMarginPxInput(
document.getElementById("controllerMarginBottom"),
tcDefaults.controllerMarginBottom
)
);
}
if (ruleEl.querySelector(".override-visibility").checked) {
rule.startHidden = ruleEl.querySelector(".site-startHidden").checked;
}
if (ruleEl.querySelector(".override-autohide").checked) {
rule.hideWithControls = ruleEl.querySelector(".site-hideWithControls").checked;
var st = parseFloat(
ruleEl.querySelector(".site-hideWithControlsTimer").value
);
rule.hideWithControlsTimer = Math.min(
15,
Math.max(0.1, Number.isFinite(st) ? st : settings.hideWithControlsTimer)
);
}
if (ruleEl.querySelector(".override-playback").checked) {
rule.rememberSpeed = ruleEl.querySelector(".site-rememberSpeed").checked;
rule.forceLastSavedSpeed =
ruleEl.querySelector(".site-forceLastSavedSpeed").checked;
rule.audioBoolean = ruleEl.querySelector(".site-audioBoolean").checked;
}
if (ruleEl.querySelector(".override-opacity").checked) {
rule.controllerOpacity =
parseFloat(ruleEl.querySelector(".site-controllerOpacity").value) ||
settings.controllerOpacity;
}
if (ruleEl.querySelector(".override-subtitleNudge").checked) {
rule.enableSubtitleNudge =
ruleEl.querySelector(".site-enableSubtitleNudge").checked;
var nudgeIv = parseInt(
ruleEl.querySelector(".site-subtitleNudgeInterval").value,
10
);
rule.subtitleNudgeInterval = Math.min(
1000,
Math.max(
10,
Number.isFinite(nudgeIv) ? nudgeIv : settings.subtitleNudgeInterval
)
);
}
if (ruleEl.querySelector(".override-controlbar").checked) {
var activeZone = ruleEl.querySelector(".site-cb-active");
if (activeZone) {
rule.controllerButtons = readControlBarOrder(activeZone);
}
}
if (ruleEl.querySelector(".override-popup-controlbar").checked) {
rule.showPopupControlBar =
ruleEl.querySelector(".site-showPopupControlBar").checked;
var popupActiveZone = ruleEl.querySelector(".site-popup-cb-active");
if (popupActiveZone) {
rule.popupControllerButtons = readControlBarOrder(popupActiveZone);
}
}
if (ruleEl.querySelector(".override-shortcuts").checked) {
var shortcuts = [];
ruleEl.querySelectorAll(".site-shortcuts-container .customs").forEach((shortcutRow) => {
var action = shortcutRow.dataset.action;
var keyInput = shortcutRow.querySelector(".customKey");
var valueInput = shortcutRow.querySelector(".customValue");
var forceCheckbox = shortcutRow.querySelector(".customForce");
var binding = normalizeStoredBinding(keyInput.vscBinding);
if (binding) {
shortcuts.push({
action: action,
key: binding.key,
keyCode: binding.keyCode,
code: binding.code,
disabled: binding.disabled === true,
value: customActionsNoValues.includes(action)
? 0
: Number(valueInput.value),
force: forceCheckbox ? forceCheckbox.checked : false
});
}
});
if (shortcuts.length > 0) rule.shortcuts = shortcuts;
}
settings.siteRules.push(rule);
});
// Legacy keys to remove
const legacyKeys = [
"resetSpeed", "speedStep", "fastSpeed", "rewindTime", "advanceTime",
"resetKeyCode", "slowerKeyCode", "fasterKeyCode", "rewindKeyCode",
"advanceKeyCode", "fastKeyCode", "blacklist"
];
chrome.storage.sync.remove(legacyKeys, function () {
chrome.storage.sync.set(settings, function () {
status.textContent = "Options saved";
setTimeout(function () {
status.textContent = "";
}, 1000);
});
});
}
function ensureDisplayBinding(storage) {
if (storage.keyBindings.some((item) => item.action === "display")) return;
storage.keyBindings.push(
createDefaultBinding(
"display",
"V",
storage.displayKeyCode || tcDefaults.displayKeyCode,
0
)
function ensureAllDefaultBindings(storage) {
tcDefaults.keyBindings.forEach((binding) => {
// Special case for "display" to support legacy displayKeyCode
if (binding.action === "display" && storage.displayKeyCode) {
ensureDefaultBinding(storage, "display", "V", storage.displayKeyCode, 0);
} else {
ensureDefaultBinding(
storage,
binding.action,
binding.key,
binding.keyCode,
binding.value
);
}
});
}
function addSiteRuleShortcut(container, action, binding, value, force) {
var div = document.createElement("div");
div.setAttribute("class", "shortcut-row customs");
div.dataset.action = action;
var actionLabel = document.createElement("div");
actionLabel.className = "shortcut-label";
var actionLabels = {
display: "Show/hide controller",
move: "Move controller",
slower: "Decrease speed",
faster: "Increase speed",
rewind: "Rewind",
advance: "Advance",
reset: "Reset speed",
fast: "Preferred speed",
muted: "Mute",
pause: "Pause",
mark: "Set marker",
jump: "Jump to marker",
toggleSubtitleNudge: "Toggle subtitle nudge"
};
var actionLabelText = actionLabels[action] || action;
if (action === "toggleSubtitleNudge") {
// Check if the site rule is for YouTube.
// We look up the pattern from the site rule element this container belongs to.
var ruleEl = container.closest(".site-rule");
var pattern = ruleEl ? ruleEl.querySelector(".site-pattern").value : "";
if (!pattern.toLowerCase().includes("youtube.com")) {
actionLabelText += " (only for YouTube embeds)";
}
}
actionLabel.textContent = actionLabelText;
var keyInput = document.createElement("input");
keyInput.className = "customKey";
keyInput.type = "text";
keyInput.placeholder = "press a key";
updateCustomShortcutInputText(keyInput, binding || createDisabledBinding());
var valueInput = document.createElement("input");
valueInput.className = "customValue";
valueInput.type = "text";
valueInput.placeholder = "value (0.10)";
if (customActionsNoValues.includes(action)) {
valueInput.value = "N/A";
valueInput.disabled = true;
} else {
valueInput.value = formatSpeedBindingDisplay(action, value || 0);
}
var forceLabel = document.createElement("label");
forceLabel.className = "force-label";
forceLabel.title = "Prevent website from capturing this key";
var forceCheckbox = document.createElement("input");
forceCheckbox.type = "checkbox";
forceCheckbox.className = "customForce";
forceCheckbox.checked = force === true || force === "true";
var forceText = document.createElement("span");
forceText.textContent = "Block site from capturing keypress";
forceText.className = "force-text";
forceLabel.appendChild(forceCheckbox);
forceLabel.appendChild(forceText);
div.appendChild(actionLabel);
div.appendChild(keyInput);
div.appendChild(valueInput);
div.appendChild(forceLabel);
container.appendChild(div);
}
function createSiteRule(rule) {
var template = document.getElementById("siteRuleTemplate");
var clone = template.content.cloneNode(true);
var ruleEl = clone.querySelector(".site-rule");
var pattern = rule && rule.pattern ? rule.pattern : "";
ruleEl.querySelector(".site-pattern").value = pattern;
// Make the rule body collapsed by default
var ruleBody = ruleEl.querySelector(".site-rule-body");
ruleBody.style.display = "none";
ruleEl.classList.add("collapsed");
var enabledCheckbox = ruleEl.querySelector(".site-enabled");
var contentEl = ruleEl.querySelector(".site-rule-content");
function updateDisabledState() {
if (enabledCheckbox.checked) {
contentEl.classList.remove("disabled-rule");
} else {
contentEl.classList.add("disabled-rule");
}
}
enabledCheckbox.addEventListener("change", updateDisabledState);
if (rule) {
if (rule.enabled !== undefined) {
enabledCheckbox.checked = rule.enabled;
} else if (rule.disableExtension !== undefined) {
enabledCheckbox.checked = !rule.disableExtension;
} else {
enabledCheckbox.checked = true;
}
} else {
enabledCheckbox.checked = true;
}
updateDisabledState();
var placementKeys = [
"controllerLocation",
"controllerMarginTop",
"controllerMarginBottom"
];
var hasPlacementOverride =
rule && placementKeys.some(function (k) { return rule[k] !== undefined; });
if (hasPlacementOverride) {
ruleEl.querySelector(".override-placement").checked = true;
ruleEl.querySelector(".site-placement-container").style.display = "block";
}
syncSiteRuleField(ruleEl, rule, "controllerLocation", false);
syncSiteRuleField(ruleEl, rule, "controllerMarginTop", false);
syncSiteRuleField(ruleEl, rule, "controllerMarginBottom", false);
if (rule && rule.startHidden !== undefined) {
ruleEl.querySelector(".override-visibility").checked = true;
ruleEl.querySelector(".site-visibility-container").style.display = "block";
}
syncSiteRuleField(ruleEl, rule, "startHidden", true);
if (
rule &&
(rule.hideWithControls !== undefined ||
rule.hideWithControlsTimer !== undefined)
) {
ruleEl.querySelector(".override-autohide").checked = true;
ruleEl.querySelector(".site-autohide-container").style.display = "block";
}
syncSiteRuleField(ruleEl, rule, "hideWithControls", true);
syncSiteRuleField(ruleEl, rule, "hideWithControlsTimer", false);
if (
rule &&
(rule.rememberSpeed !== undefined ||
rule.forceLastSavedSpeed !== undefined ||
rule.audioBoolean !== undefined)
) {
ruleEl.querySelector(".override-playback").checked = true;
ruleEl.querySelector(".site-playback-container").style.display = "block";
}
syncSiteRuleField(ruleEl, rule, "rememberSpeed", true);
syncSiteRuleField(ruleEl, rule, "forceLastSavedSpeed", true);
syncSiteRuleField(ruleEl, rule, "audioBoolean", true);
if (rule && rule.controllerOpacity !== undefined) {
ruleEl.querySelector(".override-opacity").checked = true;
ruleEl.querySelector(".site-opacity-container").style.display = "block";
}
syncSiteRuleField(ruleEl, rule, "controllerOpacity", false);
if (
rule &&
(rule.enableSubtitleNudge !== undefined ||
rule.subtitleNudgeInterval !== undefined)
) {
ruleEl.querySelector(".override-subtitleNudge").checked = true;
ruleEl.querySelector(".site-subtitleNudge-container").style.display =
"block";
}
syncSiteRuleField(ruleEl, rule, "enableSubtitleNudge", true);
syncSiteRuleField(ruleEl, rule, "subtitleNudgeInterval", false);
if (rule && Array.isArray(rule.controllerButtons)) {
ruleEl.querySelector(".override-controlbar").checked = true;
var cbContainer = ruleEl.querySelector(".site-controlbar-container");
cbContainer.style.display = "block";
populateControlBarZones(
ruleEl.querySelector(".site-cb-active"),
ruleEl.querySelector(".site-cb-available"),
rule.controllerButtons
);
}
if (
rule &&
(rule.showPopupControlBar !== undefined ||
Array.isArray(rule.popupControllerButtons))
) {
ruleEl.querySelector(".override-popup-controlbar").checked = true;
var popupCbContainer = ruleEl.querySelector(".site-popup-controlbar-container");
popupCbContainer.style.display = "block";
var sitePopupActive = ruleEl.querySelector(".site-popup-cb-active");
var sitePopupAvailable = ruleEl.querySelector(".site-popup-cb-available");
if (Array.isArray(rule.popupControllerButtons)) {
populateControlBarZones(
sitePopupActive,
sitePopupAvailable,
rule.popupControllerButtons
);
} else if (
sitePopupActive &&
sitePopupAvailable &&
sitePopupActive.children.length === 0
) {
populateControlBarZones(
sitePopupActive,
sitePopupAvailable,
getPopupControlBarOrder()
);
}
}
syncSiteRuleField(ruleEl, rule, "showPopupControlBar", true);
if (rule && Array.isArray(rule.shortcuts) && rule.shortcuts.length > 0) {
ruleEl.querySelector(".override-shortcuts").checked = true;
var container = ruleEl.querySelector(".site-shortcuts-container");
container.style.display = "block";
rule.shortcuts.forEach((shortcut) => {
addSiteRuleShortcut(
container,
shortcut.action,
shortcut,
shortcut.value,
shortcut.force
);
});
}
document.getElementById("siteRulesContainer").appendChild(ruleEl);
}
function populateDefaultSiteShortcuts(container) {
tcDefaults.keyBindings.forEach((binding) => {
addSiteRuleShortcut(container, binding.action, binding, binding.value, false);
});
}
function createControlBarBlock(buttonId) {
var def = controllerButtonDefs[buttonId];
if (!def) return null;
var block = document.createElement("div");
block.className = "cb-block";
block.dataset.buttonId = buttonId;
block.draggable = true;
var grip = document.createElement("span");
grip.className = "cb-grip";
var icon = document.createElement("span");
icon.className = "cb-icon";
fillControlBarIconElement(icon, buttonId);
var label = document.createElement("span");
label.className = "cb-label";
label.textContent = def.name;
block.appendChild(grip);
block.appendChild(icon);
block.appendChild(label);
return block;
}
function populateControlBarZones(activeZone, availableZone, activeIds) {
activeZone.innerHTML = "";
availableZone.innerHTML = "";
activeIds.forEach(function (id) {
var block = createControlBarBlock(id);
if (block) activeZone.appendChild(block);
});
Object.keys(controllerButtonDefs).forEach(function (id) {
if (!activeIds.includes(id)) {
var block = createControlBarBlock(id);
if (block) availableZone.appendChild(block);
}
});
}
function readControlBarOrder(activeZone) {
var blocks = activeZone.querySelectorAll(".cb-block");
return Array.from(blocks).map(function (block) {
return block.dataset.buttonId;
});
}
function populateControlBarEditor(activeIds) {
populateControlBarZones(
document.getElementById("controlBarActive"),
document.getElementById("controlBarAvailable"),
activeIds
);
}
function getControlBarOrder() {
return readControlBarOrder(document.getElementById("controlBarActive"));
}
function populatePopupControlBarEditor(activeIds) {
populateControlBarZones(
document.getElementById("popupControlBarActive"),
document.getElementById("popupControlBarAvailable"),
activeIds
);
}
function getPopupControlBarOrder() {
return readControlBarOrder(document.getElementById("popupControlBarActive"));
}
function updatePopupEditorDisabledState() {
var checkbox = document.getElementById("popupMatchHoverControls");
var wrap = document.getElementById("popupCbEditorWrap");
if (!checkbox || !wrap) return;
if (checkbox.checked) {
wrap.classList.add("cb-editor-disabled");
} else {
wrap.classList.remove("cb-editor-disabled");
}
}
function getDragAfterElement(container, x, y) {
var elements = Array.from(
container.querySelectorAll(".cb-block:not(.cb-dragging)")
);
for (var i = 0; i < elements.length; i++) {
var box = elements[i].getBoundingClientRect();
var centerX = box.left + box.width / 2;
var centerY = box.top + box.height / 2;
var rowThresh = box.height * 0.5;
if (y - centerY > rowThresh) continue;
if (centerY - y > rowThresh) return elements[i];
if (x < centerX) return elements[i];
}
return undefined;
}
function initControlBarEditor() {
var draggedBlock = null;
function clearControlBarDropTargets(activeZone) {
document.querySelectorAll(".cb-dropzone.cb-over").forEach(function (zone) {
if (zone !== activeZone) {
zone.classList.remove("cb-over");
}
});
}
document.addEventListener("dragstart", function (e) {
var block = e.target.closest(".cb-block");
if (!block) return;
draggedBlock = block;
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", block.dataset.buttonId);
requestAnimationFrame(function () {
block.classList.add("cb-dragging");
});
});
document.addEventListener("dragend", function (e) {
var block = e.target.closest(".cb-block");
if (!block) return;
block.classList.remove("cb-dragging");
draggedBlock = null;
clearControlBarDropTargets(null);
});
document.addEventListener("dragover", function (e) {
var zone = e.target.closest(".cb-dropzone");
if (!zone) {
clearControlBarDropTargets(null);
return;
}
e.preventDefault();
if (e.dataTransfer) {
e.dataTransfer.dropEffect = "move";
}
clearControlBarDropTargets(zone);
zone.classList.add("cb-over");
if (!draggedBlock) return;
var afterEl = getDragAfterElement(zone, e.clientX, e.clientY);
if (afterEl) {
zone.insertBefore(draggedBlock, afterEl);
} else {
zone.appendChild(draggedBlock);
}
});
document.addEventListener("drop", function (e) {
var zone = e.target.closest(".cb-dropzone");
if (zone) {
e.preventDefault();
}
clearControlBarDropTargets(null);
});
}
var lucidePickerSelectedSlug = null;
var lucideSearchTimer = null;
function setLucideStatus(msg) {
var el = document.getElementById("lucideIconStatus");
if (el) el.textContent = msg || "";
}
function repaintAllCbIconsFromCustomMap() {
document.querySelectorAll(".cb-block .cb-icon").forEach(function (icon) {
var block = icon.closest(".cb-block");
if (!block) return;
fillControlBarIconElement(icon, block.dataset.buttonId);
});
}
function persistCustomButtonIcons(map, callback) {
chrome.storage.local.set({ customButtonIcons: map }, function () {
if (chrome.runtime.lastError) {
setLucideStatus(
"Could not save icons: " + chrome.runtime.lastError.message
);
return;
}
customButtonIconsLive = map;
if (callback) callback();
repaintAllCbIconsFromCustomMap();
});
}
function initLucideButtonIconsUI() {
var actionSel = document.getElementById("lucideIconActionSelect");
var searchInput = document.getElementById("lucideIconSearch");
var resultsEl = document.getElementById("lucideIconResults");
var previewEl = document.getElementById("lucideIconPreview");
if (!actionSel || !searchInput || !resultsEl || !previewEl) return;
if (typeof getLucideTagsMap !== "function") return;
if (!actionSel.dataset.lucideInit) {
actionSel.dataset.lucideInit = "1";
actionSel.innerHTML = "";
Object.keys(controllerButtonDefs).forEach(function (aid) {
if (aid === "reset") return;
var o = document.createElement("option");
o.value = aid;
o.textContent =
controllerButtonDefs[aid].name + " (" + aid + ")";
actionSel.appendChild(o);
});
}
function renderResults(slugs) {
resultsEl.innerHTML = "";
slugs.forEach(function (slug) {
var b = document.createElement("button");
b.type = "button";
b.className = "lucide-result-tile";
b.dataset.slug = slug;
b.title = slug;
b.setAttribute("aria-label", slug);
if (slug === lucidePickerSelectedSlug) {
b.classList.add("lucide-picked");
}
var url =
typeof lucideIconSvgUrl === "function" ? lucideIconSvgUrl(slug) : "";
if (url) {
var img = document.createElement("img");
img.className = "lucide-result-thumb";
img.src = url;
img.alt = "";
img.loading = "lazy";
b.appendChild(img);
} else {
b.textContent = slug.slice(0, 3);
}
b.addEventListener("click", function () {
lucidePickerSelectedSlug = slug;
Array.prototype.forEach.call(
resultsEl.querySelectorAll("button"),
function (x) {
x.classList.toggle("lucide-picked", x.dataset.slug === slug);
}
);
fetchLucideSvg(slug)
.then(function (txt) {
var safe = sanitizeLucideSvg(txt);
if (!safe) throw new Error("Bad SVG");
previewEl.innerHTML = safe;
setLucideStatus("Preview: " + slug);
})
.catch(function (e) {
previewEl.innerHTML = "";
setLucideStatus(
"Could not load: " + slug + " — " + e.message
);
});
});
resultsEl.appendChild(b);
});
}
if (!searchInput.dataset.lucideBound) {
searchInput.dataset.lucideBound = "1";
searchInput.addEventListener("input", function () {
clearTimeout(lucideSearchTimer);
lucideSearchTimer = setTimeout(function () {
getLucideTagsMap(chrome.storage.local, false)
.then(function (map) {
var q = searchInput.value;
if (!q.trim()) {
resultsEl.innerHTML = "";
return;
}
renderResults(searchLucideSlugs(map, q, 48));
})
.catch(function (e) {
setLucideStatus("Icon list error: " + e.message);
});
}, 200);
});
}
var applyBtn = document.getElementById("lucideIconApply");
if (applyBtn && !applyBtn.dataset.lucideBound) {
applyBtn.dataset.lucideBound = "1";
applyBtn.addEventListener("click", function () {
var action = actionSel.value;
var slug = lucidePickerSelectedSlug;
if (!action || !slug) {
setLucideStatus("Pick an action and click an icon first.");
return;
}
fetchLucideSvg(slug)
.then(function (txt) {
var safe = sanitizeLucideSvg(txt);
if (!safe) throw new Error("Sanitize failed");
var next = Object.assign({}, customButtonIconsLive);
next[action] = { slug: slug, svg: safe };
persistCustomButtonIcons(next, function () {
setLucideStatus(
"Saved " +
slug +
" for " +
action +
". Reload pages for the hover bar."
);
});
})
.catch(function (e) {
setLucideStatus("Apply failed: " + e.message);
});
});
}
var clrOne = document.getElementById("lucideIconClearAction");
if (clrOne && !clrOne.dataset.lucideBound) {
clrOne.dataset.lucideBound = "1";
clrOne.addEventListener("click", function () {
var action = actionSel.value;
if (!action) return;
var next = Object.assign({}, customButtonIconsLive);
delete next[action];
persistCustomButtonIcons(next, function () {
setLucideStatus("Cleared custom icon for " + action + ".");
});
});
}
var clrAll = document.getElementById("lucideIconClearAll");
if (clrAll && !clrAll.dataset.lucideBound) {
clrAll.dataset.lucideBound = "1";
clrAll.addEventListener("click", function () {
persistCustomButtonIcons({}, function () {
setLucideStatus("All custom icons cleared.");
});
});
}
var reloadTags = document.getElementById("lucideIconReloadTags");
if (reloadTags && !reloadTags.dataset.lucideBound) {
reloadTags.dataset.lucideBound = "1";
reloadTags.addEventListener("click", function () {
getLucideTagsMap(chrome.storage.local, true)
.then(function () {
setLucideStatus("Icon name list refreshed.");
})
.catch(function (e) {
setLucideStatus("Refresh failed: " + e.message);
});
});
}
}
function restore_options() {
chrome.storage.sync.get(tcDefaults, function (storage) {
chrome.storage.local.get(["customButtonIcons"], function (loc) {
customButtonIconsLive =
loc && loc.customButtonIcons && typeof loc.customButtonIcons === "object"
? loc.customButtonIcons
: {};
document.getElementById("rememberSpeed").checked = storage.rememberSpeed;
document.getElementById("forceLastSavedSpeed").checked =
storage.forceLastSavedSpeed;
document.getElementById("audioBoolean").checked = storage.audioBoolean;
document.getElementById("enabled").checked = storage.enabled;
document.getElementById("startHidden").checked = storage.startHidden;
// Migration/Normalization for hideWithControls
const hideWithControls = typeof storage.hideWithControls !== "undefined"
? storage.hideWithControls
: storage.hideWithYouTubeControls;
document.getElementById("hideWithControls").checked = hideWithControls;
document.getElementById("hideWithControlsTimer").value =
storage.hideWithControlsTimer || tcDefaults.hideWithControlsTimer;
document.getElementById("controllerLocation").value =
normalizeControllerLocation(storage.controllerLocation);
document.getElementById("controllerOpacity").value =
storage.controllerOpacity;
document.getElementById("blacklist").value = storage.blacklist;
document.getElementById("controllerMarginTop").value =
storage.controllerMarginTop ?? tcDefaults.controllerMarginTop;
document.getElementById("controllerMarginBottom").value =
storage.controllerMarginBottom ?? tcDefaults.controllerMarginBottom;
document.getElementById("showPopupControlBar").checked =
storage.showPopupControlBar !== false;
document.getElementById("enableSubtitleNudge").checked =
storage.enableSubtitleNudge;
document.getElementById("subtitleNudgeInterval").value =
storage.subtitleNudgeInterval;
document.getElementById("subtitleNudgeAmount").value =
storage.subtitleNudgeAmount;
if (!Array.isArray(storage.keyBindings) || storage.keyBindings.length === 0) {
storage.keyBindings = tcDefaults.keyBindings.slice();
}
ensureDisplayBinding(storage);
ensureAllDefaultBindings(storage);
document.querySelectorAll(".customs:not([id])").forEach((row) => row.remove());
storage.keyBindings.forEach((item) => {
var fallbackKeyCode =
item.action === "display"
? storage.displayKeyCode || tcDefaults.displayKeyCode
: undefined;
var normalizedBinding = normalizeStoredBinding(item, fallbackKeyCode);
var row;
var row = document.getElementById(item.action);
var normalizedBinding = normalizeStoredBinding(item);
if (item.predefined) {
row = document.getElementById(item.action);
} else {
add_shortcut();
row = document.querySelector(".customs:last-of-type");
row.querySelector(".customDo").value = item.action;
if (!row) {
add_shortcut(item.action, item.value);
row = document.querySelector(".shortcut-row.customs:last-of-type");
}
if (!row) return;
var valueInput = row.querySelector(".customValue");
if (customActionsNoValues.includes(item.action)) {
valueInput.disabled = true;
var keyInput = row.querySelector(".customKey");
if (keyInput) {
updateCustomShortcutInputText(keyInput, normalizedBinding || null);
}
updateCustomShortcutInputText(
row.querySelector(".customKey"),
normalizedBinding || createDisabledBinding()
);
valueInput.value = item.value;
row.querySelector(".customForce").value = String(item.force);
var valueInput = row.querySelector(".customValue");
if (customActionsNoValues.includes(item.action)) {
if (valueInput) {
valueInput.value = "N/A";
valueInput.disabled = true;
}
} else if (valueInput) {
valueInput.value = formatSpeedBindingDisplay(item.action, item.value);
}
});
refreshAddShortcutSelector();
// Load site rules (use defaults if none in storage or empty array)
var siteRules =
Array.isArray(storage.siteRules) && storage.siteRules.length > 0
? storage.siteRules
: tcDefaults.siteRules || [];
document.getElementById("siteRulesContainer").innerHTML = "";
if (siteRules.length > 0) {
siteRules.forEach((rule) => {
if (rule && rule.pattern) {
createSiteRule(rule);
}
});
}
var controllerButtons = Array.isArray(storage.controllerButtons)
? storage.controllerButtons
: tcDefaults.controllerButtons;
populateControlBarEditor(controllerButtons);
document.getElementById("popupMatchHoverControls").checked =
storage.popupMatchHoverControls !== false;
var popupButtons = Array.isArray(storage.popupControllerButtons)
? storage.popupControllerButtons
: tcDefaults.popupControllerButtons;
populatePopupControlBarEditor(popupButtons);
updatePopupEditorDisabledState();
initLucideButtonIconsUI();
});
});
}
@@ -562,6 +1587,11 @@ function restore_options() {
function restore_defaults() {
document.querySelectorAll(".customs:not([id])").forEach((el) => el.remove());
chrome.storage.local.remove(
["customButtonIcons", "lucideTagsCacheV1", "lucideTagsCacheV1At"],
function () {}
);
chrome.storage.sync.set(tcDefaults, function () {
restore_options();
var status = document.getElementById("status");
@@ -572,12 +1602,6 @@ function restore_defaults() {
});
}
function show_experimental() {
document
.querySelectorAll(".customForce")
.forEach((item) => (item.style.display = "inline-block"));
}
document.addEventListener("DOMContentLoaded", function () {
var manifest = chrome.runtime.getManifest();
var versionElement = document.getElementById("app-version");
@@ -586,14 +1610,30 @@ document.addEventListener("DOMContentLoaded", function () {
}
restore_options();
initControlBarEditor();
document.getElementById("popupMatchHoverControls")
.addEventListener("change", updatePopupEditorDisabledState);
document.getElementById("save").addEventListener("click", save_options);
document.getElementById("add").addEventListener("click", add_shortcut);
const addSelector = document.getElementById("addShortcutSelector");
if (addSelector) {
addSelector.addEventListener("change", function (e) {
if (e.target.value) {
add_shortcut(e.target.value);
e.target.value = ""; // Reset selector
}
});
}
document
.getElementById("restore")
.addEventListener("click", restore_defaults);
document
.getElementById("experimental")
.addEventListener("click", show_experimental);
.getElementById("addSiteRule")
.addEventListener("click", function () {
createSiteRule(null);
});
function eventCaller(event, className, funcName) {
if (!event.target.classList || !event.target.classList.contains(className)) {
@@ -614,13 +1654,35 @@ document.addEventListener("DOMContentLoaded", function () {
document.addEventListener("keydown", (event) =>
eventCaller(event, "customKey", recordKeyPress)
);
document.addEventListener("click", (event) =>
eventCaller(event, "removeParent", function () {
document.addEventListener("click", (event) => {
if (event.target.classList.contains("removeParent")) {
event.target.parentNode.remove();
})
);
refreshAddShortcutSelector();
return;
}
if (event.target.classList.contains("remove-site-rule")) {
event.target.closest(".site-rule").remove();
return;
}
if (event.target.classList.contains("toggle-site-rule")) {
var ruleEl = event.target.closest(".site-rule");
var ruleBody = ruleEl.querySelector(".site-rule-body");
var isCollapsed = ruleEl.classList.contains("collapsed");
if (isCollapsed) {
ruleBody.style.display = "block";
ruleEl.classList.remove("collapsed");
event.target.textContent = "\u2212";
} else {
ruleBody.style.display = "none";
ruleEl.classList.add("collapsed");
event.target.textContent = "\u002b";
}
return;
}
});
document.addEventListener("change", (event) => {
eventCaller(event, "customDo", function () {
if (event.target.classList.contains("customDo")) {
var valueInput = event.target.nextElementSibling.nextElementSibling;
if (customActionsNoValues.includes(event.target.value)) {
valueInput.disabled = true;
@@ -628,6 +1690,93 @@ document.addEventListener("DOMContentLoaded", function () {
} else {
valueInput.disabled = false;
}
});
}
// Site rule: show/hide optional override sections
var siteOverrideContainers = {
"override-placement": "site-placement-container",
"override-visibility": "site-visibility-container",
"override-autohide": "site-autohide-container",
"override-playback": "site-playback-container",
"override-opacity": "site-opacity-container",
"override-subtitleNudge": "site-subtitleNudge-container"
};
for (var ocb in siteOverrideContainers) {
if (event.target.classList.contains(ocb)) {
var siteRuleRoot = event.target.closest(".site-rule");
var targetBox = siteRuleRoot.querySelector(
"." + siteOverrideContainers[ocb]
);
if (targetBox) {
targetBox.style.display = event.target.checked ? "block" : "none";
}
return;
}
}
// Handle site rule override checkboxes
if (event.target.classList.contains("override-shortcuts")) {
var container = event.target
.closest(".site-rule-shortcuts")
.querySelector(".site-shortcuts-container");
if (event.target.checked) {
container.style.display = "block";
if (container.children.length === 0) {
populateDefaultSiteShortcuts(container);
}
} else {
container.style.display = "none";
}
}
if (event.target.classList.contains("override-controlbar")) {
var cbContainer = event.target
.closest(".site-rule-controlbar")
.querySelector(".site-controlbar-container");
if (event.target.checked) {
cbContainer.style.display = "block";
var activeZone = cbContainer.querySelector(".site-cb-active");
var availableZone = cbContainer.querySelector(".site-cb-available");
if (
activeZone &&
availableZone &&
activeZone.children.length === 0 &&
availableZone.children.length === 0
) {
populateControlBarZones(
activeZone,
availableZone,
getControlBarOrder()
);
}
} else {
cbContainer.style.display = "none";
}
}
if (event.target.classList.contains("override-popup-controlbar")) {
var popupCbContainer = event.target
.closest(".site-rule-controlbar")
.querySelector(".site-popup-controlbar-container");
if (event.target.checked) {
popupCbContainer.style.display = "block";
var popupActiveZone = popupCbContainer.querySelector(".site-popup-cb-active");
var popupAvailableZone = popupCbContainer.querySelector(".site-popup-cb-available");
if (
popupActiveZone &&
popupAvailableZone &&
popupActiveZone.children.length === 0 &&
popupAvailableZone.children.length === 0
) {
populateControlBarZones(
popupActiveZone,
popupAvailableZone,
getPopupControlBarOrder()
);
}
} else {
popupCbContainer.style.display = "none";
}
}
});
});
+245 -55
View File
@@ -1,79 +1,269 @@
body {
min-width: 8em;
background-color: white;
color: #333;
}
.version {
margin-top: 0.7em;
font-size: 0.85em;
text-align: center;
color: #666;
}
:root {
--bg: #f4f5f7;
--panel: #ffffff;
--border: #e2e5e9;
--border-strong: #d4d9e0;
--text: #17191c;
--muted: #626b76;
--accent: #111827;
}
hr {
width: 100%;
border: 0;
height: 0;
border-top: 1px solid rgba(0, 0, 0, 0.3);
margin: 0.6em 0;
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
min-width: 220px;
background: var(--bg);
color: var(--text);
font: 13px/1.45 "Avenir Next", "SF Pro Text", "Segoe UI", sans-serif;
padding: 12px;
}
.popup-shell {
display: flex;
flex-direction: column;
gap: 10px;
}
.popup-header {
display: flex;
align-items: center;
justify-content: space-between;
padding-bottom: 8px;
border-bottom: 1px solid var(--border);
}
.popup-title {
font-weight: 600;
font-size: 15px;
font-family: "Avenir Next", "SF Pro Display", "Segoe UI", sans-serif;
letter-spacing: -0.01em;
}
.popup-version {
font-size: 11px;
font-weight: 600;
color: var(--muted);
padding: 2px 7px;
border: 1px solid var(--border);
border-radius: 999px;
background: var(--panel);
}
.popup-actions {
display: flex;
flex-direction: column;
gap: 6px;
}
button {
appearance: none;
width: 100%;
background-image: linear-gradient(#ededed, #ededed 38%, #dedede);
border: 1px solid rgba(0, 0, 0, 0.25);
border-radius: 2px;
outline: none;
box-shadow: 0 1px 0 rgba(0, 0, 0, 0.08),
inset 0 1px 2px rgba(255, 255, 255, 0.75);
color: #444;
text-shadow: 0 1px 0 rgb(240, 240, 240);
min-height: 32px;
padding: 0 12px;
border: 1px solid var(--border-strong);
border-radius: 8px;
background: var(--panel);
color: var(--text);
font: inherit;
font-weight: 500;
cursor: pointer;
transition: background 120ms ease, border-color 120ms ease;
}
button:hover {
background: #f8f9fb;
border-color: #c5ccd5;
}
button:active {
background: #f1f3f5;
}
button:focus-visible {
outline: 2px solid rgba(17, 24, 39, 0.14);
outline-offset: 2px;
}
#refresh {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
#refresh:hover {
background: #1f2937;
border-color: #1f2937;
}
.popup-divider {
height: 1px;
background: var(--border);
margin: 2px 0;
}
.popup-control-bar {
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
padding: 6px 10px;
background: var(--panel);
border: 1px solid var(--border-strong);
border-radius: 8px;
}
.popup-speed {
font-family: "Lucida Console", Monaco, monospace;
font-size: 13px;
font-weight: bold;
color: var(--text);
margin-right: 4px;
line-height: 1;
user-select: none;
white-space: nowrap;
}
.popup-control-bar button {
width: auto;
min-height: 24px;
border: 1px solid var(--border-strong);
border-radius: 6px;
background: var(--bg);
color: var(--text);
font-family: "Lucida Console", Monaco, monospace;
font-size: 13px;
line-height: 13px;
font-weight: bold;
padding: 3px 7px;
cursor: pointer;
}
.popup-control-bar button:hover {
background: var(--panel);
border-color: var(--border-strong);
}
.popup-control-bar button:active {
background: var(--bg);
}
.popup-control-bar button.rw {
opacity: 0.55;
}
.popup-control-bar button.hideButton {
opacity: 0.55;
}
.popup-control-bar button .vsc-btn-icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 16px;
height: 16px;
line-height: 0;
vertical-align: middle;
}
.popup-control-bar button .vsc-btn-icon svg {
width: 100%;
height: 100%;
flex-shrink: 0;
}
.popup-status {
font-size: 12px;
color: var(--muted);
font-weight: 500;
text-align: center;
padding: 2px 0;
}
.popup-links {
display: flex;
flex-direction: column;
gap: 6px;
padding-top: 8px;
border-top: 1px solid var(--border);
}
.popup-secondary {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.secondary {
font-size: 0.95em;
margin: 0.15em 0;
font-size: 12px;
min-height: 28px;
color: var(--muted);
}
.donate-wrap {
display: grid;
grid-template-columns: 1fr;
}
.donate-split {
display: grid;
grid-template-columns: 1fr 1fr;
}
.donate-split button {
width: auto;
border-radius: 0;
min-height: 28px;
}
.donate-split button:first-child {
border-radius: 8px 0 0 8px;
border-right: 0;
}
.donate-split button:last-child {
border-radius: 0 8px 8px 0;
}
.hide {
display: none;
display: none !important;
}
/* Dark mode styles */
@media (prefers-color-scheme: dark) {
:root {
--bg: #111315;
--panel: #171a1d;
--border: #2b3138;
--border-strong: #3a414a;
--text: #f2f4f6;
--muted: #a0a8b2;
--accent: #f2f4f6;
}
body {
background-color: #1a1a1a;
color: #e0e0e0;
}
hr {
border-top: 1px solid rgba(255, 255, 255, 0.3);
}
button {
background-image: linear-gradient(#404040, #404040 38%, #353535);
border: 1px solid rgba(255, 255, 255, 0.25);
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.08),
inset 0 1px 2px rgba(0, 0, 0, 0.75);
color: #e0e0e0;
text-shadow: 0 1px 0 rgb(20, 20, 20);
color-scheme: dark;
}
button:hover {
background-image: linear-gradient(#4a4a4a, #4a4a4a 38%, #3f3f3f);
background: #1f2226;
border-color: #4a515a;
}
button:active {
background-image: linear-gradient(#353535, #353535 38%, #2a2a2a);
background: #252a2f;
}
#status {
color: #ccc;
}
.version {
color: #aaa;
}
}
#refresh {
background: #f2f4f6;
border-color: #f2f4f6;
color: #111315;
}
#refresh:hover {
background: #dfe3e8;
border-color: #dfe3e8;
}
}
+34 -12
View File
@@ -1,21 +1,43 @@
<!doctype html>
<html>
<head>
<title>Video Speed Controller: Popup</title>
<meta charset="utf-8" />
<title>Speeder</title>
<link rel="stylesheet" href="popup.css" />
<script src="ui-icons.js"></script>
<script src="popup.js"></script>
</head>
<body>
<button id="refresh">Re-scan Page for Videos</button>
<hr />
<button id="enable" class="hide">Enable</button>
<button id="disable">Disable</button>
<span id="status" class="hide"></span>
<hr />
<button id="config">Settings</button>
<hr />
<button id="feedback" class="secondary">Send feedback</button>
<button id="about" class="secondary">About</button>
<div class="version">Version <span id="app-version"></span></div>
<div class="popup-shell">
<div class="popup-header">
<span class="popup-title">Speeder</span>
<span class="popup-version">v<span id="app-version"></span></span>
</div>
<div class="popup-actions">
<button id="refresh">Rescan page for videos</button>
<div class="popup-divider"></div>
<div id="popupControlBar" class="popup-control-bar">
<span id="popupSpeed" class="popup-speed">1.00</span>
</div>
<div class="popup-divider"></div>
<button id="enable" class="hide">Enable</button>
<button id="disable">Disable</button>
</div>
<div id="status" class="popup-status hide"></div>
<div class="popup-links">
<button id="config">Settings</button>
<div class="popup-secondary">
<button id="feedback" class="secondary">Feedback</button>
<button id="about" class="secondary">About</button>
</div>
<div id="donateWrap" class="donate-wrap">
<button id="donate" class="secondary">Donate</button>
<div id="donateOptions" class="donate-split hide">
<button id="donateKofi" class="secondary">Ko-fi</button>
<button id="donateGithub" class="secondary">Sponsors</button>
</div>
</div>
</div>
</div>
</body>
</html>
+368 -33
View File
@@ -1,4 +1,259 @@
document.addEventListener("DOMContentLoaded", function () {
var regStrip = /^[\r\t\f\v ]+|[\r\t\f\v ]+$/gm;
/* `label` is only used if ui-icons.js has no path for this action (fallback). */
var controllerButtonDefs = {
rewind: { label: "", className: "rw" },
slower: { label: "", className: "" },
faster: { label: "", className: "" },
advance: { label: "", className: "rw" },
display: { label: "", className: "hideButton" },
reset: { label: "", className: "" },
fast: { label: "", className: "" },
settings: { label: "", className: "" },
pause: { label: "", className: "" },
muted: { label: "", className: "" },
mark: { label: "", className: "" },
jump: { label: "", className: "" }
};
var defaultButtons = ["rewind", "slower", "faster", "advance", "display"];
var storageDefaults = {
enabled: true,
showPopupControlBar: true,
controllerButtons: defaultButtons,
popupMatchHoverControls: true,
popupControllerButtons: defaultButtons,
siteRules: []
};
var renderToken = 0;
function escapeStringRegExp(str) {
const m = /[|\\{}()[\]^$+*?.]/g;
return str.replace(m, "\\$&");
}
function matchSiteRule(url, siteRules) {
if (!url || !Array.isArray(siteRules)) return null;
for (var i = 0; i < siteRules.length; i++) {
var rule = siteRules[i];
if (!rule || !rule.pattern) continue;
var pattern = rule.pattern.replace(regStrip, "");
if (pattern.length === 0) continue;
var re;
if (pattern.startsWith("/") && pattern.lastIndexOf("/") > 0) {
try {
var ls = pattern.lastIndexOf("/");
re = new RegExp(pattern.substring(1, ls), pattern.substring(ls + 1));
} catch (e) {
continue;
}
} else {
re = new RegExp(escapeStringRegExp(pattern));
}
if (re && re.test(url)) return rule;
}
return null;
}
function isSiteRuleDisabled(rule) {
return Boolean(
rule &&
(rule.enabled === false || rule.disableExtension === true)
);
}
function resolvePopupButtons(storage, siteRule) {
if (siteRule && Array.isArray(siteRule.popupControllerButtons)) {
return siteRule.popupControllerButtons;
}
if (storage.popupMatchHoverControls) {
if (siteRule && Array.isArray(siteRule.controllerButtons)) {
return siteRule.controllerButtons;
}
if (Array.isArray(storage.controllerButtons)) {
return storage.controllerButtons;
}
}
if (Array.isArray(storage.popupControllerButtons)) {
return storage.popupControllerButtons;
}
return defaultButtons;
}
function setControlBarVisible(visible) {
var bar = document.getElementById("popupControlBar");
var dividers = document.querySelectorAll(".popup-divider");
if (bar) bar.style.display = visible ? "" : "none";
dividers.forEach(function (d) { d.style.display = visible ? "" : "none"; });
}
function sendToActiveTab(message, callback) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs[0] && tabs[0].id) {
chrome.tabs.sendMessage(tabs[0].id, message, function (response) {
if (chrome.runtime.lastError) {
if (callback) callback(null);
} else {
if (callback) callback(response);
}
});
} else {
if (callback) callback(null);
}
});
}
function getActiveTabContext(callback) {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var activeTab = tabs && tabs[0] ? tabs[0] : null;
if (!activeTab || !activeTab.id) {
if (callback) callback({ tab: null, url: "" });
return;
}
var tabUrl = typeof activeTab.url === "string" ? activeTab.url : "";
if (tabUrl.length > 0) {
if (callback) callback({ tab: activeTab, url: tabUrl });
return;
}
chrome.tabs.sendMessage(
activeTab.id,
{ action: "get_page_context" },
function (response) {
if (chrome.runtime.lastError) {
if (callback) callback({ tab: activeTab, url: "" });
return;
}
var pageUrl =
response && typeof response.url === "string" ? response.url : "";
if (callback) callback({ tab: activeTab, url: pageUrl });
}
);
});
}
function updateSpeedDisplay(speed) {
var el = document.getElementById("popupSpeed");
if (el) el.textContent = (speed != null ? Number(speed) : 1).toFixed(2);
}
function applySpeedAndResetFromResponse(response) {
if (response && response.speed != null) {
updateSpeedDisplay(response.speed);
}
}
function pickBestFrameSpeedResult(results) {
if (!results || !results.length) return null;
var i;
var r;
var fallback = null;
for (i = 0; i < results.length; i++) {
r = results[i];
if (!r || typeof r.speed !== "number") {
continue;
}
if (r.preferred) {
return { speed: r.speed };
}
if (!fallback) {
fallback = { speed: r.speed };
}
}
return fallback;
}
function querySpeed() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (!tabs[0] || tabs[0].id == null) {
return;
}
var tabId = tabs[0].id;
chrome.tabs.executeScript(
tabId,
{ allFrames: true, file: "frameSpeedSnapshot.js" },
function (results) {
if (chrome.runtime.lastError) {
sendToActiveTab({ action: "get_speed" }, function (response) {
applySpeedAndResetFromResponse(response || { speed: 1 });
});
return;
}
var best = pickBestFrameSpeedResult(results);
if (best) {
applySpeedAndResetFromResponse(best);
} else {
sendToActiveTab({ action: "get_speed" }, function (response) {
applySpeedAndResetFromResponse(response || { speed: 1 });
});
}
}
);
});
}
function buildControlBar(buttons, customIconsMap) {
var bar = document.getElementById("popupControlBar");
if (!bar) return;
var existing = bar.querySelectorAll("button");
existing.forEach(function (btn) { btn.remove(); });
var customMap = customIconsMap || {};
buttons.forEach(function (btnId) {
if (btnId === "nudge") return;
var def = controllerButtonDefs[btnId];
if (!def) return;
var btn = document.createElement("button");
btn.dataset.action = btnId;
var customEntry = customMap[btnId];
if (customEntry && customEntry.svg) {
var customSpan = document.createElement("span");
customSpan.className = "vsc-btn-icon";
customSpan.innerHTML = customEntry.svg;
btn.appendChild(customSpan);
} else if (typeof vscIconSvgString === "function") {
var svgStr = vscIconSvgString(btnId, 16);
if (svgStr) {
var iconSpan = document.createElement("span");
iconSpan.className = "vsc-btn-icon";
iconSpan.innerHTML = svgStr;
btn.appendChild(iconSpan);
} else {
btn.textContent = def.label || "?";
}
} else {
btn.textContent = def.label || "?";
}
if (def.className) btn.className = def.className;
btn.title = btnId.charAt(0).toUpperCase() + btnId.slice(1);
btn.addEventListener("click", function () {
if (btnId === "settings") {
window.open(chrome.runtime.getURL("options.html"));
return;
}
sendToActiveTab(
{ action: "run_action", actionName: btnId },
function () {
querySpeed();
}
);
});
bar.appendChild(btn);
});
}
var manifest = chrome.runtime.getManifest();
var versionElement = document.querySelector("#app-version");
if (versionElement) {
@@ -10,11 +265,24 @@ document.addEventListener("DOMContentLoaded", function () {
});
document.querySelector("#about").addEventListener("click", function () {
window.open("https://github.com/codebicycle/videospeed");
window.open("https://github.com/SoPat712/Speeder");
});
document.querySelector("#feedback").addEventListener("click", function () {
window.open("https://github.com/codebicycle/videospeed/issues");
window.open("https://github.com/SoPat712/Speeder/issues");
});
document.querySelector("#donate").addEventListener("click", function () {
this.classList.add("hide");
document.querySelector("#donateOptions").classList.remove("hide");
});
document.querySelector("#donateKofi").addEventListener("click", function () {
window.open("https://ko-fi.com/joshpatra");
});
document.querySelector("#donateGithub").addEventListener("click", function () {
window.open("https://github.com/sponsors/SoPat712");
});
document.querySelector("#enable").addEventListener("click", function () {
@@ -25,45 +293,106 @@ document.addEventListener("DOMContentLoaded", function () {
toggleEnabled(false, settingsSavedReloadMessage);
});
// --- REVISED: "Re-scan" button functionality ---
document.querySelector("#refresh").addEventListener("click", function () {
setStatusMessage("Re-scanning page...");
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
if (tabs[0] && tabs[0].id) {
// Send a message to the content script, asking it to re-initialize.
chrome.tabs.sendMessage(
tabs[0].id,
{ action: "rescan_page" },
function (response) {
if (chrome.runtime.lastError) {
// This error is expected on pages where content scripts cannot run.
setStatusMessage("Cannot run on this page.");
} else if (response && response.status === "complete") {
setStatusMessage("Scan complete. Closing...");
setTimeout(() => window.close(), 500); // Close popup on success.
} else {
setStatusMessage("Scan failed. Please reload the page.");
}
}
);
setStatusMessage("Rescanning page...");
sendToActiveTab({ action: "rescan_page" }, function (response) {
if (!response) {
setStatusMessage("Cannot run on this page.");
} else if (response.status === "complete") {
setStatusMessage("Scan complete. Closing...");
setTimeout(function () { window.close(); }, 500);
} else {
setStatusMessage("Scan failed. Please reload the page.");
}
});
});
chrome.storage.sync.get({ enabled: true }, function (storage) {
toggleEnabledUI(storage.enabled);
function renderForActiveTab() {
var currentRenderToken = ++renderToken;
chrome.storage.local.get(["customButtonIcons"], function (loc) {
if (currentRenderToken !== renderToken) return;
var customIconsMap =
loc && loc.customButtonIcons && typeof loc.customButtonIcons === "object"
? loc.customButtonIcons
: {};
chrome.storage.sync.get(storageDefaults, function (storage) {
if (currentRenderToken !== renderToken) return;
getActiveTabContext(function (context) {
if (currentRenderToken !== renderToken) return;
var url = context && context.url ? context.url : "";
var siteRule = matchSiteRule(url, storage.siteRules);
var siteDisabled = isSiteRuleDisabled(siteRule);
var siteAvailable = storage.enabled !== false && !siteDisabled;
var showBar = storage.showPopupControlBar !== false;
if (siteRule && siteRule.showPopupControlBar !== undefined) {
showBar = siteRule.showPopupControlBar;
}
toggleEnabledUI(storage.enabled !== false);
buildControlBar(
resolvePopupButtons(storage, siteRule),
customIconsMap
);
setControlBarVisible(siteAvailable && showBar);
if (siteDisabled) {
setStatusMessage("Speeder is disabled for this site.");
updateSpeedDisplay(1);
return;
}
clearStatusMessage();
if (siteAvailable) {
querySpeed();
} else {
updateSpeedDisplay(1);
}
});
});
});
}
chrome.tabs.onActivated.addListener(function () {
renderForActiveTab();
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (!tab || tab.active !== true) return;
if (changeInfo.url !== undefined || changeInfo.status === "complete") {
renderForActiveTab();
}
});
chrome.storage.onChanged.addListener(function (changes, areaName) {
if (areaName === "local" && changes.customButtonIcons) {
renderForActiveTab();
return;
}
if (areaName !== "sync") return;
if (
changes.enabled ||
changes.showPopupControlBar ||
changes.controllerButtons ||
changes.popupMatchHoverControls ||
changes.popupControllerButtons ||
changes.siteRules
) {
renderForActiveTab();
}
});
renderForActiveTab();
function toggleEnabled(enabled, callback) {
chrome.storage.sync.set(
{
enabled: enabled
},
function () {
toggleEnabledUI(enabled);
if (callback) callback(enabled);
}
);
chrome.storage.sync.set({ enabled: enabled }, function () {
toggleEnabledUI(enabled);
if (callback) callback(enabled);
});
}
function toggleEnabledUI(enabled) {
@@ -91,4 +420,10 @@ document.addEventListener("DOMContentLoaded", function () {
status_element.classList.toggle("hide", false);
status_element.innerText = str;
}
function clearStatusMessage() {
const status_element = document.querySelector("#status");
status_element.classList.toggle("hide", true);
status_element.innerText = "";
}
});
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env bash
# Squash beta onto main, set manifest version, one release commit, push stable tag (v* without -beta).
# Does not merge dev or push to beta — promote only what is already on beta.
# Triggers .github/workflows/deploy.yml: listed AMO submission.
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
manifest_version() {
python3 -c 'import json; print(json.load(open("manifest.json"))["version"])'
}
bump_manifest() {
local ver="$1"
VER="$ver" python3 <<'PY'
import json
import os
ver = os.environ["VER"]
path = "manifest.json"
with open(path, encoding="utf-8") as f:
data = json.load(f)
data["version"] = ver
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
f.write("\n")
PY
}
normalize_semver() {
local s="$1"
s="${s#"${s%%[![:space:]]*}"}"
s="${s%"${s##*[![:space:]]}"}"
s="${s#v}"
s="${s#V}"
printf '%s' "$s"
}
validate_semver() {
local s="$1"
if [[ -z "$s" ]]; then
echo "Error: empty version." >&2
return 1
fi
if [[ ! "$s" =~ ^[0-9]+(\.[0-9]+){0,3}(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then
echo "Error: invalid version (use something like 5.0.4)." >&2
return 1
fi
}
if [[ -n "$(git status --porcelain)" ]]; then
echo "Error: working tree is not clean. Commit or stash before releasing." >&2
exit 1
fi
git checkout beta
git pull origin beta
echo "Current version on beta (manifest.json): $(manifest_version)"
read -r -p "Release version for manifest.json + tag (e.g. 5.0.4): " SEMVER_IN
SEMVER="$(normalize_semver "$SEMVER_IN")"
validate_semver "$SEMVER"
TAG="v${SEMVER}"
if [[ "$TAG" == *-beta* ]]; then
echo "Warning: stable tags should not contain '-beta' (workflow would use unlisted + prerelease, not AMO listed)."
read -r -p "Continue anyway? [y/N] " w
[[ "${w:-}" =~ ^[yY](es)?$ ]] || { echo "Aborted."; exit 1; }
fi
echo
echo "This will:"
echo " 1. checkout main, merge --squash origin/beta (single release commit on main)"
echo " 2. set manifest.json to $SEMVER in that commit (if anything else changed, it is included too)"
echo " 3. push origin main, create tag $TAG, push tag (triggers listed AMO submit)"
echo " 4. checkout dev (merge main→dev yourself if you want them aligned)"
read -r -p "Continue? [y/N] " confirm
[[ "${confirm:-}" =~ ^[yY](es)?$ ]] || { echo "Aborted."; exit 1; }
echo "🚀 Releasing stable $TAG to AMO (listed)"
git checkout main
git pull origin main
git merge --squash beta
bump_manifest "$SEMVER"
git add -A
git commit -m "Release $TAG"
git push origin main
git tag -a "$TAG" -m "$TAG"
git push origin "$TAG"
git checkout dev
echo "✅ Done: main squashed from beta, tagged $TAG (manifest $SEMVER)"
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env bash
# Merge dev → beta, push beta, and push an annotated beta tag (v*-beta*).
# Triggers .github/workflows/deploy.yml: unlisted AMO sign + GitHub prerelease.
set -euo pipefail
ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"
manifest_version() {
python3 -c 'import json; print(json.load(open("manifest.json"))["version"])'
}
bump_manifest() {
local ver="$1"
VER="$ver" python3 <<'PY'
import json
import os
ver = os.environ["VER"]
path = "manifest.json"
with open(path, encoding="utf-8") as f:
data = json.load(f)
data["version"] = ver
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
f.write("\n")
PY
}
normalize_semver() {
local s="$1"
s="${s#"${s%%[![:space:]]*}"}"
s="${s%"${s##*[![:space:]]}"}"
s="${s#v}"
s="${s#V}"
printf '%s' "$s"
}
validate_semver() {
local s="$1"
if [[ -z "$s" ]]; then
echo "Error: empty version." >&2
return 1
fi
if [[ ! "$s" =~ ^[0-9]+(\.[0-9]+){0,3}(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$ ]]; then
echo "Error: invalid version (use something like 5.0.4 or 5.0.4-beta.1)." >&2
return 1
fi
}
if [[ -n "$(git status --porcelain)" ]]; then
echo "Error: working tree is not clean. Commit or stash before releasing." >&2
exit 1
fi
git checkout dev
git pull origin dev
echo "Current version in manifest.json: $(manifest_version)"
read -r -p "New version for manifest.json (e.g. 5.0.4): " SEMVER_IN
SEMVER="$(normalize_semver "$SEMVER_IN")"
validate_semver "$SEMVER"
echo "Beta git tag will include '-beta' (required by deploy.yml)."
read -r -p "Beta tag suffix [beta.1]: " SUFFIX_IN
SUFFIX="${SUFFIX_IN#"${SUFFIX_IN%%[![:space:]]*}"}"
SUFFIX="${SUFFIX%"${SUFFIX##*[![:space:]]}"}"
SUFFIX="${SUFFIX:-beta.1}"
TAG="v${SEMVER}-${SUFFIX}"
if [[ "$TAG" != *-beta* ]]; then
echo "Error: beta tag must contain '-beta' for the workflow (got $TAG). Try suffix like beta.1." >&2
exit 1
fi
echo
echo "This will:"
echo " 1. set manifest.json version to $SEMVER, commit on dev, push origin dev"
echo " 2. checkout beta, merge dev (no-ff), push origin beta"
echo " 3. create tag $TAG and push it (triggers beta AMO + prerelease)"
echo " 4. checkout dev (main is not modified)"
read -r -p "Continue? [y/N] " confirm
[[ "${confirm:-}" =~ ^[yY](es)?$ ]] || { echo "Aborted."; exit 1; }
echo "🚀 Releasing beta $TAG"
bump_manifest "$SEMVER"
git add manifest.json
git commit -m "Bump version to $SEMVER"
git push origin dev
git checkout beta
git pull origin beta
git merge dev --no-ff -m "$TAG"
git push origin beta
git tag -a "$TAG" -m "$TAG"
git push origin "$TAG"
git checkout dev
git pull origin dev
echo "✅ Done: beta $TAG (manifest $SEMVER; dev + beta + tag pushed)"
+213 -5
View File
@@ -4,51 +4,219 @@
font-size: 13px;
}
/* Global * uses 1.9em line-height; without this, every node inside #controller
(including svg) keeps a tall line box and the bar grows + content rides high. */
#controller * {
line-height: 1;
}
#controller:hover #controls,
#controller:focus-within #controls,
:host(:hover) #controls {
display: inline;
display: inline-flex;
vertical-align: middle;
}
#controller {
position: absolute;
top: 0;
left: 0;
transform: translate(0, 0);
pointer-events: auto;
background: black;
color: white;
border-radius: 5px;
padding: 5px;
margin: 10px 10px 10px 15px;
margin: 0;
cursor: default;
z-index: 9999999;
/* Stay above the local video surface without overtaking page-level dialogs. */
z-index: 1;
transition: top 160ms ease, left 160ms ease, transform 160ms ease,
opacity 160ms ease;
/* Insets are baked into left/top; bar must not wrap when narrow. Hover controls
extend into the inset area (past “logical” margin). */
white-space: nowrap;
overflow: visible;
max-width: none;
}
#controller:hover {
opacity: 0.7;
}
/* Space between speed readout and hover buttons — tweak this value (px) as you like */
#controller:hover > .draggable {
margin-right: 0.8em;
margin-right: 5px;
}
/* Center presets: midpoint between left- and right-preset inset lines; center bar on that X. */
#controller[data-location="top-center"]:not([data-position-mode="manual"]) {
transform: translate(-50%, 0) !important;
}
#controller[data-location="bottom-center"]:not([data-position-mode="manual"]) {
transform: translate(-50%, -100%) !important;
}
#controls {
display: none;
flex-direction: row;
flex-wrap: nowrap;
align-items: center;
gap: 3px;
white-space: nowrap;
overflow: visible;
max-width: none;
}
/* Standalone flash next to speed when N is pressed — hidden = no layout footprint */
#nudge-flash-indicator {
display: none;
margin: 0;
padding: 0;
border: 0;
width: 0;
min-width: 0;
max-width: 0;
height: 0;
min-height: 0;
overflow: hidden;
vertical-align: middle;
align-items: center;
justify-content: center;
font-size: 14px;
line-height: 14px;
font-weight: bold;
font-family: "Lucida Console", Monaco, monospace;
box-sizing: border-box;
}
/* Same 24×24 footprint as #controls button */
#nudge-flash-indicator.visible {
display: inline-flex;
box-sizing: border-box;
width: 24px;
height: 24px;
min-width: 24px;
min-height: 24px;
max-width: 24px;
max-height: 24px;
margin-left: 5px;
padding: 0;
border-width: 1px;
border-style: solid;
border-radius: 5px;
align-items: center;
justify-content: center;
font-size: 0;
line-height: 0;
overflow: hidden;
flex-shrink: 0;
}
/* Hide flash indicator when hovering — the one in #controls is visible instead */
#controller:hover #nudge-flash-indicator,
:host(:hover) #nudge-flash-indicator {
display: none !important;
width: 0;
height: 0;
margin: 0;
padding: 0;
border: 0;
overflow: hidden;
}
#nudge-flash-indicator[data-enabled="true"] {
color: #fff;
background: #4b9135;
border-color: #6ec754;
}
#nudge-flash-indicator[data-enabled="false"] {
color: #fff;
background: #943e3e;
border-color: #c06060;
}
/* Same 24×24 chip as control buttons (Lucide check / x inside) */
#nudge-indicator {
display: inline-flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
width: 24px;
height: 24px;
min-width: 24px;
min-height: 24px;
max-height: 24px;
padding: 0;
border-width: 1px;
border-style: solid;
border-radius: 5px;
font-size: 0;
line-height: 0;
cursor: pointer;
margin: 0;
flex-shrink: 0;
overflow: hidden;
}
#nudge-indicator[data-enabled="true"] {
color: #fff;
background: #4b9135;
border-color: #6ec754;
}
#nudge-indicator[data-enabled="false"] {
color: #fff;
background: #943e3e;
border-color: #c06060;
}
#nudge-indicator[data-supported="false"] {
opacity: 0.6;
}
#nudge-flash-indicator.visible .vsc-btn-icon,
#nudge-indicator .vsc-btn-icon {
display: flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
margin: 0;
padding: 0;
line-height: 0;
}
#nudge-flash-indicator.visible .vsc-btn-icon svg,
#nudge-indicator .vsc-btn-icon svg {
display: block;
width: 100%;
height: 100%;
flex-shrink: 0;
transform: translateY(0.5px);
}
#controller.dragging {
cursor: -webkit-grabbing;
cursor: -moz-grabbing;
opacity: 0.7;
transition: none;
}
#controller.dragging #controls {
display: inline;
display: inline-flex;
vertical-align: middle;
}
.draggable {
cursor: -webkit-grab;
cursor: -moz-grab;
vertical-align: middle;
}
.draggable:active {
@@ -70,6 +238,46 @@ button {
margin-bottom: 2px;
}
/* Icon buttons: square targets, compact bar (no extra vertical stretch). */
#controls button {
box-sizing: border-box;
width: 24px;
height: 24px;
min-width: 24px;
min-height: 24px;
max-height: 24px;
padding: 0;
margin: 0;
border-width: 1px;
line-height: 0;
font-size: 0;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
overflow: hidden;
}
button .vsc-btn-icon {
display: flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
margin: 0;
padding: 0;
line-height: 0;
}
button .vsc-btn-icon svg {
display: block;
width: 100%;
height: 100%;
flex-shrink: 0;
/* Lucide 24×24 paths sit slightly high in the viewBox */
transform: translateY(0.5px);
}
button:focus {
outline: 0;
}
+69
View File
@@ -0,0 +1,69 @@
/**
* Inline SVG icons (Lucide-style strokes, compatible with https://lucide.dev — ISC license).
* Use stroke="currentColor" so buttons inherit foreground for monochrome UI.
*/
var VSC_ICON_SIZE_DEFAULT = 18;
/** Inner SVG markup only (paths / shapes inside <svg>). */
var vscUiIconPaths = {
rewind:
'<polygon points="11 19 2 12 11 5 11 19"/><polygon points="22 19 13 12 22 5 22 19"/>',
advance:
'<polygon points="13 19 22 12 13 5 13 19"/><polygon points="2 19 11 12 2 5 2 19"/>',
reset:
'<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/>',
slower: '<line x1="5" y1="12" x2="19" y2="12"/>',
faster:
'<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>',
display:
'<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>',
fast: '<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>',
settings:
'<path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/>',
pause:
'<rect x="14" y="4" width="4" height="16" rx="1"/><rect x="6" y="4" width="4" height="16" rx="1"/>',
muted:
'<polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/>',
mark: '<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>',
jump:
'<polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/>',
nudge: '<path d="M22 12h-4l-3 9L9 3l-3 9H2"/>',
/** Lucide check — subtitle nudge on */
subtitleNudgeOn: '<path d="M20 6 9 17l-5-5"/>',
/** Lucide x — subtitle nudge off */
subtitleNudgeOff:
'<path d="M18 6 6 18"/><path d="m6 6 12 12"/>'
};
/**
* @param {number} [size] - width/height in px
* @returns {string} full <svg>…</svg>
*/
function vscIconSvgString(action, size) {
var inner = vscUiIconPaths[action];
if (!inner) return "";
var s = size != null ? size : VSC_ICON_SIZE_DEFAULT;
return (
'<svg xmlns="http://www.w3.org/2000/svg" width="' +
s +
'" height="' +
s +
'" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
inner +
"</svg>"
);
}
/**
* @param {Document} doc
* @param {string} action
* @returns {HTMLElement|null} wrapper span containing svg, or null if no icon
*/
function vscIconWrap(doc, action, size) {
var html = vscIconSvgString(action, size);
if (!html) return null;
var span = doc.createElement("span");
span.className = "vsc-btn-icon";
span.innerHTML = html;
return span;
}