YouTube Viewfinding

Zoom, rotate & crop YouTube videos

  1. // ==UserScript==
  2. // @name YouTube Viewfinding
  3. // @version 0.20
  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: 'Outer Thickness (px)',
  643. value: 3,
  644. predicate: (value) => value >= 0 || 'Thickness must be positive',
  645. inputAttributes: {min: 0},
  646. get: ({value: outer}) => ({outer}),
  647. },
  648. {
  649. label: 'Inner Thickness (px)',
  650. value: 1,
  651. predicate: (value) => value >= 0 || 'Thickness must be positive',
  652. inputAttributes: {min: 0},
  653. get: ({value: inner}) => ({inner}),
  654. },
  655. {
  656. label: 'Inner Diameter (px)',
  657. value: 157,
  658. predicate: (value) => value >= 0 || 'Diameter must be positive',
  659. inputAttributes: {min: 0},
  660. get: ({value: gap}) => ({gap}),
  661. },
  662. ((hideId) => ({
  663. label: 'Text',
  664. value: true,
  665. onUpdate: (value) => ({hide: {[hideId]: !value}}),
  666. get: ({value}, configs) => {
  667. if (!value) {
  668. return {};
  669. }
  670. const {translateX, translateY, ...config} = Object.assign(...configs);
  671. return {
  672. text: {
  673. translate: {
  674. x: translateX,
  675. y: translateY,
  676. },
  677. ...config,
  678. },
  679. };
  680. },
  681. children: [
  682. {
  683. label: 'Font',
  684. value: '30px "Harlow Solid", cursive',
  685. predicate: isCSSRule.bind(null, 'font'),
  686. get: ({value: font}) => ({font}),
  687. },
  688. {
  689. label: 'Position (%)',
  690. get: (_, configs) => ({position: Object.assign(...configs)}),
  691. children: ['x', 'y'].map((label) => ({
  692. label,
  693. value: 0,
  694. predicate: (value) => Math.abs(value) <= 50 || 'Position must be on-screen',
  695. inputAttributes: {min: -50, max: 50},
  696. get: ({value}) => ({[label]: value + 50}),
  697. })),
  698. },
  699. {
  700. label: 'Offset (px)',
  701. get: (_, configs) => ({offset: Object.assign(...configs)}),
  702. children: [
  703. {
  704. label: 'x',
  705. value: -6,
  706. get: ({value: x}) => ({x}),
  707. },
  708. {
  709. label: 'y',
  710. value: -25,
  711. get: ({value: y}) => ({y}),
  712. },
  713. ],
  714. },
  715. (() => {
  716. const options = ['Left', 'Center', 'Right'];
  717. return {
  718. label: 'Alignment',
  719. value: options[2],
  720. options,
  721. get: ({value}) => ({align: value.toLowerCase(), translateX: options.indexOf(value) * -50}),
  722. };
  723. })(),
  724. (() => {
  725. const options = ['Top', 'Middle', 'Bottom'];
  726. return {
  727. label: 'Baseline',
  728. value: options[0],
  729. options,
  730. get: ({value}) => ({translateY: options.indexOf(value) * -50}),
  731. };
  732. })(),
  733. {
  734. label: 'Line height (%)',
  735. value: 90,
  736. predicate: (value) => value >= 0 || 'Height must be positive',
  737. inputAttributes: {min: 0},
  738. get: ({value}) => ({height: value / 100}),
  739. },
  740. ].map((node) => ({...node, hideId})),
  741. }))(getHideId()),
  742. {
  743. label: 'Colours',
  744. get: (_, configs) => ({colour: Object.assign(...configs)}),
  745. children: [
  746. {
  747. label: 'Fill',
  748. value: '#ffffff',
  749. input: 'color',
  750. get: ({value: fill}) => ({fill}),
  751. },
  752. {
  753. label: 'Shadow',
  754. value: '#000000',
  755. input: 'color',
  756. get: ({value: shadow}) => ({shadow}),
  757. },
  758. ],
  759. },
  760. ],
  761. },
  762. ],
  763. },
  764. ],
  765. };
  766. })(),
  767. {
  768. defaultStyle: {
  769. headBase: '#c80000',
  770. headButtonExit: '#000000',
  771. borderHead: '#ffffff',
  772. borderTooltip: '#c80000',
  773. width: Math.min(90, screen.width / 16),
  774. height: 90,
  775. },
  776. outerStyle: {
  777. zIndex: 10000,
  778. scrollbarColor: 'initial',
  779. },
  780. patches: [
  781. // removing "Glow Allowance" from pan limits
  782. ({children: [, {children}]}) => {
  783. // pan
  784. children[2].children.splice(2, 1);
  785. // snap pan
  786. children[3].children.splice(1, 1);
  787. },
  788. ],
  789. },
  790. );
  791.  
  792. const CLASS_VIEWFINDER = 'viewfind-element';
  793. const DEGREES = {
  794. 45: Math.PI / 4,
  795. 90: Math.PI / 2,
  796. 180: Math.PI,
  797. 270: Math.PI / 2 * 3,
  798. 360: Math.PI * 2,
  799. };
  800. const SELECTOR_VIDEO = '#movie_player video.html5-main-video';
  801.  
  802. // STATE
  803.  
  804. // elements
  805. let video;
  806. let altTarget;
  807. let viewport;
  808. let cinematics;
  809.  
  810. // derived values
  811. let videoTheta;
  812. let videoHypotenuse;
  813. let isThin;
  814. let viewportRatio;
  815. let viewportRatioInverse;
  816. const halfDimensions = {
  817. video: {},
  818. viewport: {},
  819. };
  820.  
  821. // other
  822. let stopped = true;
  823. let stopDrag;
  824.  
  825. const handleVideoChange = () => {
  826. DimensionCache.id++;
  827. halfDimensions.video.width = video.clientWidth / 2;
  828. halfDimensions.video.height = video.clientHeight / 2;
  829. videoTheta = getTheta(0, 0, video.clientWidth, video.clientHeight);
  830. videoHypotenuse = Math.sqrt(halfDimensions.video.width * halfDimensions.video.width + halfDimensions.video.height * halfDimensions.video.height);
  831. };
  832.  
  833. const handleViewportChange = () => {
  834. DimensionCache.id++;
  835. isThin = getTheta(0, 0, viewport.clientWidth, viewport.clientHeight) < videoTheta;
  836. halfDimensions.viewport.width = viewport.clientWidth / 2;
  837. halfDimensions.viewport.height = viewport.clientHeight / 2;
  838. viewportRatio = viewport.clientWidth / viewport.clientHeight;
  839. viewportRatioInverse = 1 / viewportRatio;
  840. position.constrain();
  841. glow.handleViewChange(true);
  842. };
  843.  
  844. // ROTATION HELPERS
  845.  
  846. const getTheta = (fromX, fromY, toX, toY) => Math.atan2(toY - fromY, toX - fromX);
  847.  
  848. const getRotatedCorners = (radius, theta) => {
  849. const angle0 = DEGREES[90] - theta + rotation.value;
  850. const angle1 = theta + rotation.value - DEGREES[90];
  851. return [
  852. {
  853. x: Math.abs(radius * Math.cos(angle0)),
  854. y: Math.abs(radius * Math.sin(angle0)),
  855. },
  856. {
  857. x: Math.abs(radius * Math.cos(angle1)),
  858. y: Math.abs(radius * Math.sin(angle1)),
  859. },
  860. ];
  861. };
  862.  
  863. // CSS HELPER
  864.  
  865. const css = new function () {
  866. this.has = (name) => document.body.classList.contains(name);
  867. this.tag = (name, doAdd = true) => document.body.classList[doAdd ? 'add' : 'remove'](name);
  868. this.getSelector = (...classes) => `body.${classes.join('.')}`;
  869. const getSheet = () => {
  870. const element = document.createElement('style');
  871. document.head.appendChild(element);
  872. return element.sheet;
  873. };
  874. const getRuleString = (selector, ...declarations) => `${selector}{${declarations.map(([property, value]) => `${property}:${value};`).join('')}}`;
  875. this.add = function (...rule) {
  876. this.insertRule(getRuleString(...rule));
  877. }.bind(getSheet());
  878. this.Toggleable = class {
  879. static sheet = getSheet();
  880. static active = [];
  881. static id = 0;
  882. static add(rule, id) {
  883. this.sheet.insertRule(rule, this.active.length);
  884. this.active.push(id);
  885. }
  886. static remove(id) {
  887. let index = this.active.indexOf(id);
  888. while (index >= 0) {
  889. this.sheet.deleteRule(index);
  890. this.active.splice(index, 1);
  891. index = this.active.indexOf(id);
  892. }
  893. }
  894. id = this.constructor.id++;
  895. add(...rule) {
  896. this.constructor.add(getRuleString(...rule), this.id);
  897. }
  898. remove() {
  899. this.constructor.remove(this.id);
  900. }
  901. };
  902. }();
  903.  
  904. // ACTION MANAGER
  905.  
  906. const enabler = new function () {
  907. this.CLASS_ABLE = 'viewfind-action-able';
  908. this.CLASS_DRAGGING = 'viewfind-action-dragging';
  909. this.keys = new Set();
  910. this.didPause = false;
  911. this.isHidingGlow = false;
  912. this.setActive = (action) => {
  913. const {active, keys} = $config.get();
  914. if (active.hideGlow && Boolean(action) !== this.isHidingGlow) {
  915. if (action) {
  916. this.isHidingGlow = true;
  917. glow.hide();
  918. } else if (this.isHidingGlow) {
  919. this.isHidingGlow = false;
  920. glow.show();
  921. }
  922. }
  923. this.activeAction?.onInactive?.();
  924. if (action) {
  925. this.activeAction = action;
  926. this.toggled = keys[action.CODE].toggle;
  927. action.onActive?.();
  928. if (active.pause && !video.paused) {
  929. video.pause();
  930. this.didPause = true;
  931. }
  932. return;
  933. }
  934. if (this.didPause) {
  935. video.play();
  936. this.didPause = false;
  937. }
  938. this.activeAction = this.toggled = undefined;
  939. };
  940. this.handleChange = () => {
  941. if (stopped || stopDrag || video.ended) {
  942. return;
  943. }
  944. const {keys} = $config.get();
  945. let activeAction;
  946. for (const action of Object.values(actions)) {
  947. if (
  948. keys[action.CODE].keys.size === 0 || !this.keys.isSupersetOf(keys[action.CODE].keys) || activeAction && ('toggle' in keys[action.CODE] ?
  949. !('toggle' in keys[activeAction.CODE]) || keys[activeAction.CODE].keys.size >= keys[action.CODE].keys.size :
  950. !('toggle' in keys[activeAction.CODE]) && keys[activeAction.CODE].keys.size >= keys[action.CODE].keys.size)
  951. ) {
  952. if ('CLASS_ABLE' in action) {
  953. css.tag(action.CLASS_ABLE, false);
  954. }
  955. continue;
  956. }
  957. if (activeAction && 'CLASS_ABLE' in activeAction) {
  958. css.tag(activeAction.CLASS_ABLE, false);
  959. }
  960. activeAction = action;
  961. }
  962. if (activeAction === this.activeAction) {
  963. return;
  964. }
  965. if (activeAction) {
  966. if ('CLASS_ABLE' in activeAction) {
  967. css.tag(activeAction.CLASS_ABLE);
  968. css.tag(this.CLASS_ABLE);
  969. this.setActive(activeAction);
  970. return;
  971. }
  972. this.activeAction?.onInactive?.();
  973. activeAction.onActive();
  974. this.activeAction = activeAction;
  975. }
  976. css.tag(this.CLASS_ABLE, false);
  977. this.setActive(false);
  978. };
  979. this.stop = () => {
  980. css.tag(this.CLASS_ABLE, false);
  981. for (const action of Object.values(actions)) {
  982. if ('CLASS_ABLE' in action) {
  983. css.tag(action.CLASS_ABLE, false);
  984. }
  985. }
  986. this.setActive(false);
  987. };
  988. this.updateConfig = (() => {
  989. const rule = new css.Toggleable();
  990. const selector = `${css.getSelector(this.CLASS_ABLE)} #contentContainer.tp-yt-app-drawer[swipe-open]::after`
  991. + `,${css.getSelector(this.CLASS_ABLE)} #movie_player > .html5-video-container ~ :not(.${CLASS_VIEWFINDER})`;
  992. return () => {
  993. const {overlayRule} = $config.get().active;
  994. rule.remove();
  995. if (overlayRule) {
  996. rule.add(selector, overlayRule);
  997. }
  998. };
  999. })();
  1000. $config.ready.then(() => {
  1001. this.updateConfig();
  1002. });
  1003. // insertion order decides priority
  1004. css.add(`${css.getSelector(this.CLASS_DRAGGING)} #movie_player`, ['cursor', 'grabbing']);
  1005. css.add(`${css.getSelector(this.CLASS_ABLE)} #movie_player`, ['cursor', 'grab']);
  1006. }();
  1007.  
  1008. // ELEMENT CONTAINER SETUP
  1009.  
  1010. const containers = new function () {
  1011. for (const name of ['background', 'foreground', 'tracker']) {
  1012. this[name] = document.createElement('div');
  1013. this[name].classList.add(CLASS_VIEWFINDER);
  1014. }
  1015. // make an outline of the uncropped video
  1016. css.add(`${css.getSelector(enabler.CLASS_ABLE)} #${this.foreground.id = 'viewfind-outlined'}`, ['outline', '1px solid white']);
  1017. this.background.style.position = this.foreground.style.position = 'absolute';
  1018. this.background.style.pointerEvents = this.foreground.style.pointerEvents = this.tracker.style.pointerEvents = 'none';
  1019. this.tracker.style.height = this.tracker.style.width = '100%';
  1020. }();
  1021.  
  1022. // MODIFIERS
  1023.  
  1024. class Cache {
  1025. targets = [];
  1026. constructor(...targets) {
  1027. for (const source of targets) {
  1028. this.targets.push({source});
  1029. }
  1030. }
  1031. update(target) {
  1032. return target.value !== (target.value = target.source.value);
  1033. }
  1034. isStale() {
  1035. return this.targets.reduce((value, target) => value || this.update(target), false);
  1036. }
  1037. }
  1038.  
  1039. class ConfigCache extends Cache {
  1040. static id = 0;
  1041. id = this.constructor.id;
  1042. constructor(...targets) {
  1043. super(...targets);
  1044. }
  1045. isStale() {
  1046. if (this.id === (this.id = this.constructor.id)) {
  1047. return super.isStale();
  1048. }
  1049. for (const target of this.targets) {
  1050. target.value = target.source.value;
  1051. }
  1052. return true;
  1053. }
  1054. }
  1055.  
  1056. class DimensionCache extends ConfigCache {
  1057. static id = 0;
  1058. }
  1059.  
  1060. const rotation = new function () {
  1061. this.value = DEGREES[90];
  1062. this.reset = () => {
  1063. this.value = DEGREES[90];
  1064. video.style.removeProperty('rotate');
  1065. };
  1066. this.apply = () => {
  1067. // Conversion from anticlockwise rotation from the x-axis to clockwise rotation from the y-axis
  1068. video.style.setProperty('rotate', `${DEGREES[90] - this.value}rad`);
  1069. delete actions.reset.restore;
  1070. };
  1071. // dissimilar from other constrain functions in that no effective limit is applied
  1072. // -1.5π < rotation <= 0.5π
  1073. // 0 <= 0.5π - rotation < 2π
  1074. this.constrain = () => {
  1075. this.value %= DEGREES[360];
  1076. if (this.value > DEGREES[90]) {
  1077. this.value -= DEGREES[360];
  1078. } else if (this.value <= -DEGREES[270]) {
  1079. this.value += DEGREES[360];
  1080. }
  1081. this.apply();
  1082. };
  1083. }();
  1084.  
  1085. const zoom = new function () {
  1086. this.value = 1;
  1087. const scaleRule = new css.Toggleable();
  1088. this.reset = () => {
  1089. this.value = 1;
  1090. video.style.removeProperty('scale');
  1091. scaleRule.remove();
  1092. scaleRule.add(':root', [VAR_ZOOM, '1']);
  1093. };
  1094. this.apply = () => {
  1095. video.style.setProperty('scale', `${this.value}`);
  1096. scaleRule.remove();
  1097. scaleRule.add(':root', [VAR_ZOOM, `${this.value}`]);
  1098. delete actions.reset.restore;
  1099. };
  1100. const getFit = (corner0, corner1, doSplit = false) => {
  1101. const x = Math.max(corner0.x, corner1.x) / viewport.clientWidth;
  1102. const y = Math.max(corner0.y, corner1.y) / viewport.clientHeight;
  1103. return doSplit ? [0.5 / x, 0.5 / y] : 0.5 / Math.max(x, y);
  1104. };
  1105. this.getFit = (width, height) => getFit(...getRotatedCorners(Math.sqrt(width * width + height * height), getTheta(0, 0, width, height)));
  1106. this.getVideoFit = (doSplit) => getFit(...getRotatedCorners(videoHypotenuse, videoTheta), doSplit);
  1107. this.constrain = (() => {
  1108. const limitGetters = {
  1109. [LIMITS.static]: [({custom}) => custom, ({custom}) => custom],
  1110. [LIMITS.fit]: (() => {
  1111. const getGetter = () => {
  1112. const zoomCache = new Cache(this);
  1113. const rotationCache = new DimensionCache(rotation);
  1114. const configCache = new ConfigCache();
  1115. let updateOnZoom;
  1116. let value;
  1117. return ({frame}, glow) => {
  1118. let fallthrough = rotationCache.isStale();
  1119. if (configCache.isStale()) {
  1120. if (glow) {
  1121. const {scaled} = glow.blur;
  1122. updateOnZoom = frame > 0 && (scaled.x > 0 || scaled.y > 0);
  1123. } else {
  1124. updateOnZoom = false;
  1125. }
  1126. fallthrough = true;
  1127. }
  1128. if (zoomCache.isStale() && updateOnZoom || fallthrough) {
  1129. if (glow) {
  1130. const base = glow.end - 1;
  1131. const {scaled, unscaled} = glow.blur;
  1132. value = this.getFit(
  1133. halfDimensions.video.width + Math.max(0, base * halfDimensions.video.width + Math.max(unscaled.x, scaled.x * this.value)) * frame,
  1134. halfDimensions.video.height + Math.max(0, base * halfDimensions.video.height + Math.max(unscaled.y, scaled.y * this.value)) * frame,
  1135. );
  1136. } else {
  1137. value = this.getVideoFit();
  1138. }
  1139. }
  1140. return value;
  1141. };
  1142. };
  1143. return [getGetter(), getGetter()];
  1144. })(),
  1145. };
  1146. return () => {
  1147. const {zoomOutLimit, zoomInLimit, glow} = $config.get();
  1148. if (zoomOutLimit.type !== 'None') {
  1149. this.value = Math.max(limitGetters[zoomOutLimit.type][0](zoomOutLimit, glow), this.value);
  1150. }
  1151. if (zoomInLimit.type !== 'None') {
  1152. this.value = Math.min(limitGetters[zoomInLimit.type][1](zoomInLimit, glow, 1), this.value);
  1153. }
  1154. this.apply();
  1155. };
  1156. })();
  1157. }();
  1158.  
  1159. const position = new function () {
  1160. this.x = this.y = 0;
  1161. this.getValues = () => ({x: this.x, y: this.y});
  1162. this.reset = () => {
  1163. this.x = this.y = 0;
  1164. video.style.removeProperty('translate');
  1165. };
  1166. this.apply = () => {
  1167. video.style.setProperty('transform-origin', `${(0.5 + this.x) * 100}% ${(0.5 - this.y) * 100}%`);
  1168. video.style.setProperty('translate', `${-this.x * 100}% ${this.y * 100}%`);
  1169. delete actions.reset.restore;
  1170. };
  1171. this.constrain = (() => {
  1172. // logarithmic progress from "low" to infinity
  1173. const getProgress = (low, target) => 1 - low / target;
  1174. const getProgressed = ({x: fromX, y: fromY, z: lowZ}, {x: toX, y: toY}, targetZ) => {
  1175. const p = getProgress(lowZ, targetZ);
  1176. return {x: p * (toX - fromX) + fromX, y: p * (toY - fromY) + fromY};
  1177. };
  1178. // y = mx + c
  1179. const getLineY = ({m, c}, x = this.x) => m * x + c;
  1180. // x = (y - c) / m
  1181. const getLineX = ({m, c}, y = this.y) => (y - c) / m;
  1182. const getM = (from, to) => (to.y - from.y) / (to.x - from.x);
  1183. const getLine = (m, {x, y}) => ({c: y - m * x, m});
  1184. const getFlipped = ({x, y}) => ({x: -x, y: -y});
  1185. const correctY = (line, left, right) => {
  1186. if (this.x >= left.x && this.x <= right.x) {
  1187. this.y = getLineY(line, this.x);
  1188. return true;
  1189. }
  1190. };
  1191. const correctX = (line, bottom, top) => {
  1192. if (this.y >= bottom.y && this.y <= top.y) {
  1193. this.x = getLineX(line, this.y);
  1194. return true;
  1195. }
  1196. };
  1197. const isAbove = ({m, c}, {x, y} = this) => m * x + c < y;
  1198. const isRight = ({m, c}, {x, y} = this) => (y - c) / m < x;
  1199. const apply2DFrame = (points, lines) => {
  1200. const {x, y} = this;
  1201. if (Math.abs(lines.right.c) === Infinity) {
  1202. this.x = Math.min(points.topRight.x, Math.max(points.topLeft.x, this.x));
  1203. } else if (isRight(lines.right)) {
  1204. if (correctX(lines.right, points.bottomRight, points.topRight)) {
  1205. return;
  1206. }
  1207. } else if (!isRight(lines.left)) {
  1208. if (correctX(lines.left, points.bottomLeft, points.topLeft)) {
  1209. return;
  1210. }
  1211. }
  1212. if (isAbove(lines.top)) {
  1213. if (correctY(lines.top, points.topLeft, points.topRight)) {
  1214. return;
  1215. }
  1216. } else if (!isAbove(lines.bottom)) {
  1217. if (correctY(lines.bottom, points.bottomLeft, points.bottomRight)) {
  1218. return;
  1219. }
  1220. }
  1221. if (x <= points.bottomLeft.x && y <= points.bottomLeft.y) {
  1222. this.x = points.bottomLeft.x;
  1223. this.y = points.bottomLeft.y;
  1224. } else if (x >= points.bottomRight.x && y <= points.bottomRight.y) {
  1225. this.x = points.bottomRight.x;
  1226. this.y = points.bottomRight.y;
  1227. } else if (x <= points.topLeft.x && y >= points.topLeft.y) {
  1228. this.x = points.topLeft.x;
  1229. this.y = points.topLeft.y;
  1230. } else if (x >= points.topRight.x && y >= points.topRight.y) {
  1231. this.x = points.topRight.x;
  1232. this.y = points.topRight.y;
  1233. }
  1234. };
  1235. const apply1DSideFrame = {
  1236. x: (line) => {
  1237. this.x = Math.max(-line.x, Math.min(line.x, this.x));
  1238. this.y = getLineY(line);
  1239. },
  1240. y: (line) => {
  1241. this.y = Math.max(-line.y, Math.min(line.y, this.y));
  1242. this.x = getLineX(line);
  1243. },
  1244. };
  1245. const swap = (array, i0, i1) => {
  1246. const temp = array[i0];
  1247. array[i0] = array[i1];
  1248. array[i1] = temp;
  1249. };
  1250. const getBoundApplyFrame = (() => {
  1251. const getBound = (first, second, isTopLeft) => {
  1252. if (zoom.value <= first.z) {
  1253. return false;
  1254. }
  1255. if (zoom.value >= second.z) {
  1256. const progress = zoom.value / second.z;
  1257. const x = isTopLeft ?
  1258. -0.5 - (-0.5 - second.x) / progress :
  1259. 0.5 - (0.5 - second.x) / progress;
  1260. return {
  1261. x,
  1262. y: 0.5 - (0.5 - second.y) / progress,
  1263. };
  1264. }
  1265. return {
  1266. ...getProgressed(first, second.vpEnd, zoom.value),
  1267. axis: second.vpEnd.axis,
  1268. m: second.y / second.x,
  1269. c: 0,
  1270. };
  1271. };
  1272. const getFrame = (point0, point1) => {
  1273. const points = {};
  1274. const lines = {};
  1275. const flipped0 = getFlipped(point0);
  1276. const flipped1 = getFlipped(point1);
  1277. const m0 = getM(point0, point1);
  1278. const m1 = getM(flipped0, point1);
  1279. lines.top = getLine(m0, point0);
  1280. lines.bottom = getLine(m0, flipped0);
  1281. lines.left = getLine(m1, point0);
  1282. lines.right = getLine(m1, flipped0);
  1283. points.topLeft = point0;
  1284. points.topRight = point1;
  1285. points.bottomLeft = flipped1;
  1286. points.bottomRight = flipped0;
  1287. if (video.clientWidth < video.clientHeight) {
  1288. if (getLineX(lines.right, 0) < getLineX(lines.left, 0)) {
  1289. swap(lines, 'right', 'left');
  1290. swap(points, 'bottomLeft', 'bottomRight');
  1291. swap(points, 'topLeft', 'topRight');
  1292. }
  1293. } else {
  1294. if (lines.top.c < lines.bottom.c) {
  1295. swap(lines, 'top', 'bottom');
  1296. swap(points, 'topLeft', 'bottomLeft');
  1297. swap(points, 'topRight', 'bottomRight');
  1298. }
  1299. }
  1300. return [points, lines];
  1301. };
  1302. return (first0, second0, first1, second1) => {
  1303. const point0 = getBound(first0, second0, true);
  1304. const point1 = getBound(first1, second1, false);
  1305. if (!point0 && !point1) {
  1306. return () => {
  1307. this.x = this.y = 0;
  1308. };
  1309. }
  1310. if (!point0 || !point1 || point0.axis && point0.axis === point1.axis) {
  1311. // todo choose the longer line?
  1312. const point = point0 || point1;
  1313. const {axis} = point;
  1314. point.axis ??= Math.abs(point.x) > Math.abs(point.y) ? 'x' : 'y';
  1315. if (point[point.axis] < 0) {
  1316. point.x = -point.x;
  1317. point.y = -point.y;
  1318. }
  1319. if (!axis) {
  1320. point.m = point.y / point.x;
  1321. point.c = 0;
  1322. }
  1323. return apply1DSideFrame[point.axis].bind(null, point);
  1324. }
  1325. return apply2DFrame.bind(null, ...getFrame(point0, point1));
  1326. };
  1327. })();
  1328. const snapZoom = (() => {
  1329. const getDirected = (first, second, flipX, flipY) => {
  1330. const line0 = [first, {}];
  1331. const line1 = [{z: second.z}, {}];
  1332. if (flipX) {
  1333. line0[1].x = -second.vpEnd.x;
  1334. line1[0].x = -second.x;
  1335. line1[1].x = -0.5;
  1336. } else {
  1337. line0[1].x = second.vpEnd.x;
  1338. line1[0].x = second.x;
  1339. line1[1].x = 0.5;
  1340. }
  1341. if (flipY) {
  1342. line0[1].y = -second.vpEnd.y;
  1343. line1[0].y = -second.y;
  1344. line1[1].y = -0.5;
  1345. } else {
  1346. line0[1].y = second.vpEnd.y;
  1347. line1[0].y = second.y;
  1348. line1[1].y = 0.5;
  1349. }
  1350. return [line0, line1];
  1351. };
  1352. // https://math.stackexchange.com/questions/2223691/intersect-2-lines-at-the-same-ratio-through-a-point
  1353. const getIntersectProgress = ({x, y}, [{x: g, y: e}, {x: f, y: d}], [{x: k, y: i}, {x: j, y: h}], doFlip) => {
  1354. const a = d * j - d * k - j * e + e * k - h * f + h * g + i * f - i * g;
  1355. 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;
  1356. const c = k * e - e * x - k * y - g * i + i * x + g * y;
  1357. return (doFlip ? -b - Math.sqrt(b * b - 4 * a * c) : -b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
  1358. };
  1359. const getLineFromPoints = (from, to) => getLine(getM(from, to), from);
  1360. // line with progressed start point
  1361. const getProgressedLine = (line, {z}) => [getProgressed(...line, z), line[1]];
  1362. return (first0, _second0, first1, second1) => {
  1363. const second0 = {..._second0, x: -_second0.x, vpEnd: {..._second0.vpEnd, x: -_second0.vpEnd.x}};
  1364. const absPosition = {x: Math.abs(this.x), y: Math.abs(this.y)};
  1365. const getPairings = (flipX0, flipY0, flipX1, flipY1) => {
  1366. const [lineFirst0, lineSecond0] = getDirected(first0, second0, flipX0, flipY0);
  1367. const [lineFirst1, lineSecond1] = getDirected(first1, second1, flipX1, flipY1);
  1368. // array structure is:
  1369. // start zoom for both lines
  1370. // 0 line start and its infinite zoom point
  1371. // 1 line start and its infinite zoom point
  1372. return [
  1373. first0.z >= first1.z ?
  1374. [first0.z, lineFirst0, getProgressedLine(lineFirst1, first0)] :
  1375. [first1.z, getProgressedLine(lineFirst0, first1), lineFirst1],
  1376. ...second0.z >= second1.z ?
  1377. [
  1378. [second1.z, getProgressedLine(lineFirst0, second1), lineSecond1],
  1379. [second0.z, lineSecond0, getProgressedLine(lineSecond1, second0)],
  1380. ] :
  1381. [
  1382. [second0.z, lineSecond0, getProgressedLine(lineFirst1, second0)],
  1383. [second1.z, getProgressedLine(lineSecond0, second1), lineSecond1],
  1384. ],
  1385. ];
  1386. };
  1387. const [pair0, pair1, pair2, doFlip = false] = (() => {
  1388. if (this.x >= 0 !== this.y >= 0) {
  1389. return isAbove(getLineFromPoints(second0, {x: 0.5, y: 0.5}), absPosition) ?
  1390. [...getPairings(false, false, true, false), true] :
  1391. getPairings(false, false, false, true);
  1392. }
  1393. return isAbove(getLineFromPoints(second1, {x: 0.5, y: 0.5}), absPosition) ?
  1394. getPairings(true, false, false, false) :
  1395. [...getPairings(false, true, false, false), true];
  1396. })();
  1397. const applyZoomPairSecond = ([z, ...pair], maxP = 1) => {
  1398. const p = getIntersectProgress(absPosition, ...pair, doFlip);
  1399. if (p >= 0 && p <= maxP) {
  1400. // I don't think the >= 1 check is necessary but best be safe
  1401. zoom.value = p >= 1 ? Number.MAX_SAFE_INTEGER : z / (1 - p);
  1402. return true;
  1403. }
  1404. return false;
  1405. };
  1406. if (
  1407. applyZoomPairSecond(pair2)
  1408. || applyZoomPairSecond(pair1, getProgress(pair1[0], pair2[0]))
  1409. || applyZoomPairSecond(pair0, getProgress(pair0[0], pair1[0]))
  1410. ) {
  1411. return;
  1412. }
  1413. zoom.value = pair0[0];
  1414. };
  1415. })();
  1416. const getZoomPoints = (() => {
  1417. const getPoints = (fitZoom, doFlip) => {
  1418. const getGenericRotated = (x, y, angle) => {
  1419. const radius = Math.sqrt(x * x + y * y);
  1420. const pointTheta = getTheta(0, 0, x, y) + angle;
  1421. return {
  1422. x: radius * Math.cos(pointTheta),
  1423. y: radius * Math.sin(pointTheta),
  1424. };
  1425. };
  1426. const getRotated = (xRaw, yRaw) => {
  1427. // Multiplying by video dimensions to have the axes' scales match the video's
  1428. // Using midPoint's raw values would only work if points moved elliptically around the centre of rotation
  1429. const rotated = getGenericRotated(xRaw * video.clientWidth, yRaw * video.clientHeight, (DEGREES[90] - rotation.value) % DEGREES[180]);
  1430. rotated.x /= video.clientWidth;
  1431. rotated.y /= video.clientHeight;
  1432. return rotated;
  1433. };
  1434. return [
  1435. {...getRotated(halfDimensions.viewport.width / video.clientWidth / fitZoom[0], 0), axis: doFlip ? 'y' : 'x'},
  1436. {...getRotated(0, halfDimensions.viewport.height / video.clientHeight / fitZoom[1]), axis: doFlip ? 'x' : 'y'},
  1437. ];
  1438. };
  1439. const getIntersection = (line, corner, middle) => {
  1440. const getIntersection = (line0, line1) => {
  1441. const a0 = line0[0].y - line0[1].y;
  1442. const b0 = line0[1].x - line0[0].x;
  1443. const c0 = line0[1].x * line0[0].y - line0[0].x * line0[1].y;
  1444. const a1 = line1[0].y - line1[1].y;
  1445. const b1 = line1[1].x - line1[0].x;
  1446. const c1 = line1[1].x * line1[0].y - line1[0].x * line1[1].y;
  1447. const d = a0 * b1 - b0 * a1;
  1448. return {
  1449. x: (c0 * b1 - b0 * c1) / d,
  1450. y: (a0 * c1 - c0 * a1) / d,
  1451. };
  1452. };
  1453. const {x, y} = getIntersection([{x: 0, y: 0}, middle], [line, corner]);
  1454. const progress = isThin ? (y - line.y) / (corner.y - line.y) : (x - line.x) / (corner.x - line.x);
  1455. return {x, y, z: line.z / (1 - progress), c: line.y};
  1456. };
  1457. const getIntersect = (yIntersect, corner, right, top) => {
  1458. const point0 = getIntersection(yIntersect, corner, right);
  1459. const point1 = getIntersection(yIntersect, corner, top);
  1460. const [point, vpEnd] = point0.z > point1.z ? [point0, {...right}] : [point1, {...top}];
  1461. if (Math.sign(point[vpEnd.axis]) !== Math.sign(vpEnd[vpEnd.axis])) {
  1462. vpEnd.x = -vpEnd.x;
  1463. vpEnd.y = -vpEnd.y;
  1464. }
  1465. return {...point, vpEnd};
  1466. };
  1467. // the angle from 0,0 to the center of the video edge angled towards the viewport's upper-right corner
  1468. const getQuadrantAngle = (isEvenQuadrant) => {
  1469. const angle = (rotation.value + DEGREES[360]) % DEGREES[90];
  1470. return isEvenQuadrant ? angle : DEGREES[90] - angle;
  1471. };
  1472. return () => {
  1473. const isEvenQuadrant = (Math.floor(rotation.value / DEGREES[90]) + 3) % 2 === 0;
  1474. const quadrantAngle = getQuadrantAngle(isEvenQuadrant);
  1475. const progress = quadrantAngle / DEGREES[90] * -2 + 1;
  1476. const progressAngles = {
  1477. base: Math.atan(progress * viewportRatio),
  1478. side: Math.atan(progress * viewportRatioInverse),
  1479. };
  1480. const progressCosines = {
  1481. base: Math.cos(progressAngles.base),
  1482. side: Math.cos(progressAngles.side),
  1483. };
  1484. const fitZoom = zoom.getVideoFit(true);
  1485. const points = getPoints(fitZoom, quadrantAngle >= DEGREES[45]);
  1486. const sideIntersection = getIntersect(
  1487. ((cornerAngle) => ({
  1488. x: 0,
  1489. y: (halfDimensions.video.height - halfDimensions.video.width * Math.tan(cornerAngle)) / video.clientHeight,
  1490. z: halfDimensions.viewport.width / (progressCosines.side * Math.abs(halfDimensions.video.width / Math.cos(cornerAngle))),
  1491. }))(quadrantAngle + progressAngles.side),
  1492. isEvenQuadrant ? {x: -0.5, y: 0.5} : {x: 0.5, y: 0.5},
  1493. ...points,
  1494. );
  1495. const baseIntersection = getIntersect(
  1496. ((cornerAngle) => ({
  1497. x: 0,
  1498. y: (halfDimensions.video.height - halfDimensions.video.width * Math.tan(cornerAngle)) / video.clientHeight,
  1499. z: halfDimensions.viewport.height / (progressCosines.base * Math.abs(halfDimensions.video.width / Math.cos(cornerAngle))),
  1500. }))(DEGREES[90] - quadrantAngle - progressAngles.base),
  1501. isEvenQuadrant ? {x: 0.5, y: 0.5} : {x: -0.5, y: 0.5},
  1502. ...points,
  1503. );
  1504. const [originSide, originBase] = fitZoom.map((z) => ({x: 0, y: 0, z}));
  1505. return isEvenQuadrant ?
  1506. [...[originSide, sideIntersection], ...[originBase, baseIntersection]] :
  1507. [...[originBase, baseIntersection], ...[originSide, sideIntersection]];
  1508. };
  1509. })();
  1510. let zoomPoints;
  1511. const getEnsureZoomPoints = (() => {
  1512. const updateLog = [];
  1513. let count = 0;
  1514. return () => {
  1515. const zoomPointCache = new DimensionCache(rotation);
  1516. const callbackCache = new Cache(zoom);
  1517. const id = count++;
  1518. return () => {
  1519. if (zoomPointCache.isStale()) {
  1520. updateLog.length = 0;
  1521. zoomPoints = getZoomPoints();
  1522. }
  1523. if (callbackCache.isStale() || !updateLog[id]) {
  1524. updateLog[id] = true;
  1525. return true;
  1526. }
  1527. return false;
  1528. };
  1529. };
  1530. })();
  1531. const handlers = {
  1532. [LIMITS.static]: ({custom: ratio}) => {
  1533. const bound = 0.5 + (ratio - 0.5) / zoom.value;
  1534. this.x = Math.max(-bound, Math.min(bound, this.x));
  1535. this.y = Math.max(-bound, Math.min(bound, this.y));
  1536. },
  1537. [LIMITS.fit]: (() => {
  1538. let boundApplyFrame;
  1539. const ensure = getEnsureZoomPoints();
  1540. return () => {
  1541. if (ensure()) {
  1542. boundApplyFrame = getBoundApplyFrame(...zoomPoints);
  1543. }
  1544. boundApplyFrame();
  1545. };
  1546. })(),
  1547. };
  1548. const snapHandlers = {
  1549. [LIMITS.fit]: (() => {
  1550. const ensure = getEnsureZoomPoints();
  1551. return () => {
  1552. ensure();
  1553. snapZoom(...zoomPoints);
  1554. zoom.constrain();
  1555. };
  1556. })(),
  1557. };
  1558. return (doZoom = false) => {
  1559. const {panLimit, snapPanLimit} = $config.get();
  1560. if (doZoom) {
  1561. snapHandlers[snapPanLimit.type]?.();
  1562. }
  1563. handlers[panLimit.type]?.(panLimit);
  1564. this.apply();
  1565. };
  1566. })();
  1567. }();
  1568.  
  1569. const crop = new function () {
  1570. this.top = this.right = this.bottom = this.left = 0;
  1571. this.getValues = () => ({top: this.top, right: this.right, bottom: this.bottom, left: this.left});
  1572. this.reveal = () => {
  1573. this.top = this.right = this.bottom = this.left = 0;
  1574. rule.remove();
  1575. };
  1576. this.reset = () => {
  1577. this.reveal();
  1578. actions.crop.reset();
  1579. };
  1580. const rule = new css.Toggleable();
  1581. this.apply = () => {
  1582. rule.remove();
  1583. rule.add(
  1584. `${SELECTOR_VIDEO}:not(.${this.CLASS_ABLE} *)`,
  1585. ['clip-path', `inset(${this.top * 100}% ${this.right * 100}% ${this.bottom * 100}% ${this.left * 100}%)`],
  1586. );
  1587. delete actions.reset.restore;
  1588. glow.handleViewChange();
  1589. glow.reset();
  1590. };
  1591. this.getDimensions = (width = video.clientWidth, height = video.clientHeight) => [
  1592. width * (1 - this.left - this.right),
  1593. height * (1 - this.top - this.bottom),
  1594. ];
  1595. }();
  1596.  
  1597. // FUNCTIONALITY
  1598.  
  1599. const glow = (() => {
  1600. const videoCanvas = new OffscreenCanvas(0, 0);
  1601. const videoCtx = videoCanvas.getContext('2d', {alpha: false});
  1602. const glowCanvas = document.createElement('canvas');
  1603. const glowCtx = glowCanvas.getContext('2d', {alpha: false});
  1604. glowCanvas.style.setProperty('position', 'absolute');
  1605. class Sector {
  1606. canvas = new OffscreenCanvas(0, 0);
  1607. ctx = this.canvas.getContext('2d', {alpha: false});
  1608. update(doFill) {
  1609. if (doFill) {
  1610. this.fill();
  1611. } else {
  1612. this.shift();
  1613. this.take();
  1614. }
  1615. this.giveEdge();
  1616. if (this.hasCorners) {
  1617. this.giveCorners();
  1618. }
  1619. }
  1620. }
  1621. class Side extends Sector {
  1622. setDimensions(doShiftRight, sWidth, sHeight, sx, sy, dx, dy, dWidth, dHeight) {
  1623. this.canvas.width = sWidth;
  1624. this.canvas.height = sHeight;
  1625. this.shift = this.ctx.drawImage.bind(this.ctx, this.canvas, doShiftRight ? 1 : -1, 0);
  1626. this.fill = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, 1, sHeight, 0, 0, sWidth, sHeight);
  1627. this.take = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, 1, sHeight, doShiftRight ? 0 : sWidth - 1, 0, 1, sHeight);
  1628. this.giveEdge = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, sWidth, sHeight, dx, dy, dWidth, dHeight);
  1629. if (dy === 0) {
  1630. this.hasCorners = false;
  1631. return;
  1632. }
  1633. this.hasCorners = true;
  1634. const giveCorner0 = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, sWidth, 1, dx, 0, dWidth, dy);
  1635. const giveCorner1 = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, sHeight - 1, sWidth, 1, dx, dy + dHeight, dWidth, dy);
  1636. this.giveCorners = () => {
  1637. giveCorner0();
  1638. giveCorner1();
  1639. };
  1640. }
  1641. }
  1642. class Base extends Sector {
  1643. setDimensions(doShiftDown, sWidth, sHeight, sx, sy, dx, dy, dWidth, dHeight) {
  1644. this.canvas.width = sWidth;
  1645. this.canvas.height = sHeight;
  1646. this.shift = this.ctx.drawImage.bind(this.ctx, this.canvas, 0, doShiftDown ? 1 : -1);
  1647. this.fill = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, sWidth, 1, 0, 0, sWidth, sHeight);
  1648. this.take = this.ctx.drawImage.bind(this.ctx, videoCanvas, sx, sy, sWidth, 1, 0, doShiftDown ? 0 : sHeight - 1, sWidth, 1);
  1649. this.giveEdge = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, sWidth, sHeight, dx, dy, dWidth, dHeight);
  1650. if (dx === 0) {
  1651. this.hasCorners = false;
  1652. return;
  1653. }
  1654. this.hasCorners = true;
  1655. const giveCorner0 = glowCtx.drawImage.bind(glowCtx, this.canvas, 0, 0, 1, sHeight, 0, dy, dx, dHeight);
  1656. const giveCorner1 = glowCtx.drawImage.bind(glowCtx, this.canvas, sWidth - 1, 0, 1, sHeight, dx + dWidth, dy, dx, dHeight);
  1657. this.giveCorners = () => {
  1658. giveCorner0();
  1659. giveCorner1();
  1660. };
  1661. }
  1662. setClipPath(points) {
  1663. this.clipPath = new Path2D();
  1664. this.clipPath.moveTo(...points[0]);
  1665. this.clipPath.lineTo(...points[1]);
  1666. this.clipPath.lineTo(...points[2]);
  1667. this.clipPath.closePath();
  1668. }
  1669. update(doFill) {
  1670. glowCtx.save();
  1671. glowCtx.clip(this.clipPath);
  1672. super.update(doFill);
  1673. glowCtx.restore();
  1674. }
  1675. }
  1676. const components = {
  1677. left: new Side(),
  1678. right: new Side(),
  1679. top: new Base(),
  1680. bottom: new Base(),
  1681. };
  1682. const setComponentDimensions = (sampleCount, size, isInset, doFlip) => {
  1683. const [croppedWidth, croppedHeight] = crop.getDimensions();
  1684. const halfCanvas = {x: Math.ceil(glowCanvas.width / 2), y: Math.ceil(glowCanvas.height / 2)};
  1685. const halfVideo = {x: croppedWidth / 2, y: croppedHeight / 2};
  1686. const dWidth = Math.ceil(Math.min(halfVideo.x, size));
  1687. const dHeight = Math.ceil(Math.min(halfVideo.y, size));
  1688. const [dWidthScale, dHeightScale, sideWidth, sideHeight] = isInset ?
  1689. [0, 0, videoCanvas.width / croppedWidth * glowCanvas.width, videoCanvas.height / croppedHeight * glowCanvas.height] :
  1690. [halfCanvas.x - halfVideo.x, halfCanvas.y - halfVideo.y, croppedWidth, croppedHeight];
  1691. components.left.setDimensions(!doFlip, sampleCount, videoCanvas.height, 0, 0, 0, dHeightScale, dWidth, sideHeight);
  1692. components.right.setDimensions(doFlip, sampleCount, videoCanvas.height, videoCanvas.width - 1, 0, glowCanvas.width - dWidth, dHeightScale, dWidth, sideHeight);
  1693. components.top.setDimensions(!doFlip, videoCanvas.width, sampleCount, 0, 0, dWidthScale, 0, sideWidth, dHeight);
  1694. components.top.setClipPath([[0, 0], [halfCanvas.x, halfCanvas.y], [glowCanvas.width, 0]]);
  1695. components.bottom.setDimensions(doFlip, videoCanvas.width, sampleCount, 0, videoCanvas.height - 1, dWidthScale, glowCanvas.height - dHeight, sideWidth, dHeight);
  1696. components.bottom.setClipPath([[0, glowCanvas.height], [halfCanvas.x, halfCanvas.y], [glowCanvas.width, glowCanvas.height]]);
  1697. };
  1698. class Instance {
  1699. constructor() {
  1700. const {filter, sampleCount, size, end, doFlip} = $config.get().glow;
  1701. // Setup canvases
  1702. glowCanvas.style.setProperty('filter', filter);
  1703. [glowCanvas.width, glowCanvas.height] = crop.getDimensions().map((dimension) => dimension * end);
  1704. glowCanvas.style.setProperty('left', `${crop.left * 100 + (1 - end) * (1 - crop.left - crop.right) * 50}%`);
  1705. glowCanvas.style.setProperty('top', `${crop.top * 100 + (1 - end) * (1 - crop.top - crop.bottom) * 50}%`);
  1706. [videoCanvas.width, videoCanvas.height] = crop.getDimensions(video.videoWidth, video.videoHeight);
  1707. setComponentDimensions(sampleCount, size, end <= 1, doFlip);
  1708. this.update(true);
  1709. }
  1710. update(doFill = false) {
  1711. videoCtx.drawImage(
  1712. video,
  1713. crop.left * video.videoWidth,
  1714. crop.top * video.videoHeight,
  1715. video.videoWidth * (1 - crop.left - crop.right),
  1716. video.videoHeight * (1 - crop.top - crop.bottom),
  1717. 0,
  1718. 0,
  1719. videoCanvas.width,
  1720. videoCanvas.height,
  1721. );
  1722. components.left.update(doFill);
  1723. components.right.update(doFill);
  1724. components.top.update(doFill);
  1725. components.bottom.update(doFill);
  1726. }
  1727. }
  1728. return new function () {
  1729. const container = document.createElement('div');
  1730. container.style.display = 'none';
  1731. container.appendChild(glowCanvas);
  1732. containers.background.appendChild(container);
  1733. this.isHidden = false;
  1734. let instance, startCopyLoop, stopCopyLoop;
  1735. const play = () => {
  1736. if (!video.paused && !this.isHidden && !enabler.isHidingGlow) {
  1737. startCopyLoop?.();
  1738. }
  1739. };
  1740. const fill = () => {
  1741. if (!this.isHidden) {
  1742. instance.update(true);
  1743. }
  1744. };
  1745. const handleVisibilityChange = () => {
  1746. if (document.hidden) {
  1747. stopCopyLoop();
  1748. } else {
  1749. play();
  1750. }
  1751. };
  1752. this.handleSizeChange = () => {
  1753. instance = new Instance();
  1754. };
  1755. // set up pausing if glow isn't visible
  1756. this.handleViewChange = (() => {
  1757. const cache = new Cache(rotation, zoom);
  1758. let corners;
  1759. return (doForce = false) => {
  1760. if (doForce || cache.isStale()) {
  1761. corners = getRotatedCorners(halfDimensions.viewport.width / zoom.value, halfDimensions.viewport.height / zoom.value);
  1762. }
  1763. const videoX = position.x * video.clientWidth;
  1764. const videoY = position.y * video.clientHeight;
  1765. for (const corner of corners) {
  1766. if (
  1767. // unpause if the viewport extends more than 1 pixel beyond a video edge
  1768. videoX + corner.x > (0.5 - crop.right) * video.clientWidth + 1
  1769. || videoX - corner.x < (crop.left - 0.5) * video.clientWidth - 1
  1770. || videoY + corner.y > (0.5 - crop.top) * video.clientHeight + 1
  1771. || videoY - corner.y < (crop.bottom - 0.5) * video.clientHeight - 1
  1772. ) {
  1773. // fill if newly visible
  1774. if (this.isHidden) {
  1775. instance?.update(true);
  1776. }
  1777. this.isHidden = false;
  1778. glowCanvas.style.removeProperty('visibility');
  1779. play();
  1780. return;
  1781. }
  1782. }
  1783. this.isHidden = true;
  1784. glowCanvas.style.visibility = 'hidden';
  1785. stopCopyLoop?.();
  1786. };
  1787. })();
  1788. const loop = {};
  1789. this.start = () => {
  1790. const config = $config.get().glow;
  1791. if (!config) {
  1792. return;
  1793. }
  1794. if (!enabler.isHidingGlow) {
  1795. container.style.removeProperty('display');
  1796. }
  1797. // todo handle this?
  1798. if (crop.left + crop.right >= 1 || crop.top + crop.bottom >= 1) {
  1799. return;
  1800. }
  1801. let loopId = -1;
  1802. if (loop.interval !== config.interval || loop.fps !== config.fps) {
  1803. loop.interval = config.interval;
  1804. loop.fps = config.fps;
  1805. loop.wasSlow = false;
  1806. loop.throttleCount = 0;
  1807. }
  1808. stopCopyLoop = () => ++loopId;
  1809. instance = new Instance();
  1810. startCopyLoop = async () => {
  1811. const id = ++loopId;
  1812. await new Promise((resolve) => {
  1813. window.setTimeout(resolve, config.interval);
  1814. });
  1815. while (id === loopId) {
  1816. const startTime = Date.now();
  1817. instance.update();
  1818. const delay = loop.interval - (Date.now() - startTime);
  1819. if (delay <= 0) {
  1820. if (loop.wasSlow) {
  1821. loop.interval = 1000 / (loop.fps - ++loop.throttleCount);
  1822. }
  1823. loop.wasSlow = !loop.wasSlow;
  1824. continue;
  1825. }
  1826. if (delay > 2 && loop.throttleCount > 0) {
  1827. console.warn(`[${GM.info.script.name}] Glow update frequency reduced from ${loop.fps} hertz to ${loop.fps - loop.throttleCount} hertz due to poor performance.`);
  1828. loop.fps -= loop.throttleCount;
  1829. loop.throttleCount = 0;
  1830. }
  1831. loop.wasSlow = false;
  1832. await new Promise((resolve) => {
  1833. window.setTimeout(resolve, delay);
  1834. });
  1835. }
  1836. };
  1837. play();
  1838. video.addEventListener('pause', stopCopyLoop);
  1839. video.addEventListener('play', play);
  1840. video.addEventListener('seeked', fill);
  1841. document.addEventListener('visibilitychange', handleVisibilityChange);
  1842. };
  1843. const priorCrop = {};
  1844. this.hide = () => {
  1845. Object.assign(priorCrop, crop);
  1846. stopCopyLoop?.();
  1847. container.style.display = 'none';
  1848. };
  1849. this.show = () => {
  1850. if (Object.entries(priorCrop).some(([edge, value]) => crop[edge] !== value)) {
  1851. this.reset();
  1852. } else {
  1853. play();
  1854. }
  1855. container.style.removeProperty('display');
  1856. };
  1857. this.stop = () => {
  1858. this.hide();
  1859. video.removeEventListener('pause', stopCopyLoop);
  1860. video.removeEventListener('play', play);
  1861. video.removeEventListener('seeked', fill);
  1862. document.removeEventListener('visibilitychange', handleVisibilityChange);
  1863. startCopyLoop = undefined;
  1864. stopCopyLoop = undefined;
  1865. };
  1866. this.reset = () => {
  1867. this.stop();
  1868. this.start();
  1869. };
  1870. }();
  1871. })();
  1872.  
  1873. const peek = (stop = false) => {
  1874. const prior = {
  1875. zoom: zoom.value,
  1876. rotation: rotation.value,
  1877. crop: crop.getValues(),
  1878. position: position.getValues(),
  1879. };
  1880. position.reset();
  1881. rotation.reset();
  1882. zoom.reset();
  1883. crop.reset();
  1884. glow[stop ? 'stop' : 'reset']();
  1885. return () => {
  1886. zoom.value = prior.zoom;
  1887. rotation.value = prior.rotation;
  1888. Object.assign(position, prior.position);
  1889. Object.assign(crop, prior.crop);
  1890. actions.crop.set(prior.crop);
  1891. position.apply();
  1892. rotation.apply();
  1893. zoom.apply();
  1894. crop.apply();
  1895. };
  1896. };
  1897.  
  1898. const actions = (() => {
  1899. const drag = (event, clickCallback, moveCallback, target = video) => new Promise((resolve) => {
  1900. event.stopImmediatePropagation();
  1901. event.preventDefault();
  1902. // window blur events don't fire if devtools is open
  1903. stopDrag?.();
  1904. target.setPointerCapture(event.pointerId);
  1905. css.tag(enabler.CLASS_DRAGGING);
  1906. const cancel = (event) => {
  1907. event.stopImmediatePropagation();
  1908. event.preventDefault();
  1909. };
  1910. document.addEventListener('click', cancel, true);
  1911. document.addEventListener('dblclick', cancel, true);
  1912. const clickDisallowListener = ({clientX, clientY}) => {
  1913. const {clickCutoff} = $config.get();
  1914. const distance = Math.abs(event.clientX - clientX) + Math.abs(event.clientY - clientY);
  1915. if (distance >= clickCutoff) {
  1916. target.removeEventListener('pointermove', clickDisallowListener);
  1917. target.removeEventListener('pointerup', clickCallback);
  1918. }
  1919. };
  1920. if (clickCallback) {
  1921. target.addEventListener('pointermove', clickDisallowListener);
  1922. target.addEventListener('pointerup', clickCallback, {once: true});
  1923. }
  1924. target.addEventListener('pointermove', moveCallback);
  1925. stopDrag = () => {
  1926. css.tag(enabler.CLASS_DRAGGING, false);
  1927. target.removeEventListener('pointermove', moveCallback);
  1928. if (clickCallback) {
  1929. target.removeEventListener('pointermove', clickDisallowListener);
  1930. target.removeEventListener('pointerup', clickCallback);
  1931. }
  1932. // delay removing listeners for events that happen after pointerup
  1933. window.setTimeout(() => {
  1934. document.removeEventListener('dblclick', cancel, true);
  1935. document.removeEventListener('click', cancel, true);
  1936. }, 0);
  1937. window.removeEventListener('blur', stopDrag);
  1938. target.removeEventListener('pointerup', stopDrag);
  1939. target.releasePointerCapture(event.pointerId);
  1940. stopDrag = undefined;
  1941. enabler.handleChange();
  1942. resolve();
  1943. };
  1944. window.addEventListener('blur', stopDrag);
  1945. target.addEventListener('pointerup', stopDrag);
  1946. });
  1947. const getOnScroll = (() => {
  1948. // https://stackoverflow.com/a/30134826
  1949. const multipliers = [1, 40, 800];
  1950. return (callback) => (event) => {
  1951. event.stopImmediatePropagation();
  1952. event.preventDefault();
  1953. if (event.deltaY !== 0) {
  1954. callback(event.deltaY * multipliers[event.deltaMode]);
  1955. }
  1956. };
  1957. })();
  1958. const addListeners = ({onMouseDown, onRightClick, onScroll}, doAdd = true) => {
  1959. const property = `${doAdd ? 'add' : 'remove'}EventListener`;
  1960. altTarget[property]('pointerdown', onMouseDown);
  1961. altTarget[property]('contextmenu', onRightClick, true);
  1962. altTarget[property]('wheel', onScroll);
  1963. };
  1964. return {
  1965. crop: new function () {
  1966. let top = 0, right = 0, bottom = 0, left = 0, handle;
  1967. const values = {};
  1968. Object.defineProperty(values, 'top', {get: () => top, set: (value) => top = value});
  1969. Object.defineProperty(values, 'right', {get: () => right, set: (value) => right = value});
  1970. Object.defineProperty(values, 'bottom', {get: () => bottom, set: (value) => bottom = value});
  1971. Object.defineProperty(values, 'left', {get: () => left, set: (value) => left = value});
  1972. class Button {
  1973. // allowance for rounding errors
  1974. static ALLOWANCE_HANDLE = 0.0001;
  1975. static CLASS_HANDLE = 'viewfind-crop-handle';
  1976. static CLASS_EDGES = {
  1977. left: 'viewfind-crop-left',
  1978. top: 'viewfind-crop-top',
  1979. right: 'viewfind-crop-right',
  1980. bottom: 'viewfind-crop-bottom',
  1981. };
  1982. static OPPOSITES = {
  1983. left: 'right',
  1984. right: 'left',
  1985. top: 'bottom',
  1986. bottom: 'top',
  1987. };
  1988. callbacks = [];
  1989. element = document.createElement('div');
  1990. constructor(...edges) {
  1991. this.edges = edges;
  1992. this.isHandle = true;
  1993. this.element.style.position = 'absolute';
  1994. this.element.style.pointerEvents = 'all';
  1995. for (const edge of edges) {
  1996. this.element.style[edge] = '0';
  1997. this.element.classList.add(Button.CLASS_EDGES[edge]);
  1998. this.element.style.setProperty(`border-${Button.OPPOSITES[edge]}-width`, '1px');
  1999. }
  2000. this.element.addEventListener('contextmenu', (event) => {
  2001. event.stopPropagation();
  2002. event.preventDefault();
  2003. this.reset(false);
  2004. });
  2005. this.element.addEventListener('pointerdown', (() => {
  2006. const clickListener = ({offsetX, offsetY, target}) => {
  2007. this.set({
  2008. width: (this.edges.includes('left') ? offsetX : target.clientWidth - offsetX) / video.clientWidth,
  2009. height: (this.edges.includes('top') ? offsetY : target.clientHeight - offsetY) / video.clientHeight,
  2010. }, false);
  2011. };
  2012. const getDragListener = (event, target) => {
  2013. const getWidth = (() => {
  2014. if (this.edges.includes('left')) {
  2015. const position = this.element.clientWidth - event.offsetX;
  2016. return ({offsetX}) => offsetX + position;
  2017. }
  2018. const position = target.offsetWidth + event.offsetX;
  2019. return ({offsetX}) => position - offsetX;
  2020. })();
  2021. const getHeight = (() => {
  2022. if (this.edges.includes('top')) {
  2023. const position = this.element.clientHeight - event.offsetY;
  2024. return ({offsetY}) => offsetY + position;
  2025. }
  2026. const position = target.offsetHeight + event.offsetY;
  2027. return ({offsetY}) => position - offsetY;
  2028. })();
  2029. return (event) => {
  2030. this.set({
  2031. width: getWidth(event) / video.clientWidth,
  2032. height: getHeight(event) / video.clientHeight,
  2033. });
  2034. };
  2035. };
  2036. return async (event) => {
  2037. if (event.buttons === 1) {
  2038. const target = this.element.parentElement;
  2039. if (this.isHandle) {
  2040. this.setPanel();
  2041. }
  2042. await drag(event, clickListener, getDragListener(event, target), target);
  2043. this.updateCounterpart();
  2044. }
  2045. };
  2046. })());
  2047. }
  2048. notify() {
  2049. for (const callback of this.callbacks) {
  2050. callback();
  2051. }
  2052. }
  2053. set isHandle(value) {
  2054. this._isHandle = value;
  2055. this.element.classList[value ? 'add' : 'remove'](Button.CLASS_HANDLE);
  2056. }
  2057. get isHandle() {
  2058. return this._isHandle;
  2059. }
  2060. reset() {
  2061. this.isHandle = true;
  2062. for (const edge of this.edges) {
  2063. values[edge] = 0;
  2064. }
  2065. }
  2066. }
  2067. class EdgeButton extends Button {
  2068. constructor(edge) {
  2069. super(edge);
  2070. this.edge = edge;
  2071. }
  2072. updateCounterpart() {
  2073. if (this.counterpart.isHandle) {
  2074. this.counterpart.setHandle();
  2075. }
  2076. }
  2077. setCrop(value = 0) {
  2078. values[this.edge] = value;
  2079. }
  2080. setPanel() {
  2081. this.isHandle = false;
  2082. this.setCrop(handle);
  2083. this.setHandle();
  2084. }
  2085. }
  2086. class SideButton extends EdgeButton {
  2087. flow() {
  2088. let size = 1;
  2089. if (top <= Button.ALLOWANCE_HANDLE) {
  2090. size -= handle;
  2091. this.element.style.top = `${handle * 100}%`;
  2092. } else {
  2093. size -= top;
  2094. this.element.style.top = `${top * 100}%`;
  2095. }
  2096. if (bottom <= Button.ALLOWANCE_HANDLE) {
  2097. size -= handle;
  2098. } else {
  2099. size -= bottom;
  2100. }
  2101. this.element.style.height = `${Math.max(0, size * 100)}%`;
  2102. }
  2103. setBounds(counterpart, components) {
  2104. this.counterpart = components[counterpart];
  2105. components.top.callbacks.push(() => {
  2106. this.flow();
  2107. });
  2108. components.bottom.callbacks.push(() => {
  2109. this.flow();
  2110. });
  2111. }
  2112. setHandle(doNotify = true) {
  2113. this.element.style.width = `${Math.min(1 - values[this.counterpart.edge], handle) * 100}%`;
  2114. if (doNotify) {
  2115. this.notify();
  2116. }
  2117. }
  2118. set({width}, doUpdateCounterpart = true) {
  2119. if (this.isHandle !== (this.isHandle = width <= Button.ALLOWANCE_HANDLE)) {
  2120. this.flow();
  2121. }
  2122. if (doUpdateCounterpart) {
  2123. this.updateCounterpart();
  2124. }
  2125. if (this.isHandle) {
  2126. this.setCrop();
  2127. this.setHandle();
  2128. return;
  2129. }
  2130. const size = Math.min(1 - values[this.counterpart.edge], width);
  2131. this.setCrop(size);
  2132. this.element.style.width = `${size * 100}%`;
  2133. this.notify();
  2134. }
  2135. reset(isGeneral = true) {
  2136. super.reset();
  2137. if (isGeneral) {
  2138. this.element.style.top = `${handle * 100}%`;
  2139. this.element.style.height = `${(0.5 - handle) * 200}%`;
  2140. this.element.style.width = `${handle * 100}%`;
  2141. return;
  2142. }
  2143. this.flow();
  2144. this.setHandle();
  2145. this.updateCounterpart();
  2146. }
  2147. }
  2148. class BaseButton extends EdgeButton {
  2149. flow() {
  2150. let size = 1;
  2151. if (left <= Button.ALLOWANCE_HANDLE) {
  2152. size -= handle;
  2153. this.element.style.left = `${handle * 100}%`;
  2154. } else {
  2155. size -= left;
  2156. this.element.style.left = `${left * 100}%`;
  2157. }
  2158. if (right <= Button.ALLOWANCE_HANDLE) {
  2159. size -= handle;
  2160. } else {
  2161. size -= right;
  2162. }
  2163. this.element.style.width = `${Math.max(0, size) * 100}%`;
  2164. }
  2165. setBounds(counterpart, components) {
  2166. this.counterpart = components[counterpart];
  2167. components.left.callbacks.push(() => {
  2168. this.flow();
  2169. });
  2170. components.right.callbacks.push(() => {
  2171. this.flow();
  2172. });
  2173. }
  2174. setHandle(doNotify = true) {
  2175. this.element.style.height = `${Math.min(1 - values[this.counterpart.edge], handle) * 100}%`;
  2176. if (doNotify) {
  2177. this.notify();
  2178. }
  2179. }
  2180. set({height}, doUpdateCounterpart = false) {
  2181. if (this.isHandle !== (this.isHandle = height <= Button.ALLOWANCE_HANDLE)) {
  2182. this.flow();
  2183. }
  2184. if (doUpdateCounterpart) {
  2185. this.updateCounterpart();
  2186. }
  2187. if (this.isHandle) {
  2188. this.setCrop();
  2189. this.setHandle();
  2190. return;
  2191. }
  2192. const size = Math.min(1 - values[this.counterpart.edge], height);
  2193. this.setCrop(size);
  2194. this.element.style.height = `${size * 100}%`;
  2195. this.notify();
  2196. }
  2197. reset(isGeneral = true) {
  2198. super.reset();
  2199. if (isGeneral) {
  2200. this.element.style.left = `${handle * 100}%`;
  2201. this.element.style.width = `${(0.5 - handle) * 200}%`;
  2202. this.element.style.height = `${handle * 100}%`;
  2203. return;
  2204. }
  2205. this.flow();
  2206. this.setHandle();
  2207. this.updateCounterpart();
  2208. }
  2209. }
  2210. class CornerButton extends Button {
  2211. static CLASS_NAME = 'viewfind-crop-corner';
  2212. constructor(sectors, ...edges) {
  2213. super(...edges);
  2214. this.element.classList.add(CornerButton.CLASS_NAME);
  2215. this.sectors = sectors;
  2216. for (const sector of sectors) {
  2217. sector.callbacks.push(this.flow.bind(this));
  2218. }
  2219. }
  2220. flow() {
  2221. let isHandle = true;
  2222. if (this.sectors[0].isHandle) {
  2223. this.element.style.width = `${Math.min(1 - values[this.sectors[0].counterpart.edge], handle) * 100}%`;
  2224. } else {
  2225. this.element.style.width = `${values[this.edges[0]] * 100}%`;
  2226. isHandle = false;
  2227. }
  2228. if (this.sectors[1].isHandle) {
  2229. this.element.style.height = `${Math.min(1 - values[this.sectors[1].counterpart.edge], handle) * 100}%`;
  2230. } else {
  2231. this.element.style.height = `${values[this.edges[1]] * 100}%`;
  2232. isHandle = false;
  2233. }
  2234. this.isHandle = isHandle;
  2235. }
  2236. updateCounterpart() {
  2237. for (const sector of this.sectors) {
  2238. sector.updateCounterpart();
  2239. }
  2240. }
  2241. set(size) {
  2242. for (const sector of this.sectors) {
  2243. sector.set(size);
  2244. }
  2245. }
  2246. reset(isGeneral = true) {
  2247. this.isHandle = true;
  2248. this.element.style.width = `${handle * 100}%`;
  2249. this.element.style.height = `${handle * 100}%`;
  2250. if (isGeneral) {
  2251. return;
  2252. }
  2253. for (const sector of this.sectors) {
  2254. sector.reset(false);
  2255. }
  2256. }
  2257. setPanel() {
  2258. for (const sector of this.sectors) {
  2259. sector.setPanel();
  2260. }
  2261. }
  2262. }
  2263. this.CODE = 'crop';
  2264. this.CLASS_ABLE = 'viewfind-action-able-crop';
  2265. const container = document.createElement('div');
  2266. // todo ditch the containers object
  2267. container.style.width = container.style.height = 'inherit';
  2268. containers.foreground.append(container);
  2269. this.reset = () => {
  2270. for (const component of Object.values(this.components)) {
  2271. component.reset(true);
  2272. }
  2273. };
  2274. this.onRightClick = (event) => {
  2275. if (event.target.parentElement.id === container.id) {
  2276. return;
  2277. }
  2278. event.stopPropagation();
  2279. event.preventDefault();
  2280. if (stopDrag) {
  2281. return;
  2282. }
  2283. this.reset();
  2284. };
  2285. this.onScroll = getOnScroll((distance) => {
  2286. const increment = distance * $config.get().speeds.crop / zoom.value;
  2287. this.components.top.set({height: top + Math.min((1 - top - bottom) / 2, increment)});
  2288. this.components.left.set({width: left + Math.min((1 - left - right) / 2, increment)});
  2289. this.components.bottom.set({height: bottom + increment});
  2290. this.components.right.set({width: right + increment});
  2291. });
  2292. this.onMouseDown = (() => {
  2293. const getDragListener = () => {
  2294. const multiplier = $config.get().multipliers.crop;
  2295. const setX = ((right, left, change) => {
  2296. const clamped = Math.max(-left, Math.min(right, change * multiplier / video.clientWidth));
  2297. this.components.left.set({width: left + clamped});
  2298. this.components.right.set({width: right - clamped});
  2299. }).bind(undefined, right, left);
  2300. const setY = ((top, bottom, change) => {
  2301. const clamped = Math.max(-top, Math.min(bottom, change * multiplier / video.clientHeight));
  2302. this.components.top.set({height: top + clamped});
  2303. this.components.bottom.set({height: bottom - clamped});
  2304. }).bind(undefined, top, bottom);
  2305. let priorEvent;
  2306. return ({offsetX, offsetY}) => {
  2307. if (!priorEvent) {
  2308. priorEvent = {offsetX, offsetY};
  2309. return;
  2310. }
  2311. setX(offsetX - priorEvent.offsetX);
  2312. setY(offsetY - priorEvent.offsetY);
  2313. };
  2314. };
  2315. const clickListener = () => {
  2316. zoom.value = zoom.getFit((1 - left - right) * halfDimensions.video.width, (1 - top - bottom) * halfDimensions.video.height);
  2317. zoom.constrain();
  2318. position.x = (left - right) / 2;
  2319. position.y = (bottom - top) / 2;
  2320. position.constrain();
  2321. };
  2322. return (event) => {
  2323. if (event.buttons === 1) {
  2324. drag(event, clickListener, getDragListener(), container);
  2325. }
  2326. };
  2327. })();
  2328. this.components = {
  2329. top: new BaseButton('top'),
  2330. right: new SideButton('right'),
  2331. bottom: new BaseButton('bottom'),
  2332. left: new SideButton('left'),
  2333. };
  2334. this.components.top.setBounds('bottom', this.components);
  2335. this.components.right.setBounds('left', this.components);
  2336. this.components.bottom.setBounds('top', this.components);
  2337. this.components.left.setBounds('right', this.components);
  2338. this.components.topLeft = new CornerButton([this.components.left, this.components.top], 'left', 'top');
  2339. this.components.topRight = new CornerButton([this.components.right, this.components.top], 'right', 'top');
  2340. this.components.bottomLeft = new CornerButton([this.components.left, this.components.bottom], 'left', 'bottom');
  2341. this.components.bottomRight = new CornerButton([this.components.right, this.components.bottom], 'right', 'bottom');
  2342. container.append(...Object.values(this.components).map(({element}) => element));
  2343. this.set = ({top, right, bottom, left}) => {
  2344. this.components.top.set({height: top});
  2345. this.components.right.set({width: right});
  2346. this.components.bottom.set({height: bottom});
  2347. this.components.left.set({width: left});
  2348. };
  2349. this.onInactive = () => {
  2350. addListeners(this, false);
  2351. if (crop.left === left && crop.top === top && crop.right === right && crop.bottom === bottom) {
  2352. return;
  2353. }
  2354. crop.left = left;
  2355. crop.top = top;
  2356. crop.right = right;
  2357. crop.bottom = bottom;
  2358. crop.apply();
  2359. };
  2360. this.onActive = () => {
  2361. const config = $config.get().crop;
  2362. handle = config.handle / Math.max(zoom.value, 1);
  2363. for (const component of [this.components.top, this.components.bottom, this.components.left, this.components.right]) {
  2364. if (component.isHandle) {
  2365. component.setHandle();
  2366. }
  2367. }
  2368. crop.reveal();
  2369. addListeners(this);
  2370. if (!enabler.isHidingGlow) {
  2371. glow.handleViewChange();
  2372. glow.reset();
  2373. }
  2374. };
  2375. const draggingSelector = css.getSelector(enabler.CLASS_DRAGGING);
  2376. this.updateConfig = (() => {
  2377. const rule = new css.Toggleable();
  2378. return () => {
  2379. // set handle size
  2380. for (const button of [this.components.left, this.components.top, this.components.right, this.components.bottom]) {
  2381. if (button.isHandle) {
  2382. button.setHandle();
  2383. }
  2384. }
  2385. rule.remove();
  2386. const {colour} = $config.get().crop;
  2387. const {id} = container;
  2388. rule.add(`#${id}>:hover.${Button.CLASS_HANDLE},#${id}>:not(.${Button.CLASS_HANDLE})`, ['background-color', colour.fill]);
  2389. rule.add(`#${id}>*`, ['border-color', colour.border]);
  2390. rule.add(`#${id}:not(${draggingSelector} *)>:not(:hover)`, ['filter', `drop-shadow(${colour.shadow} 0 0 1px)`]);
  2391. };
  2392. })();
  2393. $config.ready.then(() => {
  2394. this.updateConfig();
  2395. });
  2396. container.id = 'viewfind-crop-container';
  2397. (() => {
  2398. const {id} = container;
  2399. css.add(`${css.getSelector(enabler.CLASS_DRAGGING)} #${id}`, ['cursor', 'grabbing']);
  2400. css.add(`${css.getSelector(enabler.CLASS_ABLE)} #${id}`, ['cursor', 'grab']);
  2401. css.add(`#${id}>:not(${draggingSelector} .${Button.CLASS_HANDLE})`, ['border-style', 'solid']);
  2402. css.add(`${draggingSelector} #${id}>.${Button.CLASS_HANDLE}`, ['filter', 'none']);
  2403. for (const [side, sideClass] of Object.entries(Button.CLASS_EDGES)) {
  2404. css.add(
  2405. `${draggingSelector} #${id}>.${sideClass}.${Button.CLASS_HANDLE}~.${sideClass}.${CornerButton.CLASS_NAME}`,
  2406. [`border-${CornerButton.OPPOSITES[side]}-style`, 'none'],
  2407. ['filter', 'none'],
  2408. );
  2409. // in fullscreen, 16:9 videos get an offsetLeft of 1px on my 16:9 monitor
  2410. // I'm extending buttons by 1px so that they reach the edge of screens like mine at default zoom
  2411. css.add(`#${id}>.${sideClass}`, [`margin-${side}`, '-1px'], [`padding-${side}`, '1px']);
  2412. }
  2413. css.add(`#${id}:not(.${this.CLASS_ABLE} *)`, ['display', 'none']);
  2414. })();
  2415. }(),
  2416. pan: new function () {
  2417. this.CODE = 'pan';
  2418. this.CLASS_ABLE = 'viewfind-action-able-pan';
  2419. this.onActive = () => {
  2420. this.updateCrosshair();
  2421. addListeners(this);
  2422. };
  2423. this.onInactive = () => {
  2424. addListeners(this, false);
  2425. };
  2426. this.updateCrosshair = (() => {
  2427. const getRoundedString = (number, decimal = 2) => {
  2428. const raised = `${Math.round(number * Math.pow(10, decimal))}`.padStart(decimal + 1, '0');
  2429. return `${raised.substr(0, raised.length - decimal)}.${raised.substr(raised.length - decimal)}`;
  2430. };
  2431. const getSigned = (ratio) => {
  2432. const percent = Math.round(ratio * 100);
  2433. if (percent <= 0) {
  2434. return `${percent}`;
  2435. }
  2436. return `+${percent}`;
  2437. };
  2438. return () => {
  2439. crosshair.text.innerText = `${getRoundedString(zoom.value)}×\n${getSigned(position.x)}%\n${getSigned(position.y)}%`;
  2440. };
  2441. })();
  2442. this.onScroll = getOnScroll((distance) => {
  2443. const increment = distance * $config.get().speeds.zoom;
  2444. if (increment > 0) {
  2445. zoom.value *= 1 + increment;
  2446. } else {
  2447. zoom.value /= 1 - increment;
  2448. }
  2449. zoom.constrain();
  2450. position.constrain();
  2451. this.updateCrosshair();
  2452. });
  2453. this.onRightClick = (event) => {
  2454. event.stopImmediatePropagation();
  2455. event.preventDefault();
  2456. if (stopDrag) {
  2457. return;
  2458. }
  2459. position.x = position.y = 0;
  2460. zoom.value = 1;
  2461. position.apply();
  2462. zoom.constrain();
  2463. this.updateCrosshair();
  2464. };
  2465. this.onMouseDown = (() => {
  2466. const getDragListener = () => {
  2467. const {multipliers} = $config.get();
  2468. let priorEvent;
  2469. const change = {x: 0, y: 0};
  2470. return ({offsetX, offsetY}) => {
  2471. if (priorEvent) {
  2472. change.x = (priorEvent.offsetX + change.x - offsetX) * multipliers.pan;
  2473. change.y = (priorEvent.offsetY - change.y - offsetY) * -multipliers.pan;
  2474. position.x += change.x / video.clientWidth;
  2475. position.y += change.y / video.clientHeight;
  2476. position.constrain();
  2477. this.updateCrosshair();
  2478. }
  2479. // events in firefox seem to lose their data after finishing propagation
  2480. // so assigning the whole event doesn't work
  2481. priorEvent = {offsetX, offsetY};
  2482. };
  2483. };
  2484. const clickListener = (event) => {
  2485. position.x = event.offsetX / video.clientWidth - 0.5;
  2486. // Y increases moving down the page
  2487. // I flip that to make trigonometry easier
  2488. position.y = -event.offsetY / video.clientHeight + 0.5;
  2489. position.constrain(true);
  2490. this.updateCrosshair();
  2491. };
  2492. return (event) => {
  2493. if (event.buttons === 1) {
  2494. drag(event, clickListener, getDragListener());
  2495. }
  2496. };
  2497. })();
  2498. }(),
  2499. rotate: new function () {
  2500. this.CODE = 'rotate';
  2501. this.CLASS_ABLE = 'viewfind-action-able-rotate';
  2502. this.onActive = () => {
  2503. this.updateCrosshair();
  2504. addListeners(this);
  2505. };
  2506. this.onInactive = () => {
  2507. addListeners(this, false);
  2508. };
  2509. this.updateCrosshair = () => {
  2510. const angle = DEGREES[90] - rotation.value;
  2511. crosshair.text.innerText = `${Math.floor((DEGREES[90] - rotation.value) / Math.PI * 180)}°\n${Math.round(angle / DEGREES[90]) % 4 * 90}°`;
  2512. };
  2513. this.onScroll = getOnScroll((distance) => {
  2514. rotation.value += distance * $config.get().speeds.rotate;
  2515. rotation.constrain();
  2516. zoom.constrain();
  2517. position.constrain();
  2518. this.updateCrosshair();
  2519. });
  2520. this.onRightClick = (event) => {
  2521. event.stopImmediatePropagation();
  2522. event.preventDefault();
  2523. if (stopDrag) {
  2524. return;
  2525. }
  2526. rotation.value = DEGREES[90];
  2527. rotation.apply();
  2528. zoom.constrain();
  2529. position.constrain();
  2530. this.updateCrosshair();
  2531. };
  2532. this.onMouseDown = (() => {
  2533. const getDragListener = () => {
  2534. const {multipliers} = $config.get();
  2535. const middleX = containers.tracker.clientWidth / 2;
  2536. const middleY = containers.tracker.clientHeight / 2;
  2537. const priorPosition = position.getValues();
  2538. const priorZoom = zoom.value;
  2539. let priorMouseTheta;
  2540. return (event) => {
  2541. const mouseTheta = getTheta(middleX, middleY, event.offsetX, event.offsetY);
  2542. if (priorMouseTheta === undefined) {
  2543. priorMouseTheta = mouseTheta;
  2544. return;
  2545. }
  2546. position.x = priorPosition.x;
  2547. position.y = priorPosition.y;
  2548. zoom.value = priorZoom;
  2549. rotation.value += (priorMouseTheta - mouseTheta) * multipliers.rotate;
  2550. rotation.constrain();
  2551. zoom.constrain();
  2552. position.constrain();
  2553. this.updateCrosshair();
  2554. priorMouseTheta = mouseTheta;
  2555. };
  2556. };
  2557. const clickListener = () => {
  2558. rotation.value = Math.round(rotation.value / DEGREES[90]) * DEGREES[90];
  2559. rotation.constrain();
  2560. zoom.constrain();
  2561. position.constrain();
  2562. this.updateCrosshair();
  2563. };
  2564. return (event) => {
  2565. if (event.buttons === 1) {
  2566. drag(event, clickListener, getDragListener(), containers.tracker);
  2567. }
  2568. };
  2569. })();
  2570. }(),
  2571. configure: new function () {
  2572. this.CODE = 'config';
  2573. this.onActive = async () => {
  2574. await $config.edit();
  2575. updateConfigs();
  2576. viewport.focus();
  2577. glow.reset();
  2578. position.constrain();
  2579. zoom.constrain();
  2580. };
  2581. }(),
  2582. reset: new function () {
  2583. this.CODE = 'reset';
  2584. this.onActive = () => {
  2585. if (this.restore) {
  2586. this.restore();
  2587. } else {
  2588. this.restore = peek();
  2589. }
  2590. };
  2591. }(),
  2592. };
  2593. })();
  2594.  
  2595. const crosshair = new function () {
  2596. this.container = document.createElement('div');
  2597. this.lines = {
  2598. horizontal: document.createElement('div'),
  2599. vertical: document.createElement('div'),
  2600. };
  2601. this.text = document.createElement('div');
  2602. const id = 'viewfind-crosshair';
  2603. this.container.id = id;
  2604. this.container.classList.add(CLASS_VIEWFINDER);
  2605. css.add(`#${id}:not(${css.getSelector(actions.pan.CLASS_ABLE)} *):not(${css.getSelector(actions.rotate.CLASS_ABLE)} *)`, ['display', 'none']);
  2606. this.lines.horizontal.style.position = this.lines.vertical.style.position = this.text.style.position = this.container.style.position = 'absolute';
  2607. this.lines.horizontal.style.top = '50%';
  2608. this.lines.horizontal.style.width = '100%';
  2609. this.lines.vertical.style.left = '50%';
  2610. this.lines.vertical.style.height = '100%';
  2611. this.text.style.userSelect = 'none';
  2612. this.container.style.top = '0';
  2613. this.container.style.width = '100%';
  2614. this.container.style.height = '100%';
  2615. this.container.style.pointerEvents = 'none';
  2616. this.container.append(this.lines.horizontal, this.lines.vertical);
  2617. this.clip = () => {
  2618. const {outer, inner, gap} = $config.get().crosshair;
  2619. const thickness = Math.max(inner, outer);
  2620. const {width, height} = halfDimensions.viewport;
  2621. const halfGap = gap / 2;
  2622. const startInner = (thickness - inner) / 2;
  2623. const startOuter = (thickness - outer) / 2;
  2624. const endInner = thickness - startInner;
  2625. const endOuter = thickness - startOuter;
  2626. this.lines.horizontal.style.clipPath = 'path(\''
  2627. + `M0 ${startOuter}L${width - halfGap} ${startOuter}L${width - halfGap} ${startInner}L${width + halfGap} ${startInner}L${width + halfGap} ${startOuter}L${viewport.clientWidth} ${startOuter}`
  2628. + `L${viewport.clientWidth} ${endOuter}L${width + halfGap} ${endOuter}L${width + halfGap} ${endInner}L${width - halfGap} ${endInner}L${width - halfGap} ${endOuter}L0 ${endOuter}`
  2629. + 'Z\')';
  2630. this.lines.vertical.style.clipPath = 'path(\''
  2631. + `M${startOuter} 0L${startOuter} ${height - halfGap}L${startInner} ${height - halfGap}L${startInner} ${height + halfGap}L${startOuter} ${height + halfGap}L${startOuter} ${viewport.clientHeight}`
  2632. + `L${endOuter} ${viewport.clientHeight}L${endOuter} ${height + halfGap}L${endInner} ${height + halfGap}L${endInner} ${height - halfGap}L${endOuter} ${height - halfGap}L${endOuter} 0`
  2633. + 'Z\')';
  2634. };
  2635. this.updateConfig = (doClip = true) => {
  2636. const {colour, outer, inner, text} = $config.get().crosshair;
  2637. const thickness = Math.max(inner, outer);
  2638. this.container.style.filter = `drop-shadow(${colour.shadow} 0 0 1px)`;
  2639. this.lines.horizontal.style.translate = `0 -${thickness / 2}px`;
  2640. this.lines.vertical.style.translate = `-${thickness / 2}px 0`;
  2641. this.lines.horizontal.style.height = this.lines.vertical.style.width = `${thickness}px`;
  2642. this.lines.horizontal.style.backgroundColor = this.lines.vertical.style.backgroundColor = colour.fill;
  2643. if (text) {
  2644. this.text.style.color = colour.fill;
  2645. this.text.style.font = text.font;
  2646. this.text.style.left = `${text.position.x}%`;
  2647. this.text.style.top = `${text.position.y}%`;
  2648. this.text.style.transform = `translate(${text.translate.x}%,${text.translate.y}%) translate(${text.offset.x}px,${text.offset.y}px)`;
  2649. this.text.style.textAlign = text.align;
  2650. this.text.style.lineHeight = text.height;
  2651. this.container.append(this.text);
  2652. } else {
  2653. this.text.remove();
  2654. }
  2655. if (doClip) {
  2656. this.clip();
  2657. }
  2658. };
  2659. $config.ready.then(() => {
  2660. this.updateConfig(false);
  2661. });
  2662. }();
  2663.  
  2664. // ELEMENT CHANGE LISTENERS
  2665.  
  2666. const observer = new function () {
  2667. const onResolutionChange = () => {
  2668. glow.handleSizeChange?.();
  2669. };
  2670. const styleObserver = new MutationObserver((() => {
  2671. const properties = ['top', 'left', 'width', 'height', 'scale', 'rotate', 'translate', 'transform-origin'];
  2672. let priorStyle;
  2673. return () => {
  2674. // mousemove events on video with ctrlKey=true trigger this but have no effect
  2675. if (video.style.cssText === priorStyle) {
  2676. return;
  2677. }
  2678. priorStyle = video.style.cssText;
  2679. for (const property of properties) {
  2680. containers.background.style[property] = video.style[property];
  2681. containers.foreground.style[property] = video.style[property];
  2682. // cinematics doesn't exist for embedded vids
  2683. if (cinematics) {
  2684. cinematics.style[property] = video.style[property];
  2685. }
  2686. }
  2687. glow.handleViewChange();
  2688. };
  2689. })());
  2690. const videoObserver = new ResizeObserver(() => {
  2691. handleVideoChange();
  2692. glow.handleSizeChange?.();
  2693. });
  2694. const viewportObserver = new ResizeObserver(() => {
  2695. handleViewportChange();
  2696. crosshair.clip();
  2697. });
  2698. this.start = () => {
  2699. video.addEventListener('resize', onResolutionChange);
  2700. styleObserver.observe(video, {attributes: true, attributeFilter: ['style']});
  2701. viewportObserver.observe(viewport);
  2702. videoObserver.observe(video);
  2703. glow.handleViewChange();
  2704. };
  2705. this.stop = () => {
  2706. video.removeEventListener('resize', onResolutionChange);
  2707. styleObserver.disconnect();
  2708. viewportObserver.disconnect();
  2709. videoObserver.disconnect();
  2710. };
  2711. }();
  2712.  
  2713. // NAVIGATION LISTENERS
  2714.  
  2715. const stop = () => {
  2716. if (stopped) {
  2717. return;
  2718. }
  2719. stopped = true;
  2720. enabler.stop();
  2721. stopDrag?.();
  2722. observer.stop();
  2723. containers.background.remove();
  2724. containers.foreground.remove();
  2725. containers.tracker.remove();
  2726. crosshair.container.remove();
  2727. return peek(true);
  2728. };
  2729.  
  2730. const start = () => {
  2731. if (!stopped || viewport.classList.contains('ad-showing')) {
  2732. return;
  2733. }
  2734. stopped = false;
  2735. observer.start();
  2736. glow.start();
  2737. viewport.append(containers.background, containers.foreground, containers.tracker, crosshair.container);
  2738. // User may have a static minimum zoom greater than 1
  2739. zoom.constrain();
  2740. enabler.handleChange();
  2741. };
  2742.  
  2743. const updateConfigs = () => {
  2744. ConfigCache.id++;
  2745. enabler.updateConfig();
  2746. actions.crop.updateConfig();
  2747. crosshair.updateConfig();
  2748. };
  2749.  
  2750. // LISTENER ASSIGNMENTS
  2751.  
  2752. // load & navigation
  2753. (() => {
  2754. const getNode = (node, selector, ...selectors) => new Promise((resolve) => {
  2755. for (const child of node.children) {
  2756. if (child.matches(selector)) {
  2757. resolve(selectors.length === 0 ? child : getNode(child, ...selectors));
  2758. return;
  2759. }
  2760. }
  2761. new MutationObserver((changes, observer) => {
  2762. for (const {addedNodes} of changes) {
  2763. for (const child of addedNodes) {
  2764. if (child.matches(selector)) {
  2765. resolve(selectors.length === 0 ? child : getNode(child, ...selectors));
  2766. observer.disconnect();
  2767. return;
  2768. }
  2769. }
  2770. }
  2771. }).observe(node, {childList: true});
  2772. });
  2773. const init = async () => {
  2774. if (unsafeWindow.ytplayer?.bootstrapPlayerContainer?.childElementCount > 0) {
  2775. // wait for the video to be moved to ytd-app
  2776. await new Promise((resolve) => {
  2777. new MutationObserver((changes, observer) => {
  2778. resolve();
  2779. observer.disconnect();
  2780. }).observe(unsafeWindow.ytplayer.bootstrapPlayerContainer, {childList: true});
  2781. });
  2782. }
  2783. try {
  2784. await $config.ready;
  2785. } catch (error) {
  2786. if (!$config.reset || !window.confirm(`${error.message}\n\nWould you like to erase your data?`)) {
  2787. console.error(error);
  2788. return;
  2789. }
  2790. await $config.reset();
  2791. updateConfigs();
  2792. }
  2793. if (isEmbed) {
  2794. video = document.body.querySelector(SELECTOR_VIDEO);
  2795. } else {
  2796. const pageManager = await getNode(document.body, 'ytd-app', '#content', 'ytd-page-manager');
  2797. const page = pageManager.getCurrentPage() ?? await new Promise((resolve) => {
  2798. new MutationObserver(([{addedNodes: [page]}], observer) => {
  2799. if (page) {
  2800. resolve(page);
  2801. observer.disconnect();
  2802. }
  2803. }).observe(pageManager, {childList: true});
  2804. });
  2805. await page.playerEl.getPlayerPromise();
  2806. video = page.playerEl.querySelector(SELECTOR_VIDEO);
  2807. cinematics = page.querySelector('#cinematics');
  2808. // navigation to a new video
  2809. new MutationObserver(() => {
  2810. video.removeEventListener('play', startIfReady);
  2811. power.off();
  2812. // this callback can occur after metadata loads
  2813. startIfReady();
  2814. }).observe(page, {attributes: true, attributeFilter: ['video-id']});
  2815. // navigation to a non-video page
  2816. new MutationObserver(() => {
  2817. if (video.src === '') {
  2818. video.removeEventListener('play', startIfReady);
  2819. power.off();
  2820. }
  2821. }).observe(video, {attributes: true, attributeFilter: ['src']});
  2822. }
  2823. viewport = video.parentElement.parentElement;
  2824. altTarget = viewport.parentElement;
  2825. containers.foreground.style.zIndex = crosshair.container.style.zIndex = video.parentElement.computedStyleMap?.().get('z-index').value ?? 10;
  2826. crosshair.clip();
  2827. handleVideoChange();
  2828. handleViewportChange();
  2829. const startIfReady = () => {
  2830. if (video.readyState >= HTMLMediaElement.HAVE_METADATA) {
  2831. start();
  2832. }
  2833. };
  2834. const power = new function () {
  2835. this.off = () => {
  2836. delete this.wake;
  2837. stop();
  2838. };
  2839. this.sleep = () => {
  2840. this.wake ??= stop();
  2841. };
  2842. }();
  2843. new MutationObserver((() => {
  2844. return () => {
  2845. // video end
  2846. if (viewport.classList.contains('ended-mode')) {
  2847. power.off();
  2848. video.addEventListener('play', startIfReady, {once: true});
  2849. // ad start
  2850. } else if (viewport.classList.contains('ad-showing')) {
  2851. power.sleep();
  2852. }
  2853. };
  2854. })()).observe(viewport, {attributes: true, attributeFilter: ['class']});
  2855. // glow initialisation requires video dimensions
  2856. startIfReady();
  2857. video.addEventListener('loadedmetadata', () => {
  2858. if (viewport.classList.contains('ad-showing')) {
  2859. return;
  2860. }
  2861. start();
  2862. if (power.wake) {
  2863. power.wake();
  2864. delete power.wake;
  2865. }
  2866. });
  2867. };
  2868. if (!('ytPageType' in unsafeWindow) || unsafeWindow.ytPageType === 'watch') {
  2869. init();
  2870. return;
  2871. }
  2872. const initListener = ({detail: {newPageType}}) => {
  2873. if (newPageType === 'ytd-watch-flexy') {
  2874. init();
  2875. document.body.removeEventListener('yt-page-type-changed', initListener);
  2876. }
  2877. };
  2878. document.body.addEventListener('yt-page-type-changed', initListener);
  2879. })();
  2880.  
  2881. // keyboard state change
  2882.  
  2883. document.addEventListener('keydown', ({code}) => {
  2884. if (enabler.toggled) {
  2885. enabler.keys[enabler.keys.has(code) ? 'delete' : 'add'](code);
  2886. enabler.handleChange();
  2887. } else if (!enabler.keys.has(code)) {
  2888. enabler.keys.add(code);
  2889. enabler.handleChange();
  2890. }
  2891. });
  2892.  
  2893. document.addEventListener('keyup', ({code}) => {
  2894. if (enabler.toggled) {
  2895. return;
  2896. }
  2897. if (enabler.keys.has(code)) {
  2898. enabler.keys.delete(code);
  2899. enabler.handleChange();
  2900. }
  2901. });
  2902.  
  2903. window.addEventListener('blur', () => {
  2904. if (enabler.toggled) {
  2905. stopDrag?.();
  2906. } else {
  2907. enabler.keys.clear();
  2908. enabler.handleChange();
  2909. }
  2910. });
  2911.  
  2912. // failsafe config access
  2913.  
  2914. new MutationObserver((changes) => {
  2915. for (const {addedNodes} of changes) {
  2916. for (const node of addedNodes) {
  2917. if (!node.classList.contains('ytp-contextmenu')) {
  2918. continue;
  2919. }
  2920. const container = node.querySelector('.ytp-panel-menu');
  2921. const option = container.lastElementChild.cloneNode(true);
  2922. option.children[0].style.visibility = 'hidden';
  2923. option.children[1].innerText = 'Configure Viewfinding';
  2924. option.addEventListener('click', ({button}) => {
  2925. if (button === 0) {
  2926. actions.configure.onActive();
  2927. }
  2928. });
  2929. container.appendChild(option);
  2930. new ResizeObserver((_, observer) => {
  2931. if (container.clientWidth === 0) {
  2932. option.remove();
  2933. observer.disconnect();
  2934. }
  2935. }).observe(container);
  2936. }
  2937. }
  2938. }).observe(document.body, {childList: true});
  2939. })();