Greasy Fork 还支持 简体中文。

YouTube Viewfinding

Zoom, rotate & crop YouTube videos

  1. // ==UserScript==
  2. // @name YouTube Viewfinding
  3. // @version 0.34
  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. // insertion order decides priority
  1011. css.add(`${css.getSelector(this.CLASS_DRAGGING)} #movie_player`, ['cursor', 'grabbing']);
  1012. css.add(`${css.getSelector(this.CLASS_ABLE)} #movie_player`, ['cursor', 'grab']);
  1013. }();
  1014.  
  1015. // ELEMENT CONTAINER SETUP
  1016.  
  1017. const containers = new function () {
  1018. for (const name of ['background', 'foreground', 'tracker']) {
  1019. this[name] = document.createElement('div');
  1020. this[name].classList.add(CLASS_VIEWFINDER);
  1021. }
  1022. // make an outline of the uncropped video
  1023. css.add(`${css.getSelector(enabler.CLASS_ABLE)} #${this.foreground.id = 'viewfind-outlined'}`, ['outline', '1px solid white']);
  1024. this.background.style.position = this.foreground.style.position = 'absolute';
  1025. this.background.style.pointerEvents = this.foreground.style.pointerEvents = this.tracker.style.pointerEvents = 'none';
  1026. this.tracker.style.height = this.tracker.style.width = '100%';
  1027. }();
  1028.  
  1029. // CACHE
  1030.  
  1031. class Cache {
  1032. targets = [];
  1033. constructor(...targets) {
  1034. for (const source of targets) {
  1035. this.targets.push({source});
  1036. }
  1037. }
  1038. update(target) {
  1039. return target.value !== (target.value = target.source.value);
  1040. }
  1041. isStale() {
  1042. return this.targets.reduce((value, target) => value || this.update(target), false);
  1043. }
  1044. }
  1045.  
  1046. class ConfigCache extends Cache {
  1047. static id = 0;
  1048. id = this.constructor.id;
  1049. constructor(...targets) {
  1050. super(...targets);
  1051. }
  1052. isStale() {
  1053. if (this.id === (this.id = this.constructor.id)) {
  1054. return super.isStale();
  1055. }
  1056. for (const target of this.targets) {
  1057. target.value = target.source.value;
  1058. }
  1059. return true;
  1060. }
  1061. }
  1062.  
  1063. class DimensionCache extends ConfigCache {
  1064. static id = 0;
  1065. }
  1066.  
  1067. // RESIZE OBSERVER WRAPPER
  1068.  
  1069. class FixedResizeObserver {
  1070. #observer;
  1071. #doSkip;
  1072. constructor(callback) {
  1073. this.#observer = new ResizeObserver(() => {
  1074. if (!this.#doSkip) {
  1075. callback();
  1076. }
  1077. this.#doSkip = false;
  1078. });
  1079. }
  1080. observe(target) {
  1081. this.#doSkip = true;
  1082. this.#observer.observe(target);
  1083. }
  1084. disconnect() {
  1085. this.#observer.disconnect();
  1086. }
  1087. }
  1088.  
  1089. // MODIFIERS
  1090.  
  1091. const rotation = new function () {
  1092. this.value = DEGREES[90];
  1093. this.reset = () => {
  1094. this.value = DEGREES[90];
  1095. video.style.removeProperty('rotate');
  1096. };
  1097. this.apply = () => {
  1098. // Conversion from anticlockwise rotation from the x-axis to clockwise rotation from the y-axis
  1099. video.style.setProperty('rotate', `${DEGREES[90] - this.value}rad`);
  1100. delete actions.reset.restore;
  1101. };
  1102. // dissimilar from other constrain functions in that no effective limit is applied
  1103. // -1.5π < rotation <= 0.5π
  1104. // 0 <= 0.5π - rotation < 2π
  1105. this.constrain = () => {
  1106. this.value %= DEGREES[360];
  1107. if (this.value > DEGREES[90]) {
  1108. this.value -= DEGREES[360];
  1109. } else if (this.value <= -DEGREES[270]) {
  1110. this.value += DEGREES[360];
  1111. }
  1112. this.apply();
  1113. };
  1114. }();
  1115.  
  1116. const zoom = new function () {
  1117. this.value = 1;
  1118. const scaleRule = new css.Toggleable();
  1119. this.reset = () => {
  1120. this.value = 1;
  1121. video.style.removeProperty('scale');
  1122. scaleRule.remove();
  1123. scaleRule.add(':root', [VAR_ZOOM, '1']);
  1124. };
  1125. this.apply = () => {
  1126. video.style.setProperty('scale', `${this.value}`);
  1127. scaleRule.remove();
  1128. scaleRule.add(':root', [VAR_ZOOM, `${this.value}`]);
  1129. delete actions.reset.restore;
  1130. };
  1131. const getFit = (corner0, corner1, doSplit = false) => {
  1132. const x = Math.max(corner0.x, corner1.x) / viewport.clientWidth;
  1133. const y = Math.max(corner0.y, corner1.y) / viewport.clientHeight;
  1134. return doSplit ? [0.5 / x, 0.5 / y] : 0.5 / Math.max(x, y);
  1135. };
  1136. this.getFit = (width, height) => getFit(...getRotatedCorners(Math.sqrt(width * width + height * height), getTheta(0, 0, width, height)));
  1137. this.getVideoFit = (doSplit) => getFit(...getRotatedCorners(videoHypotenuse, videoTheta), doSplit);
  1138. this.constrain = (() => {
  1139. const limitGetters = {
  1140. [LIMITS.static]: [({custom}) => custom, ({custom}) => custom],
  1141. [LIMITS.fit]: (() => {
  1142. const getGetter = () => {
  1143. const zoomCache = new Cache(this);
  1144. const rotationCache = new DimensionCache(rotation);
  1145. const configCache = new ConfigCache();
  1146. let updateOnZoom;
  1147. let value;
  1148. return ({frame}, glow) => {
  1149. let fallthrough = rotationCache.isStale();
  1150. if (configCache.isStale()) {
  1151. if (glow) {
  1152. const {scaled} = glow.blur;
  1153. updateOnZoom = frame > 0 && (scaled.x > 0 || scaled.y > 0);
  1154. } else {
  1155. updateOnZoom = false;
  1156. }
  1157. fallthrough = true;
  1158. }
  1159. if (zoomCache.isStale() && updateOnZoom || fallthrough) {
  1160. if (glow) {
  1161. const base = glow.end - 1;
  1162. const {scaled, unscaled} = glow.blur;
  1163. value = this.getFit(
  1164. halfDimensions.video.width + Math.max(0, base * halfDimensions.video.width + Math.max(unscaled.x, scaled.x * this.value)) * frame,
  1165. halfDimensions.video.height + Math.max(0, base * halfDimensions.video.height + Math.max(unscaled.y, scaled.y * this.value)) * frame,
  1166. );
  1167. } else {
  1168. value = this.getVideoFit();
  1169. }
  1170. }
  1171. return value;
  1172. };
  1173. };
  1174. return [getGetter(), getGetter()];
  1175. })(),
  1176. };
  1177. return () => {
  1178. const {zoomOutLimit, zoomInLimit, glow} = $config.get();
  1179. if (zoomOutLimit.type !== 'None') {
  1180. this.value = Math.max(limitGetters[zoomOutLimit.type][0](zoomOutLimit, glow), this.value);
  1181. }
  1182. if (zoomInLimit.type !== 'None') {
  1183. this.value = Math.min(limitGetters[zoomInLimit.type][1](zoomInLimit, glow, 1), this.value);
  1184. }
  1185. this.apply();
  1186. };
  1187. })();
  1188. }();
  1189.  
  1190. const position = new function () {
  1191. this.x = this.y = 0;
  1192. this.getValues = () => ({x: this.x, y: this.y});
  1193. this.reset = () => {
  1194. this.x = this.y = 0;
  1195. video.style.removeProperty('translate');
  1196. };
  1197. this.apply = () => {
  1198. video.style.setProperty('transform-origin', `${(0.5 + this.x) * 100}% ${(0.5 - this.y) * 100}%`);
  1199. video.style.setProperty('translate', `${-this.x * 100}% ${this.y * 100}%`);
  1200. delete actions.reset.restore;
  1201. };
  1202. const frame = new function () {
  1203. const canvas = document.createElement('canvas');
  1204. const ctx = canvas.getContext('2d');
  1205. Object.defineProperty(this, 'hide', (() => {
  1206. let hide = true;
  1207. return {
  1208. get: () => hide,
  1209. set: (value) => {
  1210. if (value) {
  1211. canvas.style.setProperty('display', 'none');
  1212. } else {
  1213. canvas.style.removeProperty('display');
  1214. }
  1215. hide = value;
  1216. },
  1217. };
  1218. })());
  1219. canvas.id = 'viewfind-frame-canvas';
  1220. // lazy code
  1221. window.setTimeout(() => {
  1222. css.add(`#${canvas.id}:not(${css.getSelector(actions.pan.CLASS_ABLE)} *):not(${css.getSelector(actions.rotate.CLASS_ABLE)} *)`, ['display', 'none']);
  1223. }, 0);
  1224. canvas.style.position = 'absolute';
  1225. containers.foreground.append(canvas);
  1226. const to = (x, y, move = false) => {
  1227. ctx[`${move ? 'move' : 'line'}To`]((x + 0.5) * video.clientWidth, (0.5 - y) * video.clientHeight);
  1228. };
  1229. this.draw = (points) => {
  1230. canvas.width = video.clientWidth;
  1231. canvas.height = video.clientHeight;
  1232. if (this.hide || !points) {
  1233. return;
  1234. }
  1235. ctx.save();
  1236. ctx.beginPath();
  1237. ctx.moveTo(0, 0);
  1238. ctx.lineTo(canvas.width, 0);
  1239. ctx.lineTo(canvas.width, canvas.height);
  1240. ctx.lineTo(0, canvas.height);
  1241. ctx.closePath();
  1242. let doMove = true;
  1243. for (const {x, y} of points) {
  1244. to(x, y, doMove);
  1245. doMove = false;
  1246. }
  1247. ctx.closePath();
  1248. ctx.clip('evenodd');
  1249. ctx.fillStyle = 'black';
  1250. ctx.globalAlpha = 0.6;
  1251. ctx.fillRect(0, 0, canvas.width, canvas.height);
  1252. ctx.restore();
  1253. ctx.beginPath();
  1254. if (points.length !== 2) {
  1255. return;
  1256. }
  1257. ctx.strokeStyle = 'white';
  1258. ctx.lineWidth = 1;
  1259. ctx.globalAlpha = 1;
  1260. doMove = true;
  1261. for (const {x, y} of points) {
  1262. to(x, y, doMove);
  1263. doMove = false;
  1264. }
  1265. ctx.stroke();
  1266. };
  1267. }();
  1268. this.updateFrameOnReset = () => {
  1269. const {panLimit, crosshair: {showFrame}} = $config.get();
  1270. if (showFrame && panLimit.type === LIMITS.fit) {
  1271. this.constrain();
  1272. }
  1273. };
  1274. this.updateFrame = () => {
  1275. const {panLimit, crosshair: {showFrame}} = $config.get();
  1276. frame.hide = !showFrame;
  1277. if (frame.hide) {
  1278. return;
  1279. }
  1280. switch (panLimit.type) {
  1281. case LIMITS.fit:
  1282. return;
  1283. case LIMITS.static:
  1284. if (panLimit.custom < 0.5) {
  1285. frame.draw([
  1286. {x: panLimit.custom, y: panLimit.custom},
  1287. {x: panLimit.custom, y: -panLimit.custom},
  1288. {x: -panLimit.custom, y: -panLimit.custom},
  1289. {x: -panLimit.custom, y: panLimit.custom},
  1290. ]);
  1291. return;
  1292. }
  1293. }
  1294. frame.draw();
  1295. };
  1296. this.constrain = (() => {
  1297. // logarithmic progress from "low" to infinity
  1298. const getProgress = (low, target) => 1 - low / target;
  1299. const getProgressed = ({x: fromX, y: fromY, z: lowZ}, {x: toX, y: toY}, targetZ) => {
  1300. const p = getProgress(lowZ, targetZ);
  1301. return {x: p * (toX - fromX) + fromX, y: p * (toY - fromY) + fromY};
  1302. };
  1303. // y = mx + c
  1304. const getLineY = ({m, c}, x = this.x) => m * x + c;
  1305. // x = (y - c) / m
  1306. const getLineX = ({m, c}, y = this.y) => (y - c) / m;
  1307. const getM = (from, to) => (to.y - from.y) / (to.x - from.x);
  1308. const getLine = (m, {x, y} = this) => ({c: y - m * x, m, x, y});
  1309. const getFlipped = ({x, y}) => ({x: -x, y: -y});
  1310. const isAbove = ({m, c}, {x, y} = this) => m * x + c < y;
  1311. const isRight = (line, {x, y} = this) => {
  1312. const lineX = (y - line.c) / line.m;
  1313. return x > (isNaN(lineX) ? line.x : lineX);
  1314. };
  1315. const constrain2D = (() => {
  1316. const isBetween = (() => {
  1317. const isBetweenBase = ({low, high}) => {
  1318. return isRight(low) && !isRight(high);
  1319. };
  1320. const isBetweenSide = ({low, high}) => {
  1321. return isAbove(low) && !isAbove(high);
  1322. };
  1323. return (line, tangent) => {
  1324. if (tangent.isSide) {
  1325. return isBetweenSide(tangent) && (tangent.isHigh ? isRight(line) : !isRight(line));
  1326. }
  1327. return isBetweenBase(tangent) && (tangent.isHigh ? isAbove(line) : !isAbove(line));
  1328. };
  1329. })();
  1330. const setTangentIntersect = (() => {
  1331. const setTangentIntersectX = (line, m, diff) => {
  1332. if (line.m === 0) {
  1333. this.y = line.y;
  1334. return;
  1335. }
  1336. const tangent = getLine(m);
  1337. this.x = (tangent.c - line.c) / diff;
  1338. this.y = getLineY(line);
  1339. };
  1340. const setTangentIntersectY = (line, m, diff) => {
  1341. if (m === 0) {
  1342. this.x = line.x;
  1343. return;
  1344. }
  1345. const tangent = getLine(m);
  1346. this.y = (m * line.c - line.m * tangent.c) / -diff;
  1347. this.x = getLineX(line);
  1348. };
  1349. return (line, {isSide}, m, diff) => {
  1350. if (isSide) {
  1351. setTangentIntersectY(line, m, diff);
  1352. } else {
  1353. setTangentIntersectX(line, m, diff);
  1354. }
  1355. };
  1356. })();
  1357. const isOutside = (tangent, property) => {
  1358. if (tangent.isSide) {
  1359. return tangent[property].isHigh ? isAbove(tangent.high) : !isAbove(tangent.low);
  1360. }
  1361. return tangent[property].isHigh ? isRight(tangent.high) : !isRight(tangent.low);
  1362. };
  1363. return (points, lines, tangents) => {
  1364. if (isBetween(lines.top, tangents.top)) {
  1365. setTangentIntersect(lines.top, tangents.top, tangents.base, tangents.baseDiff);
  1366. } else if (isBetween(lines.bottom, tangents.bottom)) {
  1367. setTangentIntersect(lines.bottom, tangents.bottom, tangents.base, tangents.baseDiff);
  1368. } else if (isBetween(lines.right, tangents.right)) {
  1369. setTangentIntersect(lines.right, tangents.right, tangents.side, tangents.sideDiff);
  1370. } else if (isBetween(lines.left, tangents.left)) {
  1371. setTangentIntersect(lines.left, tangents.left, tangents.side, tangents.sideDiff);
  1372. } else if (isOutside(tangents.top, 'right') && isOutside(tangents.right, 'top')) {
  1373. this.x = points.topRight.x;
  1374. this.y = points.topRight.y;
  1375. } else if (isOutside(tangents.bottom, 'right') && isOutside(tangents.right, 'bottom')) {
  1376. this.x = points.bottomRight.x;
  1377. this.y = points.bottomRight.y;
  1378. } else if (isOutside(tangents.top, 'left') && isOutside(tangents.left, 'top')) {
  1379. this.x = points.topLeft.x;
  1380. this.y = points.topLeft.y;
  1381. } else if (isOutside(tangents.bottom, 'left') && isOutside(tangents.left, 'bottom')) {
  1382. this.x = points.bottomLeft.x;
  1383. this.y = points.bottomLeft.y;
  1384. }
  1385. };
  1386. })();
  1387. const get1DConstrainer = (point) => {
  1388. const line = {
  1389. ...point,
  1390. m: point.y / point.x,
  1391. c: 0,
  1392. };
  1393. frame.draw([point, getFlipped(point)]);
  1394. if (!isFinite(line.m)) {
  1395. return () => {
  1396. this.y = Math.max(-point.y, Math.min(point.y, this.y));
  1397. this.x = 0;
  1398. };
  1399. }
  1400. if (line.x < 0) {
  1401. line.x = -line.x;
  1402. line.y = -line.y;
  1403. }
  1404. if (line.m === 0) {
  1405. return () => {
  1406. this.x = Math.max(-line.x, Math.min(line.x, this.x));
  1407. this.y = 0;
  1408. };
  1409. }
  1410. const tangentM = -1 / line.m;
  1411. const mDiff = line.m - tangentM;
  1412. return () => {
  1413. this.x = Math.max(-line.x, Math.min(line.x, getLine(tangentM).c / mDiff));
  1414. this.y = getLineY(line, this.x);
  1415. };
  1416. };
  1417. const getBoundApplyFrame = (() => {
  1418. const getBound = (first, second, isTopLeft) => {
  1419. if (zoom.value <= first.z) {
  1420. return false;
  1421. }
  1422. if (zoom.value >= second.z) {
  1423. const progress = zoom.value / second.z;
  1424. const x = isTopLeft ?
  1425. -0.5 - (-0.5 - second.x) / progress :
  1426. 0.5 - (0.5 - second.x) / progress;
  1427. return {
  1428. x,
  1429. y: 0.5 - (0.5 - second.y) / progress,
  1430. };
  1431. }
  1432. return {
  1433. ...getProgressed(first, second.vpEnd, zoom.value),
  1434. axis: second.vpEnd.axis,
  1435. m: second.y / second.x,
  1436. c: 0,
  1437. };
  1438. };
  1439. const swap = (array, i0, i1) => {
  1440. const temp = array[i0];
  1441. array[i0] = array[i1];
  1442. array[i1] = temp;
  1443. };
  1444. const setHighTangent = (tangent, low, high) => {
  1445. tangent.low = tangent[low];
  1446. tangent.high = tangent[high];
  1447. tangent[low].isHigh = false;
  1448. tangent[high].isHigh = true;
  1449. };
  1450. const getFrame = (point0, point1) => {
  1451. const flipped0 = getFlipped(point0);
  1452. const flipped1 = getFlipped(point1);
  1453. const m0 = getM(point0, point1);
  1454. const m1 = getM(flipped0, point1);
  1455. const tangentM0 = -1 / m0;
  1456. const tangentM1 = -1 / m1;
  1457. const lines = {
  1458. top: getLine(m0, point0),
  1459. bottom: getLine(m0, flipped0),
  1460. left: getLine(m1, point0),
  1461. right: getLine(m1, flipped0),
  1462. };
  1463. const points = {
  1464. topLeft: point0,
  1465. topRight: point1,
  1466. bottomRight: flipped0,
  1467. bottomLeft: flipped1,
  1468. };
  1469. const tangents = {
  1470. top: {
  1471. right: getLine(tangentM0, points.topRight),
  1472. left: getLine(tangentM0, points.topLeft),
  1473. },
  1474. right: {
  1475. top: getLine(tangentM1, points.topRight),
  1476. bottom: getLine(tangentM1, points.bottomRight),
  1477. },
  1478. bottom: {
  1479. right: getLine(tangentM0, points.bottomRight),
  1480. left: getLine(tangentM0, points.bottomLeft),
  1481. },
  1482. left: {
  1483. top: getLine(tangentM1, points.topLeft),
  1484. bottom: getLine(tangentM1, points.bottomLeft),
  1485. },
  1486. baseDiff: m0 - tangentM0,
  1487. sideDiff: m1 - tangentM1,
  1488. base: tangentM0,
  1489. side: tangentM1,
  1490. };
  1491. if (video.clientWidth < video.clientHeight) {
  1492. if (getLineX(lines.right, 0) < getLineX(lines.left, 0)) {
  1493. swap(lines, 'right', 'left');
  1494. swap(points, 'bottomLeft', 'bottomRight');
  1495. swap(points, 'topLeft', 'topRight');
  1496. swap(tangents, 'right', 'left');
  1497. swap(tangents.top, 'right', 'left');
  1498. swap(tangents.bottom, 'right', 'left');
  1499. }
  1500. } else {
  1501. if (lines.top.c < lines.bottom.c) {
  1502. swap(lines, 'top', 'bottom');
  1503. swap(points, 'topLeft', 'bottomLeft');
  1504. swap(points, 'topRight', 'bottomRight');
  1505. swap(tangents, 'top', 'bottom');
  1506. swap(tangents.left, 'top', 'bottom');
  1507. swap(tangents.right, 'top', 'bottom');
  1508. }
  1509. }
  1510. tangents.top.isSide = tangents.bottom.isSide = Math.abs(m0) > 1;
  1511. tangents.top.isHigh = !tangents.top.isSide || lines.top.c < 0 === m0 > 0;
  1512. tangents.bottom.isHigh = !tangents.top.isHigh;
  1513. if (tangents.top.isSide && tangents.top.isHigh) {
  1514. setHighTangent(tangents.top, 'right', 'left');
  1515. setHighTangent(tangents.bottom, 'right', 'left');
  1516. } else {
  1517. setHighTangent(tangents.top, 'left', 'right');
  1518. setHighTangent(tangents.bottom, 'left', 'right');
  1519. }
  1520. tangents.right.isSide = tangents.left.isSide = Math.abs(m1) > 1;
  1521. tangents.right.isHigh = tangents.right.isSide || lines.right.c > 0;
  1522. tangents.left.isHigh = !tangents.right.isHigh;
  1523. if (!tangents.right.isSide && tangents.right.isHigh) {
  1524. setHighTangent(tangents.right, 'top', 'bottom');
  1525. setHighTangent(tangents.left, 'top', 'bottom');
  1526. } else {
  1527. setHighTangent(tangents.right, 'bottom', 'top');
  1528. setHighTangent(tangents.left, 'bottom', 'top');
  1529. }
  1530. frame.draw(Object.values(points));
  1531. return [points, lines, tangents];
  1532. };
  1533. return (first0, second0, first1, second1) => {
  1534. const point0 = getBound(first0, second0, true);
  1535. const point1 = getBound(first1, second1, false);
  1536. if (point0 && point1) {
  1537. return constrain2D.bind(null, ...getFrame(point0, point1));
  1538. }
  1539. if (point0 || point1) {
  1540. return get1DConstrainer(point0 || point1);
  1541. }
  1542. frame.draw([]);
  1543. return () => {
  1544. this.x = this.y = 0;
  1545. };
  1546. };
  1547. })();
  1548. const snapZoom = (() => {
  1549. const getDirected = (first, second, flipX, flipY) => {
  1550. const line0 = [first, {}];
  1551. const line1 = [{z: second.z}, {}];
  1552. if (flipX) {
  1553. line0[1].x = -second.vpEnd.x;
  1554. line1[0].x = -second.x;
  1555. line1[1].x = -0.5;
  1556. } else {
  1557. line0[1].x = second.vpEnd.x;
  1558. line1[0].x = second.x;
  1559. line1[1].x = 0.5;
  1560. }
  1561. if (flipY) {
  1562. line0[1].y = -second.vpEnd.y;
  1563. line1[0].y = -second.y;
  1564. line1[1].y = -0.5;
  1565. } else {
  1566. line0[1].y = second.vpEnd.y;
  1567. line1[0].y = second.y;
  1568. line1[1].y = 0.5;
  1569. }
  1570. return [line0, line1];
  1571. };
  1572. // https://math.stackexchange.com/questions/2223691/intersect-2-lines-at-the-same-ratio-through-a-point
  1573. const getIntersectProgress = ({x, y}, [{x: g, y: e}, {x: f, y: d}], [{x: k, y: i}, {x: j, y: h}], doFlip) => {
  1574. const a = d * j - d * k - j * e + e * k - h * f + h * g + i * f - i * g;
  1575. 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;
  1576. const c = k * e - e * x - k * y - g * i + i * x + g * y;
  1577. return (doFlip ? -b - Math.sqrt(b * b - 4 * a * c) : -b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
  1578. };
  1579. // line with progressed start point
  1580. const getProgressedLine = (line, {z}) => [getProgressed(...line, z), line[1]];
  1581. const isValidZoom = (zoom) => zoom !== null && !isNaN(zoom);
  1582. const getZoom = (pair0, pair1, pair2, position, doFlip) => getZoomPairSecond(pair2, position, doFlip)
  1583. || getZoomPairSecond(pair1, position, doFlip, getProgress(pair1[0], pair2[0]))
  1584. || getZoomPairSecond(pair0, position, doFlip, getProgress(pair0[0], pair1[0]));
  1585. const getZoomPairSecond = ([z, ...pair], position, doFlip, maxP = 1) => {
  1586. if (maxP >= 0) {
  1587. const p = getIntersectProgress(position, ...pair, doFlip);
  1588. if (p >= 0 && p <= maxP) {
  1589. // I don't think the >= 1 check is necessary but best be safe
  1590. return p >= 1 ? Number.MAX_SAFE_INTEGER : z / (1 - p);
  1591. }
  1592. }
  1593. return null;
  1594. };
  1595. return (first0, _second0, first1, second1) => {
  1596. const second0 = {..._second0, x: -_second0.x, vpEnd: {..._second0.vpEnd, x: -_second0.vpEnd.x}};
  1597. const absPosition = {x: Math.abs(this.x), y: Math.abs(this.y)};
  1598. const getPairings = (flipX0, flipY0, flipX1, flipY1) => {
  1599. const [lineFirst0, lineSecond0] = getDirected(first0, second0, flipX0, flipY0);
  1600. const [lineFirst1, lineSecond1] = getDirected(first1, second1, flipX1, flipY1);
  1601. // array structure is:
  1602. // start zoom for both lines
  1603. // 0 line start and its infinite zoom point
  1604. // 1 line start and its infinite zoom point
  1605. return [
  1606. first0.z >= first1.z ?
  1607. [first0.z, lineFirst0, getProgressedLine(lineFirst1, first0)] :
  1608. [first1.z, getProgressedLine(lineFirst0, first1), lineFirst1],
  1609. ...second0.z >= second1.z ?
  1610. [
  1611. [second1.z, getProgressedLine(lineFirst0, second1), lineSecond1],
  1612. [second0.z, lineSecond0, getProgressedLine(lineSecond1, second0)],
  1613. ] :
  1614. [
  1615. [second0.z, lineSecond0, getProgressedLine(lineFirst1, second0)],
  1616. [second1.z, getProgressedLine(lineSecond0, second1), lineSecond1],
  1617. ],
  1618. ];
  1619. };
  1620. zoom.value = Math.max(...[
  1621. getZoom(...getPairings(false, false, true, false), absPosition, true),
  1622. getZoom(...getPairings(false, false, false, true), absPosition),
  1623. getZoom(...getPairings(true, false, false, false), absPosition),
  1624. getZoom(...getPairings(false, true, false, false), absPosition, true),
  1625. ].filter(isValidZoom));
  1626. };
  1627. })();
  1628. const getZoomPoints = (() => {
  1629. const getPoints = (fitZoom, doFlip) => {
  1630. const getGenericRotated = (x, y, angle) => {
  1631. const radius = Math.sqrt(x * x + y * y);
  1632. const pointTheta = getTheta(0, 0, x, y) + angle;
  1633. return {
  1634. x: radius * Math.cos(pointTheta),
  1635. y: radius * Math.sin(pointTheta),
  1636. };
  1637. };
  1638. const getRotated = (xRaw, yRaw) => {
  1639. // Multiplying by video dimensions to have the axes' scales match the video's
  1640. // Using midPoint's raw values would only work if points moved elliptically around the centre of rotation
  1641. const rotated = getGenericRotated(xRaw * video.clientWidth, yRaw * video.clientHeight, (DEGREES[90] - rotation.value) % DEGREES[180]);
  1642. rotated.x /= video.clientWidth;
  1643. rotated.y /= video.clientHeight;
  1644. return rotated;
  1645. };
  1646. return [
  1647. {...getRotated(halfDimensions.viewport.width / video.clientWidth / fitZoom[0], 0), axis: doFlip ? 'y' : 'x'},
  1648. {...getRotated(0, halfDimensions.viewport.height / video.clientHeight / fitZoom[1]), axis: doFlip ? 'x' : 'y'},
  1649. ];
  1650. };
  1651. const getIntersection = (line, corner, middle) => {
  1652. const getIntersection = (line0, line1) => {
  1653. const a0 = line0[0].y - line0[1].y;
  1654. const b0 = line0[1].x - line0[0].x;
  1655. const c0 = line0[1].x * line0[0].y - line0[0].x * line0[1].y;
  1656. const a1 = line1[0].y - line1[1].y;
  1657. const b1 = line1[1].x - line1[0].x;
  1658. const c1 = line1[1].x * line1[0].y - line1[0].x * line1[1].y;
  1659. const d = a0 * b1 - b0 * a1;
  1660. return {
  1661. x: (c0 * b1 - b0 * c1) / d,
  1662. y: (a0 * c1 - c0 * a1) / d,
  1663. };
  1664. };
  1665. const {x, y} = getIntersection([{x: 0, y: 0}, middle], [line, corner]);
  1666. const progress = isThin ? (y - line.y) / (corner.y - line.y) : (x - line.x) / (corner.x - line.x);
  1667. return {x, y, z: line.z / (1 - progress), c: line.y};
  1668. };
  1669. const getIntersect = (yIntersect, corner, right, top) => {
  1670. const point0 = getIntersection(yIntersect, corner, right);
  1671. const point1 = getIntersection(yIntersect, corner, top);
  1672. const [point, vpEnd] = point0.z > point1.z ? [point0, {...right}] : [point1, {...top}];
  1673. if (Math.sign(point[vpEnd.axis]) !== Math.sign(vpEnd[vpEnd.axis])) {
  1674. vpEnd.x = -vpEnd.x;
  1675. vpEnd.y = -vpEnd.y;
  1676. }
  1677. return {...point, vpEnd};
  1678. };
  1679. // the angle from 0,0 to the center of the video edge angled towards the viewport's upper-right corner
  1680. const getQuadrantAngle = (isEvenQuadrant) => {
  1681. const angle = (rotation.value + DEGREES[360]) % DEGREES[90];
  1682. return isEvenQuadrant ? angle : DEGREES[90] - angle;
  1683. };
  1684. return () => {
  1685. const isEvenQuadrant = (Math.floor(rotation.value / DEGREES[90]) + 3) % 2 === 0;
  1686. const quadrantAngle = getQuadrantAngle(isEvenQuadrant);
  1687. const progress = quadrantAngle / DEGREES[90] * -2 + 1;
  1688. const progressAngles = {
  1689. base: Math.atan(progress * viewportRatio),
  1690. side: Math.atan(progress * viewportRatioInverse),
  1691. };
  1692. const progressCosines = {
  1693. base: Math.cos(progressAngles.base),
  1694. side: Math.cos(progressAngles.side),
  1695. };
  1696. const fitZoom = zoom.getVideoFit(true);
  1697. const points = getPoints(fitZoom, quadrantAngle >= DEGREES[45]);
  1698. const sideIntersection = getIntersect(
  1699. ((cornerAngle) => ({
  1700. x: 0,
  1701. y: (halfDimensions.video.height - halfDimensions.video.width * Math.tan(cornerAngle)) / video.clientHeight,
  1702. z: halfDimensions.viewport.width / (progressCosines.side * Math.abs(halfDimensions.video.width / Math.cos(cornerAngle))),
  1703. }))(quadrantAngle + progressAngles.side),
  1704. isEvenQuadrant ? {x: -0.5, y: 0.5} : {x: 0.5, y: 0.5},
  1705. ...points,
  1706. );
  1707. const baseIntersection = getIntersect(
  1708. ((cornerAngle) => ({
  1709. x: 0,
  1710. y: (halfDimensions.video.height - halfDimensions.video.width * Math.tan(cornerAngle)) / video.clientHeight,
  1711. z: halfDimensions.viewport.height / (progressCosines.base * Math.abs(halfDimensions.video.width / Math.cos(cornerAngle))),
  1712. }))(DEGREES[90] - quadrantAngle - progressAngles.base),
  1713. isEvenQuadrant ? {x: 0.5, y: 0.5} : {x: -0.5, y: 0.5},
  1714. ...points,
  1715. );
  1716. const [originSide, originBase] = fitZoom.map((z) => ({x: 0, y: 0, z}));
  1717. return isEvenQuadrant ?
  1718. [...[originSide, sideIntersection], ...[originBase, baseIntersection]] :
  1719. [...[originBase, baseIntersection], ...[originSide, sideIntersection]];
  1720. };
  1721. })();
  1722. let zoomPoints;
  1723. const getEnsureZoomPoints = (() => {
  1724. const updateLog = [];
  1725. let count = 0;
  1726. return (isConfigBound = false) => {
  1727. const zoomPointCache = new DimensionCache(rotation);
  1728. // ConfigCache specifically to update frame
  1729. const callbackCache = new (isConfigBound ? ConfigCache : Cache)(zoom);
  1730. const id = count++;
  1731. return () => {
  1732. if (zoomPointCache.isStale()) {
  1733. updateLog.length = 0;
  1734. zoomPoints = getZoomPoints();
  1735. }
  1736. if (callbackCache.isStale() || !updateLog[id]) {
  1737. updateLog[id] = true;
  1738. return true;
  1739. }
  1740. return false;
  1741. };
  1742. };
  1743. })();
  1744. const handlers = {
  1745. [LIMITS.static]: ({custom: ratio}) => {
  1746. const bound = 0.5 + (ratio - 0.5);
  1747. this.x = Math.max(-bound, Math.min(bound, this.x));
  1748. this.y = Math.max(-bound, Math.min(bound, this.y));
  1749. },
  1750. [LIMITS.fit]: (() => {
  1751. let boundApplyFrame;
  1752. const ensure = getEnsureZoomPoints(true);
  1753. return () => {
  1754. if (ensure()) {
  1755. boundApplyFrame = getBoundApplyFrame(...zoomPoints);
  1756. }
  1757. boundApplyFrame();
  1758. };
  1759. })(),
  1760. };
  1761. const snapHandlers = {
  1762. [LIMITS.fit]: (() => {
  1763. const ensure = getEnsureZoomPoints();
  1764. return () => {
  1765. ensure();
  1766. snapZoom(...zoomPoints);
  1767. zoom.constrain();
  1768. };
  1769. })(),
  1770. };
  1771. return (doZoom = false) => {
  1772. const {panLimit, snapPanLimit} = $config.get();
  1773. if (doZoom) {
  1774. snapHandlers[snapPanLimit.type]?.();
  1775. }
  1776. handlers[panLimit.type]?.(panLimit);
  1777. this.apply();
  1778. };
  1779. })();
  1780. }();
  1781.  
  1782. const crop = new function () {
  1783. this.top = this.right = this.bottom = this.left = 0;
  1784. this.getValues = () => ({top: this.top, right: this.right, bottom: this.bottom, left: this.left});
  1785. this.reveal = () => {
  1786. this.top = this.right = this.bottom = this.left = 0;
  1787. rule.remove();
  1788. };
  1789. this.reset = () => {
  1790. this.reveal();
  1791. actions.crop.reset();
  1792. };
  1793. const rule = new css.Toggleable();
  1794. this.apply = () => {
  1795. rule.remove();
  1796. rule.add(
  1797. `${SELECTOR_VIDEO}:not(.${this.CLASS_ABLE} *)`,
  1798. ['clip-path', `inset(${this.top * 100}% ${this.right * 100}% ${this.bottom * 100}% ${this.left * 100}%)`],
  1799. );
  1800. delete actions.reset.restore;
  1801. glow.handleViewChange();
  1802. glow.reset();
  1803. };
  1804. this.getDimensions = (width = video.clientWidth, height = video.clientHeight) => [
  1805. width * (1 - this.left - this.right),
  1806. height * (1 - this.top - this.bottom),
  1807. ];
  1808. }();
  1809.  
  1810. // FUNCTIONALITY
  1811.  
  1812. const glow = (() => {
  1813. const videoCanvas = new OffscreenCanvas(0, 0);
  1814. const videoCtx = videoCanvas.getContext('2d', {alpha: false});
  1815. const glowCanvas = document.createElement('canvas');
  1816. const glowCtx = glowCanvas.getContext('2d', {alpha: false});
  1817. glowCanvas.style.setProperty('position', 'absolute');
  1818. class Sector {
  1819. canvas = new OffscreenCanvas(0, 0);
  1820. ctx = this.canvas.getContext('2d', {alpha: false});
  1821. update(doFill) {
  1822. if (doFill) {
  1823. this.fill();
  1824. } else {
  1825. this.shift();
  1826. this.take();
  1827. }
  1828. this.giveEdge();
  1829. if (this.hasCorners) {
  1830. this.giveCorners();
  1831. }
  1832. }
  1833. }
  1834. class Side extends Sector {
  1835. setDimensions(doShiftRight, sWidth, sHeight, sx, sy, dx, dy, dWidth, dHeight) {
  1836. this.canvas.width = sWidth;
  1837. this.canvas.height = sHeight;
  1838. this.shift = this.ctx.drawImage.bind(this.ctx, this.canvas, doShiftRight ? 1 : -1, 0);
  1839. this.fill = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, 1, sHeight, 0, 0, sWidth, sHeight);
  1840. this.take = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, 1, sHeight, doShiftRight ? 0 : sWidth - 1, 0, 1, sHeight);
  1841. this.giveEdge = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, sWidth, sHeight, dx, dy, dWidth, dHeight);
  1842. if (dy === 0) {
  1843. this.hasCorners = false;
  1844. return;
  1845. }
  1846. this.hasCorners = true;
  1847. const giveCorner0 = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, sWidth, 1, dx, 0, dWidth, dy);
  1848. const giveCorner1 = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, sHeight - 1, sWidth, 1, dx, dy + dHeight, dWidth, dy);
  1849. this.giveCorners = () => {
  1850. giveCorner0();
  1851. giveCorner1();
  1852. };
  1853. }
  1854. }
  1855. class Base extends Sector {
  1856. setDimensions(doShiftDown, sWidth, sHeight, sx, sy, dx, dy, dWidth, dHeight) {
  1857. this.canvas.width = sWidth;
  1858. this.canvas.height = sHeight;
  1859. this.shift = this.ctx.drawImage.bind(this.ctx, this.canvas, 0, doShiftDown ? 1 : -1);
  1860. this.fill = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, sWidth, 1, 0, 0, sWidth, sHeight);
  1861. this.take = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, sWidth, 1, 0, doShiftDown ? 0 : sHeight - 1, sWidth, 1);
  1862. this.giveEdge = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, sWidth, sHeight, dx, dy, dWidth, dHeight);
  1863. if (dx === 0) {
  1864. this.hasCorners = false;
  1865. return;
  1866. }
  1867. this.hasCorners = true;
  1868. const giveCorner0 = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, 1, sHeight, 0, dy, dx, dHeight);
  1869. const giveCorner1 = glowCtx.drawImage.bind(glowCtx, this.canvas, sWidth - 1, 0, 1, sHeight, dx + dWidth, dy, dx, dHeight);
  1870. this.giveCorners = () => {
  1871. giveCorner0();
  1872. giveCorner1();
  1873. };
  1874. }
  1875. setClipPath(points) {
  1876. this.clipPath = new Path2D();
  1877. this.clipPath.moveTo(...points[0]);
  1878. this.clipPath.lineTo(...points[1]);
  1879. this.clipPath.lineTo(...points[2]);
  1880. this.clipPath.closePath();
  1881. }
  1882. update(doFill) {
  1883. glowCtx.save();
  1884. glowCtx.clip(this.clipPath);
  1885. super.update(doFill);
  1886. glowCtx.restore();
  1887. }
  1888. }
  1889. const components = {
  1890. left: new Side(),
  1891. right: new Side(),
  1892. top: new Base(),
  1893. bottom: new Base(),
  1894. };
  1895. const setComponentDimensions = (sampleCount, size, isInset, doFlip) => {
  1896. const [croppedWidth, croppedHeight] = crop.getDimensions();
  1897. const halfCanvas = {x: Math.ceil(glowCanvas.width / 2), y: Math.ceil(glowCanvas.height / 2)};
  1898. const halfVideo = {x: croppedWidth / 2, y: croppedHeight / 2};
  1899. const dWidth = Math.ceil(Math.min(halfVideo.x, size));
  1900. const dHeight = Math.ceil(Math.min(halfVideo.y, size));
  1901. const [dWidthScale, dHeightScale, sideWidth, sideHeight] = isInset ?
  1902. [0, 0, videoCanvas.width / croppedWidth * glowCanvas.width, videoCanvas.height / croppedHeight * glowCanvas.height] :
  1903. [halfCanvas.x - halfVideo.x, halfCanvas.y - halfVideo.y, croppedWidth, croppedHeight];
  1904. components.left.setDimensions(!doFlip, sampleCount, videoCanvas.height, 0, 0, 0, dHeightScale, dWidth, sideHeight);
  1905. components.right.setDimensions(doFlip, sampleCount, videoCanvas.height, videoCanvas.width - 1, 0, glowCanvas.width - dWidth, dHeightScale, dWidth, sideHeight);
  1906. components.top.setDimensions(!doFlip, videoCanvas.width, sampleCount, 0, 0, dWidthScale, 0, sideWidth, dHeight);
  1907. components.top.setClipPath([[0, 0], [halfCanvas.x, halfCanvas.y], [glowCanvas.width, 0]]);
  1908. components.bottom.setDimensions(doFlip, videoCanvas.width, sampleCount, 0, videoCanvas.height - 1, dWidthScale, glowCanvas.height - dHeight, sideWidth, dHeight);
  1909. components.bottom.setClipPath([[0, glowCanvas.height], [halfCanvas.x, halfCanvas.y], [glowCanvas.width, glowCanvas.height]]);
  1910. };
  1911. class Instance {
  1912. constructor({filter, sampleCount, size, end, doFlip}) {
  1913. // Setup canvases
  1914. glowCanvas.style.setProperty('filter', filter);
  1915. [glowCanvas.width, glowCanvas.height] = crop.getDimensions().map((dimension) => dimension * end);
  1916. glowCanvas.style.setProperty('left', `${crop.left * 100 + (1 - end) * (1 - crop.left - crop.right) * 50}%`);
  1917. glowCanvas.style.setProperty('top', `${crop.top * 100 + (1 - end) * (1 - crop.top - crop.bottom) * 50}%`);
  1918. [videoCanvas.width, videoCanvas.height] = crop.getDimensions(video.videoWidth, video.videoHeight);
  1919. setComponentDimensions(sampleCount, size, end <= 1, doFlip);
  1920. this.update(true);
  1921. }
  1922. update(doFill = false) {
  1923. videoCtx.drawImage(
  1924. video,
  1925. crop.left * video.videoWidth,
  1926. crop.top * video.videoHeight,
  1927. video.videoWidth * (1 - crop.left - crop.right),
  1928. video.videoHeight * (1 - crop.top - crop.bottom),
  1929. 0,
  1930. 0,
  1931. videoCanvas.width,
  1932. videoCanvas.height,
  1933. );
  1934. components.left.update(doFill);
  1935. components.right.update(doFill);
  1936. components.top.update(doFill);
  1937. components.bottom.update(doFill);
  1938. }
  1939. }
  1940. return new function () {
  1941. const container = document.createElement('div');
  1942. container.style.display = 'none';
  1943. container.appendChild(glowCanvas);
  1944. containers.background.appendChild(container);
  1945. this.isHidden = false;
  1946. let instance, startCopyLoop, stopCopyLoop;
  1947. const play = () => {
  1948. if (!video.paused && !this.isHidden && !enabler.isHidingGlow) {
  1949. startCopyLoop?.();
  1950. }
  1951. };
  1952. const fill = () => {
  1953. if (!this.isHidden) {
  1954. instance.update(true);
  1955. }
  1956. };
  1957. const handleVisibilityChange = () => {
  1958. if (document.hidden) {
  1959. stopCopyLoop();
  1960. } else {
  1961. play();
  1962. }
  1963. };
  1964. this.handleSizeChange = () => {
  1965. const config = $config.get().glow;
  1966. if (config) {
  1967. instance = new Instance(config);
  1968. }
  1969. };
  1970. // set up pausing if glow isn't visible
  1971. this.handleViewChange = (() => {
  1972. const cache = new Cache(rotation, zoom);
  1973. let corners;
  1974. return (doForce = false) => {
  1975. if (doForce || cache.isStale()) {
  1976. const width = halfDimensions.viewport.width / zoom.value;
  1977. const height = halfDimensions.viewport.height / zoom.value;
  1978. const radius = Math.sqrt(width * width + height * height);
  1979. corners = getRotatedCorners(radius, viewportTheta);
  1980. }
  1981. const videoX = position.x * video.clientWidth;
  1982. const videoY = position.y * video.clientHeight;
  1983. for (const corner of corners) {
  1984. if (
  1985. // unpause if the viewport extends more than 1 pixel beyond a video edge
  1986. videoX + corner.x > (0.5 - crop.right) * video.clientWidth + 1
  1987. || videoX - corner.x < (crop.left - 0.5) * video.clientWidth - 1
  1988. || videoY + corner.y > (0.5 - crop.top) * video.clientHeight + 1
  1989. || videoY - corner.y < (crop.bottom - 0.5) * video.clientHeight - 1
  1990. ) {
  1991. // fill if newly visible
  1992. if (this.isHidden) {
  1993. instance?.update(true);
  1994. }
  1995. this.isHidden = false;
  1996. glowCanvas.style.removeProperty('visibility');
  1997. play();
  1998. return;
  1999. }
  2000. }
  2001. this.isHidden = true;
  2002. glowCanvas.style.visibility = 'hidden';
  2003. stopCopyLoop?.();
  2004. };
  2005. })();
  2006. const loop = {};
  2007. this.start = () => {
  2008. const config = $config.get().glow;
  2009. if (!config) {
  2010. return;
  2011. }
  2012. if (!enabler.isHidingGlow) {
  2013. container.style.removeProperty('display');
  2014. }
  2015. // todo handle this?
  2016. if (crop.left + crop.right >= 1 || crop.top + crop.bottom >= 1) {
  2017. return;
  2018. }
  2019. let loopId = -1;
  2020. if (loop.interval !== config.interval || loop.fps !== config.fps) {
  2021. loop.interval = config.interval;
  2022. loop.fps = config.fps;
  2023. loop.wasSlow = false;
  2024. loop.throttleCount = 0;
  2025. }
  2026. stopCopyLoop = () => ++loopId;
  2027. instance = new Instance(config);
  2028. startCopyLoop = async () => {
  2029. const id = ++loopId;
  2030. await new Promise((resolve) => {
  2031. window.setTimeout(resolve, config.interval);
  2032. });
  2033. while (id === loopId) {
  2034. const startTime = Date.now();
  2035. instance.update();
  2036. const delay = loop.interval - (Date.now() - startTime);
  2037. if (delay <= 0) {
  2038. if (loop.wasSlow) {
  2039. loop.interval = 1000 / (loop.fps - ++loop.throttleCount);
  2040. }
  2041. loop.wasSlow = !loop.wasSlow;
  2042. continue;
  2043. }
  2044. if (delay > 2 && loop.throttleCount > 0) {
  2045. console.warn(`[${GM.info.script.name}] Glow update frequency reduced from ${loop.fps} hertz to ${loop.fps - loop.throttleCount} hertz due to poor performance.`);
  2046. loop.fps -= loop.throttleCount;
  2047. loop.throttleCount = 0;
  2048. }
  2049. loop.wasSlow = false;
  2050. await new Promise((resolve) => {
  2051. window.setTimeout(resolve, delay);
  2052. });
  2053. }
  2054. };
  2055. play();
  2056. video.addEventListener('pause', stopCopyLoop);
  2057. video.addEventListener('play', play);
  2058. video.addEventListener('seeked', fill);
  2059. document.addEventListener('visibilitychange', handleVisibilityChange);
  2060. };
  2061. const priorCrop = {};
  2062. this.hide = () => {
  2063. Object.assign(priorCrop, crop);
  2064. stopCopyLoop?.();
  2065. container.style.display = 'none';
  2066. };
  2067. this.show = () => {
  2068. if (Object.entries(priorCrop).some(([edge, value]) => crop[edge] !== value)) {
  2069. this.reset();
  2070. } else {
  2071. play();
  2072. }
  2073. container.style.removeProperty('display');
  2074. };
  2075. this.stop = () => {
  2076. this.hide();
  2077. video.removeEventListener('pause', stopCopyLoop);
  2078. video.removeEventListener('play', play);
  2079. video.removeEventListener('seeked', fill);
  2080. document.removeEventListener('visibilitychange', handleVisibilityChange);
  2081. startCopyLoop = undefined;
  2082. stopCopyLoop = undefined;
  2083. };
  2084. this.reset = () => {
  2085. this.stop();
  2086. this.start();
  2087. };
  2088. }();
  2089. })();
  2090.  
  2091. const peek = (stop = false) => {
  2092. const prior = {
  2093. zoom: zoom.value,
  2094. rotation: rotation.value,
  2095. crop: crop.getValues(),
  2096. position: position.getValues(),
  2097. };
  2098. position.reset();
  2099. rotation.reset();
  2100. zoom.reset();
  2101. crop.reset();
  2102. glow[stop ? 'stop' : 'reset']();
  2103. return () => {
  2104. zoom.value = prior.zoom;
  2105. rotation.value = prior.rotation;
  2106. Object.assign(position, prior.position);
  2107. Object.assign(crop, prior.crop);
  2108. actions.crop.set(prior.crop);
  2109. position.apply();
  2110. rotation.apply();
  2111. zoom.apply();
  2112. crop.apply();
  2113. };
  2114. };
  2115.  
  2116. const actions = (() => {
  2117. const drag = (event, clickCallback, moveCallback, target = video) => new Promise((resolve) => {
  2118. event.stopImmediatePropagation();
  2119. event.preventDefault();
  2120. // window blur events don't fire if devtools is open
  2121. stopDrag?.();
  2122. target.setPointerCapture(event.pointerId);
  2123. css.tag(enabler.CLASS_DRAGGING);
  2124. const cancel = (event) => {
  2125. event.stopImmediatePropagation();
  2126. event.preventDefault();
  2127. };
  2128. document.addEventListener('click', cancel, true);
  2129. document.addEventListener('dblclick', cancel, true);
  2130. const clickDisallowListener = ({clientX, clientY}) => {
  2131. const {clickCutoff} = $config.get();
  2132. const distance = Math.abs(event.clientX - clientX) + Math.abs(event.clientY - clientY);
  2133. if (distance >= clickCutoff) {
  2134. target.removeEventListener('pointermove', clickDisallowListener);
  2135. target.removeEventListener('pointerup', clickCallback);
  2136. }
  2137. };
  2138. if (clickCallback) {
  2139. target.addEventListener('pointermove', clickDisallowListener);
  2140. target.addEventListener('pointerup', clickCallback, {once: true});
  2141. }
  2142. target.addEventListener('pointermove', moveCallback);
  2143. stopDrag = () => {
  2144. css.tag(enabler.CLASS_DRAGGING, false);
  2145. target.removeEventListener('pointermove', moveCallback);
  2146. if (clickCallback) {
  2147. target.removeEventListener('pointermove', clickDisallowListener);
  2148. target.removeEventListener('pointerup', clickCallback);
  2149. }
  2150. // delay removing listeners for events that happen after pointerup
  2151. window.setTimeout(() => {
  2152. document.removeEventListener('dblclick', cancel, true);
  2153. document.removeEventListener('click', cancel, true);
  2154. }, 0);
  2155. window.removeEventListener('blur', stopDrag);
  2156. target.removeEventListener('pointerup', stopDrag);
  2157. target.releasePointerCapture(event.pointerId);
  2158. stopDrag = undefined;
  2159. enabler.handleChange();
  2160. resolve();
  2161. };
  2162. window.addEventListener('blur', stopDrag);
  2163. target.addEventListener('pointerup', stopDrag);
  2164. });
  2165. const getOnScroll = (() => {
  2166. // https://stackoverflow.com/a/30134826
  2167. const multipliers = [1, 40, 800];
  2168. return (callback) => (event) => {
  2169. event.stopImmediatePropagation();
  2170. event.preventDefault();
  2171. if (event.deltaY !== 0) {
  2172. callback(event.deltaY * multipliers[event.deltaMode]);
  2173. }
  2174. };
  2175. })();
  2176. const addListeners = ({onMouseDown, onRightClick, onScroll}, doAdd = true) => {
  2177. const property = `${doAdd ? 'add' : 'remove'}EventListener`;
  2178. altTarget[property]('pointerdown', onMouseDown);
  2179. altTarget[property]('contextmenu', onRightClick, true);
  2180. altTarget[property]('wheel', onScroll);
  2181. };
  2182. return {
  2183. crop: new function () {
  2184. let top = 0, right = 0, bottom = 0, left = 0, handle;
  2185. const values = {};
  2186. Object.defineProperty(values, 'top', {get: () => top, set: (value) => top = value});
  2187. Object.defineProperty(values, 'right', {get: () => right, set: (value) => right = value});
  2188. Object.defineProperty(values, 'bottom', {get: () => bottom, set: (value) => bottom = value});
  2189. Object.defineProperty(values, 'left', {get: () => left, set: (value) => left = value});
  2190. class Button {
  2191. // allowance for rounding errors
  2192. static ALLOWANCE_HANDLE = 0.0001;
  2193. static CLASS_HANDLE = 'viewfind-crop-handle';
  2194. static CLASS_EDGES = {
  2195. left: 'viewfind-crop-left',
  2196. top: 'viewfind-crop-top',
  2197. right: 'viewfind-crop-right',
  2198. bottom: 'viewfind-crop-bottom',
  2199. };
  2200. static OPPOSITES = {
  2201. left: 'right',
  2202. right: 'left',
  2203. top: 'bottom',
  2204. bottom: 'top',
  2205. };
  2206. callbacks = [];
  2207. element = document.createElement('div');
  2208. constructor(...edges) {
  2209. this.edges = edges;
  2210. this.isHandle = true;
  2211. this.element.style.position = 'absolute';
  2212. this.element.style.pointerEvents = 'all';
  2213. for (const edge of edges) {
  2214. this.element.style[edge] = '0';
  2215. this.element.classList.add(Button.CLASS_EDGES[edge]);
  2216. this.element.style.setProperty(`border-${Button.OPPOSITES[edge]}-width`, '1px');
  2217. }
  2218. this.element.addEventListener('contextmenu', (event) => {
  2219. event.stopPropagation();
  2220. event.preventDefault();
  2221. this.reset(false);
  2222. });
  2223. this.element.addEventListener('pointerdown', (() => {
  2224. const clickListener = ({offsetX, offsetY, target}) => {
  2225. this.set({
  2226. width: (this.edges.includes('left') ? offsetX : target.clientWidth - offsetX) / video.clientWidth,
  2227. height: (this.edges.includes('top') ? offsetY : target.clientHeight - offsetY) / video.clientHeight,
  2228. }, false);
  2229. };
  2230. const getDragListener = (event, target) => {
  2231. const getWidth = (() => {
  2232. if (this.edges.includes('left')) {
  2233. const position = this.element.clientWidth - event.offsetX;
  2234. return ({offsetX}) => offsetX + position;
  2235. }
  2236. const position = target.offsetWidth + event.offsetX;
  2237. return ({offsetX}) => position - offsetX;
  2238. })();
  2239. const getHeight = (() => {
  2240. if (this.edges.includes('top')) {
  2241. const position = this.element.clientHeight - event.offsetY;
  2242. return ({offsetY}) => offsetY + position;
  2243. }
  2244. const position = target.offsetHeight + event.offsetY;
  2245. return ({offsetY}) => position - offsetY;
  2246. })();
  2247. return (event) => {
  2248. this.set({
  2249. width: getWidth(event) / video.clientWidth,
  2250. height: getHeight(event) / video.clientHeight,
  2251. });
  2252. };
  2253. };
  2254. return async (event) => {
  2255. if (event.buttons === 1) {
  2256. const target = this.element.parentElement;
  2257. if (this.isHandle) {
  2258. this.setPanel();
  2259. }
  2260. await drag(event, clickListener, getDragListener(event, target), target);
  2261. this.updateCounterpart();
  2262. }
  2263. };
  2264. })());
  2265. }
  2266. notify() {
  2267. for (const callback of this.callbacks) {
  2268. callback();
  2269. }
  2270. }
  2271. set isHandle(value) {
  2272. this._isHandle = value;
  2273. this.element.classList[value ? 'add' : 'remove'](Button.CLASS_HANDLE);
  2274. }
  2275. get isHandle() {
  2276. return this._isHandle;
  2277. }
  2278. reset() {
  2279. this.isHandle = true;
  2280. for (const edge of this.edges) {
  2281. values[edge] = 0;
  2282. }
  2283. }
  2284. }
  2285. class EdgeButton extends Button {
  2286. constructor(edge) {
  2287. super(edge);
  2288. this.edge = edge;
  2289. }
  2290. updateCounterpart() {
  2291. if (this.counterpart.isHandle) {
  2292. this.counterpart.setHandle();
  2293. }
  2294. }
  2295. setCrop(value = 0) {
  2296. values[this.edge] = value;
  2297. }
  2298. setPanel() {
  2299. this.isHandle = false;
  2300. this.setCrop(handle);
  2301. this.setHandle();
  2302. }
  2303. }
  2304. class SideButton extends EdgeButton {
  2305. flow() {
  2306. let size = 1;
  2307. if (top <= Button.ALLOWANCE_HANDLE) {
  2308. size -= handle;
  2309. this.element.style.top = `${handle * 100}%`;
  2310. } else {
  2311. size -= top;
  2312. this.element.style.top = `${top * 100}%`;
  2313. }
  2314. if (bottom <= Button.ALLOWANCE_HANDLE) {
  2315. size -= handle;
  2316. } else {
  2317. size -= bottom;
  2318. }
  2319. this.element.style.height = `${Math.max(0, size * 100)}%`;
  2320. }
  2321. setBounds(counterpart, components) {
  2322. this.counterpart = components[counterpart];
  2323. components.top.callbacks.push(() => {
  2324. this.flow();
  2325. });
  2326. components.bottom.callbacks.push(() => {
  2327. this.flow();
  2328. });
  2329. }
  2330. setHandle(doNotify = true) {
  2331. this.element.style.width = `${Math.min(1 - values[this.counterpart.edge], handle) * 100}%`;
  2332. if (doNotify) {
  2333. this.notify();
  2334. }
  2335. }
  2336. set({width}, doUpdateCounterpart = true) {
  2337. if (this.isHandle !== (this.isHandle = width <= Button.ALLOWANCE_HANDLE)) {
  2338. this.flow();
  2339. }
  2340. if (doUpdateCounterpart) {
  2341. this.updateCounterpart();
  2342. }
  2343. if (this.isHandle) {
  2344. this.setCrop();
  2345. this.setHandle();
  2346. return;
  2347. }
  2348. const size = Math.min(1 - values[this.counterpart.edge], width);
  2349. this.setCrop(size);
  2350. this.element.style.width = `${size * 100}%`;
  2351. this.notify();
  2352. }
  2353. reset(isGeneral = true) {
  2354. super.reset();
  2355. if (isGeneral) {
  2356. this.element.style.top = `${handle * 100}%`;
  2357. this.element.style.height = `${(0.5 - handle) * 200}%`;
  2358. this.element.style.width = `${handle * 100}%`;
  2359. return;
  2360. }
  2361. this.flow();
  2362. this.setHandle();
  2363. this.updateCounterpart();
  2364. }
  2365. }
  2366. class BaseButton extends EdgeButton {
  2367. flow() {
  2368. let size = 1;
  2369. if (left <= Button.ALLOWANCE_HANDLE) {
  2370. size -= handle;
  2371. this.element.style.left = `${handle * 100}%`;
  2372. } else {
  2373. size -= left;
  2374. this.element.style.left = `${left * 100}%`;
  2375. }
  2376. if (right <= Button.ALLOWANCE_HANDLE) {
  2377. size -= handle;
  2378. } else {
  2379. size -= right;
  2380. }
  2381. this.element.style.width = `${Math.max(0, size) * 100}%`;
  2382. }
  2383. setBounds(counterpart, components) {
  2384. this.counterpart = components[counterpart];
  2385. components.left.callbacks.push(() => {
  2386. this.flow();
  2387. });
  2388. components.right.callbacks.push(() => {
  2389. this.flow();
  2390. });
  2391. }
  2392. setHandle(doNotify = true) {
  2393. this.element.style.height = `${Math.min(1 - values[this.counterpart.edge], handle) * 100}%`;
  2394. if (doNotify) {
  2395. this.notify();
  2396. }
  2397. }
  2398. set({height}, doUpdateCounterpart = false) {
  2399. if (this.isHandle !== (this.isHandle = height <= Button.ALLOWANCE_HANDLE)) {
  2400. this.flow();
  2401. }
  2402. if (doUpdateCounterpart) {
  2403. this.updateCounterpart();
  2404. }
  2405. if (this.isHandle) {
  2406. this.setCrop();
  2407. this.setHandle();
  2408. return;
  2409. }
  2410. const size = Math.min(1 - values[this.counterpart.edge], height);
  2411. this.setCrop(size);
  2412. this.element.style.height = `${size * 100}%`;
  2413. this.notify();
  2414. }
  2415. reset(isGeneral = true) {
  2416. super.reset();
  2417. if (isGeneral) {
  2418. this.element.style.left = `${handle * 100}%`;
  2419. this.element.style.width = `${(0.5 - handle) * 200}%`;
  2420. this.element.style.height = `${handle * 100}%`;
  2421. return;
  2422. }
  2423. this.flow();
  2424. this.setHandle();
  2425. this.updateCounterpart();
  2426. }
  2427. }
  2428. class CornerButton extends Button {
  2429. static CLASS_NAME = 'viewfind-crop-corner';
  2430. constructor(sectors, ...edges) {
  2431. super(...edges);
  2432. this.element.classList.add(CornerButton.CLASS_NAME);
  2433. this.sectors = sectors;
  2434. for (const sector of sectors) {
  2435. sector.callbacks.push(this.flow.bind(this));
  2436. }
  2437. }
  2438. flow() {
  2439. let isHandle = true;
  2440. if (this.sectors[0].isHandle) {
  2441. this.element.style.width = `${Math.min(1 - values[this.sectors[0].counterpart.edge], handle) * 100}%`;
  2442. } else {
  2443. this.element.style.width = `${values[this.edges[0]] * 100}%`;
  2444. isHandle = false;
  2445. }
  2446. if (this.sectors[1].isHandle) {
  2447. this.element.style.height = `${Math.min(1 - values[this.sectors[1].counterpart.edge], handle) * 100}%`;
  2448. } else {
  2449. this.element.style.height = `${values[this.edges[1]] * 100}%`;
  2450. isHandle = false;
  2451. }
  2452. this.isHandle = isHandle;
  2453. }
  2454. updateCounterpart() {
  2455. for (const sector of this.sectors) {
  2456. sector.updateCounterpart();
  2457. }
  2458. }
  2459. set(size) {
  2460. for (const sector of this.sectors) {
  2461. sector.set(size);
  2462. }
  2463. }
  2464. reset(isGeneral = true) {
  2465. this.isHandle = true;
  2466. this.element.style.width = `${handle * 100}%`;
  2467. this.element.style.height = `${handle * 100}%`;
  2468. if (isGeneral) {
  2469. return;
  2470. }
  2471. for (const sector of this.sectors) {
  2472. sector.reset(false);
  2473. }
  2474. }
  2475. setPanel() {
  2476. for (const sector of this.sectors) {
  2477. sector.setPanel();
  2478. }
  2479. }
  2480. }
  2481. this.CODE = 'crop';
  2482. this.CLASS_ABLE = 'viewfind-action-able-crop';
  2483. const container = document.createElement('div');
  2484. // todo ditch the containers object
  2485. container.style.width = container.style.height = 'inherit';
  2486. containers.foreground.append(container);
  2487. this.reset = () => {
  2488. for (const component of Object.values(this.components)) {
  2489. component.reset(true);
  2490. }
  2491. };
  2492. this.onRightClick = (event) => {
  2493. if (event.target.parentElement.id === container.id) {
  2494. return;
  2495. }
  2496. event.stopPropagation();
  2497. event.preventDefault();
  2498. if (stopDrag) {
  2499. return;
  2500. }
  2501. this.reset();
  2502. };
  2503. this.onScroll = getOnScroll((distance) => {
  2504. const increment = distance * $config.get().speeds.crop / zoom.value;
  2505. this.components.top.set({height: top + Math.min((1 - top - bottom) / 2, increment)});
  2506. this.components.left.set({width: left + Math.min((1 - left - right) / 2, increment)});
  2507. this.components.bottom.set({height: bottom + increment});
  2508. this.components.right.set({width: right + increment});
  2509. });
  2510. this.onMouseDown = (() => {
  2511. const getDragListener = () => {
  2512. const multiplier = $config.get().multipliers.crop;
  2513. const setX = ((right, left, change) => {
  2514. const clamped = Math.max(-left, Math.min(right, change * multiplier / video.clientWidth));
  2515. this.components.left.set({width: left + clamped});
  2516. this.components.right.set({width: right - clamped});
  2517. }).bind(undefined, right, left);
  2518. const setY = ((top, bottom, change) => {
  2519. const clamped = Math.max(-top, Math.min(bottom, change * multiplier / video.clientHeight));
  2520. this.components.top.set({height: top + clamped});
  2521. this.components.bottom.set({height: bottom - clamped});
  2522. }).bind(undefined, top, bottom);
  2523. let priorEvent;
  2524. return ({offsetX, offsetY}) => {
  2525. if (!priorEvent) {
  2526. priorEvent = {offsetX, offsetY};
  2527. return;
  2528. }
  2529. setX(offsetX - priorEvent.offsetX);
  2530. setY(offsetY - priorEvent.offsetY);
  2531. };
  2532. };
  2533. const clickListener = () => {
  2534. zoom.value = zoom.getFit((1 - left - right) * halfDimensions.video.width, (1 - top - bottom) * halfDimensions.video.height);
  2535. zoom.constrain();
  2536. position.x = (left - right) / 2;
  2537. position.y = (bottom - top) / 2;
  2538. position.constrain();
  2539. };
  2540. return (event) => {
  2541. if (event.buttons === 1) {
  2542. drag(event, clickListener, getDragListener(), container);
  2543. }
  2544. };
  2545. })();
  2546. this.components = {
  2547. top: new BaseButton('top'),
  2548. right: new SideButton('right'),
  2549. bottom: new BaseButton('bottom'),
  2550. left: new SideButton('left'),
  2551. };
  2552. this.components.top.setBounds('bottom', this.components);
  2553. this.components.right.setBounds('left', this.components);
  2554. this.components.bottom.setBounds('top', this.components);
  2555. this.components.left.setBounds('right', this.components);
  2556. this.components.topLeft = new CornerButton([this.components.left, this.components.top], 'left', 'top');
  2557. this.components.topRight = new CornerButton([this.components.right, this.components.top], 'right', 'top');
  2558. this.components.bottomLeft = new CornerButton([this.components.left, this.components.bottom], 'left', 'bottom');
  2559. this.components.bottomRight = new CornerButton([this.components.right, this.components.bottom], 'right', 'bottom');
  2560. container.append(...Object.values(this.components).map(({element}) => element));
  2561. this.set = ({top, right, bottom, left}) => {
  2562. this.components.top.set({height: top});
  2563. this.components.right.set({width: right});
  2564. this.components.bottom.set({height: bottom});
  2565. this.components.left.set({width: left});
  2566. };
  2567. this.onInactive = () => {
  2568. addListeners(this, false);
  2569. if (crop.left === left && crop.top === top && crop.right === right && crop.bottom === bottom) {
  2570. return;
  2571. }
  2572. crop.left = left;
  2573. crop.top = top;
  2574. crop.right = right;
  2575. crop.bottom = bottom;
  2576. crop.apply();
  2577. };
  2578. this.onActive = () => {
  2579. const config = $config.get().crop;
  2580. handle = config.handle / Math.max(zoom.value, 1);
  2581. for (const component of [this.components.top, this.components.bottom, this.components.left, this.components.right]) {
  2582. if (component.isHandle) {
  2583. component.setHandle();
  2584. }
  2585. }
  2586. crop.reveal();
  2587. addListeners(this);
  2588. if (!enabler.isHidingGlow) {
  2589. glow.handleViewChange();
  2590. glow.reset();
  2591. }
  2592. };
  2593. const draggingSelector = css.getSelector(enabler.CLASS_DRAGGING);
  2594. this.updateConfig = (() => {
  2595. const rule = new css.Toggleable();
  2596. return () => {
  2597. // set handle size
  2598. for (const button of [this.components.left, this.components.top, this.components.right, this.components.bottom]) {
  2599. if (button.isHandle) {
  2600. button.setHandle();
  2601. }
  2602. }
  2603. rule.remove();
  2604. const {colour} = $config.get().crop;
  2605. const {id} = container;
  2606. rule.add(`#${id}>:hover.${Button.CLASS_HANDLE},#${id}>:not(.${Button.CLASS_HANDLE})`, ['background-color', colour.fill]);
  2607. rule.add(`#${id}>*`, ['border-color', colour.border]);
  2608. rule.add(`#${id}:not(${draggingSelector} *)>:not(:hover)`, ['filter', `drop-shadow(${colour.shadow} 0 0 1px)`]);
  2609. };
  2610. })();
  2611. container.id = 'viewfind-crop-container';
  2612. (() => {
  2613. const {id} = container;
  2614. css.add(`${css.getSelector(enabler.CLASS_DRAGGING)} #${id}`, ['cursor', 'grabbing']);
  2615. css.add(`${css.getSelector(enabler.CLASS_ABLE)} #${id}`, ['cursor', 'grab']);
  2616. css.add(`#${id}>:not(${draggingSelector} .${Button.CLASS_HANDLE})`, ['border-style', 'solid']);
  2617. css.add(`${draggingSelector} #${id}>.${Button.CLASS_HANDLE}`, ['filter', 'none']);
  2618. for (const [side, sideClass] of Object.entries(Button.CLASS_EDGES)) {
  2619. css.add(
  2620. `${draggingSelector} #${id}>.${sideClass}.${Button.CLASS_HANDLE}~.${sideClass}.${CornerButton.CLASS_NAME}`,
  2621. [`border-${CornerButton.OPPOSITES[side]}-style`, 'none'],
  2622. ['filter', 'none'],
  2623. );
  2624. // in fullscreen, 16:9 videos get an offsetLeft of 1px on my 16:9 monitor
  2625. // I'm extending buttons by 1px so that they reach the edge of screens like mine at default zoom
  2626. css.add(`#${id}>.${sideClass}`, [`margin-${side}`, '-1px'], [`padding-${side}`, '1px']);
  2627. }
  2628. css.add(`#${id}:not(.${this.CLASS_ABLE} *)`, ['display', 'none']);
  2629. })();
  2630. }(),
  2631. pan: new function () {
  2632. this.CODE = 'pan';
  2633. this.CLASS_ABLE = 'viewfind-action-able-pan';
  2634. this.onActive = () => {
  2635. this.updateCrosshair();
  2636. addListeners(this);
  2637. };
  2638. this.onInactive = () => {
  2639. addListeners(this, false);
  2640. };
  2641. this.updateCrosshair = (() => {
  2642. const getRoundedString = (number, decimal = 2) => {
  2643. const raised = `${Math.round(number * Math.pow(10, decimal))}`.padStart(decimal + 1, '0');
  2644. return `${raised.substr(0, raised.length - decimal)}.${raised.substr(raised.length - decimal)}`;
  2645. };
  2646. const getSigned = (ratio) => {
  2647. const percent = Math.round(ratio * 100);
  2648. if (percent <= 0) {
  2649. return `${percent}`;
  2650. }
  2651. return `+${percent}`;
  2652. };
  2653. return () => {
  2654. crosshair.text.innerText = `${getRoundedString(zoom.value)}×\n${getSigned(position.x)}%\n${getSigned(position.y)}%`;
  2655. };
  2656. })();
  2657. this.onScroll = getOnScroll((distance) => {
  2658. const increment = distance * $config.get().speeds.zoom;
  2659. if (increment > 0) {
  2660. zoom.value *= 1 + increment;
  2661. } else {
  2662. zoom.value /= 1 - increment;
  2663. }
  2664. zoom.constrain();
  2665. position.constrain();
  2666. this.updateCrosshair();
  2667. });
  2668. this.onRightClick = (event) => {
  2669. event.stopImmediatePropagation();
  2670. event.preventDefault();
  2671. if (stopDrag) {
  2672. return;
  2673. }
  2674. position.x = position.y = 0;
  2675. zoom.value = 1;
  2676. position.apply();
  2677. position.updateFrameOnReset();
  2678. zoom.constrain();
  2679. this.updateCrosshair();
  2680. };
  2681. this.onMouseDown = (() => {
  2682. const getDragListener = () => {
  2683. const {multipliers} = $config.get();
  2684. let priorEvent;
  2685. const change = {x: 0, y: 0};
  2686. return ({offsetX, offsetY}) => {
  2687. if (priorEvent) {
  2688. change.x = (priorEvent.offsetX + change.x - offsetX) * multipliers.pan;
  2689. change.y = (priorEvent.offsetY - change.y - offsetY) * -multipliers.pan;
  2690. position.x += change.x / video.clientWidth;
  2691. position.y += change.y / video.clientHeight;
  2692. position.constrain();
  2693. this.updateCrosshair();
  2694. }
  2695. // events in firefox seem to lose their data after finishing propagation
  2696. // so assigning the whole event doesn't work
  2697. priorEvent = {offsetX, offsetY};
  2698. };
  2699. };
  2700. const clickListener = (event) => {
  2701. position.x = event.offsetX / video.clientWidth - 0.5;
  2702. // Y increases moving down the page
  2703. // I flip that to make trigonometry easier
  2704. position.y = -event.offsetY / video.clientHeight + 0.5;
  2705. position.constrain(true);
  2706. this.updateCrosshair();
  2707. };
  2708. return (event) => {
  2709. if (event.buttons === 1) {
  2710. drag(event, clickListener, getDragListener());
  2711. }
  2712. };
  2713. })();
  2714. }(),
  2715. rotate: new function () {
  2716. this.CODE = 'rotate';
  2717. this.CLASS_ABLE = 'viewfind-action-able-rotate';
  2718. this.onActive = () => {
  2719. this.updateCrosshair();
  2720. addListeners(this);
  2721. };
  2722. this.onInactive = () => {
  2723. addListeners(this, false);
  2724. };
  2725. this.updateCrosshair = () => {
  2726. const angle = DEGREES[90] - rotation.value;
  2727. crosshair.text.innerText = `${Math.floor((DEGREES[90] - rotation.value) / Math.PI * 180)}°\n${Math.round(angle / DEGREES[90]) % 4 * 90}°`;
  2728. };
  2729. this.onScroll = getOnScroll((distance) => {
  2730. rotation.value += distance * $config.get().speeds.rotate;
  2731. rotation.constrain();
  2732. zoom.constrain();
  2733. position.constrain();
  2734. this.updateCrosshair();
  2735. });
  2736. this.onRightClick = (event) => {
  2737. event.stopImmediatePropagation();
  2738. event.preventDefault();
  2739. if (stopDrag) {
  2740. return;
  2741. }
  2742. rotation.value = DEGREES[90];
  2743. rotation.apply();
  2744. zoom.constrain();
  2745. position.constrain();
  2746. this.updateCrosshair();
  2747. };
  2748. this.onMouseDown = (() => {
  2749. const getDragListener = () => {
  2750. const {multipliers} = $config.get();
  2751. const middleX = containers.tracker.clientWidth / 2;
  2752. const middleY = containers.tracker.clientHeight / 2;
  2753. const priorPosition = position.getValues();
  2754. const priorZoom = zoom.value;
  2755. let priorMouseTheta;
  2756. return (event) => {
  2757. const mouseTheta = getTheta(middleX, middleY, event.offsetX, event.offsetY);
  2758. if (priorMouseTheta === undefined) {
  2759. priorMouseTheta = mouseTheta;
  2760. return;
  2761. }
  2762. position.x = priorPosition.x;
  2763. position.y = priorPosition.y;
  2764. zoom.value = priorZoom;
  2765. rotation.value += (priorMouseTheta - mouseTheta) * multipliers.rotate;
  2766. rotation.constrain();
  2767. zoom.constrain();
  2768. position.constrain();
  2769. this.updateCrosshair();
  2770. priorMouseTheta = mouseTheta;
  2771. };
  2772. };
  2773. const clickListener = () => {
  2774. rotation.value = Math.round(rotation.value / DEGREES[90]) * DEGREES[90];
  2775. rotation.constrain();
  2776. zoom.constrain();
  2777. position.constrain();
  2778. this.updateCrosshair();
  2779. };
  2780. return (event) => {
  2781. if (event.buttons === 1) {
  2782. drag(event, clickListener, getDragListener(), containers.tracker);
  2783. }
  2784. };
  2785. })();
  2786. }(),
  2787. configure: new function () {
  2788. this.CODE = 'config';
  2789. const updateConfigs = () => {
  2790. ConfigCache.id++;
  2791. position.updateFrame();
  2792. enabler.updateConfig();
  2793. actions.crop.updateConfig();
  2794. crosshair.updateConfig();
  2795. };
  2796. this.onActive = async () => {
  2797. await $config.edit();
  2798. updateConfigs();
  2799. viewport.focus();
  2800. glow.reset();
  2801. position.constrain();
  2802. zoom.constrain();
  2803. };
  2804. }(),
  2805. reset: new function () {
  2806. this.CODE = 'reset';
  2807. this.onActive = () => {
  2808. if (this.restore) {
  2809. this.restore();
  2810. } else {
  2811. this.restore = peek();
  2812. }
  2813. const {restore} = this;
  2814. position.updateFrameOnReset();
  2815. this.restore = restore;
  2816. };
  2817. }(),
  2818. };
  2819. })();
  2820.  
  2821. const crosshair = new function () {
  2822. this.container = document.createElement('div');
  2823. this.lines = {
  2824. horizontal: document.createElement('div'),
  2825. vertical: document.createElement('div'),
  2826. };
  2827. this.text = document.createElement('div');
  2828. const id = 'viewfind-crosshair';
  2829. this.container.id = id;
  2830. this.container.classList.add(CLASS_VIEWFINDER);
  2831. css.add(`#${id}:not(${css.getSelector(actions.pan.CLASS_ABLE)} *):not(${css.getSelector(actions.rotate.CLASS_ABLE)} *)`, ['display', 'none']);
  2832. this.lines.horizontal.style.position = this.lines.vertical.style.position = this.text.style.position = this.container.style.position = 'absolute';
  2833. this.lines.horizontal.style.top = '50%';
  2834. this.lines.horizontal.style.width = '100%';
  2835. this.lines.vertical.style.left = '50%';
  2836. this.lines.vertical.style.height = '100%';
  2837. this.text.style.userSelect = 'none';
  2838. this.container.style.top = '0';
  2839. this.container.style.width = '100%';
  2840. this.container.style.height = '100%';
  2841. this.container.style.pointerEvents = 'none';
  2842. this.container.append(this.lines.horizontal, this.lines.vertical);
  2843. this.clip = () => {
  2844. const {outer, inner, gap} = $config.get().crosshair;
  2845. const thickness = Math.max(inner, outer);
  2846. const {width, height} = halfDimensions.viewport;
  2847. const halfGap = gap / 2;
  2848. const startInner = (thickness - inner) / 2;
  2849. const startOuter = (thickness - outer) / 2;
  2850. const endInner = thickness - startInner;
  2851. const endOuter = thickness - startOuter;
  2852. this.lines.horizontal.style.clipPath = 'path(\''
  2853. + `M0 ${startOuter}L${width - halfGap} ${startOuter}L${width - halfGap} ${startInner}L${width + halfGap} ${startInner}L${width + halfGap} ${startOuter}L${viewport.clientWidth} ${startOuter}`
  2854. + `L${viewport.clientWidth} ${endOuter}L${width + halfGap} ${endOuter}L${width + halfGap} ${endInner}L${width - halfGap} ${endInner}L${width - halfGap} ${endOuter}L0 ${endOuter}`
  2855. + 'Z\')';
  2856. this.lines.vertical.style.clipPath = 'path(\''
  2857. + `M${startOuter} 0L${startOuter} ${height - halfGap}L${startInner} ${height - halfGap}L${startInner} ${height + halfGap}L${startOuter} ${height + halfGap}L${startOuter} ${viewport.clientHeight}`
  2858. + `L${endOuter} ${viewport.clientHeight}L${endOuter} ${height + halfGap}L${endInner} ${height + halfGap}L${endInner} ${height - halfGap}L${endOuter} ${height - halfGap}L${endOuter} 0`
  2859. + 'Z\')';
  2860. };
  2861. this.updateConfig = (doClip = true) => {
  2862. const {colour, outer, inner, text} = $config.get().crosshair;
  2863. const thickness = Math.max(inner, outer);
  2864. this.container.style.filter = `drop-shadow(${colour.shadow} 0 0 1px)`;
  2865. this.lines.horizontal.style.translate = `0 -${thickness / 2}px`;
  2866. this.lines.vertical.style.translate = `-${thickness / 2}px 0`;
  2867. this.lines.horizontal.style.height = this.lines.vertical.style.width = `${thickness}px`;
  2868. this.lines.horizontal.style.backgroundColor = this.lines.vertical.style.backgroundColor = colour.fill;
  2869. if (text) {
  2870. this.text.style.color = colour.fill;
  2871. this.text.style.font = text.font;
  2872. this.text.style.left = `${text.position.x}%`;
  2873. this.text.style.top = `${text.position.y}%`;
  2874. this.text.style.transform = `translate(${text.translate.x}%,${text.translate.y}%) translate(${text.offset.x}px,${text.offset.y}px)`;
  2875. this.text.style.textAlign = text.align;
  2876. this.text.style.lineHeight = text.height;
  2877. this.container.append(this.text);
  2878. } else {
  2879. this.text.remove();
  2880. }
  2881. if (doClip) {
  2882. this.clip();
  2883. }
  2884. };
  2885. }();
  2886.  
  2887. // ELEMENT CHANGE LISTENERS
  2888.  
  2889. const observer = new function () {
  2890. const onResolutionChange = () => {
  2891. glow.handleSizeChange?.();
  2892. };
  2893. const styleObserver = new MutationObserver((() => {
  2894. const properties = ['top', 'left', 'width', 'height', 'scale', 'rotate', 'translate', 'transform-origin'];
  2895. let priorStyle;
  2896. return () => {
  2897. // mousemove events on video with ctrlKey=true trigger this but have no effect
  2898. if (video.style.cssText === priorStyle) {
  2899. return;
  2900. }
  2901. priorStyle = video.style.cssText;
  2902. for (const property of properties) {
  2903. containers.background.style[property] = video.style[property];
  2904. containers.foreground.style[property] = video.style[property];
  2905. // cinematics doesn't exist for embedded vids
  2906. if (cinematics) {
  2907. cinematics.style[property] = video.style[property];
  2908. }
  2909. }
  2910. glow.handleViewChange();
  2911. };
  2912. })());
  2913. const videoObserver = new FixedResizeObserver(() => {
  2914. handleVideoChange();
  2915. glow.handleSizeChange?.();
  2916. position.updateFrame();
  2917. });
  2918. const viewportObserver = new FixedResizeObserver(() => {
  2919. handleViewportChange();
  2920. crosshair.clip();
  2921. });
  2922. this.start = () => {
  2923. video.addEventListener('resize', onResolutionChange);
  2924. styleObserver.observe(video, {attributes: true, attributeFilter: ['style']});
  2925. videoObserver.observe(video);
  2926. viewportObserver.observe(viewport);
  2927. glow.handleViewChange();
  2928. };
  2929. this.stop = () => {
  2930. video.removeEventListener('resize', onResolutionChange);
  2931. styleObserver.disconnect();
  2932. viewportObserver.disconnect();
  2933. videoObserver.disconnect();
  2934. };
  2935. }();
  2936.  
  2937. // NAVIGATION LISTENERS
  2938.  
  2939. const stop = () => {
  2940. if (stopped) {
  2941. return;
  2942. }
  2943. stopped = true;
  2944. enabler.stop();
  2945. stopDrag?.();
  2946. observer.stop();
  2947. containers.background.remove();
  2948. containers.foreground.remove();
  2949. containers.tracker.remove();
  2950. crosshair.container.remove();
  2951. return peek(true);
  2952. };
  2953.  
  2954. const start = () => {
  2955. if (!stopped || viewport.classList.contains('ad-showing')) {
  2956. return;
  2957. }
  2958. stopped = false;
  2959. observer.start();
  2960. glow.start();
  2961. viewport.append(containers.background, containers.foreground, containers.tracker, crosshair.container);
  2962. // User may have a static minimum zoom greater than 1
  2963. zoom.constrain();
  2964. enabler.handleChange();
  2965. };
  2966.  
  2967. // LISTENER ASSIGNMENTS
  2968.  
  2969. // load & navigation
  2970. (() => {
  2971. const getNode = (node, selector, ...selectors) => new Promise((resolve) => {
  2972. for (const child of node.children) {
  2973. if (child.matches(selector)) {
  2974. resolve(selectors.length === 0 ? child : getNode(child, ...selectors));
  2975. return;
  2976. }
  2977. }
  2978. new MutationObserver((changes, observer) => {
  2979. for (const {addedNodes} of changes) {
  2980. for (const child of addedNodes) {
  2981. if (child.matches(selector)) {
  2982. resolve(selectors.length === 0 ? child : getNode(child, ...selectors));
  2983. observer.disconnect();
  2984. return;
  2985. }
  2986. }
  2987. }
  2988. }).observe(node, {childList: true});
  2989. });
  2990. const setupConfigFailsafe = (parent) => {
  2991. new MutationObserver((changes) => {
  2992. for (const {addedNodes} of changes) {
  2993. for (const node of addedNodes) {
  2994. if (!node.classList.contains('ytp-contextmenu')) {
  2995. continue;
  2996. }
  2997. const container = node.querySelector('.ytp-panel-menu');
  2998. const option = container.lastElementChild.cloneNode(true);
  2999. option.children[0].style.visibility = 'hidden';
  3000. option.children[1].innerText = 'Configure Viewfinding';
  3001. option.addEventListener('click', ({button}) => {
  3002. if (button === 0) {
  3003. actions.configure.onActive();
  3004. }
  3005. });
  3006. container.appendChild(option);
  3007. new FixedResizeObserver((_, observer) => {
  3008. if (container.clientWidth === 0) {
  3009. option.remove();
  3010. observer.disconnect();
  3011. }
  3012. }).observe(container);
  3013. }
  3014. }
  3015. }).observe(parent, {childList: true});
  3016. };
  3017. const init = async () => {
  3018. if (unsafeWindow.ytplayer?.bootstrapPlayerContainer?.childElementCount > 0) {
  3019. // wait for the video to be moved to ytd-app
  3020. await new Promise((resolve) => {
  3021. new MutationObserver((changes, observer) => {
  3022. resolve();
  3023. observer.disconnect();
  3024. }).observe(unsafeWindow.ytplayer.bootstrapPlayerContainer, {childList: true});
  3025. });
  3026. }
  3027. try {
  3028. await $config.ready;
  3029. } catch (error) {
  3030. if (!$config.reset || !window.confirm(`${error.message}\n\nWould you like to erase your data?`)) {
  3031. console.error(error);
  3032. return;
  3033. }
  3034. await $config.reset();
  3035. }
  3036. if (isEmbed) {
  3037. video = document.body.querySelector(SELECTOR_VIDEO);
  3038. } else {
  3039. const pageManager = await getNode(document.body, 'ytd-app', '#content', 'ytd-page-manager');
  3040. const page = pageManager.getCurrentPage() ?? await new Promise((resolve) => {
  3041. new MutationObserver(([{addedNodes: [page]}], observer) => {
  3042. if (page) {
  3043. resolve(page);
  3044. observer.disconnect();
  3045. }
  3046. }).observe(pageManager, {childList: true});
  3047. });
  3048. await page.playerEl.getPlayerPromise();
  3049. video = page.playerEl.querySelector(SELECTOR_VIDEO);
  3050. cinematics = page.querySelector('#cinematics');
  3051. // navigation to a new video
  3052. new MutationObserver(() => {
  3053. video.removeEventListener('play', startIfReady);
  3054. power.off();
  3055. // this callback can occur after metadata loads
  3056. startIfReady();
  3057. }).observe(page, {attributes: true, attributeFilter: ['video-id']});
  3058. // navigation to a non-video page
  3059. new MutationObserver(() => {
  3060. if (video.src === '') {
  3061. video.removeEventListener('play', startIfReady);
  3062. power.off();
  3063. }
  3064. }).observe(video, {attributes: true, attributeFilter: ['src']});
  3065. }
  3066. viewport = video.parentElement.parentElement;
  3067. altTarget = viewport.parentElement;
  3068. position.updateFrame();
  3069. handleVideoChange();
  3070. handleViewportChange();
  3071. enabler.updateConfig();
  3072. actions.crop.updateConfig();
  3073. crosshair.updateConfig();
  3074. containers.foreground.style.zIndex = crosshair.container.style.zIndex = video.parentElement.computedStyleMap?.().get('z-index').value ?? 10;
  3075. setupConfigFailsafe(document.body);
  3076. setupConfigFailsafe(viewport);
  3077. const startIfReady = () => {
  3078. if (video.readyState >= HTMLMediaElement.HAVE_METADATA) {
  3079. start();
  3080. }
  3081. };
  3082. const power = new function () {
  3083. this.off = () => {
  3084. delete this.wake;
  3085. stop();
  3086. };
  3087. this.sleep = () => {
  3088. this.wake ??= stop();
  3089. };
  3090. }();
  3091. new MutationObserver((() => {
  3092. return () => {
  3093. // video end
  3094. if (viewport.classList.contains('ended-mode')) {
  3095. power.off();
  3096. video.addEventListener('play', startIfReady, {once: true});
  3097. // ad start
  3098. } else if (viewport.classList.contains('ad-showing')) {
  3099. power.sleep();
  3100. }
  3101. };
  3102. })()).observe(viewport, {attributes: true, attributeFilter: ['class']});
  3103. // glow initialisation requires video dimensions
  3104. startIfReady();
  3105. video.addEventListener('loadedmetadata', () => {
  3106. if (viewport.classList.contains('ad-showing')) {
  3107. return;
  3108. }
  3109. start();
  3110. if (power.wake) {
  3111. power.wake();
  3112. delete power.wake;
  3113. }
  3114. });
  3115. };
  3116. if (!('ytPageType' in unsafeWindow) || unsafeWindow.ytPageType === 'watch') {
  3117. init();
  3118. return;
  3119. }
  3120. const initListener = ({detail: {newPageType}}) => {
  3121. if (newPageType === 'ytd-watch-flexy') {
  3122. init();
  3123. document.body.removeEventListener('yt-page-type-changed', initListener);
  3124. }
  3125. };
  3126. document.body.addEventListener('yt-page-type-changed', initListener);
  3127. })();
  3128.  
  3129. // keyboard state change
  3130.  
  3131. document.addEventListener('keydown', ({code}) => {
  3132. if (enabler.toggled) {
  3133. enabler.keys[enabler.keys.has(code) ? 'delete' : 'add'](code);
  3134. enabler.handleChange();
  3135. } else if (!enabler.keys.has(code)) {
  3136. enabler.keys.add(code);
  3137. enabler.handleChange();
  3138. }
  3139. });
  3140.  
  3141. document.addEventListener('keyup', ({code}) => {
  3142. if (enabler.toggled) {
  3143. return;
  3144. }
  3145. if (enabler.keys.has(code)) {
  3146. enabler.keys.delete(code);
  3147. enabler.handleChange();
  3148. }
  3149. });
  3150.  
  3151. window.addEventListener('blur', () => {
  3152. if (enabler.toggled) {
  3153. stopDrag?.();
  3154. } else {
  3155. enabler.keys.clear();
  3156. enabler.handleChange();
  3157. }
  3158. });
  3159. })();