YouTube Viewfinding

Zoom, rotate & crop YouTube videos

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

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址