Guest User

new timer (February 2023)

a guest
Feb 20th, 2023
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 27.46 KB | Source Code | 0 0
  1.  
  2. // == Dependencies ==
  3.  
  4. var mediaType; // for compatibility
  5. var playerExists = false; // is set to true below if player exists
  6. var checkMediaType_enabled = true; // for debugging purposes
  7. var media_element = {}; // declaring as object
  8. var tmp="",count=0; // initiating temporary variables used inside functions and loops
  9.  
  10. function checkMediaType() {
  11.     // checks whether it is a video or an audio tag
  12.     if ( checkMediaType_enabled ) {
  13.             var mediaTypeBeforeCheck = mediaType;
  14.             if (document.getElementsByTagName("video")[0]) {
  15.                 playerExists = true; mediaType = "video";
  16.             }
  17.             if (document.getElementsByTagName("audio")[0]) {
  18.                 playerExists = true; mediaType = "audio";
  19.             }
  20.             var mediaTypeAfterCheck = mediaType;
  21.                if (mediaTypeBeforeCheck != mediaTypeAfterCheck)
  22.                   // Only show media type in console if it has changed.
  23.                   console.log("Detected media type: " + mediaType);
  24.         media_element = document.getElementsByTagName(mediaType)[0];
  25.         // Set back to false if no player is found after using customMediaElement.
  26.         media_element ? playerExists=true : playerExists=false;
  27.     }
  28. }
  29.  
  30. function customMediaElement(custom_media_element) {
  31.     checkMediaType_enabled = false;
  32.     if (custom_media_element) {
  33.         playerExists = true;
  34.         media_element = custom_media_element;
  35.         console.log("customMediaElement: Custom media element set. Reset using checkMediaType_enabled=true.");
  36.     } else { console.error("customMediaElement: No such media element found."); }
  37. }
  38. var customTitleElement;
  39.  
  40. function checkFileExtension(ext) {
  41.     if (typeof(ext) == "string") {
  42.         ext = ext.toLowerCase(); // case-insensitive
  43.         // string
  44.         if (document.location.href.search(new RegExp(ext+"$", "i")) > -1) return true; else return false;
  45.     } else if (typeof(ext) == "object") {
  46.         // array – check against multiple strings
  47.         for (var count=0; count < ext.length; count++) {
  48.             if (document.location.href.search(new RegExp(ext[count]+"$", "i")) > -1) return true;
  49.             if (count == ext.length-1) return false; // if no matches after going through them all
  50.         }
  51.     }
  52. }
  53.  
  54. function isDomain(domain) {
  55.     // Using .search() instead of .includes() to improve browser compatibility.
  56.     if (window.location.hostname.search(domain) >= 0) return true; else return false;
  57. }
  58.  
  59. // symbols
  60. var symbol_play = "▶&#xFE0E;&thinsp;"; // thin space for alignment
  61. var symbol_pause="&#10074;&thinsp;&#10074;"; // instead of "⏸" due to Edge browser putting an immutable blue box around it.
  62.  
  63. // mousedown status
  64. var mousedown_status;
  65. window.addEventListener("mousedown", function(){mousedown_status=true; } );
  66. window.addEventListener("mouseup", function(){mousedown_status=false; } );
  67.  
  68. function appendChildWithID(tagName,tagID,parent_element) {
  69.     // default parent element to document.body if unspecified
  70.     if (parent_element === undefined) parent_element = document.body;
  71.     parent_element.appendChild(document.createElement(tagName)); // add div
  72.     parent_element.lastElementChild.id=tagID; // give it ID
  73. }
  74.  
  75. function addStyle(new_style,parent_element) {
  76.     if (parent_element === undefined) parent_element = document.body;
  77.     parent_element.appendChild(document.createElement("style")); // add style
  78.     parent_element.lastElementChild.innerHTML = new_style;
  79. }
  80.  
  81. // time variables
  82. var media_time = {};
  83.  
  84. // HH:MM:SS timer
  85. function HMStimer_core(seconds) {
  86.  
  87.         // hours
  88.         media_time.HH = Math.floor( seconds/3600 );
  89.         // leading zero
  90.         if ( seconds < 36000 ) media_time.HH = "0" + media_time.HH;
  91.  
  92.         // minutes
  93.         media_time.MM = Math.floor( seconds/60%60 );
  94.         // leading zero
  95.         if ( seconds%3600 < 600 ) media_time.MM = "0" + media_time.MM;
  96.  
  97.         // seconds
  98.         media_time.SS = Math.floor( seconds%60 );
  99.         // leading zero
  100.         if ( seconds%60 < 10 ) media_time.SS = "0" + media_time.SS;
  101.  
  102.     return media_time.HH+":"+media_time.MM+":"+media_time.SS;
  103. }
  104.  
  105. function HMStimer(seconds) {
  106.     if (seconds >= 0) return HMStimer_core(seconds); // zero or positive
  107.     if (seconds < 0) // negative
  108.         {
  109.          seconds = seconds * (-1);
  110.          return "-"+HMStimer_core(seconds);
  111.         }
  112.     if (seconds == undefined || isNaN(seconds) ) return "–&thinsp;–:–&thinsp;–:–&thinsp;–";
  113.  
  114. }
  115.  
  116. // MM:SS timer
  117. function MStimer_core(seconds) {
  118.  
  119.         // minutes
  120.         media_time.MM = Math.floor( seconds/60 );
  121.         // leading zero
  122.         if ( seconds%3600 < 600 ) media_time.MM = "0" + media_time.MM;
  123.  
  124.         // seconds
  125.         media_time.SS = Math.floor( seconds%60 );
  126.         // leading zero
  127.         if ( seconds%60 < 10 ) media_time.SS = "0" + media_time.SS;
  128.  
  129.     return media_time.MM+":"+media_time.SS;
  130. }
  131.  
  132. function MStimer(seconds) {
  133.     if (seconds >= 0) return MStimer_core(seconds); // zero or positive
  134.     if (seconds < 0) // negative
  135.         {
  136.          seconds = seconds * (-1);
  137.          return "-"+MStimer_core(seconds);
  138.         }
  139.     if (seconds == undefined || isNaN(seconds) ) return "–&thinsp;–:–&thinsp;–";
  140.  
  141. }
  142.  
  143.  
  144. // implements togglePlay(); – deprecated due to compatibility issues on YouTube (broken site) and Dailymotion ("not a function" error through iframe'd player).
  145. /*
  146. Object.prototype.togglePlay = function togglePlay() {
  147.   return this.paused ? this.play() : this.pause();
  148. };
  149. */
  150.  
  151. // new function without object prototype for compatibility
  152. function togglePlay(media_element) {
  153.     if (media_element) { // validate media element first to avoid errors
  154.         media_element.paused ? media_element.play() : media_element.pause();
  155.     }
  156. }
  157.  
  158. // media file extension list
  159. var mediafileext = {
  160.     "video":[".mp4", ".mpg", ".mpeg", ".mts", ".mt2s", ".m4v", ".ts", ".ogv", ".wmv", ".3gp", ".3gpp", ".webm"],
  161.     "audio":[".mp3", ".wma", ".wav", ".ogg", ".opus", ".flac", ".oga", ".wma", ".aac", ".amr", ".alac", ".m4a"]
  162. };
  163.  
  164. // == Main code ==
  165. if (! timerUI) var timerUI = new Object({}); // create parent object if none exists
  166.  
  167.     // default system variables
  168. timerUI.debug_mode = false;
  169. timerUI.override_check = false;
  170.  
  171. timerUI.on = true;
  172. timerUI.buffer_on = true;
  173. timerUI.multiBuffer = true; // multiple buffer segments
  174. timerUI.div = {}; // unset yet, declaring to prevent reference errors
  175. timerUI.interval = {};
  176. timerUI.show_remaining = 0; // 0: show elapsed time. 1: show remaining time. 2: show elapsed and total.
  177. timerUI.update_during_seek = true; // update timer while dragging seek bar
  178. timerUI.color = "rgb(49,136,255)"; // #38F – using RGB for compatibility.
  179. timerUI.gradient = "rgba(0,0,0,0.9)"; // using RGBA instead of hexadecimal for compatibility.
  180. timerUI.font_pack = "din, futura, 'noto sans', 'open sans', ubuntu, 'segoe ui', verdana, tahoma, roboto, 'roboto light', arial, helvetica, 'trebuchet ms' ,'bitstream vera sans', sans-serif, consolas, monospace";
  181. timerUI.width_breakpoint = 768; // pixels
  182.  
  183.     // console notifications and warnings (possibly to be expanded)
  184. timerUI.msg = {
  185.     "notimer": "timerUI: No timer found; checking for media element again. Please try again.",
  186.     "nomedia": "timerUI: no media element found on page. Stopping."
  187. };
  188.  
  189.     // text containers (no const for compatibility)
  190. var timer_linefeed = "<span class=timer_linefeed><br /></span>";
  191. var timer_slash = " <span class=timer_slash>/</span> ";
  192.  
  193.     // functions
  194. timerUI.toggle = {};
  195. timerUI.toggle.main = function() {
  196.     // show and hide
  197.     if (timerUI.div) {
  198.         timerUI.update();
  199.         if (timerUI.on) {  
  200.             timerUI.div.style.display = "none";
  201.             console.log("timerUI off");
  202.         }
  203.         if (! timerUI.on ) {  
  204.             timerUI.div.style.display = "block";
  205.             console.log("timerUI on");
  206.         }
  207.         timerUI.on ? timerUI.on = false : timerUI.on = true;
  208.     } else {
  209.         console.warn(timerUI.msg.notimer);
  210.         timeUI();
  211.     }
  212. };
  213.  
  214. timerUI.toggle.buffer = function() {
  215.     if (timerUI.div) {
  216.         timerUI.update(); timerUI.updateBufferBar(true);
  217.         if (timerUI.buffer_on) {  
  218.             timerUI.buffer_bar.style.display = "none";
  219.             console.log("timerUI buffer bar off");
  220.         }
  221.         if (! timerUI.buffer_on ) {  
  222.             timerUI.buffer_bar.style.display = "block";
  223.             console.log("timerUI buffer bar on");
  224.         }
  225.         timerUI.buffer_on ? timerUI.buffer_on = false : timerUI.buffer_on = true;
  226.     } else {
  227.         console.warn(timerUI.msg.notimer);
  228.         timeUI();
  229.     }
  230. };
  231.  
  232. timerUI.toggle.title = function() {
  233.     if (timerUI.div) {
  234.         timerUI.update(); timerUI.updateBufferBar(true);
  235.         if (timerUI.title_on) {  
  236.             timerUI.title.style.display = "none";
  237.             console.log("timerUI title off");
  238.         }
  239.         if (! timerUI.title_on ) {  
  240.             timerUI.title.style.display = "block";
  241.             console.log("timerUI title on");
  242.         }
  243.         timerUI.title_on ? timerUI.title_on = false : timerUI.title_on = true;
  244.     } else {
  245.         console.warn(timerUI.msg.notimer);
  246.         timeUI();
  247.     }
  248. };
  249.  
  250. timerUI.getTitle = function() {
  251.     if (! timerUI.domainRules_checked) /* only check domain rules once */ {
  252.         timerUI.domainRules();
  253.         timerUI.domainRules_checked = true;
  254.     }
  255.     if (customTitleElement) timerUI.newTitle = customTitleElement.innerHTML;
  256.     else { // skipping this whole part if no custom title is specified
  257.         timerUI.newTitle = document.title;
  258.         timerUI.titleDomainRules();
  259.     }
  260.     if (media_element) {
  261.         timerUI.updateFileIcon();
  262.         return timerUI.file_icon+"&nbsp;"+timerUI.newTitle;
  263.     } else {
  264.         return "TimerUI – designed for home cinemas";
  265.     }
  266. };
  267.  
  268. timerUI.guessMediaType = function() {
  269.     if (isDomain("youtube.com") || isDomain("dailymotion.com") ) return "video";
  270.     if (document.location.pathname.search(/^\/video\//) > -1) return "video";
  271.     if (! media_element.videoWidth) return "audio"; // Detects files that only contain audio, even if they have a video file extension.
  272.     if (checkFileExtension(mediafileext.video) ) return "video";
  273.     if (checkFileExtension(mediafileext.audio) ) return "audio";
  274.     return "unknown"; // if nothing detected
  275. };
  276.  
  277. timerUI.updateFileIcon = function() {
  278.     timerUI.file_icon = timerUI.guessMediaType();
  279.     switch(timerUI.file_icon) {
  280.         case "video": timerUI.file_icon = "🎞️"; break;
  281.         case "audio": timerUI.file_icon = "♫"; break;
  282.         case "unknown": timerUI.file_icon = "📄"; break;
  283.     }
  284. };
  285.  
  286.  
  287. timerUI.adaptTitleWidth = function() {
  288.     if (media_element.duration > 3600 && timerUI.show_remaining == 2 && window.innerWidth > timerUI.width_breakpoint)
  289.         timerUI.title.style.maxWidth = "calc(100% - 670px)";
  290.     else
  291.         timerUI.title.style.maxWidth = "calc(100% - 400px)";
  292. };
  293.  
  294. window.addEventListener('resize', function() {
  295.     if (window.innerWidth < timerUI.width_breakpoint) timerUI.title.removeAttribute("style");
  296. } );
  297.  
  298. timerUI.update = function() {
  299.     if (media_element) {
  300.         timerUI.bar.style.width=media_element.currentTime / media_element.duration * 100 + "%";
  301.  
  302.         // buffer bar update formerly located here; removed from the scope of this function
  303.  
  304.         switch(timerUI.show_remaining) {
  305.             // 0: "HH:MM:SS"  1: "-HH:MM:SS"  2: "MM:SS / MM:SS" or "HH:MM:SS / HH:MM:SS"
  306.             case 0: timerUI.time.innerHTML=HMStimer(media_element.currentTime); break;
  307.             case 1: timerUI.time.innerHTML=HMStimer(media_element.currentTime-media_element.duration); break;
  308.             case 2:
  309.                 if (media_element.duration < 3600 || isNaN(media_element.duration) ) {
  310.                 // show hours if duration exceeds one hour
  311.                     timerUI.time.innerHTML=
  312.                         MStimer(media_element.currentTime)
  313.                         + timer_linefeed
  314.                         + timer_slash
  315.                         + MStimer(media_element.duration);
  316.                 } else {
  317.                     timerUI.time.innerHTML=
  318.                         HMStimer(media_element.currentTime)
  319.                         + timer_linefeed
  320.                         + timer_slash
  321.                         + HMStimer(media_element.duration);
  322.                 }
  323.                 break;
  324.         }
  325.  
  326.         media_element.paused == false ?
  327.             timerUI.status.innerHTML=symbol_play
  328.           : timerUI.status.innerHTML=symbol_pause;
  329.  
  330.   } else { timerUI.stop(); console.warn(timerUI.msg.nomedia); }
  331. };
  332. timerUI.updateTitle = function() { if (timerUI.title) timerUI.title.innerHTML = timerUI.getTitle(); };
  333.  
  334. // update title on URL change
  335. addEventListener('popstate', timerUI.updateTitle);
  336.  
  337. // update title fallback
  338. timerUI.interval.updateTitle = setInterval(timerUI.updateTitle, 2000);
  339.  
  340.  
  341. // buffer bar
  342. timerUI.updateBufferBar = function(override_paused) {
  343.     if (media_element && timerUI.buffer_on && (!media_element.paused || override_paused) ) {
  344.     timerUI.multiBuffer ? timerUI.update_multi_buffer() : timerUI.single_segment_buffer();
  345.   }
  346. };
  347.  
  348. // single-segment buffer bar
  349. timerUI.single_segment_buffer = function() {
  350.     if (timerUI.buffer_bar.innerHTML!="") { timerUI.buffer_bar.style=""; timerUI.buffer_bar.innerHTML=""; } // reset after switching from multi-segment buffer bar
  351.     // find out first buffer segment after current playback position
  352.     media_element.buffered.length > 0 ? timerUI.buffer_segment=media_element.buffered.length-1 : timerUI.buffer_segment=0;
  353.     // media_element.buffered.length is zero until player is initialized
  354.     // prevent timerUI.buffer_segment from going negative, as it would cause a DOMException error
  355.     if  ( timerUI.buffer_segment > 0) {
  356.         while (media_element.buffered.end(timerUI.buffer_segment-1) > media_element.currentTime && timerUI.buffer_segment > 1 ) {
  357.             timerUI.update_single_buffer();
  358.             timerUI.buffer_segment-- ;
  359.         }
  360.     }
  361. };
  362.  
  363. timerUI.update_single_buffer = function() {
  364.     if (media_element.buffered.length > 0) {
  365.     // prevent "DOMException: Index or size is negative or greater than the allowed amount"
  366.         timerUI.buffer_bar.style.width=media_element.buffered.end(timerUI.buffer_segment) / media_element.duration * 100 + "%";
  367.     } else { timerUI.buffer_bar.style.width="0%"; }
  368. };
  369.  
  370. // multi-segment buffer bar – highlight all buffered parts
  371. timerUI.update_multi_buffer = function() {
  372.     if (timerUI.buffer_bar.style.length < 1) {
  373.         timerUI.buffer_bar.style.width="100%";
  374.         timerUI.buffer_bar.style.backgroundColor="rgba(0,0,0,0)";
  375.     }
  376.     if (media_element.buffered.length > 0) {
  377.         timerUI.generate_buffer_segments();
  378.     } else { timerUI.buffer_bar.style.width="0%"; }
  379. };
  380.  
  381. timerUI.generate_buffer_segments = function() {
  382.     timerUI.buffer_bar.innerHTML=""; // reset to re-generate segments
  383.     for (count=0; count < media_element.buffered.length; count++) {
  384.         timerUI.append_buffer_segment(
  385.             timerUI.get_buffer_range(count).start_pos,
  386.             timerUI.get_buffer_range(count).end_pos
  387.         );
  388.     }
  389.     timerUI.select_segments = timerUI.buffer_bar.getElementsByClassName("timerUI_buffer_segment");
  390.     timerUI.segment_count = timerUI.select_segments.length;
  391. };
  392.  
  393. timerUI.append_buffer_segment = function(start_pos,end_pos) {
  394.     timerUI.buffer_bar.appendChild(document.createElement("div") );
  395.     timerUI.buffer_bar.lastElementChild.classList.add("timerUI_buffer_segment");
  396.     timerUI.buffer_bar.lastElementChild.style="left:"+start_pos+"%;width:"+(end_pos-start_pos)+"%;background-color:"+timerUI.color+";";
  397. };
  398.  
  399. timerUI.get_buffer_range = function(segment_number) {
  400.     return {
  401.     start_pos: media_element.buffered.start(segment_number) / media_element.duration * 100,
  402.     end_pos: media_element.buffered.end(segment_number) / media_element.duration * 100
  403.     }; // object with start and end percentages
  404. };
  405.  
  406. timerUI.set_buffer_segment = function(segment_number,start_pos,end_pos) {
  407.     var selection=timerUI.buffer_bar.getElementsByClassName("timerUI_buffer_segment");
  408.     selection[segment_number].style.left = start_pos / media_element.duration * 100 + "%";
  409.     selection[segment_number].style.width = (end_pos-start_pos) / media_element.duration * 100 + "%";
  410. };
  411.  
  412.  
  413.  
  414. // colors
  415. timerUI.setColor = function(newColor) {
  416.     newColor == "default" ? timerUI.color="rgb(49,136,255)" /* #38F */ : timerUI.color = newColor;
  417.  
  418.     timerUI.bar.style.backgroundColor=timerUI.color;
  419.     timerUI.buffer_bar.style.backgroundColor=timerUI.color;
  420.     timerUI.bar.style.boxShadow="0 0 30px 0 "+timerUI.color;
  421.     // (deprecated due to new buffer bar) timerUI.bar_placeholder.style.backgroundColor=timerUI.color;
  422.     timerUI.time.style.color=timerUI.color;
  423.     timerUI.status.style.color=timerUI.color;
  424.     timerUI.title.style.color=timerUI.color;
  425. };
  426.  
  427. timerUI.setGradient = function(newGradient) {
  428.     newGradient == "default" ? timerUI.gradient="rgba(0,0,0,0.9)" : timerUI.gradient = newGradient;
  429.     timerUI.gradient_placeholder.style.backgroundImage="linear-gradient(to top,"+timerUI.gradient+", rgba(0,0,0,0) )";
  430. };
  431.  
  432. timerUI.setFont = function(newFont) {
  433.     timerUI.time.style.fontFamily=newFont;
  434.     timerUI.title.style.fontFamily=newFont;
  435. };
  436.  
  437. timerUI.stop = function() {
  438.     timerUI.status.innerHTML="■";
  439.     timerUI.bar.style.width=0;
  440.     timerUI.buffer_bar.style.width=0;
  441.     timerUI.time.innerHTML=HMStimer(undefined);
  442. };
  443.  
  444. // Additional checks to ensure the player is detected
  445. window.onclick = function() { checkMediaType();timeUI(); };
  446. window.addEventListener("keydown", function() { checkMediaType();timeUI(); } );
  447.  
  448.  
  449. function timeUI() {
  450. // slightly different name to prevent naming collision with timerUI object
  451.  
  452.     checkMediaType();
  453.     timerUI.domainRules(); // load domain rules
  454.     // add timerUI if it does not already exist
  455.     if ( ( ! document.getElementById("timerUI") ) && playerExists || timerUI.override_check ) {
  456.  
  457.     // Adding elements
  458.  
  459.         // parent element
  460.         appendChildWithID("div","timerUI");
  461.         timerUI.div = document.getElementById("timerUI");
  462.  
  463.         // button styling
  464.         addStyle("#timerUI button { background:none; border:none; outline:none; line-height:unset; }  #timerUI button:hover { filter: brightness(1.2); }    #timerUI button:active  { filter: brightness(0.6); }", timerUI.div);
  465.             // to suppress button background and border on earlier browser versions
  466.         timerUI.div.lastElementChild.classList.add("timerUI_buttons"); // label to improve visibility in page inspector
  467.  
  468.         // background gradient
  469.         appendChildWithID("div","timerUI_bottom_gradient",timerUI.div );
  470.         timerUI.gradient_placeholder = document.getElementById("timerUI_bottom_gradient");
  471.         addStyle("#timerUI #timerUI_bottom_gradient { display:block; position:fixed; background-image:linear-gradient(to top,"+timerUI.gradient+", rgba(0,0,0,0) ); opacity:1; height:80pt; width:100%; bottom:0; pointer-events:none; }", timerUI.div);
  472.  
  473.         // progress bar
  474.         appendChildWithID("div","timerUI_progress_bar",timerUI.div );
  475.         timerUI.bar = document.getElementById("timerUI_progress_bar");
  476.         addStyle("#timerUI #timerUI_progress_bar { display:block; position:fixed; background-color:"+timerUI.color+"; box-shadow: 0 0 30px 0px "+timerUI.color+"; height:8pt; width:50%; bottom:0; }", timerUI.div);
  477.  
  478.         // buffer bar
  479.         appendChildWithID("div","timerUI_buffer_bar",timerUI.div );
  480.         timerUI.buffer_bar = document.getElementById("timerUI_buffer_bar");
  481.         addStyle("#timerUI #timerUI_buffer_bar, #timerUI .timerUI_buffer_segment { display:block; position:fixed; background-color:"+timerUI.color+"; height:8pt; width:75%; bottom:0; opacity:0.4; } #timerUI .timerUI_buffer_segment { opacity:1; }", timerUI.div);
  482.  
  483.         // media title
  484.         appendChildWithID("div","timerUI_media_title",timerUI.div );
  485.         timerUI.title = document.getElementById("timerUI_media_title");
  486.         timerUI.title.innerHTML = timerUI.getTitle();
  487.         addStyle("#timerUI #timerUI_media_title { position:fixed; text-shadow: 0 0 5px black; display:inline; display:-webkit-box; bottom:15pt; left:2pt; color:"+timerUI.color+"; font-family:"+timerUI.font_pack+"; font-size:20pt; width:60%; max-width:calc(100% - 500px); text-overflow: ellipsis;     overflow: hidden;   -webkit-box-orient: vertical; -webkit-line-clamp: 2; vertical-align: bottom;");
  488.  
  489.         // timer
  490.         appendChildWithID("button","timerUI_media_timer",timerUI.div );
  491.         timerUI.time = document.getElementById("timerUI_media_timer");
  492.         timerUI.time.innerHTML="00:00:00";
  493.         addStyle("#timerUI #timerUI_media_timer { display:block; color:"+timerUI.color+"; position:fixed; cursor:pointer; font-size:50pt; text-shadow: 0 0 20px black; line-height:60pt; bottom:10pt; right:30pt; text-align:right; font-weight:400; font-family:"+timerUI.font_pack+"; }  #timerUI #timerUI_media_timer .timer_linefeed { display:none; }", timerUI.div);
  494.  
  495.         // play/pause symbol
  496.         appendChildWithID("button","timerUI_playback_status",timerUI.div );
  497.         timerUI.status = document.getElementById("timerUI_playback_status");
  498.         timerUI.status.innerHTML="■";
  499.         addStyle("#timerUI #timerUI_playback_status { display:block; position:fixed; cursor:pointer; color:"+timerUI.color+"; font-size:24pt; line-height:40pt; bottom:30pt; right:3pt; font-family:none; }", timerUI.div);
  500.  
  501.         // progress bar placeholder – put last to be at the top in stacking context
  502.         appendChildWithID("div","timerUI_progress_placeholder",timerUI.div );
  503.         timerUI.bar_placeholder = document.getElementById("timerUI_progress_placeholder");
  504.         addStyle("#timerUI #timerUI_progress_placeholder { display:block; position:fixed; cursor:pointer; background-color:grey; height:8pt; width:100%; bottom:0; opacity:0.2; }", timerUI.div);
  505.  
  506.         // responsive - at bottom to be able to override CSS properties without !important flag.
  507.         addStyle("@media (max-width:"+timerUI.width_breakpoint+"px) { #timerUI #timerUI_media_timer { font-size:30pt; line-height:24pt; bottom:15pt; } #timerUI #timerUI_playback_status { bottom:10pt; } } @media (max-width:500px) { #timerUI #timerUI_media_timer .timer_linefeed { display:inline; } #timerUI #timerUI_media_timer .timer_slash { display:none; } } @media (max-width:"+timerUI.width_breakpoint+"px) { #timerUI #timerUI_buffer_bar { font-size:10pt; -webkit-line-clamp: 3; max-width:60%;} } @media (max-width:480px) { #timerUI #timerUI_buffer_bar { display: none; } } ", timerUI.div);
  508.         timerUI.div.lastElementChild.classList.add("timerUI_responsive");
  509.  
  510.  
  511.     // update timer during playback every fifteenth of a second and while mouse is dragging progress bar
  512.     timerUI.interval.update = setInterval(
  513.         function() { if (
  514.                 ( media_element /* exists? */ && timerUI.update_during_seek && mousedown_status )
  515.              || ( media_element && timerUI.on && ! media_element.paused )
  516.     ) timerUI.update(); }, 1000/15
  517.     );
  518.  
  519.     // Longer interval for buffer bar to minimize CPU usage
  520.     timerUI.interval.buffer = setInterval(timerUI.updateBufferBar, 1000);
  521.  
  522.  
  523.     // play and pause toggle
  524.     timerUI.status.onclick = function() { togglePlay(media_element); timerUI.update(); timerUI.updateBufferBar(true); };
  525.         // former code with object prototype caused compatibility issues on various sites: media_element.togglePlay();
  526.  
  527.     // toggle between elapsed, remaining, and elapsed/total time
  528.     timerUI.time.onclick = function() {
  529.         switch(timerUI.show_remaining) {
  530.             case 0: timerUI.show_remaining = 1; break;
  531.             case 1: timerUI.show_remaining = 2; timerUI.adaptTitleWidth(); break;
  532.             case 2: timerUI.show_remaining = 0; timerUI.adaptTitleWidth(); break;
  533.         }
  534.         timerUI.update(); timerUI.updateBufferBar(true);
  535.     };
  536.  
  537.     // clickable progress bar (experimental) - no "timerUI." notation because inside main function
  538.     timerUI.clickSeekBar = function(m){
  539.         if (media_element) {
  540.             var clickPos = m.clientX / timerUI.bar_placeholder.offsetWidth;
  541.             // go to beginning if clicked in first percentile
  542.             if (clickPos < 0.01 ) media_element.currentTime = 0;
  543.                 else media_element.currentTime = media_element.duration * clickPos;
  544.             timerUI.update(); timerUI.updateBufferBar(true);
  545.         }
  546.     };
  547.     function dragSeekBar(m){ // currently unused
  548.         m = m || window.event;
  549.         var clickPos = m.pageX / timerUI.bar_placeholder.offsetWidth;
  550.         var dragSeekBarInterval = setInterval( function() {
  551.             media_element.currentTime = media_element.duration * clickPos;
  552.             timerUI.update();
  553.             if (! mousedown_status) { clearInterval(dragSeekBarInterval); return; }
  554.         }, 200);
  555.     }
  556.     timerUI.bar_placeholder.addEventListener("mousedown", timerUI.clickSeekBar );
  557.     // (incomplete) timerUI.bar_placeholder.addEventListener("mousemove", dragSeekBar );
  558.     // (obsolete) timerUI.bar_placeholder.addEventListener("mouseup", clickSeekBar );
  559.  
  560.     timerUI.update();
  561.  
  562.     // == Patches ==
  563.  
  564.         // prevent missing out on pausing from inside a site's existing player
  565.         window.addEventListener("mouseup", function() { setTimeout(timerUI.update, 200); } );
  566.         window.addEventListener("keyup", function() { setTimeout(timerUI.update, 200); } );
  567.  
  568.         // prevent detaching from player on sites with playlists such as Internet Archive
  569.         timerUI.interval.checkMedia = setInterval( checkMediaType,1000 );
  570.  
  571.         // prevent indicating "▶" after playback finished
  572.         timerUI.interval.checkPaused = setInterval( function() {
  573.                 if ( media_element /* exists? */ && media_element.paused && ! timerUI.pause_checked) {
  574.                     timerUI.update(); timerUI.pause_checked = true;
  575.                     if (timerUI.debug_mode) console.debug("timerUI: checking paused status: "+media_element.paused);
  576.                 } else if ( media_element && ! media_element.paused ) { timerUI.pause_checked = false; }
  577.                 // to avoid redundant checks while paused
  578.         },1000 );
  579.  
  580.     } else {
  581.     // warn in console that no player exists; prevent repetition
  582.         if (! playerExists && ! timerUI.noMediaWarned) {
  583.                 console.warn(timerUI.msg.nomedia); timerUI.noMediaWarned = true;
  584.         }
  585.     }
  586. }
  587.  
  588. // == Custom domain rules ==
  589. timerUI.domainRules = function() {
  590.     if (isDomain("dailymotion.com") && document.location.pathname.search(/^\/embed\//) < 0 ) {
  591.         // Dailymotion watch page, excluding embed page.
  592.         customMediaElement(
  593.             document.getElementById("player-body").contentWindow.document.getElementsByTagName("video")[0]
  594.         );
  595.         customTitleElement = document.getElementById("media-title"); // for unlisted videos (Dailymotion only displays the video title in the HTML page title for public videos)
  596.     }
  597.  
  598.     // media embedded on Wayback Machine
  599.     if ( is_WaybackEmbed() ) {
  600.         tmp = document.getElementsByTagName("iframe")[0]; // iframe in temporary variable to deduplicate code
  601.         customMediaElement(
  602.             tmp.contentWindow.document.getElementsByTagName("video")[0]
  603.         );
  604.         // dark background for improved video visibility
  605.         tmp.contentWindow.document.body.style.backgroundColor="#222";
  606.         }
  607. };
  608.  
  609. timerUI.titleDomainRules = function() {
  610. // custom domain rules for title
  611.     if ( isDomain("youtube.com") || isDomain("dailymotion.com")
  612.         || isDomain("wikimedia.org") || isDomain("wikipedia.org")
  613.         || isDomain("wikiversity.org") || isDomain("wikibooks.org")
  614.         || isDomain("mediawiki.org")
  615.         ) {
  616.         // negative lookahead regular expression – trim after last dash
  617.         // Match both normal dash "-" and ndash "–", since the German-language wikis use the latter.
  618.         timerUI.newTitle = decodeURI(timerUI.newTitle.substring(0,timerUI.newTitle.search(/(-|–)(?:.(?!(-|–)))+$/)-1 ) );
  619.     }
  620.     // remove "File:" prefix on wikis
  621.     if ( isDomain("wiki") ) {
  622.         if (document.title.search(/^File:/)  == 0 ) timerUI.newTitle = timerUI.newTitle.substring(5);
  623.         if (document.title.search(/^Datei:/) == 0 ) timerUI.newTitle = timerUI.newTitle.substring(6);
  624.     }
  625.  
  626.     // Internet Archive library only, not Wayback Machine
  627.     if ( isDomain("archive.org") && ! isDomain("web.archive.org") ) {
  628.         // get media title from page title before first colon
  629.         timerUI.newTitle = (document.location.href+"").substring((document.location.href+" ").search(/\/(?:.(?!\/))+\/?$/)+1 );
  630.         // after last slash (additional space prevents full URL from being matched)
  631.         if (timerUI.newTitle != "") { timerUI.newTitle += " - "; }
  632.         timerUI.newTitle += document.title.substring(0,document.title.search(/:(?:.(?!:))+(?:.(?!:))+/)-1 );
  633.         // trim after second-last colon, -1 to remove space at end
  634.  
  635.         timerUI.newTitle=decodeURI(timerUI.newTitle); // prevent spaces from turning into "%20".
  636.     }
  637.     if ( is_WaybackEmbed() ) {
  638.         // Already generated by the browser inside the iframe. How convenient. Otherwise, a regular expression that matches the part after the last slash in the URL, and a decodeURI would have to be used.
  639.         timerUI.newTitle = tmp.contentWindow.document.title;
  640.     }
  641. };
  642.  
  643. function is_WaybackEmbed() {
  644.     // checks if the current page is media embedded on the Wayback Machine, for code deduplication.
  645.     if ( isDomain("web.archive.org") || isDomain("wayback.archive.org") && document.title=="Wayback Machine" && document.getElementsByTagName("iframe")[0] ) {
  646.         // separate check for ID of iframe to avoid reference error
  647.         if (document.getElementsByTagName("iframe")[0].id=="playback") {
  648.             return true;
  649.         }
  650.     } else {
  651.         return false;
  652.     }
  653. }
  654.  
  655.  
  656. // == Master function ==
  657. timeUI();
Tags: timer timerUI
Advertisement
Add Comment
Please, Sign In to add comment