Fixed input remove listener. Run tsfmt.

This commit is contained in:
Davide Tantillo 2024-09-30 11:52:02 +02:00
parent 2db1873fd5
commit 95f2119e46
3 changed files with 1101 additions and 1101 deletions

View File

@ -135,7 +135,7 @@ export class AssetManagerBase implements Disposable {
}); });
} }
reuseAssets(path: string, reuseAssets (path: string,
success: (path: string, data: any) => void = () => { }, success: (path: string, data: any) => void = () => { },
error: (path: string, message: string) => void = () => { }) { error: (path: string, message: string) => void = () => { }) {
const loadedStatus = this.assetsLoaded[path]; const loadedStatus = this.assetsLoaded[path];
@ -272,7 +272,7 @@ export class AssetManagerBase implements Disposable {
} }
// Promisified versions of load function // Promisified versions of load function
async loadBinaryAsync(path: string) { async loadBinaryAsync (path: string) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.loadBinary(path, this.loadBinary(path,
(_, binary) => resolve(binary), (_, binary) => resolve(binary),
@ -281,7 +281,7 @@ export class AssetManagerBase implements Disposable {
}); });
} }
async loadJsonAsync(path: string) { async loadJsonAsync (path: string) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.loadJson(path, this.loadJson(path,
(_, object) => resolve(object), (_, object) => resolve(object),
@ -290,7 +290,7 @@ export class AssetManagerBase implements Disposable {
}); });
} }
async loadTextureAsync(path: string) { async loadTextureAsync (path: string) {
return new Promise<Texture>((resolve, reject) => { return new Promise<Texture>((resolve, reject) => {
this.loadTexture(path, this.loadTexture(path,
(_, texture) => resolve(texture), (_, texture) => resolve(texture),
@ -299,7 +299,7 @@ export class AssetManagerBase implements Disposable {
}); });
} }
async loadTextureAtlasAsync(path: string) { async loadTextureAtlasAsync (path: string) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.loadTextureAtlas(path, this.loadTextureAtlas(path,
(_, atlas) => resolve(atlas), (_, atlas) => resolve(atlas),
@ -308,7 +308,7 @@ export class AssetManagerBase implements Disposable {
}); });
} }
async loadTextureAtlasButNoTexturesAsync(path: string) { async loadTextureAtlasButNoTexturesAsync (path: string) {
return new Promise<TextureAtlas>((resolve, reject) => { return new Promise<TextureAtlas>((resolve, reject) => {
this.loadTextureAtlasButNoTextures(path, this.loadTextureAtlasButNoTextures(path,
(_, atlas) => resolve(atlas), (_, atlas) => resolve(atlas),

View File

@ -212,16 +212,16 @@ export class Input implements Disposable {
} }
} }
dispose(): void { dispose (): void {
const element = this.element; const element = this.element;
element.addEventListener("mousedown", this.callbacks.mouseDown, true); element.removeEventListener("mousedown", this.callbacks.mouseDown, true);
element.addEventListener("mousemove", this.callbacks.mouseMove, true); element.removeEventListener("mousemove", this.callbacks.mouseMove, true);
element.addEventListener("mouseup", this.callbacks.mouseUp, true); element.removeEventListener("mouseup", this.callbacks.mouseUp, true);
element.addEventListener("wheel", this.callbacks.mouseWheel, true); element.removeEventListener("wheel", this.callbacks.mouseWheel, true);
element.addEventListener("touchstart", this.callbacks.touchStart, { passive: false, capture: false }); element.removeEventListener("touchstart", this.callbacks.touchStart, { capture: false });
element.addEventListener("touchmove", this.callbacks.touchMove, { passive: false, capture: false }); element.removeEventListener("touchmove", this.callbacks.touchMove, { capture: false });
element.addEventListener("touchend", this.callbacks.touchEnd, { passive: false, capture: false }); element.removeEventListener("touchend", this.callbacks.touchEnd, { capture: false });
element.addEventListener("touchcancel", this.callbacks.touchEnd); element.removeEventListener("touchcancel", this.callbacks.touchEnd);
this.listeners.length = 0; this.listeners.length = 0;
} }

View File

@ -66,7 +66,7 @@ type BeforeAfterUpdateSpineWidgetFunction = (skeleton: Skeleton, state: Animatio
type UpdateSpineWidgetFunction = (delta: number, skeleton: Skeleton, state: AnimationState) => void; type UpdateSpineWidgetFunction = (delta: number, skeleton: Skeleton, state: AnimationState) => void;
type OffScreenUpdateBehaviourType = "pause" | "update" | "pose"; type OffScreenUpdateBehaviourType = "pause" | "update" | "pose";
function isOffScreenUpdateBehaviourType(value: string | null): value is OffScreenUpdateBehaviourType { function isOffScreenUpdateBehaviourType (value: string | null): value is OffScreenUpdateBehaviourType {
return ( return (
value === "pause" || value === "pause" ||
value === "update" || value === "update" ||
@ -75,7 +75,7 @@ function isOffScreenUpdateBehaviourType(value: string | null): value is OffScree
} }
type ModeType = "inside" | "origin"; type ModeType = "inside" | "origin";
function isModeType(value: string | null): value is ModeType { function isModeType (value: string | null): value is ModeType {
return ( return (
value === "inside" || value === "inside" ||
value === "origin" value === "origin"
@ -83,7 +83,7 @@ function isModeType(value: string | null): value is ModeType {
} }
type FitType = "fill" | "width" | "height" | "contain" | "cover" | "none" | "scaleDown"; type FitType = "fill" | "width" | "height" | "contain" | "cover" | "none" | "scaleDown";
function isFitType(value: string | null): value is FitType { function isFitType (value: string | null): value is FitType {
return ( return (
value === "fill" || value === "fill" ||
value === "width" || value === "width" ||
@ -183,10 +183,10 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
* Optional: The name of the animation to be played * Optional: The name of the animation to be played
* Connected to `animation` attribute. * Connected to `animation` attribute.
*/ */
public get animation() : string | undefined { public get animation (): string | undefined {
return this._animation; return this._animation;
} }
public set animation(value: string | undefined) { public set animation (value: string | undefined) {
this._animation = value; this._animation = value;
this.initWidget(); this.initWidget();
} }
@ -196,10 +196,10 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
* Optional: The name of the skin to be set * Optional: The name of the skin to be set
* Connected to `skin` attribute. * Connected to `skin` attribute.
*/ */
public get skin() : string | undefined { public get skin (): string | undefined {
return this._skin; return this._skin;
} }
public set skin(value: string | undefined) { public set skin (value: string | undefined) {
this._skin = value; this._skin = value;
this.initWidget(); this.initWidget();
} }
@ -257,10 +257,10 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
* the widget will have an actual size and the div reference is the widget itself, not the div parent. * the widget will have an actual size and the div reference is the widget itself, not the div parent.
* Connected to `width` attribute. * Connected to `width` attribute.
*/ */
public get width() : number { public get width (): number {
return this._width; return this._width;
} }
public set width(value: number) { public set width (value: number) {
this._width = value; this._width = value;
this.render(); this.render();
} }
@ -271,10 +271,10 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
* the widget will have an actual size and the div reference is the widget itself, not the div parent. * the widget will have an actual size and the div reference is the widget itself, not the div parent.
* Connected to `height` attribute. * Connected to `height` attribute.
*/ */
public get height() : number { public get height (): number {
return this._height; return this._height;
} }
public set height(value: number) { public set height (value: number) {
this._height = value; this._height = value;
this.render(); this.render();
} }
@ -348,12 +348,12 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
/** /**
* This callback is invoked before the world transforms are computed allows to execute additional logic. * This callback is invoked before the world transforms are computed allows to execute additional logic.
*/ */
public beforeUpdateWorldTransforms: BeforeAfterUpdateSpineWidgetFunction = () => {}; public beforeUpdateWorldTransforms: BeforeAfterUpdateSpineWidgetFunction = () => { };
/** /**
* This callback is invoked after the world transforms are computed allows to execute additional logic. * This callback is invoked after the world transforms are computed allows to execute additional logic.
*/ */
public afterUpdateWorldTransforms: BeforeAfterUpdateSpineWidgetFunction= () => {}; public afterUpdateWorldTransforms: BeforeAfterUpdateSpineWidgetFunction = () => { };
/** /**
* A callback invoked each time div hosting the widget enters the screen viewport. * A callback invoked each time div hosting the widget enters the screen viewport.
@ -510,11 +510,11 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
offscreen: { propertyName: "offScreenUpdateBehaviour", type: "offScreenUpdateBehaviourType", defaultValue: "pause" }, offscreen: { propertyName: "offScreenUpdateBehaviour", type: "offScreenUpdateBehaviourType", defaultValue: "pause" },
} }
static get observedAttributes(): string[] { static get observedAttributes (): string[] {
return Object.keys(SpineWebComponentWidget.attributesDescription); return Object.keys(SpineWebComponentWidget.attributesDescription);
} }
constructor() { constructor () {
super(); super();
this.root = this.attachShadow({ mode: "closed" }); this.root = this.attachShadow({ mode: "closed" });
this.overlay = this.initializeOverlay(); this.overlay = this.initializeOverlay();
@ -525,7 +525,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
this.debugDragDiv.style.setProperty("pointer-events", "none"); this.debugDragDiv.style.setProperty("pointer-events", "none");
} }
connectedCallback() { connectedCallback () {
if (this.disposed) { if (this.disposed) {
throw new Error("You cannot attach a disposed widget"); throw new Error("You cannot attach a disposed widget");
}; };
@ -537,7 +537,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
this.render(); this.render();
} }
disconnectedCallback(): void { disconnectedCallback (): void {
this.loadingPromise?.then(() => { this.loadingPromise?.then(() => {
const index = this.overlay.skeletonList.indexOf(this); const index = this.overlay.skeletonList.indexOf(this);
if (index !== -1) { if (index !== -1) {
@ -547,7 +547,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
this.debugDragDiv?.remove(); this.debugDragDiv?.remove();
} }
dispose() { dispose () {
this.remove(); this.remove();
this.loadingScreen?.dispose(); this.loadingScreen?.dispose();
this.skeletonData = undefined; this.skeletonData = undefined;
@ -556,7 +556,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
this.disposed = true; this.disposed = true;
} }
attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void { attributeChangedCallback (name: string, oldValue: string | null, newValue: string | null): void {
const { type, propertyName, defaultValue } = SpineWebComponentWidget.attributesDescription[name]; const { type, propertyName, defaultValue } = SpineWebComponentWidget.attributesDescription[name];
const val = SpineWebComponentWidget.castValue(type, newValue, defaultValue ?? this[propertyName]); const val = SpineWebComponentWidget.castValue(type, newValue, defaultValue ?? this[propertyName]);
(this as any)[propertyName] = val; (this as any)[propertyName] = val;
@ -567,7 +567,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
* Starts the widget. Starting the widget means to load the assets currently set into * Starts the widget. Starting the widget means to load the assets currently set into
* {@link atlasPath} and {@link skeletonPath}. * {@link atlasPath} and {@link skeletonPath}.
*/ */
public start() { public start () {
if (this.started) { if (this.started) {
console.warn("If you want to start again the widget, first reset it"); console.warn("If you want to start again the widget, first reset it");
} }
@ -588,7 +588,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
* @param atlas the `TextureAtlas` from which to get the `TextureAtlasPage`s * @param atlas the `TextureAtlas` from which to get the `TextureAtlasPage`s
* @returns The list of loaded assets * @returns The list of loaded assets
*/ */
public async loadTexturesInPagesAttribute(atlas: TextureAtlas): Promise<Array<any>> { public async loadTexturesInPagesAttribute (atlas: TextureAtlas): Promise<Array<any>> {
const pagesIndexToLoad = this.pages ?? atlas.pages.map((_, i) => i); // if no pages provided, loads all const pagesIndexToLoad = this.pages ?? atlas.pages.map((_, i) => i); // if no pages provided, loads all
const atlasPath = this.atlasPath?.includes("/") ? this.atlasPath.substring(0, this.atlasPath.lastIndexOf("/") + 1) : ""; const atlasPath = this.atlasPath?.includes("/") ? this.atlasPath.substring(0, this.atlasPath.lastIndexOf("/") + 1) : "";
const promisePageList: Array<Promise<any>> = []; const promisePageList: Array<Promise<any>> = [];
@ -604,7 +604,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
/** /**
* @returns The `HTMLElement` where the widget is hosted. * @returns The `HTMLElement` where the widget is hosted.
*/ */
public getHTMLElementReference(): HTMLElement { public getHTMLElementReference (): HTMLElement {
return this.width <= 0 || this.width <= 0 return this.width <= 0 || this.width <= 0
? this.parentElement! ? this.parentElement!
: this; : this;
@ -615,7 +615,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
* Useful when animations or skins are set programmatically. * Useful when animations or skins are set programmatically.
* @returns void * @returns void
*/ */
public recalculateBounds(): void { public recalculateBounds (): void {
const { skeleton, state } = this; const { skeleton, state } = this;
if (!skeleton || !state) return; if (!skeleton || !state) return;
const track = state.getCurrent(0); const track = state.getCurrent(0);
@ -632,7 +632,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
* @param bounds * @param bounds
* @returns * @returns
*/ */
public setBounds(bounds: Rectangle): void { public setBounds (bounds: Rectangle): void {
const { skeleton } = this; const { skeleton } = this;
if (!skeleton) return; if (!skeleton) return;
bounds.x /= skeleton.scaleX; bounds.x /= skeleton.scaleX;
@ -643,7 +643,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
} }
// add a skeleton to the overlay and set the bounds to the given animation or to the setup pose // add a skeleton to the overlay and set the bounds to the given animation or to the setup pose
private async loadSkeleton() { private async loadSkeleton () {
this.loading = true; this.loading = true;
const { atlasPath, skeletonPath, scale = 1, animation, skeletonData: skeletonDataInput, skin } = this; const { atlasPath, skeletonPath, scale = 1, animation, skeletonData: skeletonDataInput, skin } = this;
@ -692,7 +692,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
return this; return this;
} }
private initWidget() { private initWidget () {
const { skeleton, state, animation, skin } = this; const { skeleton, state, animation, skin } = this;
if (skin) skeleton?.setSkinByName(skin); if (skin) skeleton?.setSkinByName(skin);
@ -701,7 +701,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
this.recalculateBounds(); this.recalculateBounds();
} }
private render(): void { private render (): void {
let width; let width;
let height; let height;
if (this.width === -1 || this.height === -1) { if (this.width === -1 || this.height === -1) {
@ -727,7 +727,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
// Create a new overlay webcomponent, if no one exists yet. // Create a new overlay webcomponent, if no one exists yet.
// TODO: allow the possibility to instantiate multiple overlay (eg: background, foreground), // TODO: allow the possibility to instantiate multiple overlay (eg: background, foreground),
// to give them an identifier, and to specify which overlay is assigned to a widget // to give them an identifier, and to specify which overlay is assigned to a widget
private initializeOverlay(): SpineWebComponentOverlay { private initializeOverlay (): SpineWebComponentOverlay {
let overlay = this.overlay || document.querySelector("spine-overlay") as SpineWebComponentOverlay; let overlay = this.overlay || document.querySelector("spine-overlay") as SpineWebComponentOverlay;
if (!overlay) { if (!overlay) {
overlay = document.createElement("spine-overlay") as SpineWebComponentOverlay; overlay = document.createElement("spine-overlay") as SpineWebComponentOverlay;
@ -783,15 +783,15 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
} }
} }
private static castBoolean(value: string | null, defaultValue = "") { private static castBoolean (value: string | null, defaultValue = "") {
return value === "true" || value === "" ? true : false; return value === "true" || value === "" ? true : false;
} }
private static castString(value: string | null, defaultValue = "") { private static castString (value: string | null, defaultValue = "") {
return value === null ? defaultValue : value; return value === null ? defaultValue : value;
} }
private static castNumber(value: string | null, defaultValue = 0) { private static castNumber (value: string | null, defaultValue = 0) {
if (value === null) return defaultValue; if (value === null) return defaultValue;
const parsed = parseFloat(value); const parsed = parseFloat(value);
@ -799,7 +799,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
return parsed; return parsed;
} }
private static castArrayNumber(value: string | null, defaultValue = undefined) { private static castArrayNumber (value: string | null, defaultValue = undefined) {
if (value === null) return defaultValue; if (value === null) return defaultValue;
return value.split(",").reduce((acc, pageIndex) => { return value.split(",").reduce((acc, pageIndex) => {
const index = parseInt(pageIndex); const index = parseInt(pageIndex);
@ -808,7 +808,7 @@ export class SpineWebComponentWidget extends HTMLElement implements Disposable,
}, [] as Array<number>); }, [] as Array<number>);
} }
private static castValue(type: AttributeTypes, value: string | null, defaultValue?: any) { private static castValue (type: AttributeTypes, value: string | null, defaultValue?: any) {
switch (type) { switch (type) {
case "string": case "string":
return SpineWebComponentWidget.castString(value, defaultValue); return SpineWebComponentWidget.castString(value, defaultValue);
@ -839,11 +839,11 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
private root: ShadowRoot; private root: ShadowRoot;
private div: HTMLDivElement; private div: HTMLDivElement;
private canvas:HTMLCanvasElement; private canvas: HTMLCanvasElement;
private fps: HTMLSpanElement; private fps: HTMLSpanElement;
private fpsAppended = false; private fpsAppended = false;
private intersectionObserver? : IntersectionObserver; private intersectionObserver?: IntersectionObserver;
private input?: Input; private input?: Input;
// how many pixels to add to the edges to prevent "edge cuttin" on fast scrolling // how many pixels to add to the edges to prevent "edge cuttin" on fast scrolling
@ -863,7 +863,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
private loaded = false; private loaded = false;
readonly time = new TimeKeeper(); readonly time = new TimeKeeper();
constructor() { constructor () {
super(); super();
this.root = this.attachShadow({ mode: "closed" }); this.root = this.attachShadow({ mode: "closed" });
@ -884,7 +884,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
this.canvas.style.left = "0"; this.canvas.style.left = "0";
this.canvas.style.setProperty("pointer-events", "none"); this.canvas.style.setProperty("pointer-events", "none");
this.canvas.style.transform =`translate(0px,0px)`; this.canvas.style.transform = `translate(0px,0px)`;
// this.canvas.style.setProperty("will-change", "transform"); // performance seems to be even worse with this uncommented // this.canvas.style.setProperty("will-change", "transform"); // performance seems to be even worse with this uncommented
this.fps = document.createElement("span"); this.fps = document.createElement("span");
@ -924,7 +924,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
this.loaded = true; this.loaded = true;
} }
connectedCallback(): void { connectedCallback (): void {
window.addEventListener("resize", this.resizeCallback); window.addEventListener("resize", this.resizeCallback);
window.addEventListener("scroll", this.scrollHandler); window.addEventListener("scroll", this.scrollHandler);
window.addEventListener("load", this.onLoadCallback); window.addEventListener("load", this.onLoadCallback);
@ -955,7 +955,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
this.startRenderingLoop(); this.startRenderingLoop();
} }
disconnectedCallback(): void { disconnectedCallback (): void {
window.removeEventListener("resize", this.resizeCallback); window.removeEventListener("resize", this.resizeCallback);
window.removeEventListener("scroll", this.scrollHandler); window.removeEventListener("scroll", this.scrollHandler);
window.removeEventListener("load", this.onLoadCallback); window.removeEventListener("load", this.onLoadCallback);
@ -964,19 +964,19 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
this.input?.dispose(); this.input?.dispose();
} }
dispose(): void { dispose (): void {
this.remove(); this.remove();
this.skeletonList.length = 0; this.skeletonList.length = 0;
this.renderer.dispose(); this.renderer.dispose();
this.disposed = true; this.disposed = true;
} }
addWidget(widget: SpineWebComponentWidget) { addWidget (widget: SpineWebComponentWidget) {
this.skeletonList.push(widget); this.skeletonList.push(widget);
this.intersectionObserver?.observe(widget.getHTMLElementReference()); this.intersectionObserver?.observe(widget.getHTMLElementReference());
} }
private startRenderingLoop() { private startRenderingLoop () {
const updateWidgets = () => { const updateWidgets = () => {
const delta = this.time.delta; const delta = this.time.delta;
this.skeletonList.forEach(({ skeleton, state, update, onScreen, offScreenUpdateBehaviour, beforeUpdateWorldTransforms, afterUpdateWorldTransforms }) => { this.skeletonList.forEach(({ skeleton, state, update, onScreen, offScreenUpdateBehaviour, beforeUpdateWorldTransforms, afterUpdateWorldTransforms }) => {
@ -988,7 +988,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
state.update(delta); state.update(delta);
skeleton.update(delta); skeleton.update(delta);
if (onScreen || (!onScreen && offScreenUpdateBehaviour === "pose") ) { if (onScreen || (!onScreen && offScreenUpdateBehaviour === "pose")) {
state.apply(skeleton); state.apply(skeleton);
beforeUpdateWorldTransforms(skeleton, state); beforeUpdateWorldTransforms(skeleton, state);
skeleton.updateWorldTransform(Physics.update); skeleton.updateWorldTransform(Physics.update);
@ -1126,7 +1126,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
ratioH = scaleHeight; ratioH = scaleHeight;
} else if (fit === "contain") { } else if (fit === "contain") {
// if scaled height is bigger than div height, use height ratio instead // if scaled height is bigger than div height, use height ratio instead
if (ah * scaleWidth > divHeightWorld){ if (ah * scaleWidth > divHeightWorld) {
ratioW = scaleHeight; ratioW = scaleHeight;
ratioH = scaleHeight; ratioH = scaleHeight;
} else { } else {
@ -1134,7 +1134,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
ratioH = scaleWidth; ratioH = scaleWidth;
} }
} else if (fit === "cover") { } else if (fit === "cover") {
if (ah * scaleWidth < divHeightWorld){ if (ah * scaleWidth < divHeightWorld) {
ratioW = scaleHeight; ratioW = scaleHeight;
ratioH = scaleHeight; ratioH = scaleHeight;
} else { } else {
@ -1143,7 +1143,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
} }
} else if (fit === "scaleDown") { } else if (fit === "scaleDown") {
if (aw > divWidthWorld || ah > divHeightWorld) { if (aw > divWidthWorld || ah > divHeightWorld) {
if (ah * scaleWidth > divHeightWorld){ if (ah * scaleWidth > divHeightWorld) {
ratioW = scaleHeight; ratioW = scaleHeight;
ratioH = scaleHeight; ratioH = scaleHeight;
} else { } else {
@ -1173,9 +1173,9 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
const worldOffsetY = divOriginY + offsetY + dragY; const worldOffsetY = divOriginY + offsetY + dragY;
renderer.drawSkeleton(skeleton, true, -1, -1, (vertices, size, vertexSize) => { renderer.drawSkeleton(skeleton, true, -1, -1, (vertices, size, vertexSize) => {
for (let i = 0; i < size; i+=vertexSize) { for (let i = 0; i < size; i += vertexSize) {
vertices[i] = vertices[i] + worldOffsetX; vertices[i] = vertices[i] + worldOffsetX;
vertices[i+1] = vertices[i+1] + worldOffsetY; vertices[i + 1] = vertices[i + 1] + worldOffsetY;
} }
}); });
@ -1255,7 +1255,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
const transparentWhite = new Color(1, 1, 1, .3); const transparentWhite = new Color(1, 1, 1, .3);
} }
private setupDragUtility(): Input { private setupDragUtility (): Input {
// TODO: we should use document - body might have some margin that offset the click events - Meanwhile I take event pageX/Y // TODO: we should use document - body might have some margin that offset the click events - Meanwhile I take event pageX/Y
const inputManager = new Input(document.body, false) const inputManager = new Input(document.body, false)
const point: Point = { x: 0, y: 0 }; const point: Point = { x: 0, y: 0 };
@ -1312,7 +1312,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
* Resize/scroll utilities * Resize/scroll utilities
*/ */
private updateCanvasSize() { private updateCanvasSize () {
// resize canvas, if necessary // resize canvas, if necessary
this.resizeCanvas(); this.resizeCanvas();
@ -1327,7 +1327,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
this.div.style.height = height + "px"; this.div.style.height = height + "px";
} }
private resizeCanvas() { private resizeCanvas () {
let { width, height } = this.getScreenSize(); let { width, height } = this.getScreenSize();
// this is needed because screen size is wrong when zoom levels occurs // this is needed because screen size is wrong when zoom levels occurs
@ -1354,10 +1354,10 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
} }
} }
private translateCanvas() { private translateCanvas () {
const scrollPositionX = window.scrollX - this.overflowLeftSize; const scrollPositionX = window.scrollX - this.overflowLeftSize;
const scrollPositionY = window.scrollY - this.overflowTopSize; const scrollPositionY = window.scrollY - this.overflowTopSize;
this.canvas.style.transform =`translate(${scrollPositionX}px,${scrollPositionY}px)`; this.canvas.style.transform = `translate(${scrollPositionX}px,${scrollPositionY}px)`;
requestAnimationFrame(() => { requestAnimationFrame(() => {
if (this.isConnected) this.translateCanvas(); if (this.isConnected) this.translateCanvas();
}); });
@ -1379,7 +1379,7 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
this.resize(parseFloat(this.canvas.style.width), parseFloat(this.canvas.style.height)); this.resize(parseFloat(this.canvas.style.width), parseFloat(this.canvas.style.height));
} }
private resize(width: number, height: number) { private resize (width: number, height: number) {
let canvas = this.canvas; let canvas = this.canvas;
const dpr = window.devicePixelRatio; const dpr = window.devicePixelRatio;
this.canvas.width = Math.round(width * dpr); this.canvas.width = Math.round(width * dpr);
@ -1392,13 +1392,13 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
// we need the bounding client rect otherwise decimals won't be returned // we need the bounding client rect otherwise decimals won't be returned
// this means that during zoom it might occurs that the div would be resized // this means that during zoom it might occurs that the div would be resized
// rounded 1px more making a scrollbar appear // rounded 1px more making a scrollbar appear
private getPageSize() { private getPageSize () {
return document.body.getBoundingClientRect(); return document.body.getBoundingClientRect();
} }
// screen size remain the same when it is rotated // screen size remain the same when it is rotated
// we need to swap them based and the orientation angle // we need to swap them based and the orientation angle
private getScreenSize() { private getScreenSize () {
const { screen } = window; const { screen } = window;
const { width, height } = window.screen; const { width, height } = window.screen;
const angle = screen.orientation.angle; const angle = screen.orientation.angle;
@ -1411,12 +1411,12 @@ class SpineWebComponentOverlay extends HTMLElement implements Disposable {
/* /*
* Other utilities * Other utilities
*/ */
private screenToWorld(vec: Vector3, x: number, y: number) { private screenToWorld (vec: Vector3, x: number, y: number) {
vec.set(x, y, 0); vec.set(x, y, 0);
// pay attention that clientWidth/Height rounds the size - if we don't like it, we should use getBoundingClientRect as in getPagSize // pay attention that clientWidth/Height rounds the size - if we don't like it, we should use getBoundingClientRect as in getPagSize
this.renderer.camera.screenToWorld(vec, this.canvas.clientWidth, this.canvas.clientHeight); this.renderer.camera.screenToWorld(vec, this.canvas.clientWidth, this.canvas.clientHeight);
} }
private worldToScreen(vec: Vector3, x: number, y: number) { private worldToScreen (vec: Vector3, x: number, y: number) {
vec.set(x, -y, 0); vec.set(x, -y, 0);
// pay attention that clientWidth/Height rounds the size - if we don't like it, we should use getBoundingClientRect as in getPagSize // pay attention that clientWidth/Height rounds the size - if we don't like it, we should use getBoundingClientRect as in getPagSize
// this.renderer.camera.worldToScreen(vec, this.canvas.clientWidth, this.canvas.clientHeight); // this.renderer.camera.worldToScreen(vec, this.canvas.clientWidth, this.canvas.clientHeight);
@ -1436,11 +1436,11 @@ const inside = (point: { x: number; y: number }, rectangle: Rectangle): boolean
customElements.define("spine-widget", SpineWebComponentWidget); customElements.define("spine-widget", SpineWebComponentWidget);
customElements.define("spine-overlay", SpineWebComponentOverlay); customElements.define("spine-overlay", SpineWebComponentOverlay);
export function getSpineWidget(identifier: string): SpineWebComponentWidget { export function getSpineWidget (identifier: string): SpineWebComponentWidget {
return document.querySelector(`spine-widget[identifier=${identifier}]`) as SpineWebComponentWidget; return document.querySelector(`spine-widget[identifier=${identifier}]`) as SpineWebComponentWidget;
} }
export function createSpineWidget(parameters: WidgetAttributes): SpineWebComponentWidget { export function createSpineWidget (parameters: WidgetAttributes): SpineWebComponentWidget {
const widget = document.createElement("spine-widget") as SpineWebComponentWidget; const widget = document.createElement("spine-widget") as SpineWebComponentWidget;
Object.entries(SpineWebComponentWidget.attributesDescription).forEach(entry => { Object.entries(SpineWebComponentWidget.attributesDescription).forEach(entry => {