@verygoodgraphics/vgg-wasm
Advanced tools
Comparing version 0.1.14 to 0.1.15
@@ -30,2 +30,7 @@ declare type CallbackHandlers = { | ||
declare type Frame = { | ||
id: string; | ||
name: string; | ||
}; | ||
declare enum LoadingState { | ||
@@ -46,3 +51,3 @@ StartLoading = "Start loading", | ||
constructor(selector: string, vggSdk: VggSdkType); | ||
on(eventType: EventType, callback: VGGEventCallback): Observable; | ||
on(eventType: `${EventType}`, callback: VGGEventCallback): Observable; | ||
update(data: string): void; | ||
@@ -73,3 +78,3 @@ private addEventListener; | ||
private eventManager; | ||
state: State; | ||
state: `${State}`; | ||
private onLoadingStateUpdate; | ||
@@ -99,2 +104,3 @@ private vggWasmInstance; | ||
private loadFonts; | ||
loadFontFile(font: Uint8Array, name: string): void; | ||
/** | ||
@@ -118,2 +124,10 @@ * Subscribe to VGG-generated events | ||
destroy(): this; | ||
getTextContent(): string[]; | ||
snapshot(opts?: { | ||
type: "png" | "jpg" | "webp"; | ||
quality: number; | ||
}): Uint8Array | undefined; | ||
getAllFrames(): Frame[]; | ||
setCurrentFrame(id: string): void; | ||
get currentFrameId(): string | undefined; | ||
} | ||
@@ -163,5 +177,13 @@ | ||
updateElement(id: string, value: string): void; | ||
addFont(font: Uint8Array, name: string): void; | ||
addFont(font: Uint8Array, name: string): boolean; | ||
texts(): string[]; | ||
makeImageSnapshot(opts: { | ||
type: "png" | "jpg" | "webp"; | ||
quality: number; | ||
}): Uint8Array; | ||
getFramesInfo(): string; | ||
setCurrentFrameById(frameName: string): void; | ||
currentFrameId(): string; | ||
} | ||
export { } |
@@ -1,2 +0,2 @@ | ||
var vggWasm=function(d){"use strict";var S=Object.defineProperty;var k=(d,o,c)=>o in d?S(d,o,{enumerable:!0,configurable:!0,writable:!0,value:c}):d[o]=c;var r=(d,o,c)=>(k(d,typeof o!="symbol"?o+"":o,c),c);var o=(n=>(n.Load="load",n.FirstRender="firstrender",n.LoadError="loaderror",n.StateChange="statechange",n.Click="click",n))(o||{}),c=(n=>(n.Loading="loading",n.Ready="ready",n.Rendered="rendered",n.Error="error",n.Destroyed="destroyed",n))(c||{}),g=(n=>(n.StartLoading="Start loading",n.DownloadVGGRuntimeJS="Download VGG Runtime JS",n.CreateVGGWasmInstance="Create VGG Wasm Instance",n.VGGWasmInstanceReady="VGG Wasm Instance Ready",n.DownloadSourceFile="Download Source File",n.LoadSourceFile="Load Source File",n))(g||{});class m{constructor(e=[]){this.listeners=e}getListeners(e){return this.listeners.filter(t=>t.type===e)}add(e){this.listeners.includes(e)||this.listeners.push(e)}remove(e){for(let t=0;t<this.listeners.length;t++){const s=this.listeners[t];if(s.type===e.type&&s.callback===e.callback){this.listeners.splice(t,1);break}}}removeAll(e){e?this.listeners.filter(t=>t.type===e).forEach(t=>this.remove(t)):this.listeners.splice(0,this.listeners.length)}fire(e,t){this.getListeners(e.type).forEach(a=>a.callback(e,t))}}const v=(n=21)=>crypto.getRandomValues(new Uint8Array(n)).reduce((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_","");class w{constructor(e,t){r(this,"selector");r(this,"vggSdk");this.selector=e,this.vggSdk=t}on(e,t){return this.addEventListener(this.selector,e,t),this}update(e){if(!this.vggSdk)throw new Error("VGG SDK not ready");this.vggSdk.updateElement(this.selector,e)}addEventListener(e,t,s){if(!this.vggSdk)throw new Error("VGG SDK not ready");const a=b=>s(this,b),i=v(7),l=`export default (event, opts) => { | ||
var vggWasm=function(d){"use strict";var b=Object.defineProperty;var k=(d,o,c)=>o in d?b(d,o,{enumerable:!0,configurable:!0,writable:!0,value:c}):d[o]=c;var n=(d,o,c)=>(k(d,typeof o!="symbol"?o+"":o,c),c);var o=(r=>(r.Load="load",r.FirstRender="firstrender",r.LoadError="loaderror",r.StateChange="statechange",r.Click="click",r))(o||{}),c=(r=>(r.Loading="loading",r.Ready="ready",r.Rendered="rendered",r.Error="error",r.Destroyed="destroyed",r))(c||{}),h=(r=>(r.StartLoading="Start loading",r.DownloadVGGRuntimeJS="Download VGG Runtime JS",r.CreateVGGWasmInstance="Create VGG Wasm Instance",r.VGGWasmInstanceReady="VGG Wasm Instance Ready",r.DownloadSourceFile="Download Source File",r.LoadSourceFile="Load Source File",r))(h||{});class v{constructor(e=[]){this.listeners=e}getListeners(e){return this.listeners.filter(t=>t.type===e)}add(e){this.listeners.includes(e)||this.listeners.push(e)}remove(e){for(let t=0;t<this.listeners.length;t++){const s=this.listeners[t];if(s.type===e.type&&s.callback===e.callback){this.listeners.splice(t,1);break}}}removeAll(e){e?this.listeners.filter(t=>t.type===e).forEach(t=>this.remove(t)):this.listeners.splice(0,this.listeners.length)}fire(e,t){this.getListeners(e.type).forEach(a=>a.callback(e,t))}}const w=(r=21)=>crypto.getRandomValues(new Uint8Array(r)).reduce((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_","");class y{constructor(e,t){n(this,"selector");n(this,"vggSdk");this.selector=e,this.vggSdk=t}on(e,t){return this.addEventListener(this.selector,e,t),this}update(e){if(!this.vggSdk)throw new Error("VGG SDK not ready");this.vggSdk.updateElement(this.selector,e)}addEventListener(e,t,s){if(!this.vggSdk)throw new Error("VGG SDK not ready");const a=m=>s(this,m),i=w(7),l=`export default (event, opts) => { | ||
const sdk = new opts.instance.VggSdk() | ||
@@ -25,2 +25,2 @@ | ||
} | ||
}`;this.vggSdk.addEventListener(e,t,l);const h=globalThis.vggInstances[this.vggSdk.getEnv()];return h&&h.listeners.set(i,a),{selector:e,removeEventListener:()=>{this.vggSdk.removeEventListener(e,t,l),h.listeners.delete(i)}}}}class y{constructor(e){this.debug=e}logEvent(e){this.debug&&console.log(`%cVGGEvent::${e.type}`,"background: #f59e0b; color: #78350f; font-weight: bold; border-radius: 2px; padding: 0 2.5px;",e.id?`${e.id} → ${e.path}`:"")}logLifeCycle(e){this.debug&&console.log(`%cVGGLifeCycle::${e.phase}`,"background: #f59e0b; color: #78350f; font-weight: bold; border-radius: 2px; padding: 0 2.5px;",e.status)}}const f=class f{constructor(e){r(this,"props");r(this,"defaultRuntime","https://s5.vgg.cool/runtime/latest");r(this,"canvas");r(this,"width",0);r(this,"height",0);r(this,"editMode",!1);r(this,"disableLoader",!1);r(this,"verbose");r(this,"src");r(this,"runtime");r(this,"vggInstanceKey","");r(this,"eventManager");r(this,"state",c.Loading);r(this,"onLoadingStateUpdate");r(this,"vggWasmInstance",null);r(this,"vggSdk",null);r(this,"customFonts",[]);r(this,"observables",new Map);r(this,"checkStateFrame",0);r(this,"logger");var t,s;this.props=e,this.canvas=e.canvas,this.src=e.src,this.runtime=e.runtime||this.defaultRuntime,this.width=((t=this.canvas)==null?void 0:t.width)??0,this.height=((s=this.canvas)==null?void 0:s.height)??0,this.customFonts=e.customFonts??[],this.editMode=e.editMode??!1,this.verbose=e.verbose??!1,this.logger=new y(this.verbose),this.disableLoader=e.disableLoader??!1,this.onLoadingStateUpdate=e.onLoadingStateUpdate??(()=>{}),this.eventManager=new m,e.onLoad&&this.on("load",e.onLoad),e.onLoadError&&this.on("loaderror",e.onLoadError),e.onRendered&&this.on("firstrender",e.onRendered),e.onStateChange&&this.on("statechange",e.onStateChange),e.onSelect&&this.on("click",e.onSelect)}async load(){try{this.updateLoader(g.StartLoading),await this.init({...this.props})}catch(e){this.eventManager.fire({type:"loaderror",data:e.message})}}updateLoader(e){var t;this.disableLoader||(t=this.onLoadingStateUpdate)==null||t.call(this,e)}async init({src:e}){if(this.updateLoader(g.DownloadVGGRuntimeJS),this.src=e,Array.from(document.scripts).some(s=>s.src.includes("vgg_runtime.js"))||await this.loadScript(this.runtime+"/vgg_runtime.js"),await new Promise(s=>{const a=setInterval(()=>{window._vgg_createWasmInstance&&(clearInterval(a),s(!0))},100)}),!this.canvas)throw new Error("Canvas element required");if(!this.src)throw new Error(f.missingErrorMessage);await new Promise(t=>{this.checkStateFrame=requestAnimationFrame(()=>this.checkState(t))}),await this.loadFonts(),this.logger.logLifeCycle({phase:"init",status:"end"})}async createVggWasmInstance(){const e=this.runtime;try{const t=setTimeout(()=>{throw new Error("VGG Wasm instance creation timeout")},3e4),s=await window._vgg_createWasmInstance({noInitialRun:!0,canvas:this.canvas,locateFile:function(a,i){return a.endsWith(".data")?e+"/"+a:i+a}});return clearTimeout(t),s}catch{return null}}async checkState(e){if(this.updateLoader(g.CreateVGGWasmInstance),window._vgg_createWasmInstance){const t=await this.createVggWasmInstance();if(t){this.vggWasmInstance=t;try{this.vggWasmInstance.ccall("emscripten_main","void",["number","number","boolean"],[this.width,this.height,this.editMode])}catch(a){console.error(a)}this.vggSdk=new t.VggSdk;const s=globalThis.vggInstances??{};this.vggInstanceKey=this.vggSdk.getEnv(),this.editMode?Object.assign(s,{[this.vggInstanceKey]:{instance:t,listener:a=>{try{const i=JSON.parse(a);this.logger.logEvent(i),i.type==="select"?this.eventManager.fire({type:o.Click,data:i}):i.type==="firstRender"&&(this.state=c.Rendered,this.eventManager.fire({type:o.FirstRender}))}catch(i){console.error(i)}}}}):Object.assign(s,{[this.vggInstanceKey]:{instance:t,listeners:new Map,listener:a=>{try{JSON.parse(a).type==="firstRender"&&(this.state=c.Rendered,this.eventManager.fire({type:o.FirstRender}))}catch(i){console.error(i)}}}}),globalThis.vggInstances=s,this.state=c.Ready,this.eventManager.fire({type:o.Load})}else this.state=c.Error,this.eventManager.fire({type:o.LoadError});cancelAnimationFrame(this.checkStateFrame),e(!0),this.updateLoader(g.VGGWasmInstanceReady)}else this.checkStateFrame=requestAnimationFrame(()=>this.checkState(e))}async loadScript(e){const t=document.createElement("script");return t.src=e,document.head.appendChild(t),new Promise(s=>{t.onload=()=>{s(!0)}})}async loadFonts(){const e=this.customFonts;for(const t of e)await fetch(t).then(s=>{if(s.ok)return s.arrayBuffer();throw new Error(s.statusText)}).then(s=>{var l,h;const a=new Uint8Array(s),i=((l=t.split("/").pop())==null?void 0:l.split(".")[0])??"";if(!((h=this.vggSdk)!=null&&h.addFont(a,i)))throw new Error("add font failed!")}).catch(s=>{console.error(`Failed to add font: ${s.message}`)})}on(e,t){return this.eventManager.add({type:e,callback:t}),this}async render(e,t){if(this.width=(t==null?void 0:t.width)??this.width,this.height=(t==null?void 0:t.height)??this.height,this.editMode=(t==null?void 0:t.editMode)??this.editMode,!this.vggWasmInstance)throw new Error("VGG Wasm instance not ready");const s=e??this.src;let a;if(typeof s=="string"&&s.startsWith("http")){this.updateLoader(g.DownloadSourceFile);const l=await fetch(s);if(!l.ok)throw new Error("Failed to fetch Daruma file");const h=await l.arrayBuffer();a=new Int8Array(h)}else if(s instanceof Int8Array)a=s;else throw new Error("Invalid source file");if(this.updateLoader(g.LoadSourceFile),!this.vggWasmInstance)return;if(!this.vggWasmInstance.ccall("load_file_from_mem","boolean",["string","array","number"],["name",a,a.length]))throw new Error("Failed to load Daruma file")}$(e){if(!this.vggSdk)throw new Error("VGG SDK not ready");const t=this.observables.get(e);if(!t){const s=new w(String(e),this.vggSdk);return this.observables.set(e,s),s}return t}destroy(){var t;try{(t=this.vggWasmInstance)==null||t._vggExit()}catch{}const e=globalThis.vggInstances??{};return delete e[this.vggInstanceKey],this.eventManager.removeAll(),this.vggWasmInstance=null,this.src="",this.vggSdk=null,this.state=c.Destroyed,this.logger.logLifeCycle({phase:"destroy",status:"end"}),this.observables.clear(),this}};r(f,"missingErrorMessage","Daruma source file required");let u=f;return typeof globalThis<"u"&&(globalThis.VGG=u),d.EventType=o,d.State=c,d.VGG=u,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"}),d}({}); | ||
}`;this.vggSdk.addEventListener(e,t,l);const g=globalThis.vggInstances[this.vggSdk.getEnv()];if(g)try{g.listeners.set(i,a)}catch(m){console.error(m)}return{selector:e,removeEventListener:()=>{this.vggSdk.removeEventListener(e,t,l),g.listeners.delete(i)}}}}class S{constructor(e){this.debug=e}logEvent(e){this.debug&&console.log(`%cVGGEvent::${e.type}`,"background: #f59e0b; color: #78350f; font-weight: bold; border-radius: 2px; padding: 0 2.5px;",e.id?`${e.id} → ${e.path}`:"")}logLifeCycle(e){this.debug&&console.log(`%cVGGLifeCycle::${e.phase}`,"background: #f59e0b; color: #78350f; font-weight: bold; border-radius: 2px; padding: 0 2.5px;",e.status)}}const f=class f{constructor(e){n(this,"props");n(this,"defaultRuntime","https://s5.vgg.cool/runtime/latest");n(this,"canvas");n(this,"width",0);n(this,"height",0);n(this,"editMode",!1);n(this,"disableLoader",!1);n(this,"verbose");n(this,"src");n(this,"runtime");n(this,"vggInstanceKey","");n(this,"eventManager");n(this,"state",c.Loading);n(this,"onLoadingStateUpdate");n(this,"vggWasmInstance",null);n(this,"vggSdk",null);n(this,"customFonts",[]);n(this,"observables",new Map);n(this,"checkStateFrame",0);n(this,"logger");var t,s;this.props=e,this.canvas=e.canvas,this.src=e.src,this.runtime=e.runtime||this.defaultRuntime,this.width=((t=this.canvas)==null?void 0:t.width)??0,this.height=((s=this.canvas)==null?void 0:s.height)??0,this.customFonts=e.customFonts??[],this.editMode=e.editMode??!1,this.verbose=e.verbose??!1,this.logger=new S(this.verbose),this.disableLoader=e.disableLoader??!1,this.onLoadingStateUpdate=e.onLoadingStateUpdate??(()=>{}),this.eventManager=new v,e.onLoad&&this.on("load",e.onLoad),e.onLoadError&&this.on("loaderror",e.onLoadError),e.onRendered&&this.on("firstrender",e.onRendered),e.onStateChange&&this.on("statechange",e.onStateChange),e.onSelect&&this.on("click",e.onSelect)}async load(){try{this.updateLoader(h.StartLoading),await this.init({...this.props})}catch(e){this.eventManager.fire({type:"loaderror",data:e.message})}}updateLoader(e){var t;this.disableLoader||(t=this.onLoadingStateUpdate)==null||t.call(this,e)}async init({src:e}){if(this.updateLoader(h.DownloadVGGRuntimeJS),this.src=e,Array.from(document.scripts).some(s=>s.src.includes("vgg_runtime.js"))||await this.loadScript(this.runtime+"/vgg_runtime.js"),await new Promise(s=>{const a=setInterval(()=>{window._vgg_createWasmInstance&&(clearInterval(a),s(!0))},100)}),!this.canvas)throw new Error("Canvas element required");if(!this.src)throw new Error(f.missingErrorMessage);await new Promise(t=>{this.checkStateFrame=requestAnimationFrame(()=>this.checkState(t))}),console.log("VGG SDK ready",this.vggSdk),await this.loadFonts(),this.logger.logLifeCycle({phase:"init",status:"end"})}async createVggWasmInstance(){const e=this.runtime;try{const t=setTimeout(()=>{throw new Error("VGG Wasm instance creation timeout")},3e4),s=await window._vgg_createWasmInstance({noInitialRun:!0,canvas:this.canvas,locateFile:function(a,i){return a.endsWith(".data")?e+"/"+a:i+a}});return clearTimeout(t),s}catch(t){return console.error(t),null}}async checkState(e){if(this.updateLoader(h.CreateVGGWasmInstance),window._vgg_createWasmInstance){const t=await this.createVggWasmInstance();if(console.log(88888,t),t){this.vggWasmInstance=t;try{this.vggWasmInstance.ccall("emscripten_main","void",["number","number","boolean"],[this.width,this.height,this.editMode])}catch(a){console.error(a)}this.vggSdk=new t.VggSdk;const s=globalThis.vggInstances??{};this.vggInstanceKey=this.vggSdk.getEnv(),this.editMode?Object.assign(s,{[this.vggInstanceKey]:{instance:t,listener:a=>{try{const i=JSON.parse(a);this.logger.logEvent(i),i.type==="select"?this.eventManager.fire({type:o.Click,data:i}):i.type==="firstRender"&&(this.state=c.Rendered,this.eventManager.fire({type:o.FirstRender}))}catch(i){console.error(i)}}}}):Object.assign(s,{[this.vggInstanceKey]:{instance:t,listeners:new Map,listener:a=>{try{JSON.parse(a).type==="firstRender"&&(this.state=c.Rendered,this.eventManager.fire({type:o.FirstRender}))}catch(i){console.error(i)}}}}),globalThis.vggInstances=s,this.state=c.Ready,this.eventManager.fire({type:o.Load})}else this.state=c.Error,this.eventManager.fire({type:o.LoadError});cancelAnimationFrame(this.checkStateFrame),e(!0),this.updateLoader(h.VGGWasmInstanceReady)}else this.checkStateFrame=requestAnimationFrame(()=>this.checkState(e))}async loadScript(e){const t=document.createElement("script");return t.src=e,document.head.appendChild(t),new Promise(s=>{t.onload=()=>{s(!0)}})}async loadFonts(){const e=this.customFonts;for(const t of e)await fetch(t).then(s=>{if(s.ok)return s.arrayBuffer();throw new Error(s.statusText)}).then(s=>{var l;const a=new Uint8Array(s),i=((l=t.split("/").pop())==null?void 0:l.split(".")[0])??"";this.loadFontFile(a,i)}).catch(s=>{console.error(`Failed to add font: ${s.message}`)})}loadFontFile(e,t){if(!this.vggSdk)throw new Error("VGG SDK not ready");if(!this.vggSdk.addFont(e,t))throw new Error("add font failed!")}on(e,t){return this.eventManager.add({type:e,callback:t}),this}async render(e,t){if(this.width=(t==null?void 0:t.width)??this.width,this.height=(t==null?void 0:t.height)??this.height,this.editMode=(t==null?void 0:t.editMode)??this.editMode,!this.vggWasmInstance)throw new Error("VGG Wasm instance not ready");const s=e??this.src;let a;if(typeof s=="string"){this.updateLoader(h.DownloadSourceFile);const l=await fetch(s);if(!l.ok)throw new Error("Failed to fetch Daruma file");const g=await l.arrayBuffer();a=new Int8Array(g)}else if(s instanceof Int8Array)a=s;else throw new Error("Invalid source file");if(this.updateLoader(h.LoadSourceFile),!this.vggWasmInstance)return;if(!this.vggWasmInstance.ccall("load_file_from_mem","boolean",["string","array","number"],["name",a,a.length]))throw new Error("Failed to load Daruma file")}$(e){if(!this.vggSdk)throw new Error("VGG SDK not ready");const t=this.observables.get(e);if(!t){const s=new y(String(e),this.vggSdk);return this.observables.set(e,s),s}return t}destroy(){var t;try{(t=this.vggWasmInstance)==null||t._vggExit()}catch{}const e=globalThis.vggInstances??{};return delete e[this.vggInstanceKey],this.eventManager.removeAll(),this.vggWasmInstance=null,this.src="",this.vggSdk=null,this.state=c.Destroyed,this.logger.logLifeCycle({phase:"destroy",status:"end"}),this.observables.clear(),this}getTextContent(){var t;return((t=this.vggSdk)==null?void 0:t.texts())??[]}snapshot(e={type:"png",quality:100}){var s;return(s=this.vggSdk)==null?void 0:s.makeImageSnapshot(e)}getAllFrames(){var t;const e=(t=this.vggSdk)==null?void 0:t.getFramesInfo();return e?JSON.parse(e):[]}setCurrentFrame(e){var t;(t=this.vggSdk)==null||t.setCurrentFrameById(e)}get currentFrameId(){var e;return(e=this.vggSdk)==null?void 0:e.currentFrameId()}};n(f,"missingErrorMessage","Daruma source file required");let u=f;return typeof globalThis<"u"&&(globalThis.VGG=u),d.EventType=o,d.State=c,d.VGG=u,Object.defineProperty(d,Symbol.toStringTag,{value:"Module"}),d}({}); |
@@ -9,3 +9,3 @@ { | ||
"license": "MIT", | ||
"version": "0.1.14", | ||
"version": "0.1.15", | ||
"files": [ | ||
@@ -42,3 +42,5 @@ "dist" | ||
"scripts": { | ||
"dev": "vite", | ||
"dev": "pnpm run /^watch:.*/", | ||
"watch:lib": "vite build --watch", | ||
"watch:ui": "vite", | ||
"build": "tsc && vite build", | ||
@@ -45,0 +47,0 @@ "preview": "vite preview" |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
51779
723