YouTube Viewfinding

Zoom, rotate & crop YouTube videos

目前為 2025-05-23 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name YouTube Viewfinding
  3. // @version 0.24
  4. // @description Zoom, rotate & crop YouTube videos
  5. // @author Callum Latham
  6. // @namespace https://greasyfork.org/users/696211-ctl2
  7. // @license GNU GPLv3
  8. // @compatible chrome
  9. // @compatible edge
  10. // @compatible firefox Video dimensions affect page scrolling
  11. // @compatible opera Video dimensions affect page scrolling
  12. // @match *://www.youtube.com/*
  13. // @match *://youtube.com/*
  14. // @require https://update.greasyfork.org/scripts/446506/1588535/%24Config.js
  15. // @grant GM.setValue
  16. // @grant GM.getValue
  17. // @grant GM.deleteValue
  18. // ==/UserScript==
  19.  
  20. /* global $Config */
  21.  
  22. (() => {
  23. const isEmbed = window.location.pathname.split('/')[1] === 'embed';
  24.  
  25. // Don't run in non-embed frames (e.g. stream chat frame)
  26. if (window.parent !== window && !isEmbed) {
  27. return;
  28. }
  29.  
  30. const VAR_ZOOM = '--viewfind-zoom';
  31. const LIMITS = {none: 'None', static: 'Static', fit: 'Fit'};
  32.  
  33. const $config = new $Config(
  34. 'VIEWFIND_TREE',
  35. (() => {
  36. const isCSSRule = (() => {
  37. const wrapper = document.createElement('style');
  38. const regex = /\s/g;
  39. return (property, text) => {
  40. const ruleText = `${property}:${text};`;
  41. document.head.appendChild(wrapper);
  42. wrapper.sheet.insertRule(`:not(*){${ruleText}}`);
  43. const [{style: {cssText}}] = wrapper.sheet.cssRules;
  44. wrapper.remove();
  45. return cssText.replaceAll(regex, '') === ruleText.replaceAll(regex, '') || `Must be a valid CSS ${property} rule`;
  46. };
  47. })();
  48. const getHideId = (() => {
  49. let id = -1;
  50. return () => ++id;
  51. })();
  52. const glowHideId = getHideId();
  53. return {
  54. get: (_, configs) => Object.assign(...configs),
  55. children: [
  56. {
  57. label: 'Controls',
  58. children: [
  59. {
  60. label: 'Keybinds',
  61. descendantPredicate: ([actions, reset, configure]) => {
  62. const keybinds = [...actions.children.slice(1), reset, configure].map(({children}) => children.filter(({value}) => value !== '').map(({value}) => value));
  63. for (let i = 0; i < keybinds.length - 1; ++i) {
  64. for (let j = i + 1; j < keybinds.length; ++j) {
  65. if (keybinds[i].length === keybinds[j].length && keybinds[i].every((keyA) => keybinds[j].some((keyB) => keyA === keyB))) {
  66. return 'Another action has this keybind';
  67. }
  68. }
  69. }
  70. return true;
  71. },
  72. get: (_, configs) => ({keys: Object.assign(...configs)}),
  73. children: (() => {
  74. const seed = {
  75. value: '',
  76. listeners: {
  77. keydown: (event) => {
  78. switch (event.key) {
  79. case 'Enter':
  80. case 'Escape':
  81. return;
  82. }
  83. event.preventDefault();
  84. event.target.value = event.code;
  85. event.target.dispatchEvent(new InputEvent('input'));
  86. },
  87. },
  88. };
  89. const getKeys = (children) => new Set(children.filter(({value}) => value !== '').map(({value}) => value));
  90. const getNode = (label, keys, get) => ({
  91. label,
  92. seed,
  93. children: keys.map((value) => ({...seed, value})),
  94. get,
  95. });
  96. return [
  97. {
  98. label: 'Actions',
  99. get: (_, [toggle, ...controls]) => Object.assign(...controls.map(({id, keys}) => ({
  100. [id]: {
  101. toggle,
  102. keys,
  103. },
  104. }))),
  105. children: [
  106. {
  107. label: 'Toggle?',
  108. value: false,
  109. get: ({value}) => value,
  110. },
  111. ...[
  112. ['Pan / Zoom', ['KeyZ'], 'pan'],
  113. ['Rotate', ['IntlBackslash'], 'rotate'],
  114. ['Crop', ['KeyZ', 'IntlBackslash'], 'crop'],
  115. ].map(([label, keys, id]) => getNode(label, keys, ({children}) => ({id, keys: getKeys(children)}))),
  116. ],
  117. },
  118. getNode('Reset', ['KeyX'], ({children}) => ({reset: {keys: getKeys(children)}})),
  119. getNode('Configure', ['AltLeft', 'KeyX'], ({children}) => ({config: {keys: getKeys(children)}})),
  120. ];
  121. })(),
  122. },
  123. {
  124. label: 'Scroll Speeds',
  125. get: (_, configs) => ({speeds: Object.assign(...configs)}),
  126. children: [
  127. {
  128. label: 'Zoom',
  129. value: -100,
  130. get: ({value}) => ({zoom: value / 150000}),
  131. },
  132. {
  133. label: 'Rotate',
  134. value: -100,
  135. // 150000 * (5 - 0.8) / 2π ≈ 100000
  136. get: ({value}) => ({rotate: value / 100000}),
  137. },
  138. {
  139. label: 'Crop',
  140. value: -100,
  141. get: ({value}) => ({crop: value / 300000}),
  142. },
  143. ],
  144. },
  145. {
  146. label: 'Drag Inversions',
  147. get: (_, configs) => ({multipliers: Object.assign(...configs)}),
  148. children: [
  149. ['Pan', 'pan'],
  150. ['Rotate', 'rotate'],
  151. ['Crop', 'crop'],
  152. ].map(([label, key, value = false]) => ({
  153. label,
  154. value,
  155. get: ({value}) => ({[key]: value ? -1 : 1}),
  156. })),
  157. },
  158. {
  159. label: 'Click Movement Allowance (px)',
  160. value: 2,
  161. predicate: (value) => value >= 0 || 'Allowance must be positive',
  162. inputAttributes: {min: 0},
  163. get: ({value: clickCutoff}) => ({clickCutoff}),
  164. },
  165. ],
  166. },
  167. {
  168. label: 'Behaviour',
  169. children: [
  170. ...(() => {
  171. const typeNode = {
  172. label: 'Type',
  173. get: ({value}) => ({type: value}),
  174. };
  175. const hiddenNodes = {
  176. [LIMITS.static]: {
  177. label: 'Value (%)',
  178. predicate: (value) => value >= 0 || 'Limit must be positive',
  179. inputAttributes: {min: 0},
  180. get: ({value}) => ({custom: value / 100}),
  181. },
  182. [LIMITS.fit]: {
  183. label: 'Glow Allowance (%)',
  184. predicate: (value) => value >= 0 || 'Allowance must be positive',
  185. inputAttributes: {min: 0},
  186. get: ({value}) => ({frame: value / 100}),
  187. },
  188. };
  189. const getNode = (label, key, value, options, ...hidden) => {
  190. const hideIds = {};
  191. const children = [{...typeNode, value, options}];
  192. for (const {id, value} of hidden) {
  193. const node = {...hiddenNodes[id], value, hideId: getHideId()};
  194. hideIds[node.hideId] = id;
  195. children.push(node);
  196. }
  197. if (hidden.length > 0) {
  198. children[0].onUpdate = (value) => {
  199. const hide = {};
  200. for (const [id, type] of Object.entries(hideIds)) {
  201. hide[id] = value !== type;
  202. }
  203. return {hide};
  204. };
  205. }
  206. return {
  207. label,
  208. get: (_, configs) => ({[key]: Object.assign(...configs)}),
  209. children,
  210. };
  211. };
  212. return [
  213. getNode(
  214. 'Zoom In Limit',
  215. 'zoomInLimit',
  216. LIMITS.static,
  217. [LIMITS.none, LIMITS.static, LIMITS.fit],
  218. {id: LIMITS.static, value: 500},
  219. {id: LIMITS.fit, value: 0},
  220. ),
  221. getNode(
  222. 'Zoom Out Limit',
  223. 'zoomOutLimit',
  224. LIMITS.static,
  225. [LIMITS.none, LIMITS.static, LIMITS.fit],
  226. {id: LIMITS.static, value: 80},
  227. {id: LIMITS.fit, value: 300},
  228. ),
  229. getNode(
  230. 'Pan Limit',
  231. 'panLimit',
  232. LIMITS.static,
  233. [LIMITS.none, LIMITS.static, LIMITS.fit],
  234. {id: LIMITS.static, value: 50},
  235. ),
  236. getNode(
  237. 'Snap Pan Limit',
  238. 'snapPanLimit',
  239. LIMITS.fit,
  240. [LIMITS.none, LIMITS.fit],
  241. ),
  242. ];
  243. })(),
  244. {
  245. label: 'While Viewfinding',
  246. get: (_, configs) => {
  247. const {overlayKill, overlayHide, ...config} = Object.assign(...configs);
  248. return {
  249. active: {
  250. overlayRule: overlayKill && [overlayHide ? 'display' : 'pointer-events', 'none'],
  251. ...config,
  252. },
  253. };
  254. },
  255. children: [
  256. {
  257. label: 'Pause Video?',
  258. value: false,
  259. get: ({value: pause}) => ({pause}),
  260. },
  261. {
  262. label: 'Hide Glow?',
  263. value: false,
  264. get: ({value: hideGlow}) => ({hideGlow}),
  265. hideId: glowHideId,
  266. },
  267. ...((hideId) => [
  268. {
  269. label: 'Disable Overlay?',
  270. value: true,
  271. get: ({value: overlayKill}, configs) => Object.assign({overlayKill}, ...configs),
  272. onUpdate: (value) => ({hide: {[hideId]: !value}}),
  273. children: [
  274. {
  275. label: 'Hide Overlay?',
  276. value: false,
  277. get: ({value: overlayHide}) => ({overlayHide}),
  278. hideId,
  279. },
  280. ],
  281. },
  282. ])(getHideId()),
  283. ],
  284. },
  285. ],
  286. },
  287. {
  288. label: 'Glow',
  289. value: true,
  290. onUpdate: (value) => ({hide: {[glowHideId]: !value}}),
  291. get: ({value: on}, configs) => {
  292. if (!on) {
  293. return {};
  294. }
  295. const {turnover, ...config} = Object.assign(...configs);
  296. const sampleCount = Math.floor(config.fps * turnover);
  297. // avoid taking more samples than there's space for
  298. if (sampleCount > config.size) {
  299. const fps = config.size / turnover;
  300. return {
  301. glow: {
  302. ...config,
  303. sampleCount: config.size,
  304. interval: 1000 / fps,
  305. fps,
  306. },
  307. };
  308. }
  309. return {
  310. glow: {
  311. ...config,
  312. interval: 1000 / config.fps,
  313. sampleCount,
  314. },
  315. };
  316. },
  317. children: [
  318. (() => {
  319. const [seed, getChild] = (() => {
  320. const options = ['blur', 'brightness', 'contrast', 'drop-shadow', 'grayscale', 'hue-rotate', 'invert', 'opacity', 'saturate', 'sepia'];
  321. const ids = {};
  322. const hide = {};
  323. for (const option of options) {
  324. ids[option] = getHideId();
  325. hide[ids[option]] = true;
  326. }
  327. const min0Amount = {
  328. label: 'Amount (%)',
  329. value: 100,
  330. predicate: (value) => value >= 0 || 'Amount must be positive',
  331. inputAttributes: {min: 0},
  332. };
  333. const max100Amount = {
  334. label: 'Amount (%)',
  335. value: 0,
  336. predicate: (value) => {
  337. if (value < 0) {
  338. return 'Amount must be positive';
  339. }
  340. return value <= 100 || 'Amount may not exceed 100%';
  341. },
  342. inputAttributes: {min: 0, max: 100},
  343. };
  344. const getScaled = (value) => `calc(${value}px/var(${VAR_ZOOM}))`;
  345. const root = {
  346. label: 'Function',
  347. options,
  348. value: options[0],
  349. get: ({value}, configs) => {
  350. const config = Object.assign(...configs);
  351. switch (value) {
  352. case options[0]:
  353. return {
  354. filter: config.blurScale ? `blur(${config.blur}px)` : `blur(${getScaled(config.blur)})`,
  355. blur: {
  356. x: config.blur,
  357. y: config.blur,
  358. scale: config.blurScale,
  359. },
  360. };
  361. case options[3]:
  362. return {
  363. filter: config.shadowScale ?
  364. `drop-shadow(${config.shadow} ${config.shadowX}px ${config.shadowY}px ${config.shadowSpread}px)` :
  365. `drop-shadow(${config.shadow} ${getScaled(config.shadowX)} ${getScaled(config.shadowY)} ${getScaled(config.shadowSpread)})`,
  366. blur: {
  367. x: config.shadowSpread + Math.abs(config.shadowX),
  368. y: config.shadowSpread + Math.abs(config.shadowY),
  369. scale: config.shadowScale,
  370. },
  371. };
  372. case options[5]:
  373. return {filter: `hue-rotate(${config.hueRotate}deg)`};
  374. }
  375. return {filter: `${value}(${config[value]}%)`};
  376. },
  377. onUpdate: (value) => ({hide: {...hide, [ids[value]]: false}}),
  378. };
  379. const children = {
  380. 'blur': [
  381. {
  382. label: 'Distance (px)',
  383. value: 0,
  384. get: ({value}) => ({blur: value}),
  385. predicate: (value) => value >= 0 || 'Distance must be positive',
  386. inputAttributes: {min: 0},
  387. hideId: ids.blur,
  388. },
  389. {
  390. label: 'Scale?',
  391. value: false,
  392. get: ({value}) => ({blurScale: value}),
  393. hideId: ids.blur,
  394. },
  395. ],
  396. 'brightness': [
  397. {
  398. ...min0Amount,
  399. hideId: ids.brightness,
  400. get: ({value}) => ({brightness: value}),
  401. },
  402. ],
  403. 'contrast': [
  404. {
  405. ...min0Amount,
  406. hideId: ids.contrast,
  407. get: ({value}) => ({contrast: value}),
  408. },
  409. ],
  410. 'drop-shadow': [
  411. {
  412. label: 'Colour',
  413. input: 'color',
  414. value: '#FFFFFF',
  415. get: ({value}) => ({shadow: value}),
  416. hideId: ids['drop-shadow'],
  417. },
  418. {
  419. label: 'Horizontal Offset (px)',
  420. value: 0,
  421. get: ({value}) => ({shadowX: value}),
  422. hideId: ids['drop-shadow'],
  423. },
  424. {
  425. label: 'Vertical Offset (px)',
  426. value: 0,
  427. get: ({value}) => ({shadowY: value}),
  428. hideId: ids['drop-shadow'],
  429. },
  430. {
  431. label: 'Spread (px)',
  432. value: 0,
  433. predicate: (value) => value >= 0 || 'Spread must be positive',
  434. inputAttributes: {min: 0},
  435. get: ({value}) => ({shadowSpread: value}),
  436. hideId: ids['drop-shadow'],
  437. },
  438. {
  439. label: 'Scale?',
  440. value: true,
  441. get: ({value}) => ({shadowScale: value}),
  442. hideId: ids['drop-shadow'],
  443. },
  444. ],
  445. 'grayscale': [
  446. {
  447. ...max100Amount,
  448. hideId: ids.grayscale,
  449. get: ({value}) => ({grayscale: value}),
  450. },
  451. ],
  452. 'hue-rotate': [
  453. {
  454. label: 'Angle (deg)',
  455. value: 0,
  456. get: ({value}) => ({hueRotate: value}),
  457. hideId: ids['hue-rotate'],
  458. },
  459. ],
  460. 'invert': [
  461. {
  462. ...max100Amount,
  463. hideId: ids.invert,
  464. get: ({value}) => ({invert: value}),
  465. },
  466. ],
  467. 'opacity': [
  468. {
  469. ...max100Amount,
  470. value: 100,
  471. hideId: ids.opacity,
  472. get: ({value}) => ({opacity: value}),
  473. },
  474. ],
  475. 'saturate': [
  476. {
  477. ...min0Amount,
  478. hideId: ids.saturate,
  479. get: ({value}) => ({saturate: value}),
  480. },
  481. ],
  482. 'sepia': [
  483. {
  484. ...max100Amount,
  485. hideId: ids.sepia,
  486. get: ({value}) => ({sepia: value}),
  487. },
  488. ],
  489. };
  490. return [
  491. {...root, children: Object.values(children).flat()}, (id, ...values) => {
  492. const replacements = [];
  493. for (const [i, child] of children[id].entries()) {
  494. replacements.push({...child, value: values[i]});
  495. }
  496. return {
  497. ...root,
  498. value: id,
  499. children: Object.values({...children, [id]: replacements}).flat(),
  500. };
  501. },
  502. ];
  503. })();
  504. return {
  505. label: 'Filter',
  506. get: (_, configs) => {
  507. const scaled = {x: 0, y: 0};
  508. const unscaled = {x: 0, y: 0};
  509. let filter = '';
  510. for (const config of configs) {
  511. filter += config.filter;
  512. if ('blur' in config) {
  513. const target = config.blur.scale ? scaled : unscaled;
  514. target.x = Math.max(target.x, config.blur.x);
  515. target.y = Math.max(target.y, config.blur.y);
  516. }
  517. }
  518. return {filter, blur: {scaled, unscaled}};
  519. },
  520. children: [
  521. getChild('saturate', 150),
  522. getChild('brightness', 150),
  523. getChild('blur', 25, false),
  524. ],
  525. seed,
  526. };
  527. })(),
  528. {
  529. label: 'Update',
  530. childPredicate: ([{value: fps}, {value: turnover}]) => fps * turnover >= 1 || `${turnover} second turnover cannot be achieved at ${fps} hertz`,
  531. children: [
  532. {
  533. label: 'Frequency (Hz)',
  534. value: 15,
  535. predicate: (value) => {
  536. if (value > 144) {
  537. return 'Update frequency may not be above 144 hertz';
  538. }
  539. return value >= 0 || 'Update frequency must be positive';
  540. },
  541. inputAttributes: {min: 0, max: 144},
  542. get: ({value: fps}) => ({fps}),
  543. },
  544. {
  545. label: 'Turnover Time (s)',
  546. value: 3,
  547. predicate: (value) => value >= 0 || 'Turnover time must be positive',
  548. inputAttributes: {min: 0},
  549. get: ({value: turnover}) => ({turnover}),
  550. },
  551. {
  552. label: 'Reverse?',
  553. value: false,
  554. get: ({value: doFlip}) => ({doFlip}),
  555. },
  556. ],
  557. },
  558. {
  559. label: 'Size (px)',
  560. value: 50,
  561. predicate: (value) => value >= 0 || 'Size must be positive',
  562. inputAttributes: {min: 0},
  563. get: ({value}) => ({size: value}),
  564. },
  565. {
  566. label: 'End Point (%)',
  567. value: 103,
  568. predicate: (value) => value >= 0 || 'End point must be positive',
  569. inputAttributes: {min: 0},
  570. get: ({value}) => ({end: value / 100}),
  571. },
  572. ].map((node) => ({...node, hideId: glowHideId})),
  573. },
  574. {
  575. label: 'Interfaces',
  576. children: [
  577. {
  578. label: 'Crop',
  579. get: (_, configs) => ({crop: Object.assign(...configs)}),
  580. children: [
  581. {
  582. label: 'Colours',
  583. get: (_, configs) => ({colour: Object.assign(...configs)}),
  584. children: [
  585. {
  586. label: 'Fill',
  587. get: (_, [colour, opacity]) => ({fill: `${colour}${opacity}`}),
  588. children: [
  589. {
  590. label: 'Colour',
  591. value: '#808080',
  592. input: 'color',
  593. get: ({value}) => value,
  594. },
  595. {
  596. label: 'Opacity (%)',
  597. value: 40,
  598. predicate: (value) => {
  599. if (value < 0) {
  600. return 'Opacity must be positive';
  601. }
  602. return value <= 100 || 'Opacity may not exceed 100%';
  603. },
  604. inputAttributes: {min: 0, max: 100},
  605. get: ({value}) => Math.round(255 * value / 100).toString(16),
  606. },
  607. ],
  608. },
  609. {
  610. label: 'Shadow',
  611. value: '#000000',
  612. input: 'color',
  613. get: ({value: shadow}) => ({shadow}),
  614. },
  615. {
  616. label: 'Border',
  617. value: '#ffffff',
  618. input: 'color',
  619. get: ({value: border}) => ({border}),
  620. },
  621. ],
  622. },
  623. {
  624. label: 'Handle Size (%)',
  625. value: 6,
  626. predicate: (value) => {
  627. if (value < 0) {
  628. return 'Size must be positive';
  629. }
  630. return value <= 50 || 'Size may not exceed 50%';
  631. },
  632. inputAttributes: {min: 0, max: 50},
  633. get: ({value}) => ({handle: value / 100}),
  634. },
  635. ],
  636. },
  637. {
  638. label: 'Crosshair',
  639. get: (value, configs) => ({crosshair: Object.assign(...configs)}),
  640. children: [
  641. {
  642. label: 'Show Pan Limits?',
  643. value: true,
  644. get: ({value: showFrame}) => ({showFrame}),
  645. },
  646. {
  647. label: 'Outer Thickness (px)',
  648. value: 3,
  649. predicate: (value) => value >= 0 || 'Thickness must be positive',
  650. inputAttributes: {min: 0},
  651. get: ({value: outer}) => ({outer}),
  652. },
  653. {
  654. label: 'Inner Thickness (px)',
  655. value: 1,
  656. predicate: (value) => value >= 0 || 'Thickness must be positive',
  657. inputAttributes: {min: 0},
  658. get: ({value: inner}) => ({inner}),
  659. },
  660. {
  661. label: 'Inner Diameter (px)',
  662. value: 157,
  663. predicate: (value) => value >= 0 || 'Diameter must be positive',
  664. inputAttributes: {min: 0},
  665. get: ({value: gap}) => ({gap}),
  666. },
  667. ((hideId) => ({
  668. label: 'Text',
  669. value: true,
  670. onUpdate: (value) => ({hide: {[hideId]: !value}}),
  671. get: ({value}, configs) => {
  672. if (!value) {
  673. return {};
  674. }
  675. const {translateX, translateY, ...config} = Object.assign(...configs);
  676. return {
  677. text: {
  678. translate: {
  679. x: translateX,
  680. y: translateY,
  681. },
  682. ...config,
  683. },
  684. };
  685. },
  686. children: [
  687. {
  688. label: 'Font',
  689. value: '30px "Harlow Solid", cursive',
  690. predicate: isCSSRule.bind(null, 'font'),
  691. get: ({value: font}) => ({font}),
  692. },
  693. {
  694. label: 'Position (%)',
  695. get: (_, configs) => ({position: Object.assign(...configs)}),
  696. children: ['x', 'y'].map((label) => ({
  697. label,
  698. value: 0,
  699. predicate: (value) => Math.abs(value) <= 50 || 'Position must be on-screen',
  700. inputAttributes: {min: -50, max: 50},
  701. get: ({value}) => ({[label]: value + 50}),
  702. })),
  703. },
  704. {
  705. label: 'Offset (px)',
  706. get: (_, configs) => ({offset: Object.assign(...configs)}),
  707. children: [
  708. {
  709. label: 'x',
  710. value: -6,
  711. get: ({value: x}) => ({x}),
  712. },
  713. {
  714. label: 'y',
  715. value: -25,
  716. get: ({value: y}) => ({y}),
  717. },
  718. ],
  719. },
  720. (() => {
  721. const options = ['Left', 'Center', 'Right'];
  722. return {
  723. label: 'Alignment',
  724. value: options[2],
  725. options,
  726. get: ({value}) => ({align: value.toLowerCase(), translateX: options.indexOf(value) * -50}),
  727. };
  728. })(),
  729. (() => {
  730. const options = ['Top', 'Middle', 'Bottom'];
  731. return {
  732. label: 'Baseline',
  733. value: options[0],
  734. options,
  735. get: ({value}) => ({translateY: options.indexOf(value) * -50}),
  736. };
  737. })(),
  738. {
  739. label: 'Line height (%)',
  740. value: 90,
  741. predicate: (value) => value >= 0 || 'Height must be positive',
  742. inputAttributes: {min: 0},
  743. get: ({value}) => ({height: value / 100}),
  744. },
  745. ].map((node) => ({...node, hideId})),
  746. }))(getHideId()),
  747. {
  748. label: 'Colours',
  749. get: (_, configs) => ({colour: Object.assign(...configs)}),
  750. children: [
  751. {
  752. label: 'Fill',
  753. value: '#ffffff',
  754. input: 'color',
  755. get: ({value: fill}) => ({fill}),
  756. },
  757. {
  758. label: 'Shadow',
  759. value: '#000000',
  760. input: 'color',
  761. get: ({value: shadow}) => ({shadow}),
  762. },
  763. ],
  764. },
  765. ],
  766. },
  767. ],
  768. },
  769. ],
  770. };
  771. })(),
  772. {
  773. defaultStyle: {
  774. headBase: '#c80000',
  775. headButtonExit: '#000000',
  776. borderHead: '#ffffff',
  777. borderTooltip: '#c80000',
  778. width: Math.min(90, screen.width / 16),
  779. height: 90,
  780. },
  781. outerStyle: {
  782. zIndex: 10000,
  783. scrollbarColor: 'initial',
  784. },
  785. patches: [
  786. // removing "Glow Allowance" from pan limits
  787. ({children: [, {children}]}) => {
  788. // pan
  789. children[2].children.splice(2, 1);
  790. // snap pan
  791. children[3].children.splice(1, 1);
  792. },
  793. ({children: [,,,{children: [,{children}]}]}) => {
  794. children.splice(0, 0, {
  795. label: 'Show Pan Limits?',
  796. value: true,
  797. });
  798. },
  799. ],
  800. },
  801. );
  802.  
  803. const CLASS_VIEWFINDER = 'viewfind-element';
  804. const DEGREES = {
  805. 45: Math.PI / 4,
  806. 90: Math.PI / 2,
  807. 180: Math.PI,
  808. 270: Math.PI / 2 * 3,
  809. 360: Math.PI * 2,
  810. };
  811. const SELECTOR_VIDEO = '#movie_player video.html5-main-video';
  812.  
  813. // STATE
  814.  
  815. // elements
  816. let video;
  817. let altTarget;
  818. let viewport;
  819. let cinematics;
  820.  
  821. // derived values
  822. let viewportTheta;
  823. let videoTheta;
  824. let videoHypotenuse;
  825. let isThin;
  826. let viewportRatio;
  827. let viewportRatioInverse;
  828. const halfDimensions = {video: {}, viewport: {}};
  829.  
  830. // other
  831. let stopped = true;
  832. let stopDrag;
  833.  
  834. const handleVideoChange = () => {
  835. DimensionCache.id++;
  836. halfDimensions.video.width = video.clientWidth / 2;
  837. halfDimensions.video.height = video.clientHeight / 2;
  838. videoTheta = getTheta(0, 0, video.clientWidth, video.clientHeight);
  839. videoHypotenuse = Math.sqrt(halfDimensions.video.width * halfDimensions.video.width + halfDimensions.video.height * halfDimensions.video.height);
  840. };
  841.  
  842. const handleViewportChange = () => {
  843. DimensionCache.id++;
  844. isThin = getTheta(0, 0, viewport.clientWidth, viewport.clientHeight) < videoTheta;
  845. halfDimensions.viewport.width = viewport.clientWidth / 2;
  846. halfDimensions.viewport.height = viewport.clientHeight / 2;
  847. viewportTheta = getTheta(0, 0, viewport.clientWidth, viewport.clientHeight);
  848. viewportRatio = viewport.clientWidth / viewport.clientHeight;
  849. viewportRatioInverse = 1 / viewportRatio;
  850. position.constrain();
  851. glow.handleViewChange(true);
  852. };
  853.  
  854. // ROTATION HELPERS
  855.  
  856. const getTheta = (fromX, fromY, toX, toY) => Math.atan2(toY - fromY, toX - fromX);
  857.  
  858. const getRotatedCorners = (radius, theta) => {
  859. const angle0 = DEGREES[90] - theta + rotation.value;
  860. const angle1 = theta + rotation.value - DEGREES[90];
  861. return [
  862. {
  863. x: Math.abs(radius * Math.cos(angle0)),
  864. y: Math.abs(radius * Math.sin(angle0)),
  865. },
  866. {
  867. x: Math.abs(radius * Math.cos(angle1)),
  868. y: Math.abs(radius * Math.sin(angle1)),
  869. },
  870. ];
  871. };
  872.  
  873. // CSS HELPER
  874.  
  875. const css = new function () {
  876. this.has = (name) => document.body.classList.contains(name);
  877. this.tag = (name, doAdd = true) => document.body.classList[doAdd ? 'add' : 'remove'](name);
  878. this.getSelector = (...classes) => `body.${classes.join('.')}`;
  879. const getSheet = () => {
  880. const element = document.createElement('style');
  881. document.head.appendChild(element);
  882. return element.sheet;
  883. };
  884. const getRuleString = (selector, ...declarations) => `${selector}{${declarations.map(([property, value]) => `${property}:${value};`).join('')}}`;
  885. this.add = function (...rule) {
  886. this.insertRule(getRuleString(...rule));
  887. }.bind(getSheet());
  888. this.Toggleable = class {
  889. static sheet = getSheet();
  890. static active = [];
  891. static id = 0;
  892. static add(rule, id) {
  893. this.sheet.insertRule(rule, this.active.length);
  894. this.active.push(id);
  895. }
  896. static remove(id) {
  897. let index = this.active.indexOf(id);
  898. while (index >= 0) {
  899. this.sheet.deleteRule(index);
  900. this.active.splice(index, 1);
  901. index = this.active.indexOf(id);
  902. }
  903. }
  904. id = this.constructor.id++;
  905. add(...rule) {
  906. this.constructor.add(getRuleString(...rule), this.id);
  907. }
  908. remove() {
  909. this.constructor.remove(this.id);
  910. }
  911. };
  912. }();
  913.  
  914. // ACTION MANAGER
  915.  
  916. const enabler = new function () {
  917. this.CLASS_ABLE = 'viewfind-action-able';
  918. this.CLASS_DRAGGING = 'viewfind-action-dragging';
  919. this.keys = new Set();
  920. this.didPause = false;
  921. this.isHidingGlow = false;
  922. this.setActive = (action) => {
  923. const {active, keys} = $config.get();
  924. if (active.hideGlow && Boolean(action) !== this.isHidingGlow) {
  925. if (action) {
  926. this.isHidingGlow = true;
  927. glow.hide();
  928. } else if (this.isHidingGlow) {
  929. this.isHidingGlow = false;
  930. glow.show();
  931. }
  932. }
  933. this.activeAction?.onInactive?.();
  934. if (action) {
  935. this.activeAction = action;
  936. this.toggled = keys[action.CODE].toggle;
  937. action.onActive?.();
  938. if (active.pause && !video.paused) {
  939. video.pause();
  940. this.didPause = true;
  941. }
  942. return;
  943. }
  944. if (this.didPause) {
  945. video.play();
  946. this.didPause = false;
  947. }
  948. this.activeAction = this.toggled = undefined;
  949. };
  950. this.handleChange = () => {
  951. if (stopped || stopDrag || video.ended) {
  952. return;
  953. }
  954. const {keys} = $config.get();
  955. let activeAction;
  956. for (const action of Object.values(actions)) {
  957. if (
  958. keys[action.CODE].keys.size === 0 || !this.keys.isSupersetOf(keys[action.CODE].keys) || activeAction && ('toggle' in keys[action.CODE] ?
  959. !('toggle' in keys[activeAction.CODE]) || keys[activeAction.CODE].keys.size >= keys[action.CODE].keys.size :
  960. !('toggle' in keys[activeAction.CODE]) && keys[activeAction.CODE].keys.size >= keys[action.CODE].keys.size)
  961. ) {
  962. if ('CLASS_ABLE' in action) {
  963. css.tag(action.CLASS_ABLE, false);
  964. }
  965. continue;
  966. }
  967. if (activeAction && 'CLASS_ABLE' in activeAction) {
  968. css.tag(activeAction.CLASS_ABLE, false);
  969. }
  970. activeAction = action;
  971. }
  972. if (activeAction === this.activeAction) {
  973. return;
  974. }
  975. if (activeAction) {
  976. if ('CLASS_ABLE' in activeAction) {
  977. css.tag(activeAction.CLASS_ABLE);
  978. css.tag(this.CLASS_ABLE);
  979. this.setActive(activeAction);
  980. return;
  981. }
  982. this.activeAction?.onInactive?.();
  983. activeAction.onActive();
  984. this.activeAction = activeAction;
  985. }
  986. css.tag(this.CLASS_ABLE, false);
  987. this.setActive(false);
  988. };
  989. this.stop = () => {
  990. css.tag(this.CLASS_ABLE, false);
  991. for (const action of Object.values(actions)) {
  992. if ('CLASS_ABLE' in action) {
  993. css.tag(action.CLASS_ABLE, false);
  994. }
  995. }
  996. this.setActive(false);
  997. };
  998. this.updateConfig = (() => {
  999. const rule = new css.Toggleable();
  1000. const selector = `${css.getSelector(this.CLASS_ABLE)} #contentContainer.tp-yt-app-drawer[swipe-open]::after`
  1001. + `,${css.getSelector(this.CLASS_ABLE)} #movie_player > .html5-video-container ~ :not(.${CLASS_VIEWFINDER})`;
  1002. return () => {
  1003. const {overlayRule} = $config.get().active;
  1004. rule.remove();
  1005. if (overlayRule) {
  1006. rule.add(selector, overlayRule);
  1007. }
  1008. };
  1009. })();
  1010. $config.ready.then(() => {
  1011. this.updateConfig();
  1012. });
  1013. // insertion order decides priority
  1014. css.add(`${css.getSelector(this.CLASS_DRAGGING)} #movie_player`, ['cursor', 'grabbing']);
  1015. css.add(`${css.getSelector(this.CLASS_ABLE)} #movie_player`, ['cursor', 'grab']);
  1016. }();
  1017.  
  1018. // ELEMENT CONTAINER SETUP
  1019.  
  1020. const containers = new function () {
  1021. for (const name of ['background', 'foreground', 'tracker']) {
  1022. this[name] = document.createElement('div');
  1023. this[name].classList.add(CLASS_VIEWFINDER);
  1024. }
  1025. // make an outline of the uncropped video
  1026. css.add(`${css.getSelector(enabler.CLASS_ABLE)} #${this.foreground.id = 'viewfind-outlined'}`, ['outline', '1px solid white']);
  1027. this.background.style.position = this.foreground.style.position = 'absolute';
  1028. this.background.style.pointerEvents = this.foreground.style.pointerEvents = this.tracker.style.pointerEvents = 'none';
  1029. this.tracker.style.height = this.tracker.style.width = '100%';
  1030. }();
  1031.  
  1032. // CACHE
  1033.  
  1034. class Cache {
  1035. targets = [];
  1036. constructor(...targets) {
  1037. for (const source of targets) {
  1038. this.targets.push({source});
  1039. }
  1040. }
  1041. update(target) {
  1042. return target.value !== (target.value = target.source.value);
  1043. }
  1044. isStale() {
  1045. return this.targets.reduce((value, target) => value || this.update(target), false);
  1046. }
  1047. }
  1048.  
  1049. class ConfigCache extends Cache {
  1050. static id = 0;
  1051. id = this.constructor.id;
  1052. constructor(...targets) {
  1053. super(...targets);
  1054. }
  1055. isStale() {
  1056. if (this.id === (this.id = this.constructor.id)) {
  1057. return super.isStale();
  1058. }
  1059. for (const target of this.targets) {
  1060. target.value = target.source.value;
  1061. }
  1062. return true;
  1063. }
  1064. }
  1065.  
  1066. class DimensionCache extends ConfigCache {
  1067. static id = 0;
  1068. }
  1069.  
  1070. // MODIFIERS
  1071.  
  1072. const rotation = new function () {
  1073. this.value = DEGREES[90];
  1074. this.reset = () => {
  1075. this.value = DEGREES[90];
  1076. video.style.removeProperty('rotate');
  1077. };
  1078. this.apply = () => {
  1079. // Conversion from anticlockwise rotation from the x-axis to clockwise rotation from the y-axis
  1080. video.style.setProperty('rotate', `${DEGREES[90] - this.value}rad`);
  1081. delete actions.reset.restore;
  1082. };
  1083. // dissimilar from other constrain functions in that no effective limit is applied
  1084. // -1.5π < rotation <= 0.5π
  1085. // 0 <= 0.5π - rotation < 2π
  1086. this.constrain = () => {
  1087. this.value %= DEGREES[360];
  1088. if (this.value > DEGREES[90]) {
  1089. this.value -= DEGREES[360];
  1090. } else if (this.value <= -DEGREES[270]) {
  1091. this.value += DEGREES[360];
  1092. }
  1093. this.apply();
  1094. };
  1095. }();
  1096.  
  1097. const zoom = new function () {
  1098. this.value = 1;
  1099. const scaleRule = new css.Toggleable();
  1100. this.reset = () => {
  1101. this.value = 1;
  1102. video.style.removeProperty('scale');
  1103. scaleRule.remove();
  1104. scaleRule.add(':root', [VAR_ZOOM, '1']);
  1105. };
  1106. this.apply = () => {
  1107. video.style.setProperty('scale', `${this.value}`);
  1108. scaleRule.remove();
  1109. scaleRule.add(':root', [VAR_ZOOM, `${this.value}`]);
  1110. delete actions.reset.restore;
  1111. };
  1112. const getFit = (corner0, corner1, doSplit = false) => {
  1113. const x = Math.max(corner0.x, corner1.x) / viewport.clientWidth;
  1114. const y = Math.max(corner0.y, corner1.y) / viewport.clientHeight;
  1115. return doSplit ? [0.5 / x, 0.5 / y] : 0.5 / Math.max(x, y);
  1116. };
  1117. this.getFit = (width, height) => getFit(...getRotatedCorners(Math.sqrt(width * width + height * height), getTheta(0, 0, width, height)));
  1118. this.getVideoFit = (doSplit) => getFit(...getRotatedCorners(videoHypotenuse, videoTheta), doSplit);
  1119. this.constrain = (() => {
  1120. const limitGetters = {
  1121. [LIMITS.static]: [({custom}) => custom, ({custom}) => custom],
  1122. [LIMITS.fit]: (() => {
  1123. const getGetter = () => {
  1124. const zoomCache = new Cache(this);
  1125. const rotationCache = new DimensionCache(rotation);
  1126. const configCache = new ConfigCache();
  1127. let updateOnZoom;
  1128. let value;
  1129. return ({frame}, glow) => {
  1130. let fallthrough = rotationCache.isStale();
  1131. if (configCache.isStale()) {
  1132. if (glow) {
  1133. const {scaled} = glow.blur;
  1134. updateOnZoom = frame > 0 && (scaled.x > 0 || scaled.y > 0);
  1135. } else {
  1136. updateOnZoom = false;
  1137. }
  1138. fallthrough = true;
  1139. }
  1140. if (zoomCache.isStale() && updateOnZoom || fallthrough) {
  1141. if (glow) {
  1142. const base = glow.end - 1;
  1143. const {scaled, unscaled} = glow.blur;
  1144. value = this.getFit(
  1145. halfDimensions.video.width + Math.max(0, base * halfDimensions.video.width + Math.max(unscaled.x, scaled.x * this.value)) * frame,
  1146. halfDimensions.video.height + Math.max(0, base * halfDimensions.video.height + Math.max(unscaled.y, scaled.y * this.value)) * frame,
  1147. );
  1148. } else {
  1149. value = this.getVideoFit();
  1150. }
  1151. }
  1152. return value;
  1153. };
  1154. };
  1155. return [getGetter(), getGetter()];
  1156. })(),
  1157. };
  1158. return () => {
  1159. const {zoomOutLimit, zoomInLimit, glow} = $config.get();
  1160. if (zoomOutLimit.type !== 'None') {
  1161. this.value = Math.max(limitGetters[zoomOutLimit.type][0](zoomOutLimit, glow), this.value);
  1162. }
  1163. if (zoomInLimit.type !== 'None') {
  1164. this.value = Math.min(limitGetters[zoomInLimit.type][1](zoomInLimit, glow, 1), this.value);
  1165. }
  1166. this.apply();
  1167. };
  1168. })();
  1169. }();
  1170.  
  1171. const position = new function () {
  1172. this.x = this.y = 0;
  1173. this.getValues = () => ({x: this.x, y: this.y});
  1174. this.reset = () => {
  1175. this.x = this.y = 0;
  1176. video.style.removeProperty('translate');
  1177. };
  1178. this.apply = () => {
  1179. video.style.setProperty('transform-origin', `${(0.5 + this.x) * 100}% ${(0.5 - this.y) * 100}%`);
  1180. video.style.setProperty('translate', `${-this.x * 100}% ${this.y * 100}%`);
  1181. delete actions.reset.restore;
  1182. };
  1183. const frame = new function () {
  1184. const canvas = document.createElement('canvas');
  1185. const ctx = canvas.getContext('2d');
  1186. canvas.id = 'viewfind-frame-canvas';
  1187. // lazy code
  1188. setTimeout(() => {
  1189. css.add(`#${canvas.id}:not(${css.getSelector(actions.pan.CLASS_ABLE)} *):not(${css.getSelector(actions.rotate.CLASS_ABLE)} *)`, ['display', 'none']);
  1190. }, 0);
  1191. canvas.style.position = 'absolute';
  1192. containers.foreground.append(canvas);
  1193. const to = (x, y, move = false) => {
  1194. ctx[`${move ? 'move' : 'line'}To`]((x + 0.5) * video.clientWidth, (0.5 - y) * video.clientHeight);
  1195. };
  1196. this.draw = (points) => {
  1197. canvas.width = video.clientWidth;
  1198. canvas.height = video.clientHeight;
  1199. if (this.hide) {
  1200. return;
  1201. }
  1202. if (!points) {
  1203. return;
  1204. }
  1205. ctx.save();
  1206. ctx.beginPath();
  1207. ctx.moveTo(0, 0);
  1208. ctx.lineTo(canvas.width, 0);
  1209. ctx.lineTo(canvas.width, canvas.height);
  1210. ctx.lineTo(0, canvas.height);
  1211. ctx.closePath();
  1212. let doMove = true;
  1213. for (const {x, y} of points) {
  1214. to(x, y, doMove);
  1215. doMove = false;
  1216. }
  1217. ctx.closePath();
  1218. ctx.clip('evenodd');
  1219. ctx.fillStyle = 'black';
  1220. ctx.globalAlpha = 0.6;
  1221. ctx.fillRect(0, 0, canvas.width, canvas.height);
  1222. ctx.restore();
  1223. ctx.beginPath();
  1224. ctx.strokeStyle = 'white';
  1225. ctx.lineWidth = 1;
  1226. ctx.globalAlpha = 1;
  1227. doMove = true;
  1228. for (const {x, y} of points) {
  1229. to(x, y, doMove);
  1230. doMove = false;
  1231. }
  1232. ctx.stroke();
  1233. };
  1234. }();
  1235. this.updateFrame = () => {
  1236. const {panLimit, crosshair: {showFrame}} = $config.get();
  1237. frame.hide = !showFrame;
  1238. if (frame.hide) {
  1239. return;
  1240. }
  1241. switch (panLimit.type) {
  1242. case LIMITS.fit:
  1243. return;
  1244. case LIMITS.static:
  1245. if (panLimit.custom < 0.5) {
  1246. frame.draw([
  1247. {x: panLimit.custom, y: panLimit.custom},
  1248. {x: panLimit.custom, y: -panLimit.custom},
  1249. {x: -panLimit.custom, y: -panLimit.custom},
  1250. {x: -panLimit.custom, y: panLimit.custom},
  1251. ]);
  1252. return;
  1253. }
  1254. }
  1255. frame.draw();
  1256. };
  1257. this.constrain = (() => {
  1258. // logarithmic progress from "low" to infinity
  1259. const getProgress = (low, target) => 1 - low / target;
  1260. const getProgressed = ({x: fromX, y: fromY, z: lowZ}, {x: toX, y: toY}, targetZ) => {
  1261. const p = getProgress(lowZ, targetZ);
  1262. return {x: p * (toX - fromX) + fromX, y: p * (toY - fromY) + fromY};
  1263. };
  1264. // y = mx + c
  1265. const getLineY = ({m, c}, x = this.x) => m * x + c;
  1266. // x = (y - c) / m
  1267. const getLineX = ({m, c}, y = this.y) => (y - c) / m;
  1268. const getM = (from, to) => (to.y - from.y) / (to.x - from.x);
  1269. const getLine = (m, {x, y} = this) => ({c: y - m * x, m, x, y});
  1270. const getFlipped = ({x, y}) => ({x: -x, y: -y});
  1271. const isAbove = ({m, c}, {x, y} = this) => m * x + c < y;
  1272. const isRight = (line, {x, y} = this) => {
  1273. const lineX = (y - line.c) / line.m;
  1274. return x > (isNaN(lineX) ? line.x : lineX);
  1275. };
  1276. const constrain2D = (() => {
  1277. const isBetween = (() => {
  1278. const isBetweenBase = ({low, high}) => {
  1279. return isRight(low) && !isRight(high);
  1280. };
  1281. const isBetweenSide = ({low, high}) => {
  1282. return isAbove(low) && !isAbove(high);
  1283. };
  1284. return (line, tangent) => {
  1285. if (tangent.isSide) {
  1286. return isBetweenSide(tangent) && (tangent.isHigh ? isRight(line) : !isRight(line));
  1287. }
  1288. return isBetweenBase(tangent) && (tangent.isHigh ? isAbove(line) : !isAbove(line));
  1289. };
  1290. })();
  1291. const setTangentIntersect = (() => {
  1292. const setTangentIntersectX = (line, m, diff) => {
  1293. if (line.m === 0) {
  1294. this.y = line.y;
  1295. return;
  1296. }
  1297. const tangent = getLine(m);
  1298. this.x = (tangent.c - line.c) / diff;
  1299. this.y = getLineY(line);
  1300. };
  1301. const setTangentIntersectY = (line, m, diff) => {
  1302. if (m === 0) {
  1303. this.x = line.x;
  1304. return;
  1305. }
  1306. const tangent = getLine(m);
  1307. this.y = (m * line.c - line.m * tangent.c) / -diff;
  1308. this.x = getLineX(line);
  1309. };
  1310. return (line, {isSide}, m, diff) => {
  1311. if (isSide) {
  1312. setTangentIntersectY(line, m, diff);
  1313. } else {
  1314. setTangentIntersectX(line, m, diff);
  1315. }
  1316. };
  1317. })();
  1318. const isOutside = (tangent, property) => {
  1319. if (tangent.isSide) {
  1320. return tangent[property].isHigh ? isAbove(tangent.high) : !isAbove(tangent.low);
  1321. }
  1322. return tangent[property].isHigh ? isRight(tangent.high) : !isRight(tangent.low);
  1323. };
  1324. return (points, lines, tangents) => {
  1325. if (isBetween(lines.top, tangents.top)) {
  1326. setTangentIntersect(lines.top, tangents.top, tangents.base, tangents.baseDiff);
  1327. } else if (isBetween(lines.bottom, tangents.bottom)) {
  1328. setTangentIntersect(lines.bottom, tangents.bottom, tangents.base, tangents.baseDiff);
  1329. } else if (isBetween(lines.right, tangents.right)) {
  1330. setTangentIntersect(lines.right, tangents.right, tangents.side, tangents.sideDiff);
  1331. } else if (isBetween(lines.left, tangents.left)) {
  1332. setTangentIntersect(lines.left, tangents.left, tangents.side, tangents.sideDiff);
  1333. } else if (isOutside(tangents.top, 'right') && isOutside(tangents.right, 'top')) {
  1334. this.x = points.topRight.x;
  1335. this.y = points.topRight.y;
  1336. } else if (isOutside(tangents.bottom, 'right') && isOutside(tangents.right, 'bottom')) {
  1337. this.x = points.bottomRight.x;
  1338. this.y = points.bottomRight.y;
  1339. } else if (isOutside(tangents.top, 'left') && isOutside(tangents.left, 'top')) {
  1340. this.x = points.topLeft.x;
  1341. this.y = points.topLeft.y;
  1342. } else if (isOutside(tangents.bottom, 'left') && isOutside(tangents.left, 'bottom')) {
  1343. this.x = points.bottomLeft.x;
  1344. this.y = points.bottomLeft.y;
  1345. }
  1346. };
  1347. })();
  1348. const get1DConstrainer = (point) => {
  1349. const line = {
  1350. ...point,
  1351. m: point.y / point.x,
  1352. c: 0,
  1353. };
  1354. if (line.x < 0) {
  1355. line.x = -line.x;
  1356. line.y = -line.y;
  1357. }
  1358. const tangentM = -1 / line.m;
  1359. const mDiff = line.m - tangentM;
  1360. frame.draw([point, getFlipped(point)]);
  1361. return () => {
  1362. const tangent = getLine(tangentM);
  1363. this.x = Math.max(-line.x, Math.min(line.x, tangent.c / mDiff));
  1364. this.y = getLineY(line, this.x);
  1365. };
  1366. };
  1367. const getBoundApplyFrame = (() => {
  1368. const getBound = (first, second, isTopLeft) => {
  1369. if (zoom.value <= first.z) {
  1370. return false;
  1371. }
  1372. if (zoom.value >= second.z) {
  1373. const progress = zoom.value / second.z;
  1374. const x = isTopLeft ?
  1375. -0.5 - (-0.5 - second.x) / progress :
  1376. 0.5 - (0.5 - second.x) / progress;
  1377. return {
  1378. x,
  1379. y: 0.5 - (0.5 - second.y) / progress,
  1380. };
  1381. }
  1382. return {
  1383. ...getProgressed(first, second.vpEnd, zoom.value),
  1384. axis: second.vpEnd.axis,
  1385. m: second.y / second.x,
  1386. c: 0,
  1387. };
  1388. };
  1389. const swap = (array, i0, i1) => {
  1390. const temp = array[i0];
  1391. array[i0] = array[i1];
  1392. array[i1] = temp;
  1393. };
  1394. const setHighTangent = (tangent, low, high) => {
  1395. tangent.low = tangent[low];
  1396. tangent.high = tangent[high];
  1397. tangent[low].isHigh = false;
  1398. tangent[high].isHigh = true;
  1399. };
  1400. const getFrame = (point0, point1) => {
  1401. const flipped0 = getFlipped(point0);
  1402. const flipped1 = getFlipped(point1);
  1403. const m0 = getM(point0, point1);
  1404. const m1 = getM(flipped0, point1);
  1405. const tangentM0 = -1 / m0;
  1406. const tangentM1 = -1 / m1;
  1407. const lines = {
  1408. top: getLine(m0, point0),
  1409. bottom: getLine(m0, flipped0),
  1410. left: getLine(m1, point0),
  1411. right: getLine(m1, flipped0),
  1412. };
  1413. const points = {
  1414. topLeft: point0,
  1415. topRight: point1,
  1416. bottomRight: flipped0,
  1417. bottomLeft: flipped1,
  1418. };
  1419. const tangents = {
  1420. top: {
  1421. right: getLine(tangentM0, points.topRight),
  1422. left: getLine(tangentM0, points.topLeft),
  1423. },
  1424. right: {
  1425. top: getLine(tangentM1, points.topRight),
  1426. bottom: getLine(tangentM1, points.bottomRight),
  1427. },
  1428. bottom: {
  1429. right: getLine(tangentM0, points.bottomRight),
  1430. left: getLine(tangentM0, points.bottomLeft),
  1431. },
  1432. left: {
  1433. top: getLine(tangentM1, points.topLeft),
  1434. bottom: getLine(tangentM1, points.bottomLeft),
  1435. },
  1436. baseDiff: m0 - tangentM0,
  1437. sideDiff: m1 - tangentM1,
  1438. base: tangentM0,
  1439. side: tangentM1,
  1440. };
  1441. if (video.clientWidth < video.clientHeight) {
  1442. if (getLineX(lines.right, 0) < getLineX(lines.left, 0)) {
  1443. swap(lines, 'right', 'left');
  1444. swap(points, 'bottomLeft', 'bottomRight');
  1445. swap(points, 'topLeft', 'topRight');
  1446. swap(tangents, 'right', 'left');
  1447. swap(tangents.top, 'right', 'left');
  1448. swap(tangents.bottom, 'right', 'left');
  1449. }
  1450. } else {
  1451. if (lines.top.c < lines.bottom.c) {
  1452. swap(lines, 'top', 'bottom');
  1453. swap(points, 'topLeft', 'bottomLeft');
  1454. swap(points, 'topRight', 'bottomRight');
  1455. swap(tangents, 'top', 'bottom');
  1456. swap(tangents.left, 'top', 'left');
  1457. swap(tangents.right, 'top', 'left');
  1458. }
  1459. }
  1460. if (m0 > 1) {
  1461. tangents.top.isHigh = lines.top.c < 0;
  1462. tangents.top.isSide = tangents.bottom.isSide = true;
  1463. } else if (m0 < -1) {
  1464. tangents.top.isHigh = lines.top.c > 0;
  1465. tangents.top.isSide = tangents.bottom.isSide = true;
  1466. } else {
  1467. tangents.top.isHigh = true;
  1468. tangents.top.isSide = tangents.bottom.isSide = false;
  1469. }
  1470. if (tangents.top.isSide && tangents.top.isHigh) {
  1471. setHighTangent(tangents.top, 'right', 'left');
  1472. setHighTangent(tangents.bottom, 'right', 'left');
  1473. } else {
  1474. setHighTangent(tangents.top, 'left', 'right');
  1475. setHighTangent(tangents.bottom, 'left', 'right');
  1476. }
  1477. tangents.bottom.isHigh = !tangents.top.isHigh;
  1478. if (m1 < 1 && m1 >= 0) {
  1479. tangents.right.isHigh = lines.right.c < 0;
  1480. tangents.right.isSide = tangents.left.isSide = false;
  1481. } else if (m1 > -1 && m1 <= 0) {
  1482. tangents.right.isHigh = lines.right.c > 0;
  1483. tangents.right.isSide = tangents.left.isSide = false;
  1484. } else {
  1485. tangents.right.isHigh = true;
  1486. tangents.right.isSide = tangents.left.isSide = true;
  1487. }
  1488. if (!tangents.right.isSide && tangents.right.isHigh) {
  1489. setHighTangent(tangents.right, 'top', 'bottom');
  1490. setHighTangent(tangents.left, 'top', 'bottom');
  1491. } else {
  1492. setHighTangent(tangents.right, 'bottom', 'top');
  1493. setHighTangent(tangents.left, 'bottom', 'top');
  1494. }
  1495. tangents.left.isHigh = !tangents.right.isHigh;
  1496. frame.draw(Object.values(points));
  1497. return [points, lines, tangents];
  1498. };
  1499. return (first0, second0, first1, second1) => {
  1500. const point0 = getBound(first0, second0, true);
  1501. const point1 = getBound(first1, second1, false);
  1502. if (point0 && point1) {
  1503. return constrain2D.bind(null, ...getFrame(point0, point1));
  1504. }
  1505. if (point0 || point1) {
  1506. return get1DConstrainer(point0 || point1);
  1507. }
  1508. frame.draw([]);
  1509. return () => {
  1510. this.x = this.y = 0;
  1511. };
  1512. };
  1513. })();
  1514. const snapZoom = (() => {
  1515. const getDirected = (first, second, flipX, flipY) => {
  1516. const line0 = [first, {}];
  1517. const line1 = [{z: second.z}, {}];
  1518. if (flipX) {
  1519. line0[1].x = -second.vpEnd.x;
  1520. line1[0].x = -second.x;
  1521. line1[1].x = -0.5;
  1522. } else {
  1523. line0[1].x = second.vpEnd.x;
  1524. line1[0].x = second.x;
  1525. line1[1].x = 0.5;
  1526. }
  1527. if (flipY) {
  1528. line0[1].y = -second.vpEnd.y;
  1529. line1[0].y = -second.y;
  1530. line1[1].y = -0.5;
  1531. } else {
  1532. line0[1].y = second.vpEnd.y;
  1533. line1[0].y = second.y;
  1534. line1[1].y = 0.5;
  1535. }
  1536. return [line0, line1];
  1537. };
  1538. // https://math.stackexchange.com/questions/2223691/intersect-2-lines-at-the-same-ratio-through-a-point
  1539. const getIntersectProgress = ({x, y}, [{x: g, y: e}, {x: f, y: d}], [{x: k, y: i}, {x: j, y: h}], doFlip) => {
  1540. const a = d * j - d * k - j * e + e * k - h * f + h * g + i * f - i * g;
  1541. const b = d * k - d * x - e * k + e * x + j * e - k * e - j * y + k * y - h * g + h * x + i * g - i * x - f * i + g * i + f * y - g * y;
  1542. const c = k * e - e * x - k * y - g * i + i * x + g * y;
  1543. return (doFlip ? -b - Math.sqrt(b * b - 4 * a * c) : -b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
  1544. };
  1545. // line with progressed start point
  1546. const getProgressedLine = (line, {z}) => [getProgressed(...line, z), line[1]];
  1547. const isValidZoom = (zoom) => zoom !== null && !isNaN(zoom);
  1548. const getZoom = (pair0, pair1, pair2, position, doFlip) => getZoomPairSecond(pair2, position, doFlip)
  1549. || getZoomPairSecond(pair1, position, doFlip, getProgress(pair1[0], pair2[0]))
  1550. || getZoomPairSecond(pair0, position, doFlip, getProgress(pair0[0], pair1[0]));
  1551. const getZoomPairSecond = ([z, ...pair], position, doFlip, maxP = 1) => {
  1552. if (maxP >= 0) {
  1553. const p = getIntersectProgress(position, ...pair, doFlip);
  1554. if (p >= 0 && p <= maxP) {
  1555. // I don't think the >= 1 check is necessary but best be safe
  1556. return p >= 1 ? Number.MAX_SAFE_INTEGER : z / (1 - p);
  1557. }
  1558. }
  1559. return null;
  1560. };
  1561. return (first0, _second0, first1, second1) => {
  1562. const second0 = {..._second0, x: -_second0.x, vpEnd: {..._second0.vpEnd, x: -_second0.vpEnd.x}};
  1563. const absPosition = {x: Math.abs(this.x), y: Math.abs(this.y)};
  1564. const getPairings = (flipX0, flipY0, flipX1, flipY1) => {
  1565. const [lineFirst0, lineSecond0] = getDirected(first0, second0, flipX0, flipY0);
  1566. const [lineFirst1, lineSecond1] = getDirected(first1, second1, flipX1, flipY1);
  1567. // array structure is:
  1568. // start zoom for both lines
  1569. // 0 line start and its infinite zoom point
  1570. // 1 line start and its infinite zoom point
  1571. return [
  1572. first0.z >= first1.z ?
  1573. [first0.z, lineFirst0, getProgressedLine(lineFirst1, first0)] :
  1574. [first1.z, getProgressedLine(lineFirst0, first1), lineFirst1],
  1575. ...second0.z >= second1.z ?
  1576. [
  1577. [second1.z, getProgressedLine(lineFirst0, second1), lineSecond1],
  1578. [second0.z, lineSecond0, getProgressedLine(lineSecond1, second0)],
  1579. ] :
  1580. [
  1581. [second0.z, lineSecond0, getProgressedLine(lineFirst1, second0)],
  1582. [second1.z, getProgressedLine(lineSecond0, second1), lineSecond1],
  1583. ],
  1584. ];
  1585. };
  1586. zoom.value = Math.max(...(this.x >= 0 !== this.y >= 0 ?
  1587. [
  1588. getZoom(...getPairings(false, false, true, false), absPosition, true),
  1589. getZoom(...getPairings(false, false, false, true), absPosition),
  1590. ] :
  1591. [
  1592. getZoom(...getPairings(true, false, false, false), absPosition),
  1593. getZoom(...getPairings(false, true, false, false), absPosition, true),
  1594. ]).filter(isValidZoom));
  1595. };
  1596. })();
  1597. const getZoomPoints = (() => {
  1598. const getPoints = (fitZoom, doFlip) => {
  1599. const getGenericRotated = (x, y, angle) => {
  1600. const radius = Math.sqrt(x * x + y * y);
  1601. const pointTheta = getTheta(0, 0, x, y) + angle;
  1602. return {
  1603. x: radius * Math.cos(pointTheta),
  1604. y: radius * Math.sin(pointTheta),
  1605. };
  1606. };
  1607. const getRotated = (xRaw, yRaw) => {
  1608. // Multiplying by video dimensions to have the axes' scales match the video's
  1609. // Using midPoint's raw values would only work if points moved elliptically around the centre of rotation
  1610. const rotated = getGenericRotated(xRaw * video.clientWidth, yRaw * video.clientHeight, (DEGREES[90] - rotation.value) % DEGREES[180]);
  1611. rotated.x /= video.clientWidth;
  1612. rotated.y /= video.clientHeight;
  1613. return rotated;
  1614. };
  1615. return [
  1616. {...getRotated(halfDimensions.viewport.width / video.clientWidth / fitZoom[0], 0), axis: doFlip ? 'y' : 'x'},
  1617. {...getRotated(0, halfDimensions.viewport.height / video.clientHeight / fitZoom[1]), axis: doFlip ? 'x' : 'y'},
  1618. ];
  1619. };
  1620. const getIntersection = (line, corner, middle) => {
  1621. const getIntersection = (line0, line1) => {
  1622. const a0 = line0[0].y - line0[1].y;
  1623. const b0 = line0[1].x - line0[0].x;
  1624. const c0 = line0[1].x * line0[0].y - line0[0].x * line0[1].y;
  1625. const a1 = line1[0].y - line1[1].y;
  1626. const b1 = line1[1].x - line1[0].x;
  1627. const c1 = line1[1].x * line1[0].y - line1[0].x * line1[1].y;
  1628. const d = a0 * b1 - b0 * a1;
  1629. return {
  1630. x: (c0 * b1 - b0 * c1) / d,
  1631. y: (a0 * c1 - c0 * a1) / d,
  1632. };
  1633. };
  1634. const {x, y} = getIntersection([{x: 0, y: 0}, middle], [line, corner]);
  1635. const progress = isThin ? (y - line.y) / (corner.y - line.y) : (x - line.x) / (corner.x - line.x);
  1636. return {x, y, z: line.z / (1 - progress), c: line.y};
  1637. };
  1638. const getIntersect = (yIntersect, corner, right, top) => {
  1639. const point0 = getIntersection(yIntersect, corner, right);
  1640. const point1 = getIntersection(yIntersect, corner, top);
  1641. const [point, vpEnd] = point0.z > point1.z ? [point0, {...right}] : [point1, {...top}];
  1642. if (Math.sign(point[vpEnd.axis]) !== Math.sign(vpEnd[vpEnd.axis])) {
  1643. vpEnd.x = -vpEnd.x;
  1644. vpEnd.y = -vpEnd.y;
  1645. }
  1646. return {...point, vpEnd};
  1647. };
  1648. // the angle from 0,0 to the center of the video edge angled towards the viewport's upper-right corner
  1649. const getQuadrantAngle = (isEvenQuadrant) => {
  1650. const angle = (rotation.value + DEGREES[360]) % DEGREES[90];
  1651. return isEvenQuadrant ? angle : DEGREES[90] - angle;
  1652. };
  1653. return () => {
  1654. const isEvenQuadrant = (Math.floor(rotation.value / DEGREES[90]) + 3) % 2 === 0;
  1655. const quadrantAngle = getQuadrantAngle(isEvenQuadrant);
  1656. const progress = quadrantAngle / DEGREES[90] * -2 + 1;
  1657. const progressAngles = {
  1658. base: Math.atan(progress * viewportRatio),
  1659. side: Math.atan(progress * viewportRatioInverse),
  1660. };
  1661. const progressCosines = {
  1662. base: Math.cos(progressAngles.base),
  1663. side: Math.cos(progressAngles.side),
  1664. };
  1665. const fitZoom = zoom.getVideoFit(true);
  1666. const points = getPoints(fitZoom, quadrantAngle >= DEGREES[45]);
  1667. const sideIntersection = getIntersect(
  1668. ((cornerAngle) => ({
  1669. x: 0,
  1670. y: (halfDimensions.video.height - halfDimensions.video.width * Math.tan(cornerAngle)) / video.clientHeight,
  1671. z: halfDimensions.viewport.width / (progressCosines.side * Math.abs(halfDimensions.video.width / Math.cos(cornerAngle))),
  1672. }))(quadrantAngle + progressAngles.side),
  1673. isEvenQuadrant ? {x: -0.5, y: 0.5} : {x: 0.5, y: 0.5},
  1674. ...points,
  1675. );
  1676. const baseIntersection = getIntersect(
  1677. ((cornerAngle) => ({
  1678. x: 0,
  1679. y: (halfDimensions.video.height - halfDimensions.video.width * Math.tan(cornerAngle)) / video.clientHeight,
  1680. z: halfDimensions.viewport.height / (progressCosines.base * Math.abs(halfDimensions.video.width / Math.cos(cornerAngle))),
  1681. }))(DEGREES[90] - quadrantAngle - progressAngles.base),
  1682. isEvenQuadrant ? {x: 0.5, y: 0.5} : {x: -0.5, y: 0.5},
  1683. ...points,
  1684. );
  1685. const [originSide, originBase] = fitZoom.map((z) => ({x: 0, y: 0, z}));
  1686. return isEvenQuadrant ?
  1687. [...[originSide, sideIntersection], ...[originBase, baseIntersection]] :
  1688. [...[originBase, baseIntersection], ...[originSide, sideIntersection]];
  1689. };
  1690. })();
  1691. let zoomPoints;
  1692. const getEnsureZoomPoints = (() => {
  1693. const updateLog = [];
  1694. let count = 0;
  1695. return () => {
  1696. const zoomPointCache = new DimensionCache(rotation);
  1697. const callbackCache = new Cache(zoom);
  1698. const id = count++;
  1699. return () => {
  1700. if (zoomPointCache.isStale()) {
  1701. updateLog.length = 0;
  1702. zoomPoints = getZoomPoints();
  1703. }
  1704. if (callbackCache.isStale() || !updateLog[id]) {
  1705. updateLog[id] = true;
  1706. return true;
  1707. }
  1708. return false;
  1709. };
  1710. };
  1711. })();
  1712. const handlers = {
  1713. [LIMITS.static]: ({custom: ratio}) => {
  1714. const bound = 0.5 + (ratio - 0.5);
  1715. this.x = Math.max(-bound, Math.min(bound, this.x));
  1716. this.y = Math.max(-bound, Math.min(bound, this.y));
  1717. },
  1718. [LIMITS.fit]: (() => {
  1719. let boundApplyFrame;
  1720. const ensure = getEnsureZoomPoints();
  1721. return () => {
  1722. if (ensure()) {
  1723. boundApplyFrame = getBoundApplyFrame(...zoomPoints);
  1724. }
  1725. boundApplyFrame();
  1726. };
  1727. })(),
  1728. };
  1729. const snapHandlers = {
  1730. [LIMITS.fit]: (() => {
  1731. const ensure = getEnsureZoomPoints();
  1732. return () => {
  1733. ensure();
  1734. snapZoom(...zoomPoints);
  1735. zoom.constrain();
  1736. };
  1737. })(),
  1738. };
  1739. return (doZoom = false) => {
  1740. const {panLimit, snapPanLimit} = $config.get();
  1741. if (doZoom) {
  1742. snapHandlers[snapPanLimit.type]?.();
  1743. }
  1744. handlers[panLimit.type]?.(panLimit);
  1745. this.apply();
  1746. };
  1747. })();
  1748. }();
  1749.  
  1750. const crop = new function () {
  1751. this.top = this.right = this.bottom = this.left = 0;
  1752. this.getValues = () => ({top: this.top, right: this.right, bottom: this.bottom, left: this.left});
  1753. this.reveal = () => {
  1754. this.top = this.right = this.bottom = this.left = 0;
  1755. rule.remove();
  1756. };
  1757. this.reset = () => {
  1758. this.reveal();
  1759. actions.crop.reset();
  1760. };
  1761. const rule = new css.Toggleable();
  1762. this.apply = () => {
  1763. rule.remove();
  1764. rule.add(
  1765. `${SELECTOR_VIDEO}:not(.${this.CLASS_ABLE} *)`,
  1766. ['clip-path', `inset(${this.top * 100}% ${this.right * 100}% ${this.bottom * 100}% ${this.left * 100}%)`],
  1767. );
  1768. delete actions.reset.restore;
  1769. glow.handleViewChange();
  1770. glow.reset();
  1771. };
  1772. this.getDimensions = (width = video.clientWidth, height = video.clientHeight) => [
  1773. width * (1 - this.left - this.right),
  1774. height * (1 - this.top - this.bottom),
  1775. ];
  1776. }();
  1777.  
  1778. // FUNCTIONALITY
  1779.  
  1780. const glow = (() => {
  1781. const videoCanvas = new OffscreenCanvas(0, 0);
  1782. const videoCtx = videoCanvas.getContext('2d', {alpha: false});
  1783. const glowCanvas = document.createElement('canvas');
  1784. const glowCtx = glowCanvas.getContext('2d', {alpha: false});
  1785. glowCanvas.style.setProperty('position', 'absolute');
  1786. class Sector {
  1787. canvas = new OffscreenCanvas(0, 0);
  1788. ctx = this.canvas.getContext('2d', {alpha: false});
  1789. update(doFill) {
  1790. if (doFill) {
  1791. this.fill();
  1792. } else {
  1793. this.shift();
  1794. this.take();
  1795. }
  1796. this.giveEdge();
  1797. if (this.hasCorners) {
  1798. this.giveCorners();
  1799. }
  1800. }
  1801. }
  1802. class Side extends Sector {
  1803. setDimensions(doShiftRight, sWidth, sHeight, sx, sy, dx, dy, dWidth, dHeight) {
  1804. this.canvas.width = sWidth;
  1805. this.canvas.height = sHeight;
  1806. this.shift = this.ctx.drawImage.bind(this.ctx, this.canvas, doShiftRight ? 1 : -1, 0);
  1807. this.fill = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, 1, sHeight, 0, 0, sWidth, sHeight);
  1808. this.take = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, 1, sHeight, doShiftRight ? 0 : sWidth - 1, 0, 1, sHeight);
  1809. this.giveEdge = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, sWidth, sHeight, dx, dy, dWidth, dHeight);
  1810. if (dy === 0) {
  1811. this.hasCorners = false;
  1812. return;
  1813. }
  1814. this.hasCorners = true;
  1815. const giveCorner0 = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, sWidth, 1, dx, 0, dWidth, dy);
  1816. const giveCorner1 = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, sHeight - 1, sWidth, 1, dx, dy + dHeight, dWidth, dy);
  1817. this.giveCorners = () => {
  1818. giveCorner0();
  1819. giveCorner1();
  1820. };
  1821. }
  1822. }
  1823. class Base extends Sector {
  1824. setDimensions(doShiftDown, sWidth, sHeight, sx, sy, dx, dy, dWidth, dHeight) {
  1825. this.canvas.width = sWidth;
  1826. this.canvas.height = sHeight;
  1827. this.shift = this.ctx.drawImage.bind(this.ctx, this.canvas, 0, doShiftDown ? 1 : -1);
  1828. this.fill = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, sWidth, 1, 0, 0, sWidth, sHeight);
  1829. this.take = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, sWidth, 1, 0, doShiftDown ? 0 : sHeight - 1, sWidth, 1);
  1830. this.giveEdge = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, sWidth, sHeight, dx, dy, dWidth, dHeight);
  1831. if (dx === 0) {
  1832. this.hasCorners = false;
  1833. return;
  1834. }
  1835. this.hasCorners = true;
  1836. const giveCorner0 = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, 1, sHeight, 0, dy, dx, dHeight);
  1837. const giveCorner1 = glowCtx.drawImage.bind(glowCtx, this.canvas, sWidth - 1, 0, 1, sHeight, dx + dWidth, dy, dx, dHeight);
  1838. this.giveCorners = () => {
  1839. giveCorner0();
  1840. giveCorner1();
  1841. };
  1842. }
  1843. setClipPath(points) {
  1844. this.clipPath = new Path2D();
  1845. this.clipPath.moveTo(...points[0]);
  1846. this.clipPath.lineTo(...points[1]);
  1847. this.clipPath.lineTo(...points[2]);
  1848. this.clipPath.closePath();
  1849. }
  1850. update(doFill) {
  1851. glowCtx.save();
  1852. glowCtx.clip(this.clipPath);
  1853. super.update(doFill);
  1854. glowCtx.restore();
  1855. }
  1856. }
  1857. const components = {
  1858. left: new Side(),
  1859. right: new Side(),
  1860. top: new Base(),
  1861. bottom: new Base(),
  1862. };
  1863. const setComponentDimensions = (sampleCount, size, isInset, doFlip) => {
  1864. const [croppedWidth, croppedHeight] = crop.getDimensions();
  1865. const halfCanvas = {x: Math.ceil(glowCanvas.width / 2), y: Math.ceil(glowCanvas.height / 2)};
  1866. const halfVideo = {x: croppedWidth / 2, y: croppedHeight / 2};
  1867. const dWidth = Math.ceil(Math.min(halfVideo.x, size));
  1868. const dHeight = Math.ceil(Math.min(halfVideo.y, size));
  1869. const [dWidthScale, dHeightScale, sideWidth, sideHeight] = isInset ?
  1870. [0, 0, videoCanvas.width / croppedWidth * glowCanvas.width, videoCanvas.height / croppedHeight * glowCanvas.height] :
  1871. [halfCanvas.x - halfVideo.x, halfCanvas.y - halfVideo.y, croppedWidth, croppedHeight];
  1872. components.left.setDimensions(!doFlip, sampleCount, videoCanvas.height, 0, 0, 0, dHeightScale, dWidth, sideHeight);
  1873. components.right.setDimensions(doFlip, sampleCount, videoCanvas.height, videoCanvas.width - 1, 0, glowCanvas.width - dWidth, dHeightScale, dWidth, sideHeight);
  1874. components.top.setDimensions(!doFlip, videoCanvas.width, sampleCount, 0, 0, dWidthScale, 0, sideWidth, dHeight);
  1875. components.top.setClipPath([[0, 0], [halfCanvas.x, halfCanvas.y], [glowCanvas.width, 0]]);
  1876. components.bottom.setDimensions(doFlip, videoCanvas.width, sampleCount, 0, videoCanvas.height - 1, dWidthScale, glowCanvas.height - dHeight, sideWidth, dHeight);
  1877. components.bottom.setClipPath([[0, glowCanvas.height], [halfCanvas.x, halfCanvas.y], [glowCanvas.width, glowCanvas.height]]);
  1878. };
  1879. class Instance {
  1880. constructor() {
  1881. const {filter, sampleCount, size, end, doFlip} = $config.get().glow;
  1882. // Setup canvases
  1883. glowCanvas.style.setProperty('filter', filter);
  1884. [glowCanvas.width, glowCanvas.height] = crop.getDimensions().map((dimension) => dimension * end);
  1885. glowCanvas.style.setProperty('left', `${crop.left * 100 + (1 - end) * (1 - crop.left - crop.right) * 50}%`);
  1886. glowCanvas.style.setProperty('top', `${crop.top * 100 + (1 - end) * (1 - crop.top - crop.bottom) * 50}%`);
  1887. [videoCanvas.width, videoCanvas.height] = crop.getDimensions(video.videoWidth, video.videoHeight);
  1888. setComponentDimensions(sampleCount, size, end <= 1, doFlip);
  1889. this.update(true);
  1890. }
  1891. update(doFill = false) {
  1892. videoCtx.drawImage(
  1893. video,
  1894. crop.left * video.videoWidth,
  1895. crop.top * video.videoHeight,
  1896. video.videoWidth * (1 - crop.left - crop.right),
  1897. video.videoHeight * (1 - crop.top - crop.bottom),
  1898. 0,
  1899. 0,
  1900. videoCanvas.width,
  1901. videoCanvas.height,
  1902. );
  1903. components.left.update(doFill);
  1904. components.right.update(doFill);
  1905. components.top.update(doFill);
  1906. components.bottom.update(doFill);
  1907. }
  1908. }
  1909. return new function () {
  1910. const container = document.createElement('div');
  1911. container.style.display = 'none';
  1912. container.appendChild(glowCanvas);
  1913. containers.background.appendChild(container);
  1914. this.isHidden = false;
  1915. let instance, startCopyLoop, stopCopyLoop;
  1916. const play = () => {
  1917. if (!video.paused && !this.isHidden && !enabler.isHidingGlow) {
  1918. startCopyLoop?.();
  1919. }
  1920. };
  1921. const fill = () => {
  1922. if (!this.isHidden) {
  1923. instance.update(true);
  1924. }
  1925. };
  1926. const handleVisibilityChange = () => {
  1927. if (document.hidden) {
  1928. stopCopyLoop();
  1929. } else {
  1930. play();
  1931. }
  1932. };
  1933. this.handleSizeChange = () => {
  1934. instance = new Instance();
  1935. };
  1936. // set up pausing if glow isn't visible
  1937. this.handleViewChange = (() => {
  1938. const cache = new Cache(rotation, zoom);
  1939. let corners;
  1940. return (doForce = false) => {
  1941. if (doForce || cache.isStale()) {
  1942. const width = halfDimensions.viewport.width / zoom.value;
  1943. const height = halfDimensions.viewport.height / zoom.value;
  1944. const radius = Math.sqrt(width * width + height * height);
  1945. corners = getRotatedCorners(radius, viewportTheta);
  1946. }
  1947. const videoX = position.x * video.clientWidth;
  1948. const videoY = position.y * video.clientHeight;
  1949. for (const corner of corners) {
  1950. if (
  1951. // unpause if the viewport extends more than 1 pixel beyond a video edge
  1952. videoX + corner.x > (0.5 - crop.right) * video.clientWidth + 1
  1953. || videoX - corner.x < (crop.left - 0.5) * video.clientWidth - 1
  1954. || videoY + corner.y > (0.5 - crop.top) * video.clientHeight + 1
  1955. || videoY - corner.y < (crop.bottom - 0.5) * video.clientHeight - 1
  1956. ) {
  1957. // fill if newly visible
  1958. if (this.isHidden) {
  1959. instance?.update(true);
  1960. }
  1961. this.isHidden = false;
  1962. glowCanvas.style.removeProperty('visibility');
  1963. play();
  1964. return;
  1965. }
  1966. }
  1967. this.isHidden = true;
  1968. glowCanvas.style.visibility = 'hidden';
  1969. stopCopyLoop?.();
  1970. };
  1971. })();
  1972. const loop = {};
  1973. this.start = () => {
  1974. const config = $config.get().glow;
  1975. if (!config) {
  1976. return;
  1977. }
  1978. if (!enabler.isHidingGlow) {
  1979. container.style.removeProperty('display');
  1980. }
  1981. // todo handle this?
  1982. if (crop.left + crop.right >= 1 || crop.top + crop.bottom >= 1) {
  1983. return;
  1984. }
  1985. let loopId = -1;
  1986. if (loop.interval !== config.interval || loop.fps !== config.fps) {
  1987. loop.interval = config.interval;
  1988. loop.fps = config.fps;
  1989. loop.wasSlow = false;
  1990. loop.throttleCount = 0;
  1991. }
  1992. stopCopyLoop = () => ++loopId;
  1993. instance = new Instance();
  1994. startCopyLoop = async () => {
  1995. const id = ++loopId;
  1996. await new Promise((resolve) => {
  1997. window.setTimeout(resolve, config.interval);
  1998. });
  1999. while (id === loopId) {
  2000. const startTime = Date.now();
  2001. instance.update();
  2002. const delay = loop.interval - (Date.now() - startTime);
  2003. if (delay <= 0) {
  2004. if (loop.wasSlow) {
  2005. loop.interval = 1000 / (loop.fps - ++loop.throttleCount);
  2006. }
  2007. loop.wasSlow = !loop.wasSlow;
  2008. continue;
  2009. }
  2010. if (delay > 2 && loop.throttleCount > 0) {
  2011. console.warn(`[${GM.info.script.name}] Glow update frequency reduced from ${loop.fps} hertz to ${loop.fps - loop.throttleCount} hertz due to poor performance.`);
  2012. loop.fps -= loop.throttleCount;
  2013. loop.throttleCount = 0;
  2014. }
  2015. loop.wasSlow = false;
  2016. await new Promise((resolve) => {
  2017. window.setTimeout(resolve, delay);
  2018. });
  2019. }
  2020. };
  2021. play();
  2022. video.addEventListener('pause', stopCopyLoop);
  2023. video.addEventListener('play', play);
  2024. video.addEventListener('seeked', fill);
  2025. document.addEventListener('visibilitychange', handleVisibilityChange);
  2026. };
  2027. const priorCrop = {};
  2028. this.hide = () => {
  2029. Object.assign(priorCrop, crop);
  2030. stopCopyLoop?.();
  2031. container.style.display = 'none';
  2032. };
  2033. this.show = () => {
  2034. if (Object.entries(priorCrop).some(([edge, value]) => crop[edge] !== value)) {
  2035. this.reset();
  2036. } else {
  2037. play();
  2038. }
  2039. container.style.removeProperty('display');
  2040. };
  2041. this.stop = () => {
  2042. this.hide();
  2043. video.removeEventListener('pause', stopCopyLoop);
  2044. video.removeEventListener('play', play);
  2045. video.removeEventListener('seeked', fill);
  2046. document.removeEventListener('visibilitychange', handleVisibilityChange);
  2047. startCopyLoop = undefined;
  2048. stopCopyLoop = undefined;
  2049. };
  2050. this.reset = () => {
  2051. this.stop();
  2052. this.start();
  2053. };
  2054. }();
  2055. })();
  2056.  
  2057. const peek = (stop = false) => {
  2058. const prior = {
  2059. zoom: zoom.value,
  2060. rotation: rotation.value,
  2061. crop: crop.getValues(),
  2062. position: position.getValues(),
  2063. };
  2064. position.reset();
  2065. rotation.reset();
  2066. zoom.reset();
  2067. crop.reset();
  2068. glow[stop ? 'stop' : 'reset']();
  2069. return () => {
  2070. zoom.value = prior.zoom;
  2071. rotation.value = prior.rotation;
  2072. Object.assign(position, prior.position);
  2073. Object.assign(crop, prior.crop);
  2074. actions.crop.set(prior.crop);
  2075. position.apply();
  2076. rotation.apply();
  2077. zoom.apply();
  2078. crop.apply();
  2079. };
  2080. };
  2081.  
  2082. const actions = (() => {
  2083. const drag = (event, clickCallback, moveCallback, target = video) => new Promise((resolve) => {
  2084. event.stopImmediatePropagation();
  2085. event.preventDefault();
  2086. // window blur events don't fire if devtools is open
  2087. stopDrag?.();
  2088. target.setPointerCapture(event.pointerId);
  2089. css.tag(enabler.CLASS_DRAGGING);
  2090. const cancel = (event) => {
  2091. event.stopImmediatePropagation();
  2092. event.preventDefault();
  2093. };
  2094. document.addEventListener('click', cancel, true);
  2095. document.addEventListener('dblclick', cancel, true);
  2096. const clickDisallowListener = ({clientX, clientY}) => {
  2097. const {clickCutoff} = $config.get();
  2098. const distance = Math.abs(event.clientX - clientX) + Math.abs(event.clientY - clientY);
  2099. if (distance >= clickCutoff) {
  2100. target.removeEventListener('pointermove', clickDisallowListener);
  2101. target.removeEventListener('pointerup', clickCallback);
  2102. }
  2103. };
  2104. if (clickCallback) {
  2105. target.addEventListener('pointermove', clickDisallowListener);
  2106. target.addEventListener('pointerup', clickCallback, {once: true});
  2107. }
  2108. target.addEventListener('pointermove', moveCallback);
  2109. stopDrag = () => {
  2110. css.tag(enabler.CLASS_DRAGGING, false);
  2111. target.removeEventListener('pointermove', moveCallback);
  2112. if (clickCallback) {
  2113. target.removeEventListener('pointermove', clickDisallowListener);
  2114. target.removeEventListener('pointerup', clickCallback);
  2115. }
  2116. // delay removing listeners for events that happen after pointerup
  2117. window.setTimeout(() => {
  2118. document.removeEventListener('dblclick', cancel, true);
  2119. document.removeEventListener('click', cancel, true);
  2120. }, 0);
  2121. window.removeEventListener('blur', stopDrag);
  2122. target.removeEventListener('pointerup', stopDrag);
  2123. target.releasePointerCapture(event.pointerId);
  2124. stopDrag = undefined;
  2125. enabler.handleChange();
  2126. resolve();
  2127. };
  2128. window.addEventListener('blur', stopDrag);
  2129. target.addEventListener('pointerup', stopDrag);
  2130. });
  2131. const getOnScroll = (() => {
  2132. // https://stackoverflow.com/a/30134826
  2133. const multipliers = [1, 40, 800];
  2134. return (callback) => (event) => {
  2135. event.stopImmediatePropagation();
  2136. event.preventDefault();
  2137. if (event.deltaY !== 0) {
  2138. callback(event.deltaY * multipliers[event.deltaMode]);
  2139. }
  2140. };
  2141. })();
  2142. const addListeners = ({onMouseDown, onRightClick, onScroll}, doAdd = true) => {
  2143. const property = `${doAdd ? 'add' : 'remove'}EventListener`;
  2144. altTarget[property]('pointerdown', onMouseDown);
  2145. altTarget[property]('contextmenu', onRightClick, true);
  2146. altTarget[property]('wheel', onScroll);
  2147. };
  2148. return {
  2149. crop: new function () {
  2150. let top = 0, right = 0, bottom = 0, left = 0, handle;
  2151. const values = {};
  2152. Object.defineProperty(values, 'top', {get: () => top, set: (value) => top = value});
  2153. Object.defineProperty(values, 'right', {get: () => right, set: (value) => right = value});
  2154. Object.defineProperty(values, 'bottom', {get: () => bottom, set: (value) => bottom = value});
  2155. Object.defineProperty(values, 'left', {get: () => left, set: (value) => left = value});
  2156. class Button {
  2157. // allowance for rounding errors
  2158. static ALLOWANCE_HANDLE = 0.0001;
  2159. static CLASS_HANDLE = 'viewfind-crop-handle';
  2160. static CLASS_EDGES = {
  2161. left: 'viewfind-crop-left',
  2162. top: 'viewfind-crop-top',
  2163. right: 'viewfind-crop-right',
  2164. bottom: 'viewfind-crop-bottom',
  2165. };
  2166. static OPPOSITES = {
  2167. left: 'right',
  2168. right: 'left',
  2169. top: 'bottom',
  2170. bottom: 'top',
  2171. };
  2172. callbacks = [];
  2173. element = document.createElement('div');
  2174. constructor(...edges) {
  2175. this.edges = edges;
  2176. this.isHandle = true;
  2177. this.element.style.position = 'absolute';
  2178. this.element.style.pointerEvents = 'all';
  2179. for (const edge of edges) {
  2180. this.element.style[edge] = '0';
  2181. this.element.classList.add(Button.CLASS_EDGES[edge]);
  2182. this.element.style.setProperty(`border-${Button.OPPOSITES[edge]}-width`, '1px');
  2183. }
  2184. this.element.addEventListener('contextmenu', (event) => {
  2185. event.stopPropagation();
  2186. event.preventDefault();
  2187. this.reset(false);
  2188. });
  2189. this.element.addEventListener('pointerdown', (() => {
  2190. const clickListener = ({offsetX, offsetY, target}) => {
  2191. this.set({
  2192. width: (this.edges.includes('left') ? offsetX : target.clientWidth - offsetX) / video.clientWidth,
  2193. height: (this.edges.includes('top') ? offsetY : target.clientHeight - offsetY) / video.clientHeight,
  2194. }, false);
  2195. };
  2196. const getDragListener = (event, target) => {
  2197. const getWidth = (() => {
  2198. if (this.edges.includes('left')) {
  2199. const position = this.element.clientWidth - event.offsetX;
  2200. return ({offsetX}) => offsetX + position;
  2201. }
  2202. const position = target.offsetWidth + event.offsetX;
  2203. return ({offsetX}) => position - offsetX;
  2204. })();
  2205. const getHeight = (() => {
  2206. if (this.edges.includes('top')) {
  2207. const position = this.element.clientHeight - event.offsetY;
  2208. return ({offsetY}) => offsetY + position;
  2209. }
  2210. const position = target.offsetHeight + event.offsetY;
  2211. return ({offsetY}) => position - offsetY;
  2212. })();
  2213. return (event) => {
  2214. this.set({
  2215. width: getWidth(event) / video.clientWidth,
  2216. height: getHeight(event) / video.clientHeight,
  2217. });
  2218. };
  2219. };
  2220. return async (event) => {
  2221. if (event.buttons === 1) {
  2222. const target = this.element.parentElement;
  2223. if (this.isHandle) {
  2224. this.setPanel();
  2225. }
  2226. await drag(event, clickListener, getDragListener(event, target), target);
  2227. this.updateCounterpart();
  2228. }
  2229. };
  2230. })());
  2231. }
  2232. notify() {
  2233. for (const callback of this.callbacks) {
  2234. callback();
  2235. }
  2236. }
  2237. set isHandle(value) {
  2238. this._isHandle = value;
  2239. this.element.classList[value ? 'add' : 'remove'](Button.CLASS_HANDLE);
  2240. }
  2241. get isHandle() {
  2242. return this._isHandle;
  2243. }
  2244. reset() {
  2245. this.isHandle = true;
  2246. for (const edge of this.edges) {
  2247. values[edge] = 0;
  2248. }
  2249. }
  2250. }
  2251. class EdgeButton extends Button {
  2252. constructor(edge) {
  2253. super(edge);
  2254. this.edge = edge;
  2255. }
  2256. updateCounterpart() {
  2257. if (this.counterpart.isHandle) {
  2258. this.counterpart.setHandle();
  2259. }
  2260. }
  2261. setCrop(value = 0) {
  2262. values[this.edge] = value;
  2263. }
  2264. setPanel() {
  2265. this.isHandle = false;
  2266. this.setCrop(handle);
  2267. this.setHandle();
  2268. }
  2269. }
  2270. class SideButton extends EdgeButton {
  2271. flow() {
  2272. let size = 1;
  2273. if (top <= Button.ALLOWANCE_HANDLE) {
  2274. size -= handle;
  2275. this.element.style.top = `${handle * 100}%`;
  2276. } else {
  2277. size -= top;
  2278. this.element.style.top = `${top * 100}%`;
  2279. }
  2280. if (bottom <= Button.ALLOWANCE_HANDLE) {
  2281. size -= handle;
  2282. } else {
  2283. size -= bottom;
  2284. }
  2285. this.element.style.height = `${Math.max(0, size * 100)}%`;
  2286. }
  2287. setBounds(counterpart, components) {
  2288. this.counterpart = components[counterpart];
  2289. components.top.callbacks.push(() => {
  2290. this.flow();
  2291. });
  2292. components.bottom.callbacks.push(() => {
  2293. this.flow();
  2294. });
  2295. }
  2296. setHandle(doNotify = true) {
  2297. this.element.style.width = `${Math.min(1 - values[this.counterpart.edge], handle) * 100}%`;
  2298. if (doNotify) {
  2299. this.notify();
  2300. }
  2301. }
  2302. set({width}, doUpdateCounterpart = true) {
  2303. if (this.isHandle !== (this.isHandle = width <= Button.ALLOWANCE_HANDLE)) {
  2304. this.flow();
  2305. }
  2306. if (doUpdateCounterpart) {
  2307. this.updateCounterpart();
  2308. }
  2309. if (this.isHandle) {
  2310. this.setCrop();
  2311. this.setHandle();
  2312. return;
  2313. }
  2314. const size = Math.min(1 - values[this.counterpart.edge], width);
  2315. this.setCrop(size);
  2316. this.element.style.width = `${size * 100}%`;
  2317. this.notify();
  2318. }
  2319. reset(isGeneral = true) {
  2320. super.reset();
  2321. if (isGeneral) {
  2322. this.element.style.top = `${handle * 100}%`;
  2323. this.element.style.height = `${(0.5 - handle) * 200}%`;
  2324. this.element.style.width = `${handle * 100}%`;
  2325. return;
  2326. }
  2327. this.flow();
  2328. this.setHandle();
  2329. this.updateCounterpart();
  2330. }
  2331. }
  2332. class BaseButton extends EdgeButton {
  2333. flow() {
  2334. let size = 1;
  2335. if (left <= Button.ALLOWANCE_HANDLE) {
  2336. size -= handle;
  2337. this.element.style.left = `${handle * 100}%`;
  2338. } else {
  2339. size -= left;
  2340. this.element.style.left = `${left * 100}%`;
  2341. }
  2342. if (right <= Button.ALLOWANCE_HANDLE) {
  2343. size -= handle;
  2344. } else {
  2345. size -= right;
  2346. }
  2347. this.element.style.width = `${Math.max(0, size) * 100}%`;
  2348. }
  2349. setBounds(counterpart, components) {
  2350. this.counterpart = components[counterpart];
  2351. components.left.callbacks.push(() => {
  2352. this.flow();
  2353. });
  2354. components.right.callbacks.push(() => {
  2355. this.flow();
  2356. });
  2357. }
  2358. setHandle(doNotify = true) {
  2359. this.element.style.height = `${Math.min(1 - values[this.counterpart.edge], handle) * 100}%`;
  2360. if (doNotify) {
  2361. this.notify();
  2362. }
  2363. }
  2364. set({height}, doUpdateCounterpart = false) {
  2365. if (this.isHandle !== (this.isHandle = height <= Button.ALLOWANCE_HANDLE)) {
  2366. this.flow();
  2367. }
  2368. if (doUpdateCounterpart) {
  2369. this.updateCounterpart();
  2370. }
  2371. if (this.isHandle) {
  2372. this.setCrop();
  2373. this.setHandle();
  2374. return;
  2375. }
  2376. const size = Math.min(1 - values[this.counterpart.edge], height);
  2377. this.setCrop(size);
  2378. this.element.style.height = `${size * 100}%`;
  2379. this.notify();
  2380. }
  2381. reset(isGeneral = true) {
  2382. super.reset();
  2383. if (isGeneral) {
  2384. this.element.style.left = `${handle * 100}%`;
  2385. this.element.style.width = `${(0.5 - handle) * 200}%`;
  2386. this.element.style.height = `${handle * 100}%`;
  2387. return;
  2388. }
  2389. this.flow();
  2390. this.setHandle();
  2391. this.updateCounterpart();
  2392. }
  2393. }
  2394. class CornerButton extends Button {
  2395. static CLASS_NAME = 'viewfind-crop-corner';
  2396. constructor(sectors, ...edges) {
  2397. super(...edges);
  2398. this.element.classList.add(CornerButton.CLASS_NAME);
  2399. this.sectors = sectors;
  2400. for (const sector of sectors) {
  2401. sector.callbacks.push(this.flow.bind(this));
  2402. }
  2403. }
  2404. flow() {
  2405. let isHandle = true;
  2406. if (this.sectors[0].isHandle) {
  2407. this.element.style.width = `${Math.min(1 - values[this.sectors[0].counterpart.edge], handle) * 100}%`;
  2408. } else {
  2409. this.element.style.width = `${values[this.edges[0]] * 100}%`;
  2410. isHandle = false;
  2411. }
  2412. if (this.sectors[1].isHandle) {
  2413. this.element.style.height = `${Math.min(1 - values[this.sectors[1].counterpart.edge], handle) * 100}%`;
  2414. } else {
  2415. this.element.style.height = `${values[this.edges[1]] * 100}%`;
  2416. isHandle = false;
  2417. }
  2418. this.isHandle = isHandle;
  2419. }
  2420. updateCounterpart() {
  2421. for (const sector of this.sectors) {
  2422. sector.updateCounterpart();
  2423. }
  2424. }
  2425. set(size) {
  2426. for (const sector of this.sectors) {
  2427. sector.set(size);
  2428. }
  2429. }
  2430. reset(isGeneral = true) {
  2431. this.isHandle = true;
  2432. this.element.style.width = `${handle * 100}%`;
  2433. this.element.style.height = `${handle * 100}%`;
  2434. if (isGeneral) {
  2435. return;
  2436. }
  2437. for (const sector of this.sectors) {
  2438. sector.reset(false);
  2439. }
  2440. }
  2441. setPanel() {
  2442. for (const sector of this.sectors) {
  2443. sector.setPanel();
  2444. }
  2445. }
  2446. }
  2447. this.CODE = 'crop';
  2448. this.CLASS_ABLE = 'viewfind-action-able-crop';
  2449. const container = document.createElement('div');
  2450. // todo ditch the containers object
  2451. container.style.width = container.style.height = 'inherit';
  2452. containers.foreground.append(container);
  2453. this.reset = () => {
  2454. for (const component of Object.values(this.components)) {
  2455. component.reset(true);
  2456. }
  2457. };
  2458. this.onRightClick = (event) => {
  2459. if (event.target.parentElement.id === container.id) {
  2460. return;
  2461. }
  2462. event.stopPropagation();
  2463. event.preventDefault();
  2464. if (stopDrag) {
  2465. return;
  2466. }
  2467. this.reset();
  2468. };
  2469. this.onScroll = getOnScroll((distance) => {
  2470. const increment = distance * $config.get().speeds.crop / zoom.value;
  2471. this.components.top.set({height: top + Math.min((1 - top - bottom) / 2, increment)});
  2472. this.components.left.set({width: left + Math.min((1 - left - right) / 2, increment)});
  2473. this.components.bottom.set({height: bottom + increment});
  2474. this.components.right.set({width: right + increment});
  2475. });
  2476. this.onMouseDown = (() => {
  2477. const getDragListener = () => {
  2478. const multiplier = $config.get().multipliers.crop;
  2479. const setX = ((right, left, change) => {
  2480. const clamped = Math.max(-left, Math.min(right, change * multiplier / video.clientWidth));
  2481. this.components.left.set({width: left + clamped});
  2482. this.components.right.set({width: right - clamped});
  2483. }).bind(undefined, right, left);
  2484. const setY = ((top, bottom, change) => {
  2485. const clamped = Math.max(-top, Math.min(bottom, change * multiplier / video.clientHeight));
  2486. this.components.top.set({height: top + clamped});
  2487. this.components.bottom.set({height: bottom - clamped});
  2488. }).bind(undefined, top, bottom);
  2489. let priorEvent;
  2490. return ({offsetX, offsetY}) => {
  2491. if (!priorEvent) {
  2492. priorEvent = {offsetX, offsetY};
  2493. return;
  2494. }
  2495. setX(offsetX - priorEvent.offsetX);
  2496. setY(offsetY - priorEvent.offsetY);
  2497. };
  2498. };
  2499. const clickListener = () => {
  2500. zoom.value = zoom.getFit((1 - left - right) * halfDimensions.video.width, (1 - top - bottom) * halfDimensions.video.height);
  2501. zoom.constrain();
  2502. position.x = (left - right) / 2;
  2503. position.y = (bottom - top) / 2;
  2504. position.constrain();
  2505. };
  2506. return (event) => {
  2507. if (event.buttons === 1) {
  2508. drag(event, clickListener, getDragListener(), container);
  2509. }
  2510. };
  2511. })();
  2512. this.components = {
  2513. top: new BaseButton('top'),
  2514. right: new SideButton('right'),
  2515. bottom: new BaseButton('bottom'),
  2516. left: new SideButton('left'),
  2517. };
  2518. this.components.top.setBounds('bottom', this.components);
  2519. this.components.right.setBounds('left', this.components);
  2520. this.components.bottom.setBounds('top', this.components);
  2521. this.components.left.setBounds('right', this.components);
  2522. this.components.topLeft = new CornerButton([this.components.left, this.components.top], 'left', 'top');
  2523. this.components.topRight = new CornerButton([this.components.right, this.components.top], 'right', 'top');
  2524. this.components.bottomLeft = new CornerButton([this.components.left, this.components.bottom], 'left', 'bottom');
  2525. this.components.bottomRight = new CornerButton([this.components.right, this.components.bottom], 'right', 'bottom');
  2526. container.append(...Object.values(this.components).map(({element}) => element));
  2527. this.set = ({top, right, bottom, left}) => {
  2528. this.components.top.set({height: top});
  2529. this.components.right.set({width: right});
  2530. this.components.bottom.set({height: bottom});
  2531. this.components.left.set({width: left});
  2532. };
  2533. this.onInactive = () => {
  2534. addListeners(this, false);
  2535. if (crop.left === left && crop.top === top && crop.right === right && crop.bottom === bottom) {
  2536. return;
  2537. }
  2538. crop.left = left;
  2539. crop.top = top;
  2540. crop.right = right;
  2541. crop.bottom = bottom;
  2542. crop.apply();
  2543. };
  2544. this.onActive = () => {
  2545. const config = $config.get().crop;
  2546. handle = config.handle / Math.max(zoom.value, 1);
  2547. for (const component of [this.components.top, this.components.bottom, this.components.left, this.components.right]) {
  2548. if (component.isHandle) {
  2549. component.setHandle();
  2550. }
  2551. }
  2552. crop.reveal();
  2553. addListeners(this);
  2554. if (!enabler.isHidingGlow) {
  2555. glow.handleViewChange();
  2556. glow.reset();
  2557. }
  2558. };
  2559. const draggingSelector = css.getSelector(enabler.CLASS_DRAGGING);
  2560. this.updateConfig = (() => {
  2561. const rule = new css.Toggleable();
  2562. return () => {
  2563. // set handle size
  2564. for (const button of [this.components.left, this.components.top, this.components.right, this.components.bottom]) {
  2565. if (button.isHandle) {
  2566. button.setHandle();
  2567. }
  2568. }
  2569. rule.remove();
  2570. const {colour} = $config.get().crop;
  2571. const {id} = container;
  2572. rule.add(`#${id}>:hover.${Button.CLASS_HANDLE},#${id}>:not(.${Button.CLASS_HANDLE})`, ['background-color', colour.fill]);
  2573. rule.add(`#${id}>*`, ['border-color', colour.border]);
  2574. rule.add(`#${id}:not(${draggingSelector} *)>:not(:hover)`, ['filter', `drop-shadow(${colour.shadow} 0 0 1px)`]);
  2575. };
  2576. })();
  2577. $config.ready.then(() => {
  2578. this.updateConfig();
  2579. });
  2580. container.id = 'viewfind-crop-container';
  2581. (() => {
  2582. const {id} = container;
  2583. css.add(`${css.getSelector(enabler.CLASS_DRAGGING)} #${id}`, ['cursor', 'grabbing']);
  2584. css.add(`${css.getSelector(enabler.CLASS_ABLE)} #${id}`, ['cursor', 'grab']);
  2585. css.add(`#${id}>:not(${draggingSelector} .${Button.CLASS_HANDLE})`, ['border-style', 'solid']);
  2586. css.add(`${draggingSelector} #${id}>.${Button.CLASS_HANDLE}`, ['filter', 'none']);
  2587. for (const [side, sideClass] of Object.entries(Button.CLASS_EDGES)) {
  2588. css.add(
  2589. `${draggingSelector} #${id}>.${sideClass}.${Button.CLASS_HANDLE}~.${sideClass}.${CornerButton.CLASS_NAME}`,
  2590. [`border-${CornerButton.OPPOSITES[side]}-style`, 'none'],
  2591. ['filter', 'none'],
  2592. );
  2593. // in fullscreen, 16:9 videos get an offsetLeft of 1px on my 16:9 monitor
  2594. // I'm extending buttons by 1px so that they reach the edge of screens like mine at default zoom
  2595. css.add(`#${id}>.${sideClass}`, [`margin-${side}`, '-1px'], [`padding-${side}`, '1px']);
  2596. }
  2597. css.add(`#${id}:not(.${this.CLASS_ABLE} *)`, ['display', 'none']);
  2598. })();
  2599. }(),
  2600. pan: new function () {
  2601. this.CODE = 'pan';
  2602. this.CLASS_ABLE = 'viewfind-action-able-pan';
  2603. this.onActive = () => {
  2604. this.updateCrosshair();
  2605. addListeners(this);
  2606. };
  2607. this.onInactive = () => {
  2608. addListeners(this, false);
  2609. };
  2610. this.updateCrosshair = (() => {
  2611. const getRoundedString = (number, decimal = 2) => {
  2612. const raised = `${Math.round(number * Math.pow(10, decimal))}`.padStart(decimal + 1, '0');
  2613. return `${raised.substr(0, raised.length - decimal)}.${raised.substr(raised.length - decimal)}`;
  2614. };
  2615. const getSigned = (ratio) => {
  2616. const percent = Math.round(ratio * 100);
  2617. if (percent <= 0) {
  2618. return `${percent}`;
  2619. }
  2620. return `+${percent}`;
  2621. };
  2622. return () => {
  2623. crosshair.text.innerText = `${getRoundedString(zoom.value)}×\n${getSigned(position.x)}%\n${getSigned(position.y)}%`;
  2624. };
  2625. })();
  2626. this.onScroll = getOnScroll((distance) => {
  2627. const increment = distance * $config.get().speeds.zoom;
  2628. if (increment > 0) {
  2629. zoom.value *= 1 + increment;
  2630. } else {
  2631. zoom.value /= 1 - increment;
  2632. }
  2633. zoom.constrain();
  2634. position.constrain();
  2635. this.updateCrosshair();
  2636. });
  2637. this.onRightClick = (event) => {
  2638. event.stopImmediatePropagation();
  2639. event.preventDefault();
  2640. if (stopDrag) {
  2641. return;
  2642. }
  2643. position.x = position.y = 0;
  2644. zoom.value = 1;
  2645. position.apply();
  2646. zoom.constrain();
  2647. this.updateCrosshair();
  2648. };
  2649. this.onMouseDown = (() => {
  2650. const getDragListener = () => {
  2651. const {multipliers} = $config.get();
  2652. let priorEvent;
  2653. const change = {x: 0, y: 0};
  2654. return ({offsetX, offsetY}) => {
  2655. if (priorEvent) {
  2656. change.x = (priorEvent.offsetX + change.x - offsetX) * multipliers.pan;
  2657. change.y = (priorEvent.offsetY - change.y - offsetY) * -multipliers.pan;
  2658. position.x += change.x / video.clientWidth;
  2659. position.y += change.y / video.clientHeight;
  2660. position.constrain();
  2661. this.updateCrosshair();
  2662. }
  2663. // events in firefox seem to lose their data after finishing propagation
  2664. // so assigning the whole event doesn't work
  2665. priorEvent = {offsetX, offsetY};
  2666. };
  2667. };
  2668. const clickListener = (event) => {
  2669. position.x = event.offsetX / video.clientWidth - 0.5;
  2670. // Y increases moving down the page
  2671. // I flip that to make trigonometry easier
  2672. position.y = -event.offsetY / video.clientHeight + 0.5;
  2673. position.constrain(true);
  2674. this.updateCrosshair();
  2675. };
  2676. return (event) => {
  2677. if (event.buttons === 1) {
  2678. drag(event, clickListener, getDragListener());
  2679. }
  2680. };
  2681. })();
  2682. }(),
  2683. rotate: new function () {
  2684. this.CODE = 'rotate';
  2685. this.CLASS_ABLE = 'viewfind-action-able-rotate';
  2686. this.onActive = () => {
  2687. this.updateCrosshair();
  2688. addListeners(this);
  2689. };
  2690. this.onInactive = () => {
  2691. addListeners(this, false);
  2692. };
  2693. this.updateCrosshair = () => {
  2694. const angle = DEGREES[90] - rotation.value;
  2695. crosshair.text.innerText = `${Math.floor((DEGREES[90] - rotation.value) / Math.PI * 180)}°\n${Math.round(angle / DEGREES[90]) % 4 * 90}°`;
  2696. };
  2697. this.onScroll = getOnScroll((distance) => {
  2698. rotation.value += distance * $config.get().speeds.rotate;
  2699. rotation.constrain();
  2700. zoom.constrain();
  2701. position.constrain();
  2702. this.updateCrosshair();
  2703. });
  2704. this.onRightClick = (event) => {
  2705. event.stopImmediatePropagation();
  2706. event.preventDefault();
  2707. if (stopDrag) {
  2708. return;
  2709. }
  2710. rotation.value = DEGREES[90];
  2711. rotation.apply();
  2712. zoom.constrain();
  2713. position.constrain();
  2714. this.updateCrosshair();
  2715. };
  2716. this.onMouseDown = (() => {
  2717. const getDragListener = () => {
  2718. const {multipliers} = $config.get();
  2719. const middleX = containers.tracker.clientWidth / 2;
  2720. const middleY = containers.tracker.clientHeight / 2;
  2721. const priorPosition = position.getValues();
  2722. const priorZoom = zoom.value;
  2723. let priorMouseTheta;
  2724. return (event) => {
  2725. const mouseTheta = getTheta(middleX, middleY, event.offsetX, event.offsetY);
  2726. if (priorMouseTheta === undefined) {
  2727. priorMouseTheta = mouseTheta;
  2728. return;
  2729. }
  2730. position.x = priorPosition.x;
  2731. position.y = priorPosition.y;
  2732. zoom.value = priorZoom;
  2733. rotation.value += (priorMouseTheta - mouseTheta) * multipliers.rotate;
  2734. rotation.constrain();
  2735. zoom.constrain();
  2736. position.constrain();
  2737. this.updateCrosshair();
  2738. priorMouseTheta = mouseTheta;
  2739. };
  2740. };
  2741. const clickListener = () => {
  2742. rotation.value = Math.round(rotation.value / DEGREES[90]) * DEGREES[90];
  2743. rotation.constrain();
  2744. zoom.constrain();
  2745. position.constrain();
  2746. this.updateCrosshair();
  2747. };
  2748. return (event) => {
  2749. if (event.buttons === 1) {
  2750. drag(event, clickListener, getDragListener(), containers.tracker);
  2751. }
  2752. };
  2753. })();
  2754. }(),
  2755. configure: new function () {
  2756. this.CODE = 'config';
  2757. this.onActive = async () => {
  2758. await $config.edit();
  2759. updateConfigs();
  2760. viewport.focus();
  2761. glow.reset();
  2762. position.constrain();
  2763. zoom.constrain();
  2764. };
  2765. }(),
  2766. reset: new function () {
  2767. this.CODE = 'reset';
  2768. this.onActive = () => {
  2769. if (this.restore) {
  2770. this.restore();
  2771. } else {
  2772. this.restore = peek();
  2773. }
  2774. };
  2775. }(),
  2776. };
  2777. })();
  2778.  
  2779. const crosshair = new function () {
  2780. this.container = document.createElement('div');
  2781. this.lines = {
  2782. horizontal: document.createElement('div'),
  2783. vertical: document.createElement('div'),
  2784. };
  2785. this.text = document.createElement('div');
  2786. const id = 'viewfind-crosshair';
  2787. this.container.id = id;
  2788. this.container.classList.add(CLASS_VIEWFINDER);
  2789. css.add(`#${id}:not(${css.getSelector(actions.pan.CLASS_ABLE)} *):not(${css.getSelector(actions.rotate.CLASS_ABLE)} *)`, ['display', 'none']);
  2790. this.lines.horizontal.style.position = this.lines.vertical.style.position = this.text.style.position = this.container.style.position = 'absolute';
  2791. this.lines.horizontal.style.top = '50%';
  2792. this.lines.horizontal.style.width = '100%';
  2793. this.lines.vertical.style.left = '50%';
  2794. this.lines.vertical.style.height = '100%';
  2795. this.text.style.userSelect = 'none';
  2796. this.container.style.top = '0';
  2797. this.container.style.width = '100%';
  2798. this.container.style.height = '100%';
  2799. this.container.style.pointerEvents = 'none';
  2800. this.container.append(this.lines.horizontal, this.lines.vertical);
  2801. this.clip = () => {
  2802. const {outer, inner, gap} = $config.get().crosshair;
  2803. const thickness = Math.max(inner, outer);
  2804. const {width, height} = halfDimensions.viewport;
  2805. const halfGap = gap / 2;
  2806. const startInner = (thickness - inner) / 2;
  2807. const startOuter = (thickness - outer) / 2;
  2808. const endInner = thickness - startInner;
  2809. const endOuter = thickness - startOuter;
  2810. this.lines.horizontal.style.clipPath = 'path(\''
  2811. + `M0 ${startOuter}L${width - halfGap} ${startOuter}L${width - halfGap} ${startInner}L${width + halfGap} ${startInner}L${width + halfGap} ${startOuter}L${viewport.clientWidth} ${startOuter}`
  2812. + `L${viewport.clientWidth} ${endOuter}L${width + halfGap} ${endOuter}L${width + halfGap} ${endInner}L${width - halfGap} ${endInner}L${width - halfGap} ${endOuter}L0 ${endOuter}`
  2813. + 'Z\')';
  2814. this.lines.vertical.style.clipPath = 'path(\''
  2815. + `M${startOuter} 0L${startOuter} ${height - halfGap}L${startInner} ${height - halfGap}L${startInner} ${height + halfGap}L${startOuter} ${height + halfGap}L${startOuter} ${viewport.clientHeight}`
  2816. + `L${endOuter} ${viewport.clientHeight}L${endOuter} ${height + halfGap}L${endInner} ${height + halfGap}L${endInner} ${height - halfGap}L${endOuter} ${height - halfGap}L${endOuter} 0`
  2817. + 'Z\')';
  2818. };
  2819. this.updateConfig = (doClip = true) => {
  2820. const {colour, outer, inner, text} = $config.get().crosshair;
  2821. const thickness = Math.max(inner, outer);
  2822. this.container.style.filter = `drop-shadow(${colour.shadow} 0 0 1px)`;
  2823. this.lines.horizontal.style.translate = `0 -${thickness / 2}px`;
  2824. this.lines.vertical.style.translate = `-${thickness / 2}px 0`;
  2825. this.lines.horizontal.style.height = this.lines.vertical.style.width = `${thickness}px`;
  2826. this.lines.horizontal.style.backgroundColor = this.lines.vertical.style.backgroundColor = colour.fill;
  2827. if (text) {
  2828. this.text.style.color = colour.fill;
  2829. this.text.style.font = text.font;
  2830. this.text.style.left = `${text.position.x}%`;
  2831. this.text.style.top = `${text.position.y}%`;
  2832. this.text.style.transform = `translate(${text.translate.x}%,${text.translate.y}%) translate(${text.offset.x}px,${text.offset.y}px)`;
  2833. this.text.style.textAlign = text.align;
  2834. this.text.style.lineHeight = text.height;
  2835. this.container.append(this.text);
  2836. } else {
  2837. this.text.remove();
  2838. }
  2839. if (doClip) {
  2840. this.clip();
  2841. }
  2842. };
  2843. $config.ready.then(() => {
  2844. this.updateConfig(false);
  2845. });
  2846. }();
  2847.  
  2848. // ELEMENT CHANGE LISTENERS
  2849.  
  2850. const observer = new function () {
  2851. const onResolutionChange = () => {
  2852. glow.handleSizeChange?.();
  2853. };
  2854. const styleObserver = new MutationObserver((() => {
  2855. const properties = ['top', 'left', 'width', 'height', 'scale', 'rotate', 'translate', 'transform-origin'];
  2856. let priorStyle;
  2857. return () => {
  2858. // mousemove events on video with ctrlKey=true trigger this but have no effect
  2859. if (video.style.cssText === priorStyle) {
  2860. return;
  2861. }
  2862. priorStyle = video.style.cssText;
  2863. for (const property of properties) {
  2864. containers.background.style[property] = video.style[property];
  2865. containers.foreground.style[property] = video.style[property];
  2866. // cinematics doesn't exist for embedded vids
  2867. if (cinematics) {
  2868. cinematics.style[property] = video.style[property];
  2869. }
  2870. }
  2871. glow.handleViewChange();
  2872. };
  2873. })());
  2874. const videoObserver = new ResizeObserver(() => {
  2875. handleVideoChange();
  2876. glow.handleSizeChange?.();
  2877. });
  2878. const viewportObserver = new ResizeObserver(() => {
  2879. handleViewportChange();
  2880. crosshair.clip();
  2881. });
  2882. this.start = () => {
  2883. video.addEventListener('resize', onResolutionChange);
  2884. styleObserver.observe(video, {attributes: true, attributeFilter: ['style']});
  2885. viewportObserver.observe(viewport);
  2886. videoObserver.observe(video);
  2887. glow.handleViewChange();
  2888. };
  2889. this.stop = () => {
  2890. video.removeEventListener('resize', onResolutionChange);
  2891. styleObserver.disconnect();
  2892. viewportObserver.disconnect();
  2893. videoObserver.disconnect();
  2894. };
  2895. }();
  2896.  
  2897. // NAVIGATION LISTENERS
  2898.  
  2899. const stop = () => {
  2900. if (stopped) {
  2901. return;
  2902. }
  2903. stopped = true;
  2904. enabler.stop();
  2905. stopDrag?.();
  2906. observer.stop();
  2907. containers.background.remove();
  2908. containers.foreground.remove();
  2909. containers.tracker.remove();
  2910. crosshair.container.remove();
  2911. return peek(true);
  2912. };
  2913.  
  2914. const start = () => {
  2915. if (!stopped || viewport.classList.contains('ad-showing')) {
  2916. return;
  2917. }
  2918. stopped = false;
  2919. observer.start();
  2920. glow.start();
  2921. viewport.append(containers.background, containers.foreground, containers.tracker, crosshair.container);
  2922. // User may have a static minimum zoom greater than 1
  2923. zoom.constrain();
  2924. enabler.handleChange();
  2925. };
  2926.  
  2927. const updateConfigs = () => {
  2928. ConfigCache.id++;
  2929. position.updateFrame();
  2930. enabler.updateConfig();
  2931. actions.crop.updateConfig();
  2932. crosshair.updateConfig();
  2933. };
  2934.  
  2935. // LISTENER ASSIGNMENTS
  2936.  
  2937. // load & navigation
  2938. (() => {
  2939. const getNode = (node, selector, ...selectors) => new Promise((resolve) => {
  2940. for (const child of node.children) {
  2941. if (child.matches(selector)) {
  2942. resolve(selectors.length === 0 ? child : getNode(child, ...selectors));
  2943. return;
  2944. }
  2945. }
  2946. new MutationObserver((changes, observer) => {
  2947. for (const {addedNodes} of changes) {
  2948. for (const child of addedNodes) {
  2949. if (child.matches(selector)) {
  2950. resolve(selectors.length === 0 ? child : getNode(child, ...selectors));
  2951. observer.disconnect();
  2952. return;
  2953. }
  2954. }
  2955. }
  2956. }).observe(node, {childList: true});
  2957. });
  2958. const setupConfigFailsafe = (parent) => {
  2959. new MutationObserver((changes) => {
  2960. for (const {addedNodes} of changes) {
  2961. for (const node of addedNodes) {
  2962. if (!node.classList.contains('ytp-contextmenu')) {
  2963. continue;
  2964. }
  2965. const container = node.querySelector('.ytp-panel-menu');
  2966. const option = container.lastElementChild.cloneNode(true);
  2967. option.children[0].style.visibility = 'hidden';
  2968. option.children[1].innerText = 'Configure Viewfinding';
  2969. option.addEventListener('click', ({button}) => {
  2970. if (button === 0) {
  2971. actions.configure.onActive();
  2972. }
  2973. });
  2974. container.appendChild(option);
  2975. new ResizeObserver((_, observer) => {
  2976. if (container.clientWidth === 0) {
  2977. option.remove();
  2978. observer.disconnect();
  2979. }
  2980. }).observe(container);
  2981. }
  2982. }
  2983. }).observe(parent, {childList: true});
  2984. };
  2985. const init = async () => {
  2986. if (unsafeWindow.ytplayer?.bootstrapPlayerContainer?.childElementCount > 0) {
  2987. // wait for the video to be moved to ytd-app
  2988. await new Promise((resolve) => {
  2989. new MutationObserver((changes, observer) => {
  2990. resolve();
  2991. observer.disconnect();
  2992. }).observe(unsafeWindow.ytplayer.bootstrapPlayerContainer, {childList: true});
  2993. });
  2994. }
  2995. try {
  2996. await $config.ready;
  2997. } catch (error) {
  2998. if (!$config.reset || !window.confirm(`${error.message}\n\nWould you like to erase your data?`)) {
  2999. console.error(error);
  3000. return;
  3001. }
  3002. await $config.reset();
  3003. updateConfigs();
  3004. }
  3005. if (isEmbed) {
  3006. video = document.body.querySelector(SELECTOR_VIDEO);
  3007. } else {
  3008. const pageManager = await getNode(document.body, 'ytd-app', '#content', 'ytd-page-manager');
  3009. const page = pageManager.getCurrentPage() ?? await new Promise((resolve) => {
  3010. new MutationObserver(([{addedNodes: [page]}], observer) => {
  3011. if (page) {
  3012. resolve(page);
  3013. observer.disconnect();
  3014. }
  3015. }).observe(pageManager, {childList: true});
  3016. });
  3017. await page.playerEl.getPlayerPromise();
  3018. video = page.playerEl.querySelector(SELECTOR_VIDEO);
  3019. cinematics = page.querySelector('#cinematics');
  3020. // navigation to a new video
  3021. new MutationObserver(() => {
  3022. video.removeEventListener('play', startIfReady);
  3023. power.off();
  3024. // this callback can occur after metadata loads
  3025. startIfReady();
  3026. }).observe(page, {attributes: true, attributeFilter: ['video-id']});
  3027. // navigation to a non-video page
  3028. new MutationObserver(() => {
  3029. if (video.src === '') {
  3030. video.removeEventListener('play', startIfReady);
  3031. power.off();
  3032. }
  3033. }).observe(video, {attributes: true, attributeFilter: ['src']});
  3034. }
  3035. viewport = video.parentElement.parentElement;
  3036. altTarget = viewport.parentElement;
  3037. containers.foreground.style.zIndex = crosshair.container.style.zIndex = video.parentElement.computedStyleMap?.().get('z-index').value ?? 10;
  3038. crosshair.clip();
  3039. handleVideoChange();
  3040. handleViewportChange();
  3041. setupConfigFailsafe(document.body);
  3042. setupConfigFailsafe(viewport);
  3043. const startIfReady = () => {
  3044. if (video.readyState >= HTMLMediaElement.HAVE_METADATA) {
  3045. start();
  3046. }
  3047. };
  3048. const power = new function () {
  3049. this.off = () => {
  3050. delete this.wake;
  3051. stop();
  3052. };
  3053. this.sleep = () => {
  3054. this.wake ??= stop();
  3055. };
  3056. }();
  3057. new MutationObserver((() => {
  3058. return () => {
  3059. // video end
  3060. if (viewport.classList.contains('ended-mode')) {
  3061. power.off();
  3062. video.addEventListener('play', startIfReady, {once: true});
  3063. // ad start
  3064. } else if (viewport.classList.contains('ad-showing')) {
  3065. power.sleep();
  3066. }
  3067. };
  3068. })()).observe(viewport, {attributes: true, attributeFilter: ['class']});
  3069. // glow initialisation requires video dimensions
  3070. startIfReady();
  3071. video.addEventListener('loadedmetadata', () => {
  3072. if (viewport.classList.contains('ad-showing')) {
  3073. return;
  3074. }
  3075. start();
  3076. if (power.wake) {
  3077. power.wake();
  3078. delete power.wake;
  3079. }
  3080. });
  3081. };
  3082. if (!('ytPageType' in unsafeWindow) || unsafeWindow.ytPageType === 'watch') {
  3083. init();
  3084. return;
  3085. }
  3086. const initListener = ({detail: {newPageType}}) => {
  3087. if (newPageType === 'ytd-watch-flexy') {
  3088. init();
  3089. document.body.removeEventListener('yt-page-type-changed', initListener);
  3090. }
  3091. };
  3092. document.body.addEventListener('yt-page-type-changed', initListener);
  3093. })();
  3094.  
  3095. // keyboard state change
  3096.  
  3097. document.addEventListener('keydown', ({code}) => {
  3098. if (enabler.toggled) {
  3099. enabler.keys[enabler.keys.has(code) ? 'delete' : 'add'](code);
  3100. enabler.handleChange();
  3101. } else if (!enabler.keys.has(code)) {
  3102. enabler.keys.add(code);
  3103. enabler.handleChange();
  3104. }
  3105. });
  3106.  
  3107. document.addEventListener('keyup', ({code}) => {
  3108. if (enabler.toggled) {
  3109. return;
  3110. }
  3111. if (enabler.keys.has(code)) {
  3112. enabler.keys.delete(code);
  3113. enabler.handleChange();
  3114. }
  3115. });
  3116.  
  3117. window.addEventListener('blur', () => {
  3118. if (enabler.toggled) {
  3119. stopDrag?.();
  3120. } else {
  3121. enabler.keys.clear();
  3122. enabler.handleChange();
  3123. }
  3124. });
  3125. })();