mirror of
https://github.com/zhw2590582/ArtPlayer.git
synced 2026-10-11 22:06:17 -08:00
fix(thumbnail): [PKG-TOOL-THUMB-03] own input resources and separate sheet export
This commit is contained in:
1 parent
1cb7779192
commit
426c0c5d42
22 files changed
+13724
-256
No files matched your search
@@ -4,4 +4,4 @@
|
||||
* (c) 2017-2026 Harvey Zhao
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
!function(t,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"==typeof define&&define.amd?(t.ArtplayerToolThumbnail=e(),define(function(){return t.ArtplayerToolThumbnail})):(t="undefined"!==typeof globalThis?globalThis:t||self).ArtplayerToolThumbnail=e()}(this,function(){"use strict";class t{on(t,e,i){const n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:i}),this}once(t,e,i){const n=this;function o(...s){n.off(t,o),e.apply(i,s)}return o._=e,this.on(t,o,i)}emit(t,...e){const i=((this.e||(this.e={}))[t]||[]).slice();for(let n=0;n<i.length;n+=1)i[n].fn.apply(i[n].ctx,e);return this}off(t,e){const i=this.e||(this.e={}),n=i[t],o=[];if(n&&e)for(let s=0,r=n.length;s<r;s+=1)n[s].fn!==e&&n[s].fn._!==e&&o.push(n[s]);return o.length?i[t]=o:delete i[t],this}}function e(t,e,i){return Math.max(Math.min(t,Math.max(e,i)),Math.min(e,i))}class i extends t{constructor(t={}){super(),this.processing=!1,this.option={},this.setup(Object.assign({},i.DEFAULTS,t)),this.video=i.creatVideo(),this.duration=0,this.inputChange=this.inputChange.bind(this),this.ondrop=this.ondrop.bind(this),this.option.fileInput.addEventListener("change",this.inputChange),this.option.fileInput.addEventListener("dragover",i.ondragover),this.option.fileInput.addEventListener("drop",i.ondrop)}static get DEFAULTS(){return{number:60,width:160,height:90,column:10,begin:0,end:Number.NaN}}static ondragover(t){t.preventDefault()}ondrop(t){t.preventDefault();const e=t.dataTransfer.files[0];this.loadVideo(e)}setup(t={}){this.option=Object.assign({},this.option,t);const{fileInput:i,number:n,width:o,column:s}=this.option;if(this.errorHandle(i instanceof Element,"The 'fileInput' is not a Element"),"INPUT"!==i.tagName||"file"!==i.type){i.style.position="relative";const t=document.createElement("input");t.type="file",t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.right="0",t.style.bottom="0",t.style.opacity="0",i.appendChild(t),this.option.fileInput=t}return["number","width","column","begin","end"].forEach(t=>{this.errorHandle("number"===typeof this.option[t],`The '${t}' is not a number`)}),this.option.number=e(n,10,1e3),this.option.width=e(o,10,1e3),this.option.column=e(s,1,1e3),this}static creatVideo(){const t=document.createElement("video");return t.style.position="absolute",t.style.top="-9999px",t.style.left="-9999px",t.muted=!0,t.controls=!0,document.body.appendChild(t),t}inputChange(t){const e=this.option.fileInput.files[0];this.loadVideo(e),t.target.value=""}loadVideo(t){if(t){const e=this.video.canPlayType(t.type);this.errorHandle("maybe"===e||"probably"===e,`Playback of this file format is not supported: ${t.type}`);const i=URL.createObjectURL(t);this.videoUrl=i,this.file=t,this.emit("file",this.file),this.video.src=i,this.emit("video",this.video)}}start(){if(!this.video.duration)return(t=1e3,new Promise(e=>setTimeout(e,t))).then(()=>this.start());var t;const{width:i,number:n,begin:o,end:s}=this.option,r=this.video.videoHeight/this.video.videoWidth*i;this.option.height=r,this.option.begin=e(o,0,this.video.duration),this.option.end=e(s||this.video.duration,o,this.video.duration),this.errorHandle(this.option.end>this.option.begin,"End time must be greater than the start time"),this.duration=this.option.end-this.option.begin,this.density=n/this.duration,this.errorHandle(this.file&&this.video,"Please select the video file first"),this.errorHandle(!this.processing,"There is currently a task in progress, please wait a moment..."),this.errorHandle(this.density<=1,`The preview density cannot be greater than 1, but got ${this.density}`);const h=this.creatScreenshotDate(),a=this.creatCanvas(),l=a.getContext("2d");this.emit("canvas",a);const d=h.map((t,e)=>()=>new Promise(o=>{this.video.oncanplay=()=>{l.drawImage(this.video,t.x,t.y,i,r),a.toBlob(t=>{this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl),this.thumbnailUrl=URL.createObjectURL(t),this.emit("update",this.thumbnailUrl,(e+1)/n),this.video.oncanplay=null,o()})},this.video.currentTime=t.time}));return this.processing=!0,(p=d,p.reduce((t,e)=>t.then(e),Promise.resolve())).then(()=>{this.processing=!1,this.emit("done")}).catch(t=>{throw this.processing=!1,this.emit("error",t.message),t});var p}creatScreenshotDate(){const{number:t,width:e,height:i,column:n,begin:o}=this.option,s=this.duration/t,r=[o+s];for(;r.length<t;){const t=r[r.length-1];r.push(t+s)}return r.map((t,o)=>({time:t-s/2,x:o%n*e,y:Math.floor(o/n)*i}))}creatCanvas(){const{number:t,width:e,height:i,column:n}=this.option,o=document.createElement("canvas"),s=o.getContext("2d");return o.width=e*n,o.height=Math.ceil(t/n)*i+30,s.fillStyle="black",s.fillRect(0,0,o.width,o.height),s.font="14px Georgia",s.fillStyle="#fff",s.fillText(`From: https://artplayer.org/, Number: ${t}, Width: ${e}, Height: ${i}, Column: ${n}`,10,o.height-11),o}download(){this.errorHandle(this.file&&this.thumbnailUrl,"Download does not seem to be ready, please create previeLine truncated
|
||||
!function(t,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"==typeof define&&define.amd?(t.ArtplayerToolThumbnail=e(),define(function(){return t.ArtplayerToolThumbnail})):(t="undefined"!==typeof globalThis?globalThis:t||self).ArtplayerToolThumbnail=e()}(this,function(){"use strict";class t{on(t,e,i){const n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:i}),this}once(t,e,i){const n=this;function o(...s){n.off(t,o),e.apply(i,s)}return o._=e,this.on(t,o,i)}emit(t,...e){const i=((this.e||(this.e={}))[t]||[]).slice();for(let n=0;n<i.length;n+=1)i[n].fn.apply(i[n].ctx,e);return this}off(t,e){const i=this.e||(this.e={}),n=i[t],o=[];if(n&&e)for(let s=0,r=n.length;s<r;s+=1)n[s].fn!==e&&n[s].fn._!==e&&o.push(n[s]);return o.length?i[t]=o:delete i[t],this}}function e(t,e,i){return Math.max(Math.min(t,Math.max(e,i)),Math.min(e,i))}const i=new WeakMap;function n(t){let e;for(const[n,o]of t.listeners.splice(0))try{t.input.removeEventListener(n,o)}catch(i){e||(e=i)}if(t.wrapper){try{t.input.parentNode&&t.input.parentNode.removeChild(t.input)}catch(i){e||(e=i)}"relative"===t.wrapper.style.position&&(t.wrapper.style.position=t.position)}if(e)throw e}function o(t,e){try{for(const[i,n]of e)t.listeners.push([i,n]),t.input.addEventListener(i,n)}catch(i){try{n(t)}catch{}throw i}}function s(t){const e=i.get(t);e&&(i.delete(t),n(e))}const r=new WeakSet;class h extends t{constructor(t={}){super(),this.processing=!1,this.option={};try{this.setup(Object.assign({},h.DEFAULTS,t)),this.video=h.creatVideo(),this.duration=0,this.inputChange=this.inputChange.bind(this),this.ondrop=this.ondrop.bind(this),function(t,e){const n=i.get(t);n.callbacks=[["change",t.inputChange],["dragover",e],["drop",t.ondrop]],o(n,n.callbacks)}(this,h.ondragover)}catch(e){try{s(this)}catch{}try{this.video?.parentNode&&this.video.parentNode.removeChild(this.video)}catch{}throw e}}static get DEFAULTS(){return{number:60,width:160,height:90,column:10,begin:0,end:Number.NaN}}static ondragover(t){t.preventDefault()}ondrop(t){if(r.has(this))return;t.preventDefault();const e=t.dataTransfer.files[0];this.loadVideo(e)}setup(t={}){return r.has(this)||(this.option=function(t,s){const r=Object.assign({},t.option,s),h=r.fileInput;t.errorHandle(h instanceof Element,"The 'fileInput' is not a Element");for(const e of["number","width","column","begin","end"])t.errorHandle("number"===typeof r[e],`The '${e}' is not a number`);r.number=e(r.number,10,1e3),r.width=e(r.width,10,1e3),r.column=e(r.column,1,1e3);const a=i.get(t);if(a&&(h===a.input||h===a.wrapper))return r.fileInput=a.input,r;const l={input:h,wrapper:null,position:"",listeners:[],callbacks:a?.callbacks||null};try{"INPUT"===h.tagName&&"file"===h.type||(l.wrapper=h,l.position=h.style.position,l.input=document.createElement("input"),l.input.type="file",Object.assign(l.input.style,{position:"absolute",width:"100%",height:"100%",left:"0",top:"0",right:"0",bottom:"0",opacity:"0"}),h.style.position="relative",h.appendChild(l.input)),l.callbacks&&o(l,l.callbacks)}catch(c){try{n(l)}catch{}throw c}return r.fileInput=l.input,i.set(t,l),t.option=r,a&&n(a),r}(this,t)),this}static creatVideo(){const t=document.createElement("video");t.style.position="absolute",t.style.top="-9999px",t.style.left="-9999px",t.muted=!0,t.controls=!0;try{document.body.appendChild(t)}catch(e){throw t.parentNode&&t.parentNode.removeChild(t),e}return t}inputChange(t){if(r.has(this))return;const e=this.option.fileInput.files[0];this.loadVideo(e),t.target.value=""}loadVideo(t){if(t&&!r.has(this)){const e=this.video.canPlayType(t.type);this.errorHandle("maybe"===e||"probably"===e,`Playback of this file format is not supported: ${t.type}`);const i=URL.createObjectURL(t);this.videoUrl=i,this.file=t,this.emit("file",this.file),this.video.src=i,this.emit("video",this.video)}}start(){if(!this.video.duration)return(t=1e3,new Promise(e=>setTimeout(e,t))).then(()=>this.start());var t;const{width:i,number:n,begin:o,end:s}=this.option,r=this.video.videoHeight/this.video.videoWidth*i;this.option.height=r,this.option.begin=e(o,0,this.video.duration),this.option.end=e(s||this.video.duration,o,this.video.duration),this.errorHandle(this.option.end>this.option.begin,"End time must be greater than the start time"),this.duration=this.option.end-this.option.begin,this.density=n/this.duration,this.errorHandle(this.file&&this.video,"Please select the video file first"),this.errorHandle(!this.processing,"There is currently a task in progress, please wait a moment..."),this.errorHandle(this.density<=1,`The preview density cannot be greater than 1, but got ${this.density}`);const h=this.creatScreenshotDate(),a=this.creatCanvas(),l=a.getContext("2d");this.emit("canvas",a);const c=h.map((t,e)=>()=>new Promise(o=>{this.video.oncanplay=()=>{l.drawImage(this.video,t.x,t.y,i,r),a.toBlob(t=>{this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl),this.thumbnailUrl=URL.createObjectURL(t),this.emit("update",this.thumbnailUrl,(e+1)/n),this.videLine truncated
|
||||
@@ -4,4 +4,4 @@
|
||||
* (c) 2017-2026 Harvey Zhao
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
!function(t,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"==typeof define&&define.amd?(t.ArtplayerToolThumbnail=e(),define(function(){return t.ArtplayerToolThumbnail})):(t="undefined"!==typeof globalThis?globalThis:t||self).ArtplayerToolThumbnail=e()}(this,function(){"use strict";class t{on(t,e,i){const n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:i}),this}once(t,e,i){const n=this;function o(...s){n.off(t,o),e.apply(i,s)}return o._=e,this.on(t,o,i)}emit(t,...e){const i=((this.e||(this.e={}))[t]||[]).slice();for(let n=0;n<i.length;n+=1)i[n].fn.apply(i[n].ctx,e);return this}off(t,e){const i=this.e||(this.e={}),n=i[t],o=[];if(n&&e)for(let s=0,r=n.length;s<r;s+=1)n[s].fn!==e&&n[s].fn._!==e&&o.push(n[s]);return o.length?i[t]=o:delete i[t],this}}function e(t,e,i){return Math.max(Math.min(t,Math.max(e,i)),Math.min(e,i))}class i extends t{constructor(t={}){super(),this.processing=!1,this.option={},this.setup(Object.assign({},i.DEFAULTS,t)),this.video=i.creatVideo(),this.duration=0,this.inputChange=this.inputChange.bind(this),this.ondrop=this.ondrop.bind(this),this.option.fileInput.addEventListener("change",this.inputChange),this.option.fileInput.addEventListener("dragover",i.ondragover),this.option.fileInput.addEventListener("drop",i.ondrop)}static get DEFAULTS(){return{number:60,width:160,height:90,column:10,begin:0,end:Number.NaN}}static ondragover(t){t.preventDefault()}ondrop(t){t.preventDefault();const e=t.dataTransfer.files[0];this.loadVideo(e)}setup(t={}){this.option=Object.assign({},this.option,t);const{fileInput:i,number:n,width:o,column:s}=this.option;if(this.errorHandle(i instanceof Element,"The 'fileInput' is not a Element"),"INPUT"!==i.tagName||"file"!==i.type){i.style.position="relative";const t=document.createElement("input");t.type="file",t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.right="0",t.style.bottom="0",t.style.opacity="0",i.appendChild(t),this.option.fileInput=t}return["number","width","column","begin","end"].forEach(t=>{this.errorHandle("number"===typeof this.option[t],`The '${t}' is not a number`)}),this.option.number=e(n,10,1e3),this.option.width=e(o,10,1e3),this.option.column=e(s,1,1e3),this}static creatVideo(){const t=document.createElement("video");return t.style.position="absolute",t.style.top="-9999px",t.style.left="-9999px",t.muted=!0,t.controls=!0,document.body.appendChild(t),t}inputChange(t){const e=this.option.fileInput.files[0];this.loadVideo(e),t.target.value=""}loadVideo(t){if(t){const e=this.video.canPlayType(t.type);this.errorHandle("maybe"===e||"probably"===e,`Playback of this file format is not supported: ${t.type}`);const i=URL.createObjectURL(t);this.videoUrl=i,this.file=t,this.emit("file",this.file),this.video.src=i,this.emit("video",this.video)}}start(){if(!this.video.duration)return(t=1e3,new Promise(e=>setTimeout(e,t))).then(()=>this.start());var t;const{width:i,number:n,begin:o,end:s}=this.option,r=this.video.videoHeight/this.video.videoWidth*i;this.option.height=r,this.option.begin=e(o,0,this.video.duration),this.option.end=e(s||this.video.duration,o,this.video.duration),this.errorHandle(this.option.end>this.option.begin,"End time must be greater than the start time"),this.duration=this.option.end-this.option.begin,this.density=n/this.duration,this.errorHandle(this.file&&this.video,"Please select the video file first"),this.errorHandle(!this.processing,"There is currently a task in progress, please wait a moment..."),this.errorHandle(this.density<=1,`The preview density cannot be greater than 1, but got ${this.density}`);const h=this.creatScreenshotDate(),a=this.creatCanvas(),l=a.getContext("2d");this.emit("canvas",a);const d=h.map((t,e)=>()=>new Promise(o=>{this.video.oncanplay=()=>{l.drawImage(this.video,t.x,t.y,i,r),a.toBlob(t=>{this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl),this.thumbnailUrl=URL.createObjectURL(t),this.emit("update",this.thumbnailUrl,(e+1)/n),this.video.oncanplay=null,o()})},this.video.currentTime=t.time}));return this.processing=!0,(p=d,p.reduce((t,e)=>t.then(e),Promise.resolve())).then(()=>{this.processing=!1,this.emit("done")}).catch(t=>{throw this.processing=!1,this.emit("error",t.message),t});var p}creatScreenshotDate(){const{number:t,width:e,height:i,column:n,begin:o}=this.option,s=this.duration/t,r=[o+s];for(;r.length<t;){const t=r[r.length-1];r.push(t+s)}return r.map((t,o)=>({time:t-s/2,x:o%n*e,y:Math.floor(o/n)*i}))}creatCanvas(){const{number:t,width:e,height:i,column:n}=this.option,o=document.createElement("canvas"),s=o.getContext("2d");return o.width=e*n,o.height=Math.ceil(t/n)*i+30,s.fillStyle="black",s.fillRect(0,0,o.width,o.height),s.font="14px Georgia",s.fillStyle="#fff",s.fillText(`From: https://artplayer.org/, Number: ${t}, Width: ${e}, Height: ${i}, Column: ${n}`,10,o.height-11),o}download(){this.errorHandle(this.file&&this.thumbnailUrl,"Download does not seem to be ready, please create previeLine truncated
|
||||
!function(t,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"==typeof define&&define.amd?(t.ArtplayerToolThumbnail=e(),define(function(){return t.ArtplayerToolThumbnail})):(t="undefined"!==typeof globalThis?globalThis:t||self).ArtplayerToolThumbnail=e()}(this,function(){"use strict";class t{on(t,e,i){const n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:i}),this}once(t,e,i){const n=this;function o(...s){n.off(t,o),e.apply(i,s)}return o._=e,this.on(t,o,i)}emit(t,...e){const i=((this.e||(this.e={}))[t]||[]).slice();for(let n=0;n<i.length;n+=1)i[n].fn.apply(i[n].ctx,e);return this}off(t,e){const i=this.e||(this.e={}),n=i[t],o=[];if(n&&e)for(let s=0,r=n.length;s<r;s+=1)n[s].fn!==e&&n[s].fn._!==e&&o.push(n[s]);return o.length?i[t]=o:delete i[t],this}}function e(t,e,i){return Math.max(Math.min(t,Math.max(e,i)),Math.min(e,i))}const i=new WeakMap;function n(t){let e;for(const[n,o]of t.listeners.splice(0))try{t.input.removeEventListener(n,o)}catch(i){e||(e=i)}if(t.wrapper){try{t.input.parentNode&&t.input.parentNode.removeChild(t.input)}catch(i){e||(e=i)}"relative"===t.wrapper.style.position&&(t.wrapper.style.position=t.position)}if(e)throw e}function o(t,e){try{for(const[i,n]of e)t.listeners.push([i,n]),t.input.addEventListener(i,n)}catch(i){try{n(t)}catch(o){}throw i}}function s(t){const e=i.get(t);e&&(i.delete(t),n(e))}const r=new WeakSet;class h extends t{constructor(t={}){var e;super(),this.processing=!1,this.option={};try{this.setup(Object.assign({},h.DEFAULTS,t)),this.video=h.creatVideo(),this.duration=0,this.inputChange=this.inputChange.bind(this),this.ondrop=this.ondrop.bind(this),function(t,e){const n=i.get(t);n.callbacks=[["change",t.inputChange],["dragover",e],["drop",t.ondrop]],o(n,n.callbacks)}(this,h.ondragover)}catch(n){try{s(this)}catch(r){}try{(null==(e=this.video)?void 0:e.parentNode)&&this.video.parentNode.removeChild(this.video)}catch(r){}throw n}}static get DEFAULTS(){return{number:60,width:160,height:90,column:10,begin:0,end:Number.NaN}}static ondragover(t){t.preventDefault()}ondrop(t){if(r.has(this))return;t.preventDefault();const e=t.dataTransfer.files[0];this.loadVideo(e)}setup(t={}){return r.has(this)||(this.option=function(t,s){const r=Object.assign({},t.option,s),h=r.fileInput;t.errorHandle(h instanceof Element,"The 'fileInput' is not a Element");for(const e of["number","width","column","begin","end"])t.errorHandle("number"===typeof r[e],`The '${e}' is not a number`);r.number=e(r.number,10,1e3),r.width=e(r.width,10,1e3),r.column=e(r.column,1,1e3);const a=i.get(t);if(a&&(h===a.input||h===a.wrapper))return r.fileInput=a.input,r;const l={input:h,wrapper:null,position:"",listeners:[],callbacks:(null==a?void 0:a.callbacks)||null};try{"INPUT"===h.tagName&&"file"===h.type||(l.wrapper=h,l.position=h.style.position,l.input=document.createElement("input"),l.input.type="file",Object.assign(l.input.style,{position:"absolute",width:"100%",height:"100%",left:"0",top:"0",right:"0",bottom:"0",opacity:"0"}),h.style.position="relative",h.appendChild(l.input)),l.callbacks&&o(l,l.callbacks)}catch(c){try{n(l)}catch(d){}throw c}return r.fileInput=l.input,i.set(t,l),t.option=r,a&&n(a),r}(this,t)),this}static creatVideo(){const t=document.createElement("video");t.style.position="absolute",t.style.top="-9999px",t.style.left="-9999px",t.muted=!0,t.controls=!0;try{document.body.appendChild(t)}catch(e){throw t.parentNode&&t.parentNode.removeChild(t),e}return t}inputChange(t){if(r.has(this))return;const e=this.option.fileInput.files[0];this.loadVideo(e),t.target.value=""}loadVideo(t){if(t&&!r.has(this)){const e=this.video.canPlayType(t.type);this.errorHandle("maybe"===e||"probably"===e,`Playback of this file format is not supported: ${t.type}`);const i=URL.createObjectURL(t);this.videoUrl=i,this.file=t,this.emit("file",this.file),this.video.src=i,this.emit("video",this.video)}}start(){if(!this.video.duration)return(t=1e3,new Promise(e=>setTimeout(e,t))).then(()=>this.start());var t;const{width:i,number:n,begin:o,end:s}=this.option,r=this.video.videoHeight/this.video.videoWidth*i;this.option.height=r,this.option.begin=e(o,0,this.video.duration),this.option.end=e(s||this.video.duration,o,this.video.duration),this.errorHandle(this.option.end>this.option.begin,"End time must be greater than the start time"),this.duration=this.option.end-this.option.begin,this.density=n/this.duration,this.errorHandle(this.file&&this.video,"Please select the video file first"),this.errorHandle(!this.processing,"There is currently a task in progress, please wait a moment..."),this.errorHandle(this.density<=1,`The preview density cannot be greater than 1, but got ${this.density}`);const h=this.creatScreenshotDate(),a=this.creatCanvas(),l=a.getContext("2d");this.emit("canvas",a);const c=h.map((t,e)=>()=>new Promise(o=>{this.video.oncanplay=()=>{l.drawImage(this.video,t.x,t.y,i,r),a.toBlob(t=>{this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl),this.thumbnailUrl=URL.createObjectURL(t),tLine truncated
|
||||
@@ -58,19 +58,166 @@ function getFileName(name) {
|
||||
function clamp(num, a, b) {
|
||||
return Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
|
||||
}
|
||||
const inputs = /* @__PURE__ */ new WeakMap();
|
||||
function release(record) {
|
||||
let failure;
|
||||
for (const [name, callback] of record.listeners.splice(0)) {
|
||||
try {
|
||||
record.input.removeEventListener(name, callback);
|
||||
} catch (error) {
|
||||
failure || (failure = error);
|
||||
}
|
||||
}
|
||||
if (record.wrapper) {
|
||||
try {
|
||||
if (record.input.parentNode)
|
||||
record.input.parentNode.removeChild(record.input);
|
||||
} catch (error) {
|
||||
failure || (failure = error);
|
||||
}
|
||||
if (record.wrapper.style.position === "relative")
|
||||
record.wrapper.style.position = record.position;
|
||||
}
|
||||
if (failure)
|
||||
throw failure;
|
||||
}
|
||||
function connect(record, callbacks) {
|
||||
try {
|
||||
for (const [name, callback] of callbacks) {
|
||||
record.listeners.push([name, callback]);
|
||||
record.input.addEventListener(name, callback);
|
||||
}
|
||||
} catch (error) {
|
||||
try {
|
||||
release(record);
|
||||
} catch {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function setupInput(tool, patch) {
|
||||
const option = Object.assign({}, tool.option, patch);
|
||||
const target = option.fileInput;
|
||||
tool.errorHandle(target instanceof Element, "The 'fileInput' is not a Element");
|
||||
for (const name of ["number", "width", "column", "begin", "end"])
|
||||
tool.errorHandle(typeof option[name] === "number", `The '${name}' is not a number`);
|
||||
option.number = clamp(option.number, 10, 1e3);
|
||||
option.width = clamp(option.width, 10, 1e3);
|
||||
option.column = clamp(option.column, 1, 1e3);
|
||||
const previous = inputs.get(tool);
|
||||
if (previous && (target === previous.input || target === previous.wrapper)) {
|
||||
option.fileInput = previous.input;
|
||||
return option;
|
||||
}
|
||||
const record = { input: target, wrapper: null, position: "", listeners: [], callbacks: previous?.callbacks || null };
|
||||
try {
|
||||
if (!(target.tagName === "INPUT" && target.type === "file")) {
|
||||
record.wrapper = target;
|
||||
record.position = target.style.position;
|
||||
record.input = document.createElement("input");
|
||||
record.input.type = "file";
|
||||
Object.assign(record.input.style, { position: "absolute", width: "100%", height: "100%", left: "0", top: "0", right: "0", bottom: "0", opacity: "0" });
|
||||
target.style.position = "relative";
|
||||
target.appendChild(record.input);
|
||||
}
|
||||
if (record.callbacks)
|
||||
connect(record, record.callbacks);
|
||||
} catch (error) {
|
||||
try {
|
||||
release(record);
|
||||
} catch {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
option.fileInput = record.input;
|
||||
inputs.set(tool, record);
|
||||
tool.option = option;
|
||||
if (previous)
|
||||
release(previous);
|
||||
return option;
|
||||
}
|
||||
function connectInput(tool, dragover) {
|
||||
const record = inputs.get(tool);
|
||||
record.callbacks = [["change", tool.inputChange], ["dragover", dragover], ["drop", tool.ondrop]];
|
||||
connect(record, record.callbacks);
|
||||
}
|
||||
function releaseInput(tool) {
|
||||
const record = inputs.get(tool);
|
||||
if (!record)
|
||||
return;
|
||||
inputs.delete(tool);
|
||||
release(record);
|
||||
}
|
||||
function screenshotPoints(option, duration) {
|
||||
const { number, width, height, column, begin } = option;
|
||||
const timeGap = duration / number;
|
||||
const timePoints = [begin + timeGap];
|
||||
while (timePoints.length < number) {
|
||||
const last = timePoints[timePoints.length - 1];
|
||||
timePoints.push(last + timeGap);
|
||||
}
|
||||
return timePoints.map((item, index) => ({
|
||||
time: item - timeGap / 2,
|
||||
x: index % column * width,
|
||||
y: Math.floor(index / column) * height
|
||||
}));
|
||||
}
|
||||
function createSheet(option) {
|
||||
const { number, width, height, column } = option;
|
||||
const canvas = document.createElement("canvas");
|
||||
const context = canvas.getContext("2d");
|
||||
canvas.width = width * column;
|
||||
canvas.height = Math.ceil(number / column) * height + 30;
|
||||
context.fillStyle = "black";
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
context.font = "14px Georgia";
|
||||
context.fillStyle = "#fff";
|
||||
context.fillText(
|
||||
`From: https://artplayer.org/, Number: ${number}, Width: ${width}, Height: ${height}, Column: ${column}`,
|
||||
10,
|
||||
canvas.height - 11
|
||||
);
|
||||
return canvas;
|
||||
}
|
||||
function downloadSheet(file, url) {
|
||||
const link = document.createElement("a");
|
||||
const name = `${getFileName(file.name)}.png`;
|
||||
link.download = name;
|
||||
link.href = url;
|
||||
try {
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
} finally {
|
||||
if (link.parentNode)
|
||||
link.parentNode.removeChild(link);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
const destroyed = /* @__PURE__ */ new WeakSet();
|
||||
class ArtplayerToolThumbnail extends Emitter {
|
||||
constructor(option = {}) {
|
||||
super();
|
||||
this.processing = false;
|
||||
this.option = {};
|
||||
this.setup(Object.assign({}, ArtplayerToolThumbnail.DEFAULTS, option));
|
||||
this.video = ArtplayerToolThumbnail.creatVideo();
|
||||
this.duration = 0;
|
||||
this.inputChange = this.inputChange.bind(this);
|
||||
this.ondrop = this.ondrop.bind(this);
|
||||
this.option.fileInput.addEventListener("change", this.inputChange);
|
||||
this.option.fileInput.addEventListener("dragover", ArtplayerToolThumbnail.ondragover);
|
||||
this.option.fileInput.addEventListener("drop", ArtplayerToolThumbnail.ondrop);
|
||||
try {
|
||||
this.setup(Object.assign({}, ArtplayerToolThumbnail.DEFAULTS, option));
|
||||
this.video = ArtplayerToolThumbnail.creatVideo();
|
||||
this.duration = 0;
|
||||
this.inputChange = this.inputChange.bind(this);
|
||||
this.ondrop = this.ondrop.bind(this);
|
||||
connectInput(this, ArtplayerToolThumbnail.ondragover);
|
||||
} catch (error) {
|
||||
try {
|
||||
releaseInput(this);
|
||||
} catch {
|
||||
}
|
||||
try {
|
||||
if (this.video?.parentNode)
|
||||
this.video.parentNode.removeChild(this.video);
|
||||
} catch {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
static get DEFAULTS() {
|
||||
return {
|
||||
@@ -86,35 +233,15 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
event.preventDefault();
|
||||
}
|
||||
ondrop(event) {
|
||||
if (destroyed.has(this))
|
||||
return;
|
||||
event.preventDefault();
|
||||
const file = event.dataTransfer.files[0];
|
||||
this.loadVideo(file);
|
||||
}
|
||||
setup(option = {}) {
|
||||
this.option = Object.assign({}, this.option, option);
|
||||
const { fileInput, number, width, column } = this.option;
|
||||
this.errorHandle(fileInput instanceof Element, "The 'fileInput' is not a Element");
|
||||
if (!(fileInput.tagName === "INPUT" && fileInput.type === "file")) {
|
||||
fileInput.style.position = "relative";
|
||||
const newFileInput = document.createElement("input");
|
||||
newFileInput.type = "file";
|
||||
newFileInput.style.position = "absolute";
|
||||
newFileInput.style.width = "100%";
|
||||
newFileInput.style.height = "100%";
|
||||
newFileInput.style.left = "0";
|
||||
newFileInput.style.top = "0";
|
||||
newFileInput.style.right = "0";
|
||||
newFileInput.style.bottom = "0";
|
||||
newFileInput.style.opacity = "0";
|
||||
fileInput.appendChild(newFileInput);
|
||||
this.option.fileInput = newFileInput;
|
||||
}
|
||||
["number", "width", "column", "begin", "end"].forEach((item) => {
|
||||
this.errorHandle(typeof this.option[item] === "number", `The '${item}' is not a number`);
|
||||
});
|
||||
this.option.number = clamp(number, 10, 1e3);
|
||||
this.option.width = clamp(width, 10, 1e3);
|
||||
this.option.column = clamp(column, 1, 1e3);
|
||||
if (!destroyed.has(this))
|
||||
this.option = setupInput(this, option);
|
||||
return this;
|
||||
}
|
||||
static creatVideo() {
|
||||
@@ -124,16 +251,24 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
video.style.left = "-9999px";
|
||||
video.muted = true;
|
||||
video.controls = true;
|
||||
document.body.appendChild(video);
|
||||
try {
|
||||
document.body.appendChild(video);
|
||||
} catch (error) {
|
||||
if (video.parentNode)
|
||||
video.parentNode.removeChild(video);
|
||||
throw error;
|
||||
}
|
||||
return video;
|
||||
}
|
||||
inputChange(event) {
|
||||
if (destroyed.has(this))
|
||||
return;
|
||||
const file = this.option.fileInput.files[0];
|
||||
this.loadVideo(file);
|
||||
event.target.value = "";
|
||||
}
|
||||
loadVideo(file) {
|
||||
if (file) {
|
||||
if (file && !destroyed.has(this)) {
|
||||
const canPlayType = this.video.canPlayType(file.type);
|
||||
this.errorHandle(
|
||||
canPlayType === "maybe" || canPlayType === "probably",
|
||||
@@ -193,35 +328,10 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
});
|
||||
}
|
||||
creatScreenshotDate() {
|
||||
const { number, width, height, column, begin } = this.option;
|
||||
const timeGap = this.duration / number;
|
||||
const timePoints = [begin + timeGap];
|
||||
while (timePoints.length < number) {
|
||||
const last = timePoints[timePoints.length - 1];
|
||||
timePoints.push(last + timeGap);
|
||||
}
|
||||
return timePoints.map((item, index) => ({
|
||||
time: item - timeGap / 2,
|
||||
x: index % column * width,
|
||||
y: Math.floor(index / column) * height
|
||||
}));
|
||||
return screenshotPoints(this.option, this.duration);
|
||||
}
|
||||
creatCanvas() {
|
||||
const { number, width, height, column } = this.option;
|
||||
const canvas = document.createElement("canvas");
|
||||
const context2D = canvas.getContext("2d");
|
||||
canvas.width = width * column;
|
||||
canvas.height = Math.ceil(number / column) * height + 30;
|
||||
context2D.fillStyle = "black";
|
||||
context2D.fillRect(0, 0, canvas.width, canvas.height);
|
||||
context2D.font = "14px Georgia";
|
||||
context2D.fillStyle = "#fff";
|
||||
context2D.fillText(
|
||||
`From: https://artplayer.org/, Number: ${number}, Width: ${width}, Height: ${height}, Column: ${column}`,
|
||||
10,
|
||||
canvas.height - 11
|
||||
);
|
||||
return canvas;
|
||||
return createSheet(this.option);
|
||||
}
|
||||
download() {
|
||||
this.errorHandle(
|
||||
@@ -229,13 +339,7 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
"Download does not seem to be ready, please create preview first"
|
||||
);
|
||||
this.errorHandle(!this.processing, "There is currently a task in progress, please wait a moment...");
|
||||
const elink = document.createElement("a");
|
||||
const name = `${getFileName(this.file.name)}.png`;
|
||||
elink.download = name;
|
||||
elink.href = this.thumbnailUrl;
|
||||
document.body.appendChild(elink);
|
||||
elink.click();
|
||||
document.body.removeChild(elink);
|
||||
const name = downloadSheet(this.file, this.thumbnailUrl);
|
||||
this.emit("download", name);
|
||||
return this;
|
||||
}
|
||||
@@ -246,17 +350,25 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
}
|
||||
}
|
||||
destroy() {
|
||||
this.option.fileInput.removeEventListener("change", this.inputChange);
|
||||
this.option.fileInput.removeEventListener("dragover", ArtplayerToolThumbnail.ondragover);
|
||||
this.option.fileInput.removeEventListener("drop", ArtplayerToolThumbnail.ondrop);
|
||||
document.body.removeChild(this.video);
|
||||
if (this.videoUrl) {
|
||||
URL.revokeObjectURL(this.videoUrl);
|
||||
if (destroyed.has(this))
|
||||
return;
|
||||
destroyed.add(this);
|
||||
let failure;
|
||||
for (const cleanup of [
|
||||
() => releaseInput(this),
|
||||
() => this.video.parentNode?.removeChild(this.video),
|
||||
() => this.videoUrl && URL.revokeObjectURL(this.videoUrl),
|
||||
() => this.thumbnailUrl && URL.revokeObjectURL(this.thumbnailUrl),
|
||||
() => this.emit("destroy")
|
||||
]) {
|
||||
try {
|
||||
cleanup();
|
||||
} catch (error) {
|
||||
failure || (failure = error);
|
||||
}
|
||||
}
|
||||
if (this.thumbnailUrl) {
|
||||
URL.revokeObjectURL(this.thumbnailUrl);
|
||||
}
|
||||
this.emit("destroy");
|
||||
if (failure)
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
export {
|
||||
|
||||
+2
-2
@@ -51,7 +51,7 @@
|
||||
"ci:build": "yarn build:types && yarn build all && yarn build:i18n && yarn build:ts && yarn build:docs && yarn test:imports",
|
||||
"test:imports": "node --test test/esm.test.js test/i18n.test.js test/ssr.test.js",
|
||||
"typecheck": "node scripts/typecheck.mjs",
|
||||
"test:unit": "node --test test/thumbnail.test.js test/iframe-navigation.test.js test/iframe-boundaries.test.js test/iframe-lifecycle.test.js test/iframe.test.js test/mediabunny.test.js test/mediabunny-shim.test.js test/mediabunny-coordination.test.js test/mediabunny-video.test.js test/mediabunny-audio.test.js test/mediabunny-hls.test.js test/mediabunny-entry.test.js test/mediabunny-capability.test.js test/mediabunny-load.test.js test/mediabunny-input.test.js test/dpip.test.js test/dpip-lifecycle.test.js test/canvas.test.js test/canvas-lifecycle.test.js test/ambilight.test.js test/ambilight-lifecycle.test.js test/ambilight-proxy.test.js test/vast.test.js test/vast-lifecycle.test.js test/ads.test.js test/ads-lifecycle.test.js test/playback.test.js test/dash-control.test.js test/dash-contract.test.js test/dash-lifecycle.test.js test/dash-events.test.js test/hls-control.test.js test/audio-track.test.js test/public-behavior.test.js test/helpers.test.js test/chapter.test.js test/utils.test.js test/resource-scope.test.js test/instance-lifecycle.test.js test/options.test.js test/media-hosts.test.js test/plugins.test.js test/source.test.js test/playback-properties.test.js test/media-events.test.js test/template-resources.test.js test/core-vendor.test.js test/component-resources.test.js test/setting-model.test.js test/setting-layout.test.js test/setting-resources.test.js test/subtitle.test.js test/display-native.test.js test/display-video-fullscreen.test.js test/display-pip.test.js test/display-mini.test.js test/display-sizing.test.js test/display-orientation.test.js test/hotkey.test.js test/listener-registry.test.js test/global-events.test.js test/pointer-events.test.js test/gesture.test.js test/event-scheduling.test.js test/notice.test.js test/fast-forward.test.js test/auto-playback.test.js test/builtin-layers.test.js test/prompt-components.test.js test/screenshot.test.js test/thumbnails.test.js test/progress.test.js test/environment.test.js test/storage.test.js test/facade-properties.test.js test/dom-boundaries.test.js test/initialization.test.js test/entry.test.js test/accessibility-button.test.js test/accessibility-focus.test.js test/accessibility-slider.test.js",
|
||||
"test:unit": "node --test test/thumbnail-input.test.js test/thumbnail.test.js test/iframe-navigation.test.js test/iframe-boundaries.test.js test/iframe-lifecycle.test.js test/iframe.test.js test/mediabunny.test.js test/mediabunny-shim.test.js test/mediabunny-coordination.test.js test/mediabunny-video.test.js test/mediabunny-audio.test.js test/mediabunny-hls.test.js test/mediabunny-entry.test.js test/mediabunny-capability.test.js test/mediabunny-load.test.js test/mediabunny-input.test.js test/dpip.test.js test/dpip-lifecycle.test.js test/canvas.test.js test/canvas-lifecycle.test.js test/ambilight.test.js test/ambilight-lifecycle.test.js test/ambilight-proxy.test.js test/vast.test.js test/vast-lifecycle.test.js test/ads.test.js test/ads-lifecycle.test.js test/playback.test.js test/dash-control.test.js test/dash-contract.test.js test/dash-lifecycle.test.js test/dash-events.test.js test/hls-control.test.js test/audio-track.test.js test/public-behavior.test.js test/helpers.test.js test/chapter.test.js test/utils.test.js test/resource-scope.test.js test/instance-lifecycle.test.js test/options.test.js test/media-hosts.test.js test/plugins.test.js test/source.test.js test/playback-properties.test.js test/media-events.test.js test/template-resources.test.js test/core-vendor.test.js test/component-resources.test.js test/setting-model.test.js test/setting-layout.test.js test/setting-resources.test.js test/subtitle.test.js test/display-native.test.js test/display-video-fullscreen.test.js test/display-pip.test.js test/display-mini.test.js test/display-sizing.test.js test/display-orientation.test.js test/hotkey.test.js test/listener-registry.test.js test/global-events.test.js test/pointer-events.test.js test/gesture.test.js test/event-scheduling.test.js test/notice.test.js test/fast-forward.test.js test/auto-playback.test.js test/builtin-layers.test.js test/prompt-components.test.js test/screenshot.test.js test/thumbnails.test.js test/progress.test.js test/environment.test.js test/storage.test.js test/facade-properties.test.js test/dom-boundaries.test.js test/initialization.test.js test/entry.test.js test/accessibility-button.test.js test/accessibility-focus.test.js test/accessibility-slider.test.js",
|
||||
"test:coverage": "node --test test/coverage.test.js && node scripts/coverage.mjs",
|
||||
"test": "yarn test:node && yarn test:baseline",
|
||||
"test:browser": "playwright test",
|
||||
@@ -83,7 +83,7 @@
|
||||
"generate:media:hls": "node scripts/generate-hls-fixture.mjs",
|
||||
"test:iframe": "node --test test/iframe-navigation.test.js test/iframe-boundaries.test.js test/iframe.test.js test/iframe-lifecycle.test.js refactor/scripts/iframe-contract.test.mjs refactor/scripts/iframe-types.test.mjs",
|
||||
"test:iframe-types-package": "node refactor/scripts/iframe-package-types.mjs",
|
||||
"test:thumbnail": "node --test test/thumbnail.test.js refactor/scripts/thumbnail-contract.test.mjs"
|
||||
"test:thumbnail": "node --test test/thumbnail-input.test.js test/thumbnail.test.js refactor/scripts/thumbnail-contract.test.mjs"
|
||||
},
|
||||
"browserslist": "last 1 Chrome version",
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Thumbnail tool maintenance map
|
||||
|
||||
This package is being migrated under PKG-TOOL-THUMB-03. Input ownership and sheet
|
||||
export are separated; extraction/source cancellation is still being implemented.
|
||||
Strict TS and published declaration work belongs to PKG-TOOL-THUMB-04. Do not
|
||||
infer complete migration or release readiness from this checkpoint.
|
||||
|
||||
| File | Responsibility |
|
||||
| --- | --- |
|
||||
| src/index.js | Public class, historical method names, file/video events, current extraction loop and destruction entry |
|
||||
| src/input.js | Option validation/clamps, file-input wrapper creation, listener registration/replacement and release |
|
||||
| src/sheet.js | Midpoint grid, canvas/footer geometry, temporary download anchor |
|
||||
| src/emitter.js | Existing on/once/emit/off semantics; provenance review remains in 04 |
|
||||
| src/utils.js | Existing clamp, filename, sleep and serial-promise helpers |
|
||||
|
||||
The entry delegates to input/sheet modules; neither module imports the entry.
|
||||
Input records live in a private WeakMap, so callers replacing `option` cannot
|
||||
lose ownership of generated inputs/listeners. Normal construction preserves the
|
||||
existing instance-field order and bound inputChange/ondrop methods. DEFAULTS,
|
||||
file/video event order, public method spelling and return values stay unchanged.
|
||||
|
||||
Input setup validates options before changing DOM or committed options. A wrapper
|
||||
receives one owned input; repeated setup with that wrapper reuses it. Replacement
|
||||
installs the new listeners before releasing the old input. A failed new listener
|
||||
installation rolls back its partial listeners/DOM. Explicit caller-provided file
|
||||
inputs are never removed. Generated inputs are removed and the wrapper's previous
|
||||
position is restored only if its current position still matches the tool's write.
|
||||
The existing bound ondrop method is now registered correctly.
|
||||
|
||||
Destroy is idempotent and attempts input, video, current URL and destroy-event
|
||||
cleanup even when one step throws; the first cleanup error escapes afterward.
|
||||
Setup/file-input/drop/load calls cannot recreate input/source resources after
|
||||
destruction. The emitter is not globally cleared. This does **not yet** cancel
|
||||
existing extraction timers or late Blob callbacks; pending work and replaced
|
||||
source URLs remain tracked risks for the rest of 03.
|
||||
|
||||
Sheet extraction preserves fractional coordinates, historical `creat*` names,
|
||||
the 30-pixel footer and the filename algorithm. The temporary download anchor is
|
||||
removed even if click throws. Default aspect-derived height and synchronous video
|
||||
events currently match workspace 4.4.0; recovered 3.5.31 differs. See the frozen
|
||||
[contract](../../refactor/baselines/thumbnail-contract.md) before changing defaults.
|
||||
|
||||
## Validation and continuation
|
||||
|
||||
Use Yarn and the repository scripts:
|
||||
|
||||
```sh
|
||||
yarn test:thumbnail
|
||||
yarn build artplayer-tool-thumbnail
|
||||
yarn test:browser test/browser/thumbnail-tool.spec.js test/browser/thumbnail-native.spec.js test/browser/thumbnail-input.spec.js
|
||||
```
|
||||
|
||||
`test/thumbnail-input.test.js` contains candidate input/export regressions; set
|
||||
ARTPLAYER_THUMBNAIL_BASELINE=1 to reproduce failures against frozen workspace
|
||||
main. ARTPLAYER_THUMBNAIL_ARTIFACT selects an actual built artifact for Node and
|
||||
browser candidate checks. `test/thumbnail.test.js` remains immutable-behavior
|
||||
evidence against old implementations, including intentionally reproduced bugs.
|
||||
|
||||
Browser records distinguish actual extraction from native Blob-unavailable
|
||||
controls. Windows WebKit can load tested MP4 files over HTTP but returns error 4
|
||||
for native Blob URLs; this is not successful file extraction. Actual input/DOM
|
||||
cleanup runs on all three engines, while extraction acceptance needs supported
|
||||
Safari/WebKit evidence in 05. The independent tool example is
|
||||
`docs/assets/example/tool.thumbnail.js`, not the external thumbnail plugin example.
|
||||
|
||||
Continue 03 by introducing owned metadata/extraction jobs and source/thumbnail
|
||||
URL cleanup. Add candidate failure/cancellation regressions and preserve old
|
||||
tests; do not change default delay/height policy silently. Then migrate the final
|
||||
module boundaries to strict TS in 04 and verify installed declarations/old paths.
|
||||
See [task plan](../../refactor/plan.md) and [risk ledger](../../refactor/risks.json).
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
Thumbnail tool for ArtPlayer
|
||||
|
||||
Implementation and migration notes: [ARCHITECTURE.md](./ARCHITECTURE.md).
|
||||
|
||||
## Demo
|
||||
|
||||
[https://artplayer.org](https://artplayer.org/?libs=./uncompiled/artplayer-tool-thumbnail/index.js&example=thumbnail)
|
||||
|
||||
@@ -4,4 +4,4 @@
|
||||
* (c) 2017-2026 Harvey Zhao
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
!function(t,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"==typeof define&&define.amd?(t.ArtplayerToolThumbnail=e(),define(function(){return t.ArtplayerToolThumbnail})):(t="undefined"!==typeof globalThis?globalThis:t||self).ArtplayerToolThumbnail=e()}(this,function(){"use strict";class t{on(t,e,i){const n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:i}),this}once(t,e,i){const n=this;function o(...s){n.off(t,o),e.apply(i,s)}return o._=e,this.on(t,o,i)}emit(t,...e){const i=((this.e||(this.e={}))[t]||[]).slice();for(let n=0;n<i.length;n+=1)i[n].fn.apply(i[n].ctx,e);return this}off(t,e){const i=this.e||(this.e={}),n=i[t],o=[];if(n&&e)for(let s=0,r=n.length;s<r;s+=1)n[s].fn!==e&&n[s].fn._!==e&&o.push(n[s]);return o.length?i[t]=o:delete i[t],this}}function e(t,e,i){return Math.max(Math.min(t,Math.max(e,i)),Math.min(e,i))}class i extends t{constructor(t={}){super(),this.processing=!1,this.option={},this.setup(Object.assign({},i.DEFAULTS,t)),this.video=i.creatVideo(),this.duration=0,this.inputChange=this.inputChange.bind(this),this.ondrop=this.ondrop.bind(this),this.option.fileInput.addEventListener("change",this.inputChange),this.option.fileInput.addEventListener("dragover",i.ondragover),this.option.fileInput.addEventListener("drop",i.ondrop)}static get DEFAULTS(){return{number:60,width:160,height:90,column:10,begin:0,end:Number.NaN}}static ondragover(t){t.preventDefault()}ondrop(t){t.preventDefault();const e=t.dataTransfer.files[0];this.loadVideo(e)}setup(t={}){this.option=Object.assign({},this.option,t);const{fileInput:i,number:n,width:o,column:s}=this.option;if(this.errorHandle(i instanceof Element,"The 'fileInput' is not a Element"),"INPUT"!==i.tagName||"file"!==i.type){i.style.position="relative";const t=document.createElement("input");t.type="file",t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.right="0",t.style.bottom="0",t.style.opacity="0",i.appendChild(t),this.option.fileInput=t}return["number","width","column","begin","end"].forEach(t=>{this.errorHandle("number"===typeof this.option[t],`The '${t}' is not a number`)}),this.option.number=e(n,10,1e3),this.option.width=e(o,10,1e3),this.option.column=e(s,1,1e3),this}static creatVideo(){const t=document.createElement("video");return t.style.position="absolute",t.style.top="-9999px",t.style.left="-9999px",t.muted=!0,t.controls=!0,document.body.appendChild(t),t}inputChange(t){const e=this.option.fileInput.files[0];this.loadVideo(e),t.target.value=""}loadVideo(t){if(t){const e=this.video.canPlayType(t.type);this.errorHandle("maybe"===e||"probably"===e,`Playback of this file format is not supported: ${t.type}`);const i=URL.createObjectURL(t);this.videoUrl=i,this.file=t,this.emit("file",this.file),this.video.src=i,this.emit("video",this.video)}}start(){if(!this.video.duration)return(t=1e3,new Promise(e=>setTimeout(e,t))).then(()=>this.start());var t;const{width:i,number:n,begin:o,end:s}=this.option,r=this.video.videoHeight/this.video.videoWidth*i;this.option.height=r,this.option.begin=e(o,0,this.video.duration),this.option.end=e(s||this.video.duration,o,this.video.duration),this.errorHandle(this.option.end>this.option.begin,"End time must be greater than the start time"),this.duration=this.option.end-this.option.begin,this.density=n/this.duration,this.errorHandle(this.file&&this.video,"Please select the video file first"),this.errorHandle(!this.processing,"There is currently a task in progress, please wait a moment..."),this.errorHandle(this.density<=1,`The preview density cannot be greater than 1, but got ${this.density}`);const h=this.creatScreenshotDate(),a=this.creatCanvas(),l=a.getContext("2d");this.emit("canvas",a);const d=h.map((t,e)=>()=>new Promise(o=>{this.video.oncanplay=()=>{l.drawImage(this.video,t.x,t.y,i,r),a.toBlob(t=>{this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl),this.thumbnailUrl=URL.createObjectURL(t),this.emit("update",this.thumbnailUrl,(e+1)/n),this.video.oncanplay=null,o()})},this.video.currentTime=t.time}));return this.processing=!0,(p=d,p.reduce((t,e)=>t.then(e),Promise.resolve())).then(()=>{this.processing=!1,this.emit("done")}).catch(t=>{throw this.processing=!1,this.emit("error",t.message),t});var p}creatScreenshotDate(){const{number:t,width:e,height:i,column:n,begin:o}=this.option,s=this.duration/t,r=[o+s];for(;r.length<t;){const t=r[r.length-1];r.push(t+s)}return r.map((t,o)=>({time:t-s/2,x:o%n*e,y:Math.floor(o/n)*i}))}creatCanvas(){const{number:t,width:e,height:i,column:n}=this.option,o=document.createElement("canvas"),s=o.getContext("2d");return o.width=e*n,o.height=Math.ceil(t/n)*i+30,s.fillStyle="black",s.fillRect(0,0,o.width,o.height),s.font="14px Georgia",s.fillStyle="#fff",s.fillText(`From: https://artplayer.org/, Number: ${t}, Width: ${e}, Height: ${i}, Column: ${n}`,10,o.height-11),o}download(){this.errorHandle(this.file&&this.thumbnailUrl,"Download does not seem to be ready, please create previeLine truncated
|
||||
!function(t,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"==typeof define&&define.amd?(t.ArtplayerToolThumbnail=e(),define(function(){return t.ArtplayerToolThumbnail})):(t="undefined"!==typeof globalThis?globalThis:t||self).ArtplayerToolThumbnail=e()}(this,function(){"use strict";class t{on(t,e,i){const n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:i}),this}once(t,e,i){const n=this;function o(...s){n.off(t,o),e.apply(i,s)}return o._=e,this.on(t,o,i)}emit(t,...e){const i=((this.e||(this.e={}))[t]||[]).slice();for(let n=0;n<i.length;n+=1)i[n].fn.apply(i[n].ctx,e);return this}off(t,e){const i=this.e||(this.e={}),n=i[t],o=[];if(n&&e)for(let s=0,r=n.length;s<r;s+=1)n[s].fn!==e&&n[s].fn._!==e&&o.push(n[s]);return o.length?i[t]=o:delete i[t],this}}function e(t,e,i){return Math.max(Math.min(t,Math.max(e,i)),Math.min(e,i))}const i=new WeakMap;function n(t){let e;for(const[n,o]of t.listeners.splice(0))try{t.input.removeEventListener(n,o)}catch(i){e||(e=i)}if(t.wrapper){try{t.input.parentNode&&t.input.parentNode.removeChild(t.input)}catch(i){e||(e=i)}"relative"===t.wrapper.style.position&&(t.wrapper.style.position=t.position)}if(e)throw e}function o(t,e){try{for(const[i,n]of e)t.listeners.push([i,n]),t.input.addEventListener(i,n)}catch(i){try{n(t)}catch{}throw i}}function s(t){const e=i.get(t);e&&(i.delete(t),n(e))}const r=new WeakSet;class h extends t{constructor(t={}){super(),this.processing=!1,this.option={};try{this.setup(Object.assign({},h.DEFAULTS,t)),this.video=h.creatVideo(),this.duration=0,this.inputChange=this.inputChange.bind(this),this.ondrop=this.ondrop.bind(this),function(t,e){const n=i.get(t);n.callbacks=[["change",t.inputChange],["dragover",e],["drop",t.ondrop]],o(n,n.callbacks)}(this,h.ondragover)}catch(e){try{s(this)}catch{}try{this.video?.parentNode&&this.video.parentNode.removeChild(this.video)}catch{}throw e}}static get DEFAULTS(){return{number:60,width:160,height:90,column:10,begin:0,end:Number.NaN}}static ondragover(t){t.preventDefault()}ondrop(t){if(r.has(this))return;t.preventDefault();const e=t.dataTransfer.files[0];this.loadVideo(e)}setup(t={}){return r.has(this)||(this.option=function(t,s){const r=Object.assign({},t.option,s),h=r.fileInput;t.errorHandle(h instanceof Element,"The 'fileInput' is not a Element");for(const e of["number","width","column","begin","end"])t.errorHandle("number"===typeof r[e],`The '${e}' is not a number`);r.number=e(r.number,10,1e3),r.width=e(r.width,10,1e3),r.column=e(r.column,1,1e3);const a=i.get(t);if(a&&(h===a.input||h===a.wrapper))return r.fileInput=a.input,r;const l={input:h,wrapper:null,position:"",listeners:[],callbacks:a?.callbacks||null};try{"INPUT"===h.tagName&&"file"===h.type||(l.wrapper=h,l.position=h.style.position,l.input=document.createElement("input"),l.input.type="file",Object.assign(l.input.style,{position:"absolute",width:"100%",height:"100%",left:"0",top:"0",right:"0",bottom:"0",opacity:"0"}),h.style.position="relative",h.appendChild(l.input)),l.callbacks&&o(l,l.callbacks)}catch(c){try{n(l)}catch{}throw c}return r.fileInput=l.input,i.set(t,l),t.option=r,a&&n(a),r}(this,t)),this}static creatVideo(){const t=document.createElement("video");t.style.position="absolute",t.style.top="-9999px",t.style.left="-9999px",t.muted=!0,t.controls=!0;try{document.body.appendChild(t)}catch(e){throw t.parentNode&&t.parentNode.removeChild(t),e}return t}inputChange(t){if(r.has(this))return;const e=this.option.fileInput.files[0];this.loadVideo(e),t.target.value=""}loadVideo(t){if(t&&!r.has(this)){const e=this.video.canPlayType(t.type);this.errorHandle("maybe"===e||"probably"===e,`Playback of this file format is not supported: ${t.type}`);const i=URL.createObjectURL(t);this.videoUrl=i,this.file=t,this.emit("file",this.file),this.video.src=i,this.emit("video",this.video)}}start(){if(!this.video.duration)return(t=1e3,new Promise(e=>setTimeout(e,t))).then(()=>this.start());var t;const{width:i,number:n,begin:o,end:s}=this.option,r=this.video.videoHeight/this.video.videoWidth*i;this.option.height=r,this.option.begin=e(o,0,this.video.duration),this.option.end=e(s||this.video.duration,o,this.video.duration),this.errorHandle(this.option.end>this.option.begin,"End time must be greater than the start time"),this.duration=this.option.end-this.option.begin,this.density=n/this.duration,this.errorHandle(this.file&&this.video,"Please select the video file first"),this.errorHandle(!this.processing,"There is currently a task in progress, please wait a moment..."),this.errorHandle(this.density<=1,`The preview density cannot be greater than 1, but got ${this.density}`);const h=this.creatScreenshotDate(),a=this.creatCanvas(),l=a.getContext("2d");this.emit("canvas",a);const c=h.map((t,e)=>()=>new Promise(o=>{this.video.oncanplay=()=>{l.drawImage(this.video,t.x,t.y,i,r),a.toBlob(t=>{this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl),this.thumbnailUrl=URL.createObjectURL(t),this.emit("update",this.thumbnailUrl,(e+1)/n),this.videLine truncated
|
||||
@@ -4,4 +4,4 @@
|
||||
* (c) 2017-2026 Harvey Zhao
|
||||
* Released under the MIT License.
|
||||
*/
|
||||
!function(t,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"==typeof define&&define.amd?(t.ArtplayerToolThumbnail=e(),define(function(){return t.ArtplayerToolThumbnail})):(t="undefined"!==typeof globalThis?globalThis:t||self).ArtplayerToolThumbnail=e()}(this,function(){"use strict";class t{on(t,e,i){const n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:i}),this}once(t,e,i){const n=this;function o(...s){n.off(t,o),e.apply(i,s)}return o._=e,this.on(t,o,i)}emit(t,...e){const i=((this.e||(this.e={}))[t]||[]).slice();for(let n=0;n<i.length;n+=1)i[n].fn.apply(i[n].ctx,e);return this}off(t,e){const i=this.e||(this.e={}),n=i[t],o=[];if(n&&e)for(let s=0,r=n.length;s<r;s+=1)n[s].fn!==e&&n[s].fn._!==e&&o.push(n[s]);return o.length?i[t]=o:delete i[t],this}}function e(t,e,i){return Math.max(Math.min(t,Math.max(e,i)),Math.min(e,i))}class i extends t{constructor(t={}){super(),this.processing=!1,this.option={},this.setup(Object.assign({},i.DEFAULTS,t)),this.video=i.creatVideo(),this.duration=0,this.inputChange=this.inputChange.bind(this),this.ondrop=this.ondrop.bind(this),this.option.fileInput.addEventListener("change",this.inputChange),this.option.fileInput.addEventListener("dragover",i.ondragover),this.option.fileInput.addEventListener("drop",i.ondrop)}static get DEFAULTS(){return{number:60,width:160,height:90,column:10,begin:0,end:Number.NaN}}static ondragover(t){t.preventDefault()}ondrop(t){t.preventDefault();const e=t.dataTransfer.files[0];this.loadVideo(e)}setup(t={}){this.option=Object.assign({},this.option,t);const{fileInput:i,number:n,width:o,column:s}=this.option;if(this.errorHandle(i instanceof Element,"The 'fileInput' is not a Element"),"INPUT"!==i.tagName||"file"!==i.type){i.style.position="relative";const t=document.createElement("input");t.type="file",t.style.position="absolute",t.style.width="100%",t.style.height="100%",t.style.left="0",t.style.top="0",t.style.right="0",t.style.bottom="0",t.style.opacity="0",i.appendChild(t),this.option.fileInput=t}return["number","width","column","begin","end"].forEach(t=>{this.errorHandle("number"===typeof this.option[t],`The '${t}' is not a number`)}),this.option.number=e(n,10,1e3),this.option.width=e(o,10,1e3),this.option.column=e(s,1,1e3),this}static creatVideo(){const t=document.createElement("video");return t.style.position="absolute",t.style.top="-9999px",t.style.left="-9999px",t.muted=!0,t.controls=!0,document.body.appendChild(t),t}inputChange(t){const e=this.option.fileInput.files[0];this.loadVideo(e),t.target.value=""}loadVideo(t){if(t){const e=this.video.canPlayType(t.type);this.errorHandle("maybe"===e||"probably"===e,`Playback of this file format is not supported: ${t.type}`);const i=URL.createObjectURL(t);this.videoUrl=i,this.file=t,this.emit("file",this.file),this.video.src=i,this.emit("video",this.video)}}start(){if(!this.video.duration)return(t=1e3,new Promise(e=>setTimeout(e,t))).then(()=>this.start());var t;const{width:i,number:n,begin:o,end:s}=this.option,r=this.video.videoHeight/this.video.videoWidth*i;this.option.height=r,this.option.begin=e(o,0,this.video.duration),this.option.end=e(s||this.video.duration,o,this.video.duration),this.errorHandle(this.option.end>this.option.begin,"End time must be greater than the start time"),this.duration=this.option.end-this.option.begin,this.density=n/this.duration,this.errorHandle(this.file&&this.video,"Please select the video file first"),this.errorHandle(!this.processing,"There is currently a task in progress, please wait a moment..."),this.errorHandle(this.density<=1,`The preview density cannot be greater than 1, but got ${this.density}`);const h=this.creatScreenshotDate(),a=this.creatCanvas(),l=a.getContext("2d");this.emit("canvas",a);const d=h.map((t,e)=>()=>new Promise(o=>{this.video.oncanplay=()=>{l.drawImage(this.video,t.x,t.y,i,r),a.toBlob(t=>{this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl),this.thumbnailUrl=URL.createObjectURL(t),this.emit("update",this.thumbnailUrl,(e+1)/n),this.video.oncanplay=null,o()})},this.video.currentTime=t.time}));return this.processing=!0,(p=d,p.reduce((t,e)=>t.then(e),Promise.resolve())).then(()=>{this.processing=!1,this.emit("done")}).catch(t=>{throw this.processing=!1,this.emit("error",t.message),t});var p}creatScreenshotDate(){const{number:t,width:e,height:i,column:n,begin:o}=this.option,s=this.duration/t,r=[o+s];for(;r.length<t;){const t=r[r.length-1];r.push(t+s)}return r.map((t,o)=>({time:t-s/2,x:o%n*e,y:Math.floor(o/n)*i}))}creatCanvas(){const{number:t,width:e,height:i,column:n}=this.option,o=document.createElement("canvas"),s=o.getContext("2d");return o.width=e*n,o.height=Math.ceil(t/n)*i+30,s.fillStyle="black",s.fillRect(0,0,o.width,o.height),s.font="14px Georgia",s.fillStyle="#fff",s.fillText(`From: https://artplayer.org/, Number: ${t}, Width: ${e}, Height: ${i}, Column: ${n}`,10,o.height-11),o}download(){this.errorHandle(this.file&&this.thumbnailUrl,"Download does not seem to be ready, please create previeLine truncated
|
||||
!function(t,e){"object"===typeof exports&&"undefined"!==typeof module?module.exports=e():"function"==typeof define&&define.amd?(t.ArtplayerToolThumbnail=e(),define(function(){return t.ArtplayerToolThumbnail})):(t="undefined"!==typeof globalThis?globalThis:t||self).ArtplayerToolThumbnail=e()}(this,function(){"use strict";class t{on(t,e,i){const n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:i}),this}once(t,e,i){const n=this;function o(...s){n.off(t,o),e.apply(i,s)}return o._=e,this.on(t,o,i)}emit(t,...e){const i=((this.e||(this.e={}))[t]||[]).slice();for(let n=0;n<i.length;n+=1)i[n].fn.apply(i[n].ctx,e);return this}off(t,e){const i=this.e||(this.e={}),n=i[t],o=[];if(n&&e)for(let s=0,r=n.length;s<r;s+=1)n[s].fn!==e&&n[s].fn._!==e&&o.push(n[s]);return o.length?i[t]=o:delete i[t],this}}function e(t,e,i){return Math.max(Math.min(t,Math.max(e,i)),Math.min(e,i))}const i=new WeakMap;function n(t){let e;for(const[n,o]of t.listeners.splice(0))try{t.input.removeEventListener(n,o)}catch(i){e||(e=i)}if(t.wrapper){try{t.input.parentNode&&t.input.parentNode.removeChild(t.input)}catch(i){e||(e=i)}"relative"===t.wrapper.style.position&&(t.wrapper.style.position=t.position)}if(e)throw e}function o(t,e){try{for(const[i,n]of e)t.listeners.push([i,n]),t.input.addEventListener(i,n)}catch(i){try{n(t)}catch(o){}throw i}}function s(t){const e=i.get(t);e&&(i.delete(t),n(e))}const r=new WeakSet;class h extends t{constructor(t={}){var e;super(),this.processing=!1,this.option={};try{this.setup(Object.assign({},h.DEFAULTS,t)),this.video=h.creatVideo(),this.duration=0,this.inputChange=this.inputChange.bind(this),this.ondrop=this.ondrop.bind(this),function(t,e){const n=i.get(t);n.callbacks=[["change",t.inputChange],["dragover",e],["drop",t.ondrop]],o(n,n.callbacks)}(this,h.ondragover)}catch(n){try{s(this)}catch(r){}try{(null==(e=this.video)?void 0:e.parentNode)&&this.video.parentNode.removeChild(this.video)}catch(r){}throw n}}static get DEFAULTS(){return{number:60,width:160,height:90,column:10,begin:0,end:Number.NaN}}static ondragover(t){t.preventDefault()}ondrop(t){if(r.has(this))return;t.preventDefault();const e=t.dataTransfer.files[0];this.loadVideo(e)}setup(t={}){return r.has(this)||(this.option=function(t,s){const r=Object.assign({},t.option,s),h=r.fileInput;t.errorHandle(h instanceof Element,"The 'fileInput' is not a Element");for(const e of["number","width","column","begin","end"])t.errorHandle("number"===typeof r[e],`The '${e}' is not a number`);r.number=e(r.number,10,1e3),r.width=e(r.width,10,1e3),r.column=e(r.column,1,1e3);const a=i.get(t);if(a&&(h===a.input||h===a.wrapper))return r.fileInput=a.input,r;const l={input:h,wrapper:null,position:"",listeners:[],callbacks:(null==a?void 0:a.callbacks)||null};try{"INPUT"===h.tagName&&"file"===h.type||(l.wrapper=h,l.position=h.style.position,l.input=document.createElement("input"),l.input.type="file",Object.assign(l.input.style,{position:"absolute",width:"100%",height:"100%",left:"0",top:"0",right:"0",bottom:"0",opacity:"0"}),h.style.position="relative",h.appendChild(l.input)),l.callbacks&&o(l,l.callbacks)}catch(c){try{n(l)}catch(d){}throw c}return r.fileInput=l.input,i.set(t,l),t.option=r,a&&n(a),r}(this,t)),this}static creatVideo(){const t=document.createElement("video");t.style.position="absolute",t.style.top="-9999px",t.style.left="-9999px",t.muted=!0,t.controls=!0;try{document.body.appendChild(t)}catch(e){throw t.parentNode&&t.parentNode.removeChild(t),e}return t}inputChange(t){if(r.has(this))return;const e=this.option.fileInput.files[0];this.loadVideo(e),t.target.value=""}loadVideo(t){if(t&&!r.has(this)){const e=this.video.canPlayType(t.type);this.errorHandle("maybe"===e||"probably"===e,`Playback of this file format is not supported: ${t.type}`);const i=URL.createObjectURL(t);this.videoUrl=i,this.file=t,this.emit("file",this.file),this.video.src=i,this.emit("video",this.video)}}start(){if(!this.video.duration)return(t=1e3,new Promise(e=>setTimeout(e,t))).then(()=>this.start());var t;const{width:i,number:n,begin:o,end:s}=this.option,r=this.video.videoHeight/this.video.videoWidth*i;this.option.height=r,this.option.begin=e(o,0,this.video.duration),this.option.end=e(s||this.video.duration,o,this.video.duration),this.errorHandle(this.option.end>this.option.begin,"End time must be greater than the start time"),this.duration=this.option.end-this.option.begin,this.density=n/this.duration,this.errorHandle(this.file&&this.video,"Please select the video file first"),this.errorHandle(!this.processing,"There is currently a task in progress, please wait a moment..."),this.errorHandle(this.density<=1,`The preview density cannot be greater than 1, but got ${this.density}`);const h=this.creatScreenshotDate(),a=this.creatCanvas(),l=a.getContext("2d");this.emit("canvas",a);const c=h.map((t,e)=>()=>new Promise(o=>{this.video.oncanplay=()=>{l.drawImage(this.video,t.x,t.y,i,r),a.toBlob(t=>{this.thumbnailUrl&&URL.revokeObjectURL(this.thumbnailUrl),this.thumbnailUrl=URL.createObjectURL(t),tLine truncated
|
||||
+190
-78
@@ -58,19 +58,166 @@ function getFileName(name) {
|
||||
function clamp(num, a, b) {
|
||||
return Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
|
||||
}
|
||||
const inputs = /* @__PURE__ */ new WeakMap();
|
||||
function release(record) {
|
||||
let failure;
|
||||
for (const [name, callback] of record.listeners.splice(0)) {
|
||||
try {
|
||||
record.input.removeEventListener(name, callback);
|
||||
} catch (error) {
|
||||
failure || (failure = error);
|
||||
}
|
||||
}
|
||||
if (record.wrapper) {
|
||||
try {
|
||||
if (record.input.parentNode)
|
||||
record.input.parentNode.removeChild(record.input);
|
||||
} catch (error) {
|
||||
failure || (failure = error);
|
||||
}
|
||||
if (record.wrapper.style.position === "relative")
|
||||
record.wrapper.style.position = record.position;
|
||||
}
|
||||
if (failure)
|
||||
throw failure;
|
||||
}
|
||||
function connect(record, callbacks) {
|
||||
try {
|
||||
for (const [name, callback] of callbacks) {
|
||||
record.listeners.push([name, callback]);
|
||||
record.input.addEventListener(name, callback);
|
||||
}
|
||||
} catch (error) {
|
||||
try {
|
||||
release(record);
|
||||
} catch {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
function setupInput(tool, patch) {
|
||||
const option = Object.assign({}, tool.option, patch);
|
||||
const target = option.fileInput;
|
||||
tool.errorHandle(target instanceof Element, "The 'fileInput' is not a Element");
|
||||
for (const name of ["number", "width", "column", "begin", "end"])
|
||||
tool.errorHandle(typeof option[name] === "number", `The '${name}' is not a number`);
|
||||
option.number = clamp(option.number, 10, 1e3);
|
||||
option.width = clamp(option.width, 10, 1e3);
|
||||
option.column = clamp(option.column, 1, 1e3);
|
||||
const previous = inputs.get(tool);
|
||||
if (previous && (target === previous.input || target === previous.wrapper)) {
|
||||
option.fileInput = previous.input;
|
||||
return option;
|
||||
}
|
||||
const record = { input: target, wrapper: null, position: "", listeners: [], callbacks: previous?.callbacks || null };
|
||||
try {
|
||||
if (!(target.tagName === "INPUT" && target.type === "file")) {
|
||||
record.wrapper = target;
|
||||
record.position = target.style.position;
|
||||
record.input = document.createElement("input");
|
||||
record.input.type = "file";
|
||||
Object.assign(record.input.style, { position: "absolute", width: "100%", height: "100%", left: "0", top: "0", right: "0", bottom: "0", opacity: "0" });
|
||||
target.style.position = "relative";
|
||||
target.appendChild(record.input);
|
||||
}
|
||||
if (record.callbacks)
|
||||
connect(record, record.callbacks);
|
||||
} catch (error) {
|
||||
try {
|
||||
release(record);
|
||||
} catch {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
option.fileInput = record.input;
|
||||
inputs.set(tool, record);
|
||||
tool.option = option;
|
||||
if (previous)
|
||||
release(previous);
|
||||
return option;
|
||||
}
|
||||
function connectInput(tool, dragover) {
|
||||
const record = inputs.get(tool);
|
||||
record.callbacks = [["change", tool.inputChange], ["dragover", dragover], ["drop", tool.ondrop]];
|
||||
connect(record, record.callbacks);
|
||||
}
|
||||
function releaseInput(tool) {
|
||||
const record = inputs.get(tool);
|
||||
if (!record)
|
||||
return;
|
||||
inputs.delete(tool);
|
||||
release(record);
|
||||
}
|
||||
function screenshotPoints(option, duration) {
|
||||
const { number, width, height, column, begin } = option;
|
||||
const timeGap = duration / number;
|
||||
const timePoints = [begin + timeGap];
|
||||
while (timePoints.length < number) {
|
||||
const last = timePoints[timePoints.length - 1];
|
||||
timePoints.push(last + timeGap);
|
||||
}
|
||||
return timePoints.map((item, index) => ({
|
||||
time: item - timeGap / 2,
|
||||
x: index % column * width,
|
||||
y: Math.floor(index / column) * height
|
||||
}));
|
||||
}
|
||||
function createSheet(option) {
|
||||
const { number, width, height, column } = option;
|
||||
const canvas = document.createElement("canvas");
|
||||
const context = canvas.getContext("2d");
|
||||
canvas.width = width * column;
|
||||
canvas.height = Math.ceil(number / column) * height + 30;
|
||||
context.fillStyle = "black";
|
||||
context.fillRect(0, 0, canvas.width, canvas.height);
|
||||
context.font = "14px Georgia";
|
||||
context.fillStyle = "#fff";
|
||||
context.fillText(
|
||||
`From: https://artplayer.org/, Number: ${number}, Width: ${width}, Height: ${height}, Column: ${column}`,
|
||||
10,
|
||||
canvas.height - 11
|
||||
);
|
||||
return canvas;
|
||||
}
|
||||
function downloadSheet(file, url) {
|
||||
const link = document.createElement("a");
|
||||
const name = `${getFileName(file.name)}.png`;
|
||||
link.download = name;
|
||||
link.href = url;
|
||||
try {
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
} finally {
|
||||
if (link.parentNode)
|
||||
link.parentNode.removeChild(link);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
const destroyed = /* @__PURE__ */ new WeakSet();
|
||||
class ArtplayerToolThumbnail extends Emitter {
|
||||
constructor(option = {}) {
|
||||
super();
|
||||
this.processing = false;
|
||||
this.option = {};
|
||||
this.setup(Object.assign({}, ArtplayerToolThumbnail.DEFAULTS, option));
|
||||
this.video = ArtplayerToolThumbnail.creatVideo();
|
||||
this.duration = 0;
|
||||
this.inputChange = this.inputChange.bind(this);
|
||||
this.ondrop = this.ondrop.bind(this);
|
||||
this.option.fileInput.addEventListener("change", this.inputChange);
|
||||
this.option.fileInput.addEventListener("dragover", ArtplayerToolThumbnail.ondragover);
|
||||
this.option.fileInput.addEventListener("drop", ArtplayerToolThumbnail.ondrop);
|
||||
try {
|
||||
this.setup(Object.assign({}, ArtplayerToolThumbnail.DEFAULTS, option));
|
||||
this.video = ArtplayerToolThumbnail.creatVideo();
|
||||
this.duration = 0;
|
||||
this.inputChange = this.inputChange.bind(this);
|
||||
this.ondrop = this.ondrop.bind(this);
|
||||
connectInput(this, ArtplayerToolThumbnail.ondragover);
|
||||
} catch (error) {
|
||||
try {
|
||||
releaseInput(this);
|
||||
} catch {
|
||||
}
|
||||
try {
|
||||
if (this.video?.parentNode)
|
||||
this.video.parentNode.removeChild(this.video);
|
||||
} catch {
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
static get DEFAULTS() {
|
||||
return {
|
||||
@@ -86,35 +233,15 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
event.preventDefault();
|
||||
}
|
||||
ondrop(event) {
|
||||
if (destroyed.has(this))
|
||||
return;
|
||||
event.preventDefault();
|
||||
const file = event.dataTransfer.files[0];
|
||||
this.loadVideo(file);
|
||||
}
|
||||
setup(option = {}) {
|
||||
this.option = Object.assign({}, this.option, option);
|
||||
const { fileInput, number, width, column } = this.option;
|
||||
this.errorHandle(fileInput instanceof Element, "The 'fileInput' is not a Element");
|
||||
if (!(fileInput.tagName === "INPUT" && fileInput.type === "file")) {
|
||||
fileInput.style.position = "relative";
|
||||
const newFileInput = document.createElement("input");
|
||||
newFileInput.type = "file";
|
||||
newFileInput.style.position = "absolute";
|
||||
newFileInput.style.width = "100%";
|
||||
newFileInput.style.height = "100%";
|
||||
newFileInput.style.left = "0";
|
||||
newFileInput.style.top = "0";
|
||||
newFileInput.style.right = "0";
|
||||
newFileInput.style.bottom = "0";
|
||||
newFileInput.style.opacity = "0";
|
||||
fileInput.appendChild(newFileInput);
|
||||
this.option.fileInput = newFileInput;
|
||||
}
|
||||
["number", "width", "column", "begin", "end"].forEach((item) => {
|
||||
this.errorHandle(typeof this.option[item] === "number", `The '${item}' is not a number`);
|
||||
});
|
||||
this.option.number = clamp(number, 10, 1e3);
|
||||
this.option.width = clamp(width, 10, 1e3);
|
||||
this.option.column = clamp(column, 1, 1e3);
|
||||
if (!destroyed.has(this))
|
||||
this.option = setupInput(this, option);
|
||||
return this;
|
||||
}
|
||||
static creatVideo() {
|
||||
@@ -124,16 +251,24 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
video.style.left = "-9999px";
|
||||
video.muted = true;
|
||||
video.controls = true;
|
||||
document.body.appendChild(video);
|
||||
try {
|
||||
document.body.appendChild(video);
|
||||
} catch (error) {
|
||||
if (video.parentNode)
|
||||
video.parentNode.removeChild(video);
|
||||
throw error;
|
||||
}
|
||||
return video;
|
||||
}
|
||||
inputChange(event) {
|
||||
if (destroyed.has(this))
|
||||
return;
|
||||
const file = this.option.fileInput.files[0];
|
||||
this.loadVideo(file);
|
||||
event.target.value = "";
|
||||
}
|
||||
loadVideo(file) {
|
||||
if (file) {
|
||||
if (file && !destroyed.has(this)) {
|
||||
const canPlayType = this.video.canPlayType(file.type);
|
||||
this.errorHandle(
|
||||
canPlayType === "maybe" || canPlayType === "probably",
|
||||
@@ -193,35 +328,10 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
});
|
||||
}
|
||||
creatScreenshotDate() {
|
||||
const { number, width, height, column, begin } = this.option;
|
||||
const timeGap = this.duration / number;
|
||||
const timePoints = [begin + timeGap];
|
||||
while (timePoints.length < number) {
|
||||
const last = timePoints[timePoints.length - 1];
|
||||
timePoints.push(last + timeGap);
|
||||
}
|
||||
return timePoints.map((item, index) => ({
|
||||
time: item - timeGap / 2,
|
||||
x: index % column * width,
|
||||
y: Math.floor(index / column) * height
|
||||
}));
|
||||
return screenshotPoints(this.option, this.duration);
|
||||
}
|
||||
creatCanvas() {
|
||||
const { number, width, height, column } = this.option;
|
||||
const canvas = document.createElement("canvas");
|
||||
const context2D = canvas.getContext("2d");
|
||||
canvas.width = width * column;
|
||||
canvas.height = Math.ceil(number / column) * height + 30;
|
||||
context2D.fillStyle = "black";
|
||||
context2D.fillRect(0, 0, canvas.width, canvas.height);
|
||||
context2D.font = "14px Georgia";
|
||||
context2D.fillStyle = "#fff";
|
||||
context2D.fillText(
|
||||
`From: https://artplayer.org/, Number: ${number}, Width: ${width}, Height: ${height}, Column: ${column}`,
|
||||
10,
|
||||
canvas.height - 11
|
||||
);
|
||||
return canvas;
|
||||
return createSheet(this.option);
|
||||
}
|
||||
download() {
|
||||
this.errorHandle(
|
||||
@@ -229,13 +339,7 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
"Download does not seem to be ready, please create preview first"
|
||||
);
|
||||
this.errorHandle(!this.processing, "There is currently a task in progress, please wait a moment...");
|
||||
const elink = document.createElement("a");
|
||||
const name = `${getFileName(this.file.name)}.png`;
|
||||
elink.download = name;
|
||||
elink.href = this.thumbnailUrl;
|
||||
document.body.appendChild(elink);
|
||||
elink.click();
|
||||
document.body.removeChild(elink);
|
||||
const name = downloadSheet(this.file, this.thumbnailUrl);
|
||||
this.emit("download", name);
|
||||
return this;
|
||||
}
|
||||
@@ -246,17 +350,25 @@ class ArtplayerToolThumbnail extends Emitter {
|
||||
}
|
||||
}
|
||||
destroy() {
|
||||
this.option.fileInput.removeEventListener("change", this.inputChange);
|
||||
this.option.fileInput.removeEventListener("dragover", ArtplayerToolThumbnail.ondragover);
|
||||
this.option.fileInput.removeEventListener("drop", ArtplayerToolThumbnail.ondrop);
|
||||
document.body.removeChild(this.video);
|
||||
if (this.videoUrl) {
|
||||
URL.revokeObjectURL(this.videoUrl);
|
||||
if (destroyed.has(this))
|
||||
return;
|
||||
destroyed.add(this);
|
||||
let failure;
|
||||
for (const cleanup of [
|
||||
() => releaseInput(this),
|
||||
() => this.video.parentNode?.removeChild(this.video),
|
||||
() => this.videoUrl && URL.revokeObjectURL(this.videoUrl),
|
||||
() => this.thumbnailUrl && URL.revokeObjectURL(this.thumbnailUrl),
|
||||
() => this.emit("destroy")
|
||||
]) {
|
||||
try {
|
||||
cleanup();
|
||||
} catch (error) {
|
||||
failure || (failure = error);
|
||||
}
|
||||
}
|
||||
if (this.thumbnailUrl) {
|
||||
URL.revokeObjectURL(this.thumbnailUrl);
|
||||
}
|
||||
this.emit("destroy");
|
||||
if (failure)
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
export {
|
||||
|
||||
@@ -1,19 +1,35 @@
|
||||
import Emitter from './emitter'
|
||||
import { clamp, getFileName, runPromisesInSeries, sleep } from './utils'
|
||||
import { connectInput, releaseInput, setupInput } from './input'
|
||||
import { createSheet, downloadSheet, screenshotPoints } from './sheet'
|
||||
import { clamp, runPromisesInSeries, sleep } from './utils'
|
||||
|
||||
const destroyed = new WeakSet()
|
||||
|
||||
export default class ArtplayerToolThumbnail extends Emitter {
|
||||
constructor(option = {}) {
|
||||
super()
|
||||
this.processing = false
|
||||
this.option = {}
|
||||
this.setup(Object.assign({}, ArtplayerToolThumbnail.DEFAULTS, option))
|
||||
this.video = ArtplayerToolThumbnail.creatVideo()
|
||||
this.duration = 0
|
||||
this.inputChange = this.inputChange.bind(this)
|
||||
this.ondrop = this.ondrop.bind(this)
|
||||
this.option.fileInput.addEventListener('change', this.inputChange)
|
||||
this.option.fileInput.addEventListener('dragover', ArtplayerToolThumbnail.ondragover)
|
||||
this.option.fileInput.addEventListener('drop', ArtplayerToolThumbnail.ondrop)
|
||||
try {
|
||||
this.setup(Object.assign({}, ArtplayerToolThumbnail.DEFAULTS, option))
|
||||
this.video = ArtplayerToolThumbnail.creatVideo()
|
||||
this.duration = 0
|
||||
this.inputChange = this.inputChange.bind(this)
|
||||
this.ondrop = this.ondrop.bind(this)
|
||||
connectInput(this, ArtplayerToolThumbnail.ondragover)
|
||||
}
|
||||
catch (error) {
|
||||
try {
|
||||
releaseInput(this)
|
||||
}
|
||||
catch {}
|
||||
try {
|
||||
if (this.video?.parentNode)
|
||||
this.video.parentNode.removeChild(this.video)
|
||||
}
|
||||
catch {}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
static get DEFAULTS() {
|
||||
@@ -32,40 +48,16 @@ export default class ArtplayerToolThumbnail extends Emitter {
|
||||
}
|
||||
|
||||
ondrop(event) {
|
||||
if (destroyed.has(this))
|
||||
return
|
||||
event.preventDefault()
|
||||
const file = event.dataTransfer.files[0]
|
||||
this.loadVideo(file)
|
||||
}
|
||||
|
||||
setup(option = {}) {
|
||||
this.option = Object.assign({}, this.option, option)
|
||||
const { fileInput, number, width, column } = this.option
|
||||
|
||||
this.errorHandle(fileInput instanceof Element, 'The \'fileInput\' is not a Element')
|
||||
|
||||
if (!(fileInput.tagName === 'INPUT' && fileInput.type === 'file')) {
|
||||
fileInput.style.position = 'relative'
|
||||
const newFileInput = document.createElement('input')
|
||||
newFileInput.type = 'file'
|
||||
newFileInput.style.position = 'absolute'
|
||||
newFileInput.style.width = '100%'
|
||||
newFileInput.style.height = '100%'
|
||||
newFileInput.style.left = '0'
|
||||
newFileInput.style.top = '0'
|
||||
newFileInput.style.right = '0'
|
||||
newFileInput.style.bottom = '0'
|
||||
newFileInput.style.opacity = '0'
|
||||
fileInput.appendChild(newFileInput)
|
||||
this.option.fileInput = newFileInput
|
||||
}
|
||||
|
||||
['number', 'width', 'column', 'begin', 'end'].forEach((item) => {
|
||||
this.errorHandle(typeof this.option[item] === 'number', `The '${item}' is not a number`)
|
||||
})
|
||||
|
||||
this.option.number = clamp(number, 10, 1000)
|
||||
this.option.width = clamp(width, 10, 1000)
|
||||
this.option.column = clamp(column, 1, 1000)
|
||||
if (!destroyed.has(this))
|
||||
this.option = setupInput(this, option)
|
||||
return this
|
||||
}
|
||||
|
||||
@@ -76,18 +68,27 @@ export default class ArtplayerToolThumbnail extends Emitter {
|
||||
video.style.left = '-9999px'
|
||||
video.muted = true
|
||||
video.controls = true
|
||||
document.body.appendChild(video)
|
||||
try {
|
||||
document.body.appendChild(video)
|
||||
}
|
||||
catch (error) {
|
||||
if (video.parentNode)
|
||||
video.parentNode.removeChild(video)
|
||||
throw error
|
||||
}
|
||||
return video
|
||||
}
|
||||
|
||||
inputChange(event) {
|
||||
if (destroyed.has(this))
|
||||
return
|
||||
const file = this.option.fileInput.files[0]
|
||||
this.loadVideo(file)
|
||||
event.target.value = ''
|
||||
}
|
||||
|
||||
loadVideo(file) {
|
||||
if (file) {
|
||||
if (file && !destroyed.has(this)) {
|
||||
const canPlayType = this.video.canPlayType(file.type)
|
||||
this.errorHandle(
|
||||
canPlayType === 'maybe' || canPlayType === 'probably',
|
||||
@@ -151,36 +152,11 @@ export default class ArtplayerToolThumbnail extends Emitter {
|
||||
}
|
||||
|
||||
creatScreenshotDate() {
|
||||
const { number, width, height, column, begin } = this.option
|
||||
const timeGap = this.duration / number
|
||||
const timePoints = [begin + timeGap]
|
||||
while (timePoints.length < number) {
|
||||
const last = timePoints[timePoints.length - 1]
|
||||
timePoints.push(last + timeGap)
|
||||
}
|
||||
return timePoints.map((item, index) => ({
|
||||
time: item - timeGap / 2,
|
||||
x: (index % column) * width,
|
||||
y: Math.floor(index / column) * height,
|
||||
}))
|
||||
return screenshotPoints(this.option, this.duration)
|
||||
}
|
||||
|
||||
creatCanvas() {
|
||||
const { number, width, height, column } = this.option
|
||||
const canvas = document.createElement('canvas')
|
||||
const context2D = canvas.getContext('2d')
|
||||
canvas.width = width * column
|
||||
canvas.height = Math.ceil(number / column) * height + 30
|
||||
context2D.fillStyle = 'black'
|
||||
context2D.fillRect(0, 0, canvas.width, canvas.height)
|
||||
context2D.font = '14px Georgia'
|
||||
context2D.fillStyle = '#fff'
|
||||
context2D.fillText(
|
||||
`From: https://artplayer.org/, Number: ${number}, Width: ${width}, Height: ${height}, Column: ${column}`,
|
||||
10,
|
||||
canvas.height - 11,
|
||||
)
|
||||
return canvas
|
||||
return createSheet(this.option)
|
||||
}
|
||||
|
||||
download() {
|
||||
@@ -189,13 +165,7 @@ export default class ArtplayerToolThumbnail extends Emitter {
|
||||
'Download does not seem to be ready, please create preview first',
|
||||
)
|
||||
this.errorHandle(!this.processing, 'There is currently a task in progress, please wait a moment...')
|
||||
const elink = document.createElement('a')
|
||||
const name = `${getFileName(this.file.name)}.png`
|
||||
elink.download = name
|
||||
elink.href = this.thumbnailUrl
|
||||
document.body.appendChild(elink)
|
||||
elink.click()
|
||||
document.body.removeChild(elink)
|
||||
const name = downloadSheet(this.file, this.thumbnailUrl)
|
||||
this.emit('download', name)
|
||||
return this
|
||||
}
|
||||
@@ -208,16 +178,23 @@ export default class ArtplayerToolThumbnail extends Emitter {
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.option.fileInput.removeEventListener('change', this.inputChange)
|
||||
this.option.fileInput.removeEventListener('dragover', ArtplayerToolThumbnail.ondragover)
|
||||
this.option.fileInput.removeEventListener('drop', ArtplayerToolThumbnail.ondrop)
|
||||
document.body.removeChild(this.video)
|
||||
if (this.videoUrl) {
|
||||
URL.revokeObjectURL(this.videoUrl)
|
||||
if (destroyed.has(this))
|
||||
return
|
||||
destroyed.add(this)
|
||||
let failure
|
||||
for (const cleanup of [
|
||||
() => releaseInput(this),
|
||||
() => this.video.parentNode?.removeChild(this.video),
|
||||
() => this.videoUrl && URL.revokeObjectURL(this.videoUrl),
|
||||
() => this.thumbnailUrl && URL.revokeObjectURL(this.thumbnailUrl),
|
||||
() => this.emit('destroy'),
|
||||
]) {
|
||||
try {
|
||||
cleanup()
|
||||
}
|
||||
catch (error) { failure ||= error }
|
||||
}
|
||||
if (this.thumbnailUrl) {
|
||||
URL.revokeObjectURL(this.thumbnailUrl)
|
||||
}
|
||||
this.emit('destroy')
|
||||
if (failure)
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import { clamp } from './utils'
|
||||
|
||||
const inputs = new WeakMap()
|
||||
|
||||
function release(record) {
|
||||
let failure
|
||||
for (const [name, callback] of record.listeners.splice(0)) {
|
||||
try {
|
||||
record.input.removeEventListener(name, callback)
|
||||
}
|
||||
catch (error) {
|
||||
failure ||= error
|
||||
}
|
||||
}
|
||||
if (record.wrapper) {
|
||||
try {
|
||||
if (record.input.parentNode)
|
||||
record.input.parentNode.removeChild(record.input)
|
||||
}
|
||||
catch (error) {
|
||||
failure ||= error
|
||||
}
|
||||
if (record.wrapper.style.position === 'relative')
|
||||
record.wrapper.style.position = record.position
|
||||
}
|
||||
if (failure)
|
||||
throw failure
|
||||
}
|
||||
|
||||
function connect(record, callbacks) {
|
||||
try {
|
||||
for (const [name, callback] of callbacks) {
|
||||
record.listeners.push([name, callback])
|
||||
record.input.addEventListener(name, callback)
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
try {
|
||||
release(record)
|
||||
}
|
||||
catch {}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export function setupInput(tool, patch) {
|
||||
const option = Object.assign({}, tool.option, patch)
|
||||
const target = option.fileInput
|
||||
tool.errorHandle(target instanceof Element, 'The \'fileInput\' is not a Element')
|
||||
for (const name of ['number', 'width', 'column', 'begin', 'end'])
|
||||
tool.errorHandle(typeof option[name] === 'number', `The '${name}' is not a number`)
|
||||
option.number = clamp(option.number, 10, 1000)
|
||||
option.width = clamp(option.width, 10, 1000)
|
||||
option.column = clamp(option.column, 1, 1000)
|
||||
|
||||
const previous = inputs.get(tool)
|
||||
if (previous && (target === previous.input || target === previous.wrapper)) {
|
||||
option.fileInput = previous.input
|
||||
return option
|
||||
}
|
||||
const record = { input: target, wrapper: null, position: '', listeners: [], callbacks: previous?.callbacks || null }
|
||||
try {
|
||||
if (!(target.tagName === 'INPUT' && target.type === 'file')) {
|
||||
record.wrapper = target
|
||||
record.position = target.style.position
|
||||
record.input = document.createElement('input')
|
||||
record.input.type = 'file'
|
||||
Object.assign(record.input.style, { position: 'absolute', width: '100%', height: '100%', left: '0', top: '0', right: '0', bottom: '0', opacity: '0' })
|
||||
target.style.position = 'relative'
|
||||
target.appendChild(record.input)
|
||||
}
|
||||
if (record.callbacks)
|
||||
connect(record, record.callbacks)
|
||||
}
|
||||
catch (error) {
|
||||
try {
|
||||
release(record)
|
||||
}
|
||||
catch {}
|
||||
throw error
|
||||
}
|
||||
option.fileInput = record.input
|
||||
inputs.set(tool, record)
|
||||
tool.option = option
|
||||
if (previous)
|
||||
release(previous)
|
||||
return option
|
||||
}
|
||||
|
||||
export function connectInput(tool, dragover) {
|
||||
const record = inputs.get(tool)
|
||||
record.callbacks = [['change', tool.inputChange], ['dragover', dragover], ['drop', tool.ondrop]]
|
||||
connect(record, record.callbacks)
|
||||
}
|
||||
|
||||
export function releaseInput(tool) {
|
||||
const record = inputs.get(tool)
|
||||
if (!record)
|
||||
return
|
||||
inputs.delete(tool)
|
||||
release(record)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { getFileName } from './utils'
|
||||
|
||||
export function screenshotPoints(option, duration) {
|
||||
const { number, width, height, column, begin } = option
|
||||
const timeGap = duration / number
|
||||
const timePoints = [begin + timeGap]
|
||||
while (timePoints.length < number) {
|
||||
const last = timePoints[timePoints.length - 1]
|
||||
timePoints.push(last + timeGap)
|
||||
}
|
||||
return timePoints.map((item, index) => ({
|
||||
time: item - timeGap / 2,
|
||||
x: (index % column) * width,
|
||||
y: Math.floor(index / column) * height,
|
||||
}))
|
||||
}
|
||||
|
||||
export function createSheet(option) {
|
||||
const { number, width, height, column } = option
|
||||
const canvas = document.createElement('canvas')
|
||||
const context = canvas.getContext('2d')
|
||||
canvas.width = width * column
|
||||
canvas.height = Math.ceil(number / column) * height + 30
|
||||
context.fillStyle = 'black'
|
||||
context.fillRect(0, 0, canvas.width, canvas.height)
|
||||
context.font = '14px Georgia'
|
||||
context.fillStyle = '#fff'
|
||||
context.fillText(
|
||||
`From: https://artplayer.org/, Number: ${number}, Width: ${width}, Height: ${height}, Column: ${column}`,
|
||||
10,
|
||||
canvas.height - 11,
|
||||
)
|
||||
return canvas
|
||||
}
|
||||
|
||||
export function downloadSheet(file, url) {
|
||||
const link = document.createElement('a')
|
||||
const name = `${getFileName(file.name)}.png`
|
||||
link.download = name
|
||||
link.href = url
|
||||
try {
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
}
|
||||
finally {
|
||||
if (link.parentNode)
|
||||
link.parentNode.removeChild(link)
|
||||
}
|
||||
return name
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,71 @@
|
||||
# PKG-TOOL-THUMB-03 input and sheet checkpoint
|
||||
|
||||
Started from 1cb7779192cf552c0dfabcbb6de4f26b39e33045. Task 03 remains **doing**:
|
||||
this checkpoint changes production input ownership and separates sheet/export
|
||||
logic; extraction jobs and source/Blob cancellation still need implementation.
|
||||
|
||||
## Source changes and compatibility
|
||||
|
||||
`src/input.js` owns generated inputs, wrapper positioning and registered callbacks
|
||||
in a private WeakMap. Setup validates before mutating committed options/DOM,
|
||||
reuses an existing owned wrapper input, installs replacement listeners and then
|
||||
cleans up the previous target. Caller-provided file inputs are retained. Failed
|
||||
registration removes partial new listeners; failed construction rolls back owned
|
||||
input/video resources. The historical instance ondrop method is now actually
|
||||
registered for drop events. This repairs the undefined static callback defect.
|
||||
|
||||
Destroy is idempotent and attempts all input/video/current-URL/event cleanup even
|
||||
when a cleanup step throws. It preserves the first cleanup failure. Mutating the
|
||||
public option field does not erase the input ownership record. After destruction,
|
||||
setup/inputChange/ondrop/loadVideo cannot allocate new input/source resources.
|
||||
Wrapper position is restored only when it still matches the tool's relative write.
|
||||
|
||||
`src/sheet.js` contains midpoint coordinates, footer/canvas creation and download
|
||||
anchor handling. Historical calculations, attribution, creat* spellings and
|
||||
filename behavior stay unchanged. Download removes its temporary anchor even if
|
||||
click fails. The public class delegates existing methods rather than adding new
|
||||
public entry points. Constructor fields/order, direct class exports, defaults,
|
||||
event timing and chaining remain covered. Runtime source is still JS pending 04;
|
||||
emitter provenance and public declarations are not claimed complete.
|
||||
|
||||
The package now has an actual ARCHITECTURE.md map, maintenance commands, ownership
|
||||
rules and explicit continuation boundaries. Normal package builds regenerate
|
||||
main/legacy/ESM plus docs copies. No hand editing of generated artifacts occurs.
|
||||
|
||||
## Evidence
|
||||
|
||||
`test/thumbnail-input.test.js` adds 14 candidate regressions. The unchanged tests
|
||||
on frozen workspace main produce **2 passes/12 failures**. Source and both built
|
||||
UMD variants pass all 14. These include real defect contrasts and compatibility
|
||||
checks, not only assertions that new helper functions exist.
|
||||
|
||||
Browser candidate coverage is added alongside frozen implementations. A separate
|
||||
native DOM test selects files through generated inputs, replaces/reuses wrappers,
|
||||
dispatches events to old detached inputs, verifies listener removal, restores
|
||||
styles and verifies cleanup when a destroy listener throws. It runs without
|
||||
requiring Blob media decoding and therefore also executes on Windows WebKit.
|
||||
|
||||
Each source/main/legacy run contains 54 rows: 32 actual tool scenarios in
|
||||
Chromium/Firefox across old and candidate versions, 3 candidate input/DOM scenarios
|
||||
across all engines, 16 Windows WebKit Blob-unavailable controls and 3 native media
|
||||
comparison tests. The 16 controls are not successful extraction. Old defect rows
|
||||
remain unchanged; candidate drop and repeated-destroy expectations reflect fixes.
|
||||
The candidate late-Blob and replacement-URL scenarios still reproduce outstanding
|
||||
03 defects, explicitly preventing a claim of complete lifecycle repair.
|
||||
|
||||
Final logs, per-case measurements, artifact hashes and CI results are recorded in
|
||||
`refactor/baselines/thumbnail-input-checkpoint.json`. The current coverage policy
|
||||
only measures core/chapter; no thumbnail coverage percentage is claimed here.
|
||||
No hosted CI, physical Safari acceptance, npm publish or version bump occurred.
|
||||
|
||||
## Remaining work and rollback
|
||||
|
||||
Finish 03 with owned metadata waiting, extraction jobs, native error handling,
|
||||
source/thumbnail URL lifetime and cancellation/late-callback protection. The
|
||||
current pending extraction behavior is intentionally not declared fixed. Test
|
||||
failure-path reentrancy during constructor/setup cleanup as part of that ownership
|
||||
pass. Preserve the frozen default delay/height conflict until a concrete policy
|
||||
is documented. Task 04 owns strict TS, emitter attribution and missing types;
|
||||
05/06 retain full media/core integration, Safari/WebKit and distribution gates.
|
||||
All thumbnail risks remain open. Revert this checkpoint and run the normal package
|
||||
build to roll back the input/sheet change. The task completion count does not change.
|
||||
+3
-2
@@ -4,7 +4,7 @@
|
||||
|
||||
基线:`40fcda6a37d0049d42e49c1e64e70d4fd9ba5f7f`。总任务 222 项,范围 22 个包及工作区/示例。
|
||||
|
||||
状态:todo 101 / doing 10 / blocked 0 / done 111 / deferred 0。风险 L/M/H 表示兼容风险,不表示工期。
|
||||
状态:todo 100 / doing 11 / blocked 0 / done 111 / deferred 0。风险 L/M/H 表示兼容风险,不表示工期。
|
||||
|
||||
前置依赖是启动条件;验收是完成条件。任务可以继续拆分,但不能复用或悄悄删除旧 ID。
|
||||
|
||||
@@ -357,7 +357,7 @@
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| PKG-TOOL-THUMB-01 | artplayer-tool-thumbnail<br>核对包契约与历史用法 | BASE-05 | 构造/defaults/事件/方法/历史拼写、.esm.js 入口和缺失 types | 源码/声明/README/demo/可恢复发布内容差异已登记;公开形状和版本范围冻结;区分旧 npm 的 main/CSS 与当前工作区无 main、.esm.js/类型缺失,不把工作区状态冒称旧 npm 发布事实 | H | done |
|
||||
| PKG-TOOL-THUMB-02 | artplayer-tool-thumbnail<br>建立特有行为与错误测试 | PKG-TOOL-THUMB-01, ENG-03, ENG-05 | 文件输入/拖放、抽帧网格、begin/end、进度/失败/重复任务 | 旧版本行为可重跑,成功/失败/切源/销毁有必要断言 | H | done |
|
||||
| PKG-TOOL-THUMB-03 | artplayer-tool-thumbnail<br>整理内部职责与资源 | PKG-TOOL-THUMB-02, CORE-01 | 输入、抽帧队列、网格导出、URL/监听清理分离 | 结构变化和缺陷修复分开记录;原 API/事件/资源生命周期通过 | H | todo |
|
||||
| PKG-TOOL-THUMB-03 | artplayer-tool-thumbnail<br>整理内部职责与资源 | PKG-TOOL-THUMB-02, CORE-01 | 输入、抽帧队列、网格导出、URL/监听清理分离 | 结构变化和缺陷修复分开记录;原 API/事件/资源生命周期通过 | H | doing |
|
||||
| PKG-TOOL-THUMB-04 | artplayer-tool-thumbnail<br>迁移自有源码和公开类型 | PKG-TOOL-THUMB-03, ENG-04, ENG-06, CORE-07 | 补齐真实 API 声明,自有 emitter/utils TS 化 | 严格类型检查、旧消费样例通过;声明路径/导出和同步异步兼容;为 BASE-DIST-01 提供兼容入口/声明及消费者验证 | H | todo |
|
||||
| PKG-TOOL-THUMB-05 | artplayer-tool-thumbnail<br>验证新旧核心和组合 | PKG-TOOL-THUMB-04, CORE-22 | 工具独立浏览器使用,生成缩略图在核心中显示 | 最终核心与原支持范围核心分别通过;设备/SDK 缺证据不能标完成 | H | todo |
|
||||
| PKG-TOOL-THUMB-06 | artplayer-tool-thumbnail<br>验证分发并同步文档 | PKG-TOOL-THUMB-05, ENG-07 | tool.thumbnail.js、历史 ESM 兼容文件、types 路径和 tarball | tarball 入口/资源、类型、8082 demo 和 README 一致,有回退记录 | H | todo |
|
||||
@@ -537,4 +537,5 @@
|
||||
- PKG-IFRAME-05: [记录](changes/2026-09-13-PKG-IFRAME-05-integration.md) [记录](baselines/iframe-integration-validation.json) [记录](changes/2026-09-13-PKG-IFRAME-05-history.md) [记录](baselines/iframe-history-validation.json)
|
||||
- PKG-TOOL-THUMB-01: [记录](baselines/thumbnail-release.json) [记录](baselines/thumbnail-contract.md) [记录](changes/2026-09-13-PKG-TOOL-THUMB-01-contract.md) [记录](baselines/thumbnail-contract-validation.json)
|
||||
- PKG-TOOL-THUMB-02: [记录](baselines/thumbnail-behavior-validation.json) [记录](changes/2026-09-13-PKG-TOOL-THUMB-02-behavior.md)
|
||||
- PKG-TOOL-THUMB-03: [记录](changes/2026-09-13-PKG-TOOL-THUMB-03-input-checkpoint.md) [记录](baselines/thumbnail-input-checkpoint.json)
|
||||
- PKG-FACTORY-01: [记录](baselines/factory-assignment-gaps.json) [记录](baselines/factory-compatibility-proposals.json) [记录](factory-compatibility-decision.md) [记录](changes/2026-09-12-PKG-FACTORY-01-decision.md)
|
||||
@@ -1,5 +1,17 @@
|
||||
# 进度与证据
|
||||
|
||||
## PKG-TOOL-THUMB-03 输入与导出源码检查点(doing)
|
||||
|
||||
生产入口拆出input/sheet模块,修复drop注册、输入切换与wrapper所有权、构造/安装失败
|
||||
回滚、重复destroy及下载锚点清理;新增包内ARCHITECTURE.md。公开字段/方法/defaults
|
||||
和正常事件顺序保持。14项新回归在旧版2通过/12失败,源码/main/legacy各14通过。
|
||||
三份浏览器各54项通过:32真实工具场景、3候选原生输入场景、16WebKit Blob不可用
|
||||
对照、3原生媒体对照;不把不可用对照算作成功抽帧。正常构建同步dist/docs副本。
|
||||
完整CI1620、330生产TS与3导入测试通过。队列/URL取消、迟到Blob和失败重入仍需继续,
|
||||
本项不标done;04负责最终TS与声明。见[变更](changes/2026-09-13-PKG-TOOL-THUMB-03-input-checkpoint.md)
|
||||
和[验证](baselines/thumbnail-input-checkpoint.json)。222项:111 done、11 doing、100 todo。
|
||||
|
||||
|
||||
## PKG-TOOL-THUMB-02 完成:抽帧、失败与资源基线
|
||||
|
||||
新增36项历史抽帧/生命周期测试,与26项契约共同通过;普通CI已接入新测试。
|
||||
|
||||
+7
-2
@@ -3879,7 +3879,7 @@
|
||||
"PKG-TOOL-THUMB-03",
|
||||
"PKG-TOOL-THUMB-05"
|
||||
],
|
||||
"compatibleResolution": "36 frozen behavior tests reproduce timer/input/source/callback ownership gaps and historical error ordering. Actual Chromium/Firefox native Blob callbacks prove late update and URL leaks after destroy. Task 03 must add corrected candidate regressions and owned cleanup; 05 retains real integration acceptance.",
|
||||
"compatibleResolution": "03 input checkpoint fixes registered drop, input/wrapper ownership, failed setup/construction cleanup, repeated destroy and temporary download anchors. Candidate input regressions contrast 12 old failures; source/main/legacy verify preserved shape. Pending extraction callbacks, source URL replacement, cancellation and failure reentrancy remain open for the rest of 03 and real integration in 05.",
|
||||
"closureCriteria": "Deterministic old failure/candidate success for replacement, error and destruction plus real media/browser resource validation.",
|
||||
"status": "open",
|
||||
"evidence": [
|
||||
@@ -3889,7 +3889,12 @@
|
||||
"refactor/baselines/thumbnail-behavior-validation.json",
|
||||
"refactor/changes/2026-09-13-PKG-TOOL-THUMB-02-behavior.md",
|
||||
"test/thumbnail.test.js",
|
||||
"test/browser/thumbnail-tool.spec.js"
|
||||
"test/browser/thumbnail-tool.spec.js",
|
||||
"refactor/changes/2026-09-13-PKG-TOOL-THUMB-03-input-checkpoint.md",
|
||||
"packages/artplayer-tool-thumbnail/ARCHITECTURE.md",
|
||||
"test/thumbnail-input.test.js",
|
||||
"test/browser/thumbnail-input.spec.js",
|
||||
"refactor/baselines/thumbnail-input-checkpoint.json"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
+5
-2
@@ -3785,11 +3785,14 @@
|
||||
"PKG-TOOL-THUMB-02",
|
||||
"CORE-01"
|
||||
],
|
||||
"status": "todo",
|
||||
"status": "doing",
|
||||
"risk": "H",
|
||||
"deliverable": "输入、抽帧队列、网格导出、URL/监听清理分离",
|
||||
"acceptance": "结构变化和缺陷修复分开记录;原 API/事件/资源生命周期通过",
|
||||
"evidence": []
|
||||
"evidence": [
|
||||
"changes/2026-09-13-PKG-TOOL-THUMB-03-input-checkpoint.md",
|
||||
"baselines/thumbnail-input-checkpoint.json"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "PKG-TOOL-THUMB-04",
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { hash } from '../../refactor/scripts/releases.mjs'
|
||||
import { thumbnailCandidate } from '../helpers/thumbnail.js'
|
||||
import { expect, test } from './fixtures.js'
|
||||
|
||||
const implementation = await thumbnailCandidate()
|
||||
const sample = fileURLToPath(new URL('./media/thumbnail-pattern.mp4', import.meta.url))
|
||||
|
||||
test('Thumbnail input ownership replaces real DOM listeners and generated inputs', async ({ page }, testInfo) => {
|
||||
await page.goto('/test/player.html?core=published')
|
||||
await page.setContent('<!doctype html><div id="first" style="position:sticky"></div><div id="second" style="position:absolute"></div>')
|
||||
await page.addScriptTag({ content: implementation.code })
|
||||
await page.evaluate(() => {
|
||||
window.inputEvents = []
|
||||
window.inputTool = new window.ArtplayerToolThumbnail({ fileInput: document.querySelector('#first') })
|
||||
window.firstInput = window.inputTool.option.fileInput
|
||||
window.inputTool.on('file', file => window.inputEvents.push(file.name))
|
||||
window.inputTool.setup({ fileInput: document.querySelector('#first') })
|
||||
})
|
||||
await expect(page.locator('#first input')).toHaveCount(1)
|
||||
await page.locator('#first input').setInputFiles(sample)
|
||||
const switched = await page.evaluate(() => {
|
||||
const tool = window.inputTool
|
||||
const firstInput = window.firstInput
|
||||
const value = firstInput.value
|
||||
tool.setup({ fileInput: document.querySelector('#second') })
|
||||
firstInput.dispatchEvent(new Event('change'))
|
||||
firstInput.dispatchEvent(new Event('drop'))
|
||||
return { value, events: window.inputEvents.slice(), firstPosition: document.querySelector('#first').style.position, disconnected: !firstInput.isConnected }
|
||||
})
|
||||
expect(switched).toEqual({ value: '', events: ['thumbnail-pattern.mp4'], firstPosition: 'sticky', disconnected: true })
|
||||
await expect(page.locator('#first input')).toHaveCount(0)
|
||||
await page.locator('#second input').setInputFiles(sample)
|
||||
const result = await page.evaluate(() => {
|
||||
const tool = window.inputTool
|
||||
const input = tool.option.fileInput
|
||||
const error = new Error('expected destroyed callback')
|
||||
let notifications = 0
|
||||
tool.on('destroy', () => {
|
||||
notifications++
|
||||
throw error
|
||||
})
|
||||
let sameError = false
|
||||
try {
|
||||
tool.destroy()
|
||||
}
|
||||
catch (thrown) { sameError = thrown === error }
|
||||
tool.destroy()
|
||||
input.dispatchEvent(new Event('change'))
|
||||
input.dispatchEvent(new Event('drop'))
|
||||
tool.setup({ fileInput: document.querySelector('#first') })
|
||||
return { events: window.inputEvents, sameError, notifications, inputConnected: input.isConnected, videoConnected: tool.video.isConnected, secondPosition: document.querySelector('#second').style.position, inputs: document.querySelectorAll('input').length }
|
||||
})
|
||||
expect(result).toEqual({ events: ['thumbnail-pattern.mp4', 'thumbnail-pattern.mp4'], sameError: true, notifications: 1, inputConnected: false, videoConnected: false, secondPosition: 'absolute', inputs: 0 })
|
||||
await testInfo.attach('thumbnail-input-ownership', { contentType: 'application/json', body: JSON.stringify({ implementation: implementation.name, sha256: hash(implementation.code), scope: 'Native file input/DOM/listeners only; does not claim media decoding.', switched, result }) })
|
||||
})
|
||||
@@ -3,7 +3,7 @@ import path from 'node:path'
|
||||
import process from 'node:process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { hash } from '../../refactor/scripts/releases.mjs'
|
||||
import { thumbnailHistorical } from '../helpers/thumbnail.js'
|
||||
import { thumbnailCandidate, thumbnailHistorical } from '../helpers/thumbnail.js'
|
||||
import { expect, test } from './fixtures.js'
|
||||
|
||||
const sample = fileURLToPath(new URL('./media/thumbnail-pattern.mp4', import.meta.url))
|
||||
@@ -27,7 +27,8 @@ async function capabilityControl(page, testInfo) {
|
||||
return true
|
||||
}
|
||||
|
||||
for (const implementation of thumbnailHistorical()) {
|
||||
const implementations = [...thumbnailHistorical(), { ...await thumbnailCandidate(), inputOwnership: true }]
|
||||
for (const implementation of implementations) {
|
||||
test.describe(`Thumbnail tool ${implementation.name}`, () => {
|
||||
test.beforeEach(async ({ page }, testInfo) => {
|
||||
await page.goto('/test/player.html?core=published')
|
||||
@@ -127,7 +128,7 @@ for (const implementation of thumbnailHistorical()) {
|
||||
await testInfo.attach('thumbnail-extraction', { contentType: 'application/json', body: JSON.stringify(result) })
|
||||
})
|
||||
|
||||
test('DOM drop dispatch exposes missing listener while callable ondrop works', async ({ page }, testInfo) => {
|
||||
test(`DOM drop dispatch ${implementation.inputOwnership ? 'uses the registered handler' : 'exposes missing listener'} while callable ondrop works`, async ({ page }, testInfo) => {
|
||||
if (await capabilityControl(page, testInfo))
|
||||
return
|
||||
const result = await page.evaluate(async () => {
|
||||
@@ -142,7 +143,7 @@ for (const implementation of thumbnailHistorical()) {
|
||||
tool.ondrop(event)
|
||||
return { fromListener, afterDirect: observed.filter(item => item.event === 'file').length, prevented: event.defaultPrevented }
|
||||
})
|
||||
expect(result).toEqual({ fromListener: { files: 0, prevented: false }, afterDirect: 1, prevented: true })
|
||||
expect(result).toEqual({ fromListener: { files: implementation.inputOwnership ? 1 : 0, prevented: !!implementation.inputOwnership }, afterDirect: implementation.inputOwnership ? 2 : 1, prevented: true })
|
||||
await expect.poll(() => page.evaluate(() => tool.video.readyState)).toBeGreaterThanOrEqual(2)
|
||||
await page.evaluate(() => tool.destroy())
|
||||
})
|
||||
@@ -169,7 +170,7 @@ for (const implementation of thumbnailHistorical()) {
|
||||
expect(result.created).toHaveLength(2)
|
||||
expect(result.revoked).toEqual([result.created[1]])
|
||||
expect(result.revoked).not.toContain(failed.first)
|
||||
expect(result.repeated).toBe('NotFoundError')
|
||||
expect(result.repeated).toBe(implementation.inputOwnership ? undefined : 'NotFoundError')
|
||||
expect(result.value === '').toBe(!implementation.legacy)
|
||||
await testInfo.attach('thumbnail-media-failure', { contentType: 'application/json', body: JSON.stringify({ failed, result }) })
|
||||
})
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import fs from 'node:fs'
|
||||
import process from 'node:process'
|
||||
import vm from 'node:vm'
|
||||
import { verifyThumbnailContract } from '../../refactor/scripts/thumbnail-contract.mjs'
|
||||
import { compilePackage } from './load.js'
|
||||
|
||||
export async function thumbnailCandidate() {
|
||||
if (process.env.ARTPLAYER_THUMBNAIL_BASELINE === '1')
|
||||
return thumbnailHistorical().find(item => item.name === 'workspace.js')
|
||||
return { name: process.env.ARTPLAYER_THUMBNAIL_ARTIFACT ? 'candidate-artifact' : 'candidate-source', code: process.env.ARTPLAYER_THUMBNAIL_ARTIFACT ? fs.readFileSync(process.env.ARTPLAYER_THUMBNAIL_ARTIFACT, 'utf8') : await compilePackage('artplayer-tool-thumbnail', 'umd') }
|
||||
}
|
||||
|
||||
export function thumbnailHistorical() {
|
||||
const { source, historical } = verifyThumbnailContract()
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import assert from 'node:assert/strict'
|
||||
// eslint-disable-next-line test/no-import-node-test -- Candidate fixes also run against the frozen baseline.
|
||||
import test from 'node:test'
|
||||
import { thumbnailCandidate, thumbnailEnvironment } from './helpers/thumbnail.js'
|
||||
|
||||
const implementation = await thumbnailCandidate()
|
||||
function setup(wrapper = false) {
|
||||
const env = thumbnailEnvironment(implementation)
|
||||
const target = new env.Element(wrapper ? 'div' : 'input')
|
||||
const instance = new env.Factory({ fileInput: target, number: 10, width: 20, height: 30, column: 3 })
|
||||
return { ...env, target, instance }
|
||||
}
|
||||
|
||||
test('Thumbnail input ownership preserves class methods, constructor fields and defaults', () => {
|
||||
const { instance, Factory, exported } = setup()
|
||||
assert.equal(typeof exported, 'function')
|
||||
assert.equal(exported.default, undefined)
|
||||
assert.deepEqual(Object.keys(instance), ['processing', 'option', 'video', 'duration', 'inputChange', 'ondrop'])
|
||||
assert.deepEqual(Object.getOwnPropertyNames(Factory.prototype), ['constructor', 'ondrop', 'setup', 'inputChange', 'loadVideo', 'start', 'creatScreenshotDate', 'creatCanvas', 'download', 'errorHandle', 'destroy'])
|
||||
assert.deepEqual(Object.keys(Factory.DEFAULTS), ['number', 'width', 'height', 'column', 'begin', 'end'])
|
||||
assert.equal(instance.setup({ custom: 7 }), instance)
|
||||
assert.equal(instance.option.custom, 7)
|
||||
instance.destroy()
|
||||
})
|
||||
|
||||
test('Thumbnail actual registered drop callback loads the first file and prevents default', () => {
|
||||
const { instance, target } = setup()
|
||||
const file = { name: 'drop.mp4', type: 'video/mp4' }
|
||||
let prevented = 0
|
||||
for (const callback of target.handlers.get('drop') || [])
|
||||
callback({ preventDefault() { prevented++ }, dataTransfer: { files: [file] } })
|
||||
assert.equal(instance.file, file)
|
||||
assert.equal(prevented, 1)
|
||||
assert.equal(target.handlers.get('drop').has(instance.ondrop), true)
|
||||
instance.destroy()
|
||||
})
|
||||
|
||||
test('Thumbnail replacing input moves all listeners and reads the new file', () => {
|
||||
const { instance, target, Element } = setup()
|
||||
const next = new Element('input')
|
||||
assert.equal(instance.setup({ fileInput: next }), instance)
|
||||
for (const name of ['change', 'dragover', 'drop']) {
|
||||
assert.equal(target.handlers.get(name)?.size || 0, 0)
|
||||
assert.equal(next.handlers.get(name)?.size, 1)
|
||||
}
|
||||
next.files = [{ name: 'new.mp4', type: 'video/mp4' }]
|
||||
next.value = 'new.mp4'
|
||||
for (const callback of next.handlers.get('change'))
|
||||
callback({ target: next })
|
||||
assert.equal(instance.file, next.files[0])
|
||||
assert.equal(next.value, '')
|
||||
instance.destroy()
|
||||
assert.equal(next.handlers.get('change').size, 0)
|
||||
})
|
||||
|
||||
test('Thumbnail repeated wrapper setup reuses the owned input and restores replaced wrapper style', () => {
|
||||
const env = thumbnailEnvironment(implementation)
|
||||
const first = new env.Element('div')
|
||||
first.style.position = 'sticky'
|
||||
const instance = new env.Factory({ fileInput: first })
|
||||
const input = instance.option.fileInput
|
||||
instance.setup({ fileInput: first })
|
||||
assert.equal(first.children.length, 1)
|
||||
assert.equal(instance.option.fileInput, input)
|
||||
const second = new env.Element('div')
|
||||
second.style.position = 'absolute'
|
||||
instance.setup({ fileInput: second })
|
||||
assert.equal(first.children.length, 0)
|
||||
assert.equal(first.style.position, 'sticky')
|
||||
assert.equal(input.handlers.get('change').size, 0)
|
||||
instance.destroy()
|
||||
assert.equal(second.children.length, 0)
|
||||
assert.equal(second.style.position, 'absolute')
|
||||
})
|
||||
|
||||
test('Thumbnail does not overwrite a wrapper style changed by its owner', () => {
|
||||
const { instance, target } = setup(true)
|
||||
target.style.position = 'fixed'
|
||||
instance.destroy()
|
||||
assert.equal(target.children.length, 0)
|
||||
assert.equal(target.style.position, 'fixed')
|
||||
})
|
||||
|
||||
test('Thumbnail setup validation is atomic and cannot append an orphan input', () => {
|
||||
const { instance, Element } = setup()
|
||||
const previous = instance.option
|
||||
const wrapper = new Element('div')
|
||||
assert.throws(() => instance.setup({ fileInput: wrapper, width: 'invalid' }), /width/)
|
||||
assert.equal(instance.option, previous)
|
||||
assert.equal(wrapper.children.length, 0)
|
||||
assert.equal(wrapper.style.position, undefined)
|
||||
instance.destroy()
|
||||
})
|
||||
|
||||
test('Thumbnail failed replacement listener installation removes partial listeners and keeps old ownership', () => {
|
||||
const { instance, target, Element } = setup()
|
||||
const next = new Element('input')
|
||||
const failure = new Error('listener failed')
|
||||
const add = next.addEventListener
|
||||
next.addEventListener = function (name, callback) {
|
||||
add.call(this, name, callback)
|
||||
if (name === 'dragover')
|
||||
throw failure
|
||||
}
|
||||
assert.throws(() => instance.setup({ fileInput: next }), error => error === failure)
|
||||
assert.equal(instance.option.fileInput, target)
|
||||
assert.equal(target.handlers.get('change').size, 1)
|
||||
for (const callbacks of next.handlers.values())
|
||||
assert.equal(callbacks.size, 0)
|
||||
instance.destroy()
|
||||
})
|
||||
|
||||
test('Thumbnail failed video attachment rolls back generated input and attached video', () => {
|
||||
const env = thumbnailEnvironment(implementation)
|
||||
const wrapper = new env.Element('div')
|
||||
wrapper.style.position = 'fixed'
|
||||
const failure = new Error('append failed')
|
||||
const append = env.body.appendChild
|
||||
env.body.appendChild = function (child) {
|
||||
append.call(this, child)
|
||||
throw failure
|
||||
}
|
||||
assert.throws(() => new env.Factory({ fileInput: wrapper }), error => error === failure)
|
||||
assert.equal(env.body.children.length, 0)
|
||||
assert.equal(wrapper.children.length, 0)
|
||||
assert.equal(wrapper.style.position, 'fixed')
|
||||
})
|
||||
|
||||
test('Thumbnail failed constructor listener attachment removes every partial resource', () => {
|
||||
const env = thumbnailEnvironment(implementation)
|
||||
const target = new env.Element('input')
|
||||
const failure = new Error('drop registration failed')
|
||||
const add = target.addEventListener
|
||||
target.addEventListener = function (name, callback) {
|
||||
add.call(this, name, callback)
|
||||
if (name === 'drop')
|
||||
throw failure
|
||||
}
|
||||
assert.throws(() => new env.Factory({ fileInput: target }), error => error === failure)
|
||||
assert.equal(env.body.children.length, 0)
|
||||
for (const callbacks of target.handlers.values())
|
||||
assert.equal(callbacks.size, 0)
|
||||
})
|
||||
|
||||
test('Thumbnail externally detached video and repeated destroy are safe', () => {
|
||||
const { instance, body, target } = setup()
|
||||
let count = 0
|
||||
instance.on('destroy', () => count++)
|
||||
body.removeChild(instance.video)
|
||||
assert.equal(instance.destroy(), undefined)
|
||||
assert.equal(instance.destroy(), undefined)
|
||||
assert.equal(count, 1)
|
||||
for (const callbacks of target.handlers.values())
|
||||
assert.equal(callbacks.size, 0)
|
||||
})
|
||||
|
||||
test('Thumbnail destroy uses private input ownership despite public option replacement', () => {
|
||||
const { instance, target, Element } = setup(true)
|
||||
const ownedInput = instance.option.fileInput
|
||||
instance.option = { fileInput: new Element('input') }
|
||||
instance.destroy()
|
||||
assert.equal(target.children.length, 0)
|
||||
for (const callbacks of ownedInput.handlers.values())
|
||||
assert.equal(callbacks.size, 0)
|
||||
})
|
||||
|
||||
test('Thumbnail cleanup continues after listener removal failure and cannot reload after destroy', () => {
|
||||
const { instance, target, body, operations, Element } = setup()
|
||||
instance.loadVideo({ name: 'first.mp4', type: 'video/mp4' })
|
||||
const failure = new Error('remove failed')
|
||||
const remove = target.removeEventListener
|
||||
target.removeEventListener = function (name, callback) {
|
||||
if (name === 'change')
|
||||
throw failure
|
||||
remove.call(this, name, callback)
|
||||
}
|
||||
let count = 0
|
||||
instance.on('destroy', () => count++)
|
||||
assert.throws(() => instance.destroy(), error => error === failure)
|
||||
assert.equal(body.children.length, 0)
|
||||
assert.equal(count, 1)
|
||||
assert.equal(target.handlers.get('dragover').size, 0)
|
||||
assert.equal(operations.filter(item => item.name === 'revokeURL').length, 1)
|
||||
const wrapper = new Element('div')
|
||||
assert.equal(instance.setup({ fileInput: wrapper }), instance)
|
||||
instance.loadVideo({ name: 'late.mp4', type: 'video/mp4' })
|
||||
instance.inputChange({ target })
|
||||
instance.ondrop({ preventDefault() {
|
||||
throw new Error('should not run')
|
||||
} })
|
||||
assert.equal(wrapper.children.length, 0)
|
||||
assert.equal(operations.filter(item => item.name === 'createURL').length, 1)
|
||||
assert.equal(instance.destroy(), undefined)
|
||||
})
|
||||
|
||||
test('Thumbnail download removes its temporary anchor even when click fails', () => {
|
||||
const { instance, Element, body } = setup()
|
||||
instance.file = { name: 'video.part.mp4' }
|
||||
instance.thumbnailUrl = 'blob:sheet'
|
||||
const failure = new Error('click failed')
|
||||
Element.prototype.click = () => {
|
||||
throw failure
|
||||
}
|
||||
assert.throws(() => instance.download(), error => error === failure)
|
||||
assert.deepEqual(body.children.map(child => child.tagName), ['VIDEO'])
|
||||
instance.destroy()
|
||||
})
|
||||
|
||||
test('Thumbnail extracted sheet helpers preserve midpoint coordinates and footer', () => {
|
||||
const { instance, operations } = setup()
|
||||
instance.duration = 100
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(instance.creatScreenshotDate())), Array.from({ length: 10 }, (_, i) => ({ time: 5 + i * 10, x: i % 3 * 20, y: Math.floor(i / 3) * 30 })))
|
||||
const canvas = instance.creatCanvas()
|
||||
assert.equal(canvas.width, 60)
|
||||
assert.equal(canvas.height, 150)
|
||||
assert.deepEqual(operations.find(item => item.name === 'fillText').args, ['From: https://artplayer.org/, Number: 10, Width: 20, Height: 30, Column: 3', 10, 139])
|
||||
instance.destroy()
|
||||
})
|
||||
Reference in new issue
Block a user