Advertisement
Guest User

Timer UI source code (October 10th, 2022)

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