Floating PIP Button = Enable Picture in Picture for mobile

Adds a floating button to toggle Picture-in-Picture mode for videos on mobile devices.

当前为 2025-02-01 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Floating PIP Button = Enable Picture in Picture for mobile
  3. // @name:bg Плаващ PIP бутон = Активиране на картина в картина за мобилни устройства
  4. // @name:cs Plovoucí tlačítko PIP = Povolit obraz v obraze pro mobilní zařízení
  5. // @name:da Flydende PIP-knap = Aktiver billede i billede til mobile enheder
  6. // @name:de Schwebender PIP-Button = Bild-in-Bild für mobile Geräte aktivieren
  7. // @name:el Επιπλέων κουμπί PIP = Ενεργοποίηση εικόνας σε εικόνα για κινητές συσκευές
  8. // @name:en Floating PIP Button = Enable Picture in Picture for mobile
  9. // @name:eo Flosanta PIP-Butono = Ebligi Bildon en Bildo por poŝtelefonoj
  10. // @name:es Botón Flotante PIP = Habilita Imagen en Imagen para móvil
  11. // @name:fi Kelluva PIP-painike = Ota käyttöön kuva kuvassa mobiililaitteille
  12. // @name:fr Bouton PIP flottant = Activer l'image dans l'image pour mobile
  13. // @name:fr-CA Bouton PIP flottant = Activer l'image dans l'image pour mobile
  14. // @name:he כפתור PIP צף = הפעלת תמונה בתוך תמונה לנייד
  15. // @name:hr Plutajući PIP gumb = Omogući sliku u slici za mobilne uređaje
  16. // @name:hu Lebegő PIP gomb = Kép a képben engedélyezése mobil eszközökre
  17. // @name:id Tombol PIP Mengambang = Aktifkan Gambar dalam Gambar untuk seluler
  18. // @name:it Pulsante PIP flottante = Abilita immagine nell'immagine per dispositivi mobili
  19. // @name:ja 浮動PIPボタン = モバイル用のピクチャーインピクチャーを有効にする
  20. // @name:ka მცურავი PIP ღილაკი = ჩართეთ სურათი სურათში მობილური მოწყობილობებისთვის
  21. // @name:ko 플로팅 PIP 버튼 = 모바일용 화면 속 화면 활성화
  22. // @name:nb Flytende PIP-knapp = Aktiver bilde i bilde for mobil
  23. // @name:nl Zwevende PIP-knop = Schakel beeld in beeld in voor mobiel
  24. // @name:pl Pływający przycisk PIP = Włącz obraz w obrazie dla urządzeń mobilnych
  25. // @name:pt-BR Botão PIP Flutuante = Ativar imagem em imagem para celular
  26. // @name:ro Buton PIP plutitor = Activează imagine în imagine pentru mobil
  27. // @name:sv Flytande PIP-knapp = Aktivera bild i bild för mobil
  28. // @name:th ปุ่ม PIP ลอย = เปิดใช้งานภาพในภาพสำหรับมือถือ
  29. // @name:tr Yüzen PIP Düğmesi = Mobil için Resim içinde Resim'i etkinleştir
  30. // @name:ug ھۆلۈپ تۇرغان PIP كۇنۇپكىسى = يانفونلار ئۈچۈن رەسىم ئىچىدە رەسىمنى قوزغىتىش
  31. // @name:uk Плаваюча кнопка PIP = Увімкнути картинку в картинці для мобільних пристроїв
  32. // @name:vi Nút PIP nổi = Bật chế độ Hình trong Hình cho di động
  33. // @name:zh-TW 浮動PIP按鈕 = 啟用行動裝置的畫中畫模式
  34. // @namespace https://jlcareglio.github.io/
  35. // @version 0.9.6
  36. // @description Adds a floating button to toggle Picture-in-Picture mode for videos on mobile devices.
  37. // @description:bg Добавя плаващ бутон за превключване на режим картина в картина за видеоклипове на мобилни устройства.
  38. // @description:cs Přidává plovoucí tlačítko pro přepínání režimu obraz v obraze pro videa na mobilních zařízeních.
  39. // @description:da Tilføjer en flydende knap til at skifte billede-i-billede-tilstand for videoer på mobile enheder.
  40. // @description:de Fügt eine schwebende Schaltfläche hinzu, um den Bild-in-Bild-Modus für Videos auf mobilen Geräten umzuschalten.
  41. // @description:el Προσθέτει ένα επιπλέον κουμπί για εναλλαγή της λειτουργίας εικόνας σε εικόνα για βίντεο σε κινητές συσκευές.
  42. // @description:en Adds a floating button to toggle Picture-in-Picture mode for videos on mobile devices.
  43. // @description:eo Aldonas flosantan butonon por ŝalti Bildon en Bildo-reĝimon por videoj en poŝtelefonoj.
  44. // @description:es Agrega un botón flotante para alternar el modo Imagen en Imagen para videos en dispositivos móviles.
  45. // @description:fi Lisää kelluvan painikkeen, jolla voi vaihtaa kuva kuvassa -tilan videoille mobiililaitteissa.
  46. // @description:fr Ajoute un bouton flottant pour basculer en mode image dans l'image pour les vidéos sur les appareils mobiles.
  47. // @description:fr-CA Ajoute un bouton flottant pour basculer en mode image dans l'image pour les vidéos sur les appareils mobiles.
  48. // @description:he מוסיף כפתור צף למעבר למצב תמונה בתוך תמונה עבור סרטונים במכשירים ניידים.
  49. // @description:hr Dodaje plutajući gumb za prebacivanje načina slike u slici za videozapise na mobilnim uređajima.
  50. // @description:hu Hozzáad egy lebegő gombot a kép a képben mód váltásához videókhoz mobil eszközökön.
  51. // @description:id Menambahkan tombol mengambang untuk beralih ke mode Gambar dalam Gambar untuk video di perangkat seluler.
  52. // @description:it Aggiunge un pulsante flottante per attivare la modalità immagine nell'immagine per i video sui dispositivi mobili.
  53. // @description:ja モバイルデバイスでビデオのピクチャーインピクチャーモードを切り替えるための浮動ボタンを追加します。
  54. // @description:ka ამატებს მცურავ ღილაკს მობილური მოწყობილობებისთვის ვიდეოების სურათში სურათის რეჟიმის ჩასართავად.
  55. // @description:ko 모바일 장치에서 비디오의 화면 속 화면 모드를 전환하는 플로팅 버튼을 추가합니다.
  56. // @description:nb Legger til en flytende knapp for å bytte bilde-i-bilde-modus for videoer på mobile enheter.
  57. // @description:nl Voegt een zwevende knop toe om de modus Beeld-in-Beeld voor video's op mobiele apparaten in te schakelen.
  58. // @description:pl Dodaje pływający przycisk do przełączania trybu obraz w obrazie dla filmów na urządzeniach mobilnych.
  59. // @description:pt-BR Adiciona um botão flutuante para alternar o modo Imagem em Imagem para vídeos em dispositivos móveis.
  60. // @description:ro Adaugă un buton plutitor pentru a comuta modul imagine în imagine pentru videoclipuri pe dispozitive mobile.
  61. // @description:sv Lägger till en flytande knapp för att växla bild-i-bild-läge för videor på mobila enheter.
  62. // @description:th เพิ่มปุ่มลอยเพื่อสลับโหมดภาพในภาพสำหรับวิดีโอบนอุปกรณ์เคลื่อนที่
  63. // @description:tr Mobil cihazlarda videolar için Resim içinde Resim modunu değiştirmek için yüzen bir düğme ekler.
  64. // @description:ug يانفونلاردا ۋىدىئولار ئۈچۈن رەسىم ئىچىدە رەسىم ھالىتىنى ئالماشتۇرۇش ئۈچۈن ھۆلۈپ تۇرغان كۇنۇپكا قوشىدۇ.
  65. // @description:uk Додає плаваючу кнопку для перемикання режиму картинка в картинці для відео на мобільних пристроях.
  66. // @description:vi Thêm nút nổi để chuyển đổi chế độ Hình trong Hình cho video trên thiết bị di động.
  67. // @description:zh-TW 添加一個浮動按鈕,以切換行動裝置上的影片畫中畫模式。
  68. // @icon https://lh3.googleusercontent.com/cvfpnTKw3B67DtM1ZpJG2PNAIjP6hVMOyYy403X4FMkOuStgG1y4cjCn21vmTnnsip1dTZSVsWBA9IxutGuA3dVDWhg
  69. // @grant none
  70. // @author Jesús Lautaro Careglio Albornoz
  71. // @source https://gist.githubusercontent.com/JLCareglio/22d3f9c9752352a29006f0c90c72d193/raw/01_Floating-PIP-Button.js
  72. // @match *://*/*
  73. // @license MIT
  74. // @compatible firefox
  75. // @compatible edge
  76. // @compatible kiwi
  77. // @supportURL https://gist.github.com/JLCareglio/22d3f9c9752352a29006f0c90c72d193
  78. // ==/UserScript==
  79.  
  80. (async () => {
  81. const CONSTANTS = {
  82. BUTTON: {
  83. STYLE: `
  84. .pipButton {
  85. position: fixed; background-color: rgba(0, 0, 0, 0.5); border-radius: 50%; width: 60px; height: 60px; cursor: pointer; z-index: 9999; display: none; --delete-progress: 0; isolation: isolate;
  86. transform: scale(1);
  87. transition: transform 0.1s ease-out;
  88. }
  89. .pipButton:before {
  90. pointer-events: none; content: ""; position: absolute; top: 0; bottom: 0; width: 100%; z-index: 2;
  91. background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 36 36' width='100%25' height='100%25'%3E%3Cpath d='M25,17 L17,17 L17,23 L25,23 L25,17 L25,17 Z M29,25 L29,10.98 C29,9.88 28.1,9 27,9 L9,9 C7.9,9 7,9.88 7,10.98 L7,25 C7,26.1 7.9,27 9,27 L27,27 C28.1,27 29,26.1 29,25 L29,25 Z M27,25.02 L9,25.02 L9,10.97 L27,10.97 L27,25.02 L27,25.02 Z' fill='%23fff'/%3E%3C/svg%3E") no-repeat center;
  92. }
  93. .pipButton:after {
  94. content: ""; position: absolute; inset: 0; background-color: rgba(255, 0, 0, 0.8); border-radius: 50%; transform: scale(var(--delete-progress)); transition: transform 0.5s ease; z-index: 1;
  95. }
  96. `,
  97. DEFAULT_POSITION: {
  98. right: 20,
  99. bottom: 20,
  100. },
  101. },
  102. TOUCH: {
  103. MOVE_THRESHOLD: 10,
  104. CLICK_TIMEOUT: 200,
  105. LONG_PRESS_TIMEOUT: 1000,
  106. LONG_PRESS_MOVE_THRESHOLD: 15,
  107. ANIMATION_DELAY: 300,
  108. },
  109. STORAGE: {
  110. POSITION_KEY: "pip_button_position",
  111. },
  112. };
  113.  
  114. /**
  115. * Main class to handle the PIP button and its functionality
  116. */
  117. class PIPButton {
  118. #button;
  119. #watchedVideos;
  120. #observer;
  121. #isDragging = false;
  122. #touchStartTime = 0;
  123. #dragOffset = { x: 0, y: 0 };
  124. #initialPosition = { x: 0, y: 0 };
  125. #longPressTimer = null;
  126. #longPressStartPosition = { x: 0, y: 0 };
  127. #animationTimer = null;
  128. #isManuallyHidden = false;
  129.  
  130. constructor() {
  131. this.#initializeButton();
  132. this.#initializeVideoObserver();
  133. this.#initializeDragHandlers();
  134. this.#detectInitialVideos();
  135. this.#initializeLongPressHandlers();
  136. }
  137.  
  138. /**
  139. * Initializes the button and its styles
  140. * @private
  141. */
  142. #initializeButton() {
  143. this.#button = document.createElement("div");
  144. this.#button.classList.add("pipButton");
  145. this.#injectStyles();
  146. document.body.appendChild(this.#button);
  147. this.#watchedVideos = new Set();
  148. this.#loadButtonPosition();
  149. }
  150.  
  151. /**
  152. * Injects required CSS styles
  153. * @private
  154. */
  155. #injectStyles() {
  156. const style = document.createElement("style");
  157. style.textContent = CONSTANTS.BUTTON.STYLE;
  158. document.head.appendChild(style);
  159. }
  160.  
  161. /**
  162. * Initializes the video observer
  163. * @private
  164. */
  165. #initializeVideoObserver() {
  166. this.#observer = new MutationObserver(this.#handleMutations.bind(this));
  167. this.#observer.observe(document.body, {
  168. childList: true,
  169. subtree: true,
  170. });
  171. }
  172.  
  173. /**
  174. * Handles DOM mutations to detect new videos
  175. * @private
  176. * @param {MutationRecord[]} mutations
  177. */
  178. #handleMutations(mutations) {
  179. mutations.forEach((mutation) => {
  180. mutation.addedNodes.forEach((node) => {
  181. if (node instanceof HTMLVideoElement) {
  182. this.#addVideo(node);
  183. }
  184. });
  185. });
  186. this.#updateButtonVisibility();
  187. }
  188.  
  189. /**
  190. * Adds a video to the collection of observed videos
  191. * @private
  192. * @param {HTMLVideoElement} video
  193. */
  194. #addVideo(video) {
  195. if (!this.#watchedVideos.has(video)) {
  196. this.#watchedVideos.add(video);
  197. }
  198. }
  199.  
  200. /**
  201. * Detects existing videos in the DOM on startup
  202. * @private
  203. */
  204. #detectInitialVideos() {
  205. document
  206. .querySelectorAll("video")
  207. .forEach((video) => this.#addVideo(video));
  208. this.#updateButtonVisibility();
  209. }
  210.  
  211. /**
  212. * Toggles PIP mode for the active video
  213. * @private
  214. */
  215. #togglePIP() {
  216. try {
  217. if (this.#watchedVideos.size === 0) return;
  218.  
  219. if (document.pictureInPictureElement) {
  220. document.exitPictureInPicture();
  221. return;
  222. }
  223.  
  224. const playingVideo = Array.from(this.#watchedVideos).find(
  225. (video) => !video.paused && !video.ended && video.currentTime > 0
  226. );
  227.  
  228. const videoToShow = playingVideo || Array.from(this.#watchedVideos)[0];
  229. videoToShow?.requestPictureInPicture().catch(console.error);
  230. } catch (error) {
  231. console.error("Error toggling PIP:", error);
  232. }
  233. }
  234.  
  235. /**
  236. * Initializes event handlers for dragging
  237. * @private
  238. */
  239. #initializeDragHandlers() {
  240. this.#button.addEventListener(
  241. "mousedown",
  242. this.#handleDragStart.bind(this)
  243. );
  244. this.#button.addEventListener(
  245. "touchstart",
  246. this.#handleDragStart.bind(this)
  247. );
  248.  
  249. document.addEventListener("mousemove", this.#handleDragMove.bind(this));
  250. document.addEventListener("touchmove", this.#handleDragMove.bind(this), {
  251. passive: false,
  252. });
  253.  
  254. document.addEventListener("mouseup", this.#handleDragEnd.bind(this));
  255. document.addEventListener("touchend", this.#handleDragEnd.bind(this));
  256. document.addEventListener("touchcancel", this.#handleDragEnd.bind(this));
  257. }
  258.  
  259. /**
  260. * Handles drag start
  261. * @private
  262. * @param {MouseEvent|TouchEvent} event
  263. */
  264. #handleDragStart(event) {
  265. this.#isDragging = true;
  266. this.#button.style.transform = "scale(2)";
  267. const rect = this.#button.getBoundingClientRect();
  268. this.#initialPosition = { x: rect.left, y: rect.top };
  269.  
  270. const clientX = event.clientX || event.touches[0].clientX;
  271. const clientY = event.clientY || event.touches[0].clientY;
  272.  
  273. this.#dragOffset = {
  274. x: clientX - this.#initialPosition.x,
  275. y: clientY - this.#initialPosition.y,
  276. };
  277.  
  278. this.#touchStartTime = Date.now();
  279. event.preventDefault();
  280. event.stopPropagation();
  281. if (this.#longPressTimer) {
  282. clearTimeout(this.#longPressTimer);
  283. }
  284. }
  285.  
  286. /**
  287. * Handles movement during drag
  288. * @private
  289. * @param {MouseEvent|TouchEvent} event
  290. */
  291. #handleDragMove(event) {
  292. if (!this.#isDragging) return;
  293.  
  294. const clientX = event.clientX || event.touches[0].clientX;
  295. const clientY = event.clientY || event.touches[0].clientY;
  296.  
  297. const newPosition = this.#calculateNewPosition(
  298. clientX - this.#dragOffset.x,
  299. clientY - this.#dragOffset.y
  300. );
  301.  
  302. this.#updateButtonPosition(newPosition);
  303. event.preventDefault();
  304. event.stopPropagation();
  305. }
  306.  
  307. /**
  308. * Calculates new button position
  309. * @private
  310. * @param {number} x
  311. * @param {number} y
  312. * @returns {{x: number, y: number}}
  313. */
  314. #calculateNewPosition(x, y) {
  315. const maxX = window.innerWidth - this.#button.offsetWidth;
  316. const maxY = window.innerHeight - this.#button.offsetHeight;
  317. return {
  318. x: Math.max(0, Math.min(x, maxX)),
  319. y: Math.max(0, Math.min(y, maxY)),
  320. };
  321. }
  322.  
  323. /**
  324. * Updates button position
  325. * @private
  326. * @param {{x: number, y: number}} position
  327. */
  328. #updateButtonPosition(position) {
  329. this.#button.style.left = `${position.x}px`;
  330. this.#button.style.top = `${position.y}px`;
  331. this.#button.style.right = "auto";
  332. this.#button.style.bottom = "auto";
  333. }
  334.  
  335. /**
  336. * Handles drag end
  337. * @private
  338. * @param {MouseEvent|TouchEvent} event
  339. */
  340. #handleDragEnd(event) {
  341. if (!this.#isDragging) return;
  342.  
  343. this.#button.style.transform = "scale(1)";
  344. const distance = this.#calculateDragDistance();
  345. const elapsedTime = Date.now() - this.#touchStartTime;
  346.  
  347. if (
  348. elapsedTime < CONSTANTS.TOUCH.CLICK_TIMEOUT &&
  349. distance <= CONSTANTS.TOUCH.MOVE_THRESHOLD &&
  350. event.button !== 2
  351. )
  352. this.#togglePIP();
  353.  
  354. const position = {
  355. x: this.#button.offsetLeft,
  356. y: this.#button.offsetTop,
  357. };
  358. if (!this.#isManuallyHidden)
  359. localStorage.setItem(
  360. CONSTANTS.STORAGE.POSITION_KEY,
  361. JSON.stringify(position)
  362. );
  363.  
  364. this.#isDragging = false;
  365. event.preventDefault();
  366. event.stopPropagation();
  367. }
  368.  
  369. /**
  370. * Calculates drag distance
  371. * @private
  372. * @returns {number}
  373. */
  374. #calculateDragDistance() {
  375. const dx = this.#button.offsetLeft - this.#initialPosition.x;
  376. const dy = this.#button.offsetTop - this.#initialPosition.y;
  377. return Math.sqrt(dx * dx + dy * dy);
  378. }
  379.  
  380. /**
  381. * Updates button visibility
  382. * @private
  383. */
  384. #updateButtonVisibility() {
  385. this.#button.style.display =
  386. this.#watchedVideos.size > 0 && !this.#isManuallyHidden
  387. ? "block"
  388. : "none";
  389. }
  390.  
  391. /**
  392. * Initializes handlers for long press and right-click
  393. * @private
  394. */
  395. #initializeLongPressHandlers() {
  396. this.#button.addEventListener("contextmenu", (e) => {
  397. e.preventDefault();
  398. this.#hideButton();
  399. });
  400.  
  401. const startLongPress = (e) => {
  402. const pos = e.touches ? e.touches[0] : e;
  403. this.#longPressStartPosition = { x: pos.clientX, y: pos.clientY };
  404.  
  405. this.#button.style.setProperty("--delete-progress", "0");
  406.  
  407. this.#animationTimer = setTimeout(() => {
  408. requestAnimationFrame(() => {
  409. this.#button.style.setProperty("--delete-progress", "1");
  410. });
  411. }, CONSTANTS.TOUCH.ANIMATION_DELAY);
  412.  
  413. this.#longPressTimer = setTimeout(() => {
  414. this.#hideButton();
  415. }, CONSTANTS.TOUCH.LONG_PRESS_TIMEOUT);
  416. };
  417.  
  418. const moveDuringPress = (e) => {
  419. if (this.#longPressTimer) {
  420. const pos = e.touches ? e.touches[0] : e;
  421. const moveDistance = Math.sqrt(
  422. Math.pow(pos.clientX - this.#longPressStartPosition.x, 2) +
  423. Math.pow(pos.clientY - this.#longPressStartPosition.y, 2)
  424. );
  425.  
  426. if (moveDistance > CONSTANTS.TOUCH.LONG_PRESS_MOVE_THRESHOLD) {
  427. clearTimeout(this.#longPressTimer);
  428. clearTimeout(this.#animationTimer);
  429. this.#longPressTimer = null;
  430. this.#animationTimer = null;
  431. this.#button.style.setProperty("--delete-progress", "0");
  432. }
  433. }
  434. };
  435.  
  436. const endLongPress = () => {
  437. if (this.#longPressTimer) {
  438. clearTimeout(this.#longPressTimer);
  439. clearTimeout(this.#animationTimer);
  440. this.#button.style.setProperty("--delete-progress", "0");
  441. }
  442. };
  443.  
  444. // Touch events
  445. this.#button.addEventListener("touchstart", startLongPress);
  446. this.#button.addEventListener("touchmove", moveDuringPress);
  447. this.#button.addEventListener("touchend", endLongPress);
  448.  
  449. // Mouse events
  450. this.#button.addEventListener("mousedown", (e) => {
  451. if (e.button === 0) startLongPress(e);
  452. });
  453. this.#button.addEventListener("mousemove", moveDuringPress);
  454. this.#button.addEventListener("mouseup", endLongPress);
  455. this.#button.addEventListener("mouseleave", endLongPress);
  456. }
  457.  
  458. /**
  459. * Hides the PIP button
  460. * @private
  461. */
  462. #hideButton() {
  463. this.#isManuallyHidden = true;
  464. this.#button.style.display = "none";
  465. }
  466.  
  467. #loadButtonPosition() {
  468. const savedPosition = localStorage.getItem(
  469. CONSTANTS.STORAGE.POSITION_KEY
  470. );
  471. if (savedPosition) {
  472. const position = JSON.parse(savedPosition);
  473. this.#updateButtonPosition(position);
  474. } else {
  475. this.#button.style.right = `${CONSTANTS.BUTTON.DEFAULT_POSITION.right}px`;
  476. this.#button.style.bottom = `${CONSTANTS.BUTTON.DEFAULT_POSITION.bottom}px`;
  477. }
  478. }
  479. }
  480.  
  481. if (document.readyState === "loading")
  482. document.addEventListener("DOMContentLoaded", () => new PIPButton());
  483. else new PIPButton();
  484. })();