kritzel-stencil 0.3.36 → 0.3.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/cjs/index.cjs.js +1 -1
  2. package/dist/cjs/kritzel-active-users_46.cjs.entry.js +2 -2
  3. package/dist/cjs/{schema.constants-Di56GD6q.js → schema.constants-fuAsi56H.js} +55 -11
  4. package/dist/collection/classes/objects/path.class.js +55 -11
  5. package/dist/collection/constants/version.js +1 -1
  6. package/dist/components/index.js +1 -1
  7. package/dist/components/kritzel-awareness-cursors.js +1 -1
  8. package/dist/components/kritzel-controls.js +1 -1
  9. package/dist/components/kritzel-editor.js +1 -1
  10. package/dist/components/kritzel-engine.js +1 -1
  11. package/dist/components/kritzel-settings.js +1 -1
  12. package/dist/components/kritzel-tool-config.js +1 -1
  13. package/dist/components/{p-nxfv7vyD.js → p-5uYZiJvd.js} +1 -1
  14. package/dist/components/{p-BlozPPKi.js → p-BR0Hnrhc.js} +1 -1
  15. package/dist/components/{p-BH4AasB1.js → p-C4XDwGU0.js} +1 -1
  16. package/dist/components/{p-BoA6RXEA.js → p-CwbZCXKh.js} +1 -1
  17. package/dist/components/{p-BJlf4iHH.js → p-D8NvNMcU.js} +1 -1
  18. package/dist/components/{p-BcAIRHf1.js → p-DVq8T3Mv.js} +2 -2
  19. package/dist/components/p-UEf2EN23.js +1 -0
  20. package/dist/esm/index.js +2 -2
  21. package/dist/esm/kritzel-active-users_46.entry.js +2 -2
  22. package/dist/esm/{schema.constants-Cphx5M7a.js → schema.constants-Cv5-yM39.js} +55 -11
  23. package/dist/stencil/index.esm.js +1 -1
  24. package/dist/stencil/p-Cv5-yM39.js +1 -0
  25. package/dist/stencil/{p-e6d0699a.entry.js → p-ddc462e9.entry.js} +2 -2
  26. package/dist/stencil/stencil.esm.js +1 -1
  27. package/dist/types/classes/objects/path.class.d.ts +30 -2
  28. package/dist/types/constants/version.d.ts +1 -1
  29. package/package.json +1 -1
  30. package/dist/components/p-2Swq9rEm.js +0 -1
  31. package/dist/stencil/p-Cphx5M7a.js +0 -1
@@ -0,0 +1 @@
1
+ import{O as t}from"./p-Dd-pMvlr.js";import{a as i}from"./p-BmyTdQGy.js";class s{static doPolygonsIntersect(t,i){const s=[t.bottomLeft,t.bottomRight,t.topRight,t.topLeft],h=[i.bottomLeft,i.bottomRight,i.topRight,i.topLeft];for(const t of s)if(this.isPointInPolygon(t,h))return!0;for(const t of h)if(this.isPointInPolygon(t,s))return!0;for(let t=0;t<s.length;t++){const i=s[t],e=s[(t+1)%s.length];for(let t=0;t<h.length;t++)if(this.intersectLines(i,e,h[t],h[(t+1)%h.length]))return!0}return!1}static isPointInPolygon(t,i){let s=!1;for(let h=0,e=i.length-1;h<i.length;e=h++){const n=i[h].x,r=i[h].y,o=i[e].y;r>t.y!=o>t.y&&t.x<(i[e].x-n)*(t.y-r)/(o-r)+n&&(s=!s)}return s}static intersectLines(t,i,s,h){const e=(i.x-t.x)*(h.y-s.y)-(i.y-t.y)*(h.x-s.x);if(0===e)return!1;const n=((s.x-t.x)*(h.y-s.y)-(s.y-t.y)*(h.x-s.x))/e,r=-((t.x-s.x)*(i.y-t.y)-(t.y-s.y)*(i.x-t.x))/e;return n>=0&&n<=1&&r>=0&&r<=1}static getLineIntersectionPoint(t,i,s,h){const e=(i.x-t.x)*(h.y-s.y)-(i.y-t.y)*(h.x-s.x);if(0===e)return null;const n=((s.x-t.x)*(h.y-s.y)-(s.y-t.y)*(h.x-s.x))/e,r=-((t.x-s.x)*(i.y-t.y)-(t.y-s.y)*(i.x-t.x))/e;return n>=0&&n<=1&&r>=0&&r<=1?{x:t.x+n*(i.x-t.x),y:t.y+n*(i.y-t.y)}:null}static getLinePolygonIntersection(t,i,s){const h=[s.topLeft,s.topRight,s.bottomRight,s.bottomLeft];let e=null,n=1/0;for(let s=0;s<h.length;s++){const r=this.getLineIntersectionPoint(t,i,h[s],h[(s+1)%h.length]);if(r){const i=Math.sqrt(Math.pow(r.x-t.x,2)+Math.pow(r.y-t.y,2));i<n&&(n=i,e=r)}}return e}static getEllipsePolygonApproximation(t,i,s,h,e=32,n=0){const r=[],o=Math.cos(n),a=Math.sin(n);for(let n=0;n<e;n++){const u=2*Math.PI*n/e,l=s*Math.cos(u),c=h*Math.sin(u);r.push({x:t+l*o-c*a,y:i+l*a+c*o})}return r}static getLinePointsArrayIntersection(t,i,s){let h=null,e=1/0;for(let n=0;n<s.length;n++){const r=this.getLineIntersectionPoint(t,i,s[n],s[(n+1)%s.length]);if(r){const i=Math.sqrt(Math.pow(r.x-t.x,2)+Math.pow(r.y-t.y,2));i<e&&(e=i,h=r)}}return h}static isPointInPolygonPoints(t,i){return this.isPointInPolygon(t,i)}}class h{__class__="KritzelBaseObject";_core;_elementRef;id;workspaceId;x;y;translateX;translateY;height;width;backgroundColor;borderColor;borderWidth=0;opacity=1;padding=0;scale;resizing=!1;rotation=0;markedForRemoval=!1;zIndex=0;userId;isVisible=!0;isSelected=!1;isHovered=!1;isMounted=!1;isEditable=!1;isInteractive=!1;isResizable=!0;isRotatable=!0;get totalWidth(){return this.width+2*this.padding}get totalHeight(){return this.height+2*this.padding}set elementRef(t){this._elementRef=t}get elementRef(){return this._elementRef}get boundingBox(){return{x:this.translateX,y:this.translateY,z:this.scale,width:this.totalWidth/this.scale,height:this.totalHeight/this.scale}}get rotatedBoundingBox(){const t=this.rotatedPolygon,i=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],s=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],h=Math.min(...i),e=Math.max(...i),n=Math.min(...s),r=Math.max(...s);return{x:h,y:n,z:this.scale,width:e-h,height:r-n}}get rotatedPolygon(){const t=this.translateX+this.totalWidth/2/this.scale,i=this.translateY+this.totalHeight/2/this.scale,s=this.rotation,h=Math.cos(s),e=Math.sin(s),n=this.translateX,r=this.translateY,o=n+this.totalWidth/this.scale,a=r+this.totalHeight/this.scale,u=(s,n)=>({x:h*(s-t)-e*(n-i)+t,y:e*(s-t)+h*(n-i)+i});return{topLeft:u(n,r),topRight:u(o,r),bottomRight:u(o,a),bottomLeft:u(n,a)}}get minXRotated(){return Math.min(this.rotatedPolygon.topLeft.x,this.rotatedPolygon.topRight.x,this.rotatedPolygon.bottomRight.x,this.rotatedPolygon.bottomLeft.x)}get minYRotated(){return Math.min(this.rotatedPolygon.topLeft.y,this.rotatedPolygon.topRight.y,this.rotatedPolygon.bottomRight.y,this.rotatedPolygon.bottomLeft.y)}get maxXRotated(){return Math.max(this.rotatedPolygon.topLeft.x,this.rotatedPolygon.topRight.x,this.rotatedPolygon.bottomRight.x,this.rotatedPolygon.bottomLeft.x)}get maxYRotated(){return Math.max(this.rotatedPolygon.topLeft.y,this.rotatedPolygon.topRight.y,this.rotatedPolygon.bottomRight.y,this.rotatedPolygon.bottomLeft.y)}get transformationMatrix(){const t=1/this.scale;return`matrix(${t}, 0, 0, ${t}, ${this.translateX}, ${this.translateY})`}get rotationDegrees(){return this.rotation*(180/Math.PI)}get centerX(){return this.translateX+this.totalWidth/2/this.scale}get centerY(){return this.translateY+this.totalHeight/2/this.scale}constructor(){this.id=this.generateId()}static create(t){const i=new h;return i._core=t,i.zIndex=t.store.currentZIndex,i.workspaceId=t.store.state.activeWorkspace.id,i.userId=t.user?.id,i}mount(t){this.isMounted||(this.elementRef=t,this.isMounted=!0)}generateId(){return t.generateUUID()}isInViewport(){const t=this._core.store.state.scale;if(this.boundingBox.width*t*(this.boundingBox.height*t)<.5)return!1;const i=-this._core.store.state.translateX/this._core.store.state.scale,s=-this._core.store.state.translateY/this._core.store.state.scale;return this.rotatedBoundingBox.x<i+this._core.store.state.viewportWidth/this._core.store.state.scale&&this.rotatedBoundingBox.x+this.rotatedBoundingBox.width>i&&this.rotatedBoundingBox.y<s+this._core.store.state.viewportHeight/this._core.store.state.scale&&this.rotatedBoundingBox.y+this.rotatedBoundingBox.height>s}centerInViewport(){const{viewportWidth:t,viewportHeight:i,translateX:s,translateY:h,scale:e}=this._core.store.state,{x:n,y:r,width:o,height:a}=this.rotatedBoundingBox;this.updatePosition(this.translateX+((t/2-s)/e-(n+o/2)),this.translateY+((i/2-h)/e-(r+a/2)))}update(){this._core.store.objects.update(this)}move(t,i,s,h){const e=(i-h)/this._core.store.state.scale;this.translateX+=(t-s)/this._core.store.state.scale,this.translateY+=e,this._core.store.objects.update(this)}resize(t,i,s,h){s<=1||h<=1||(this.width=s,this.height=h,this.translateX=t,this.translateY=i,this._core.store.objects.update(this),this._core.anchorManager.updateAnchorsForObject(this.id))}rotate(t){this.rotation=t,this._core.store.objects.update(this)}clone(){const t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this),t.id=this.id,t}copy(){const t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this),t.id=this.generateId(),t.isMounted=!1,t.isSelected=!1,t.isHovered=!1,t.isInteractive=!1,t.resizing=!1,t.markedForRemoval=!1,t.isVisible=!0,t}serialize(){const{_core:t,_elementRef:i,element:s,totalWidth:h,totalHeight:e,isSelected:n,isHovered:r,isMounted:o,isInteractive:a,resizing:u,markedForRemoval:l,isVisible:c,...f}=this;return structuredClone(f)}deserialize(t){return Object.assign(this,t),this.isSelected=!1,this.isHovered=!1,this.isMounted=!1,this.isInteractive=!1,this.resizing=!1,this.markedForRemoval=!1,this.isVisible=!0,"_adjustedPoints"in this&&(this._adjustedPoints=null),"_clipInfo"in this&&(this._clipInfo=null),this}adoptTransientStateFrom(t){}isClass(t){return this.__class__===t}edit(t){}onAfterUpdate(t){}hitTest(t,i){return!0}hitTestPolygon(t){return s.doPolygonsIntersect(this.rotatedPolygon,t)}updatePosition(t,i){this.translateX=t,this.translateY=i,this._core.store.objects.update(this)}}class e{static average(t,i){return(t+i)/2}static degreesToRadians(t){return t*(Math.PI/180)}}var n,r={},o=(n||(n=1,function(t){Object.defineProperties(t,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const{PI:i}=Math,s=i+1e-4,h=[1,1];function e(t,i,s,h=t=>t){return t*h(.5-i*(.5-s))}const{min:n}=Math;function r(t,i,s){let h=n(1,i/s);return n(1,t+(n(1,1-h)-t)*(.275*h))}function o(t,i){return[t[0]+i[0],t[1]+i[1]]}function a(t,i,s){return t[0]=i[0]+s[0],t[1]=i[1]+s[1],t}function u(t,i){return[t[0]-i[0],t[1]-i[1]]}function l(t,i,s){return t[0]=i[0]-s[0],t[1]=i[1]-s[1],t}function c(t,i){return[t[0]*i,t[1]*i]}function f(t,i,s){return t[0]=i[0]*s,t[1]=i[1]*s,t}function d(t){return[t[1],-t[0]]}function M(t,i){let s=i[0];return t[0]=i[1],t[1]=-s,t}function g(t,i){return t[0]*i[0]+t[1]*i[1]}function m(t,i){return t[0]===i[0]&&t[1]===i[1]}function p(t,i){let s=t[0]-i[0],h=t[1]-i[1];return s*s+h*h}function x(t){return function(t,i){return[t[0]/i,t[1]/i]}(t,function(t){return Math.hypot(t[0],t[1])}(t))}function y(t,i){return Math.hypot(t[1]-i[1],t[0]-i[0])}function v(t,i,s){let h=Math.sin(s),e=Math.cos(s),n=t[0]-i[0],r=t[1]-i[1];return[n*e-r*h+i[0],n*h+r*e+i[1]]}function P(t,i,s,h){let e=Math.sin(h),n=Math.cos(h),r=i[0]-s[0],o=i[1]-s[1],a=r*e+o*n;return t[0]=r*n-o*e+s[0],t[1]=a+s[1],t}function b(t,i,s){return o(t,c(u(i,t),s))}function $(t,i,s,h){let e=s[1]-i[1];return t[0]=i[0]+(s[0]-i[0])*h,t[1]=i[1]+e*h,t}function w(t,i,s){return o(t,c(i,s))}const z=[0,0],L=[0,0],_=[0,0];function I(t,i){let h=w(t,x(d(u(t,o(t,[1,1])))),-i),e=[],n=1/13;for(let i=n;i<=1;i+=n)e.push(v(h,t,2*s*i));return e}function X(t,i,h){let e=[],n=1/h;for(let h=n;h<=1;h+=n)e.push(v(i,t,s*h));return e}function Y(t,i,s){let h=u(i,s),e=c(h,.5),n=c(h,.51);return[u(t,e),u(t,n),o(t,n),o(t,e)]}function k(t,i,h,e){let n=[],r=w(t,i,h),o=1/e;for(let i=o;i<1;i+=o)n.push(v(r,t,3*s*i));return n}function R(t,i,s){return[o(t,c(i,s)),o(t,c(i,.99*s)),u(t,c(i,.99*s)),u(t,c(i,s))]}function j(t,i,s){return!1===t||void 0===t?0:!0===t?Math.max(i,s):t}function A(t,i={}){let{size:h=16,smoothing:n=.5,thinning:c=.5,simulatePressure:m=!0,easing:x=t=>t,start:y={},end:v={},last:b=!1}=i,{cap:w=!0,easing:A=t=>t*(2-t)}=y,{cap:B=!0,easing:S=t=>--t*t*t+1}=v;if(0===t.length||h<=0)return[];let T,C=t[t.length-1].runningLength,O=j(y.taper,h,C),D=j(v.taper,h,C),V=(h*n)**2,W=[],F=[],H=function(t,i,s){return t.slice(0,10).reduce(((t,h)=>{let e=h.pressure;return i&&(e=r(t,h.distance,s)),(t+e)/2}),t[0].pressure)}(t,m,h),E=e(h,c,t[t.length-1].pressure,x),K=t[0].vector,Q=t[0].point,U=Q,G=Q,Z=U,q=!1;for(let i=0;i<t.length;i++){let{pressure:n}=t[i],{point:d,vector:y,distance:v,runningLength:b}=t[i],w=i===t.length-1;if(!w&&C-b<3)continue;c?(m&&(n=r(H,v,h)),E=e(h,c,n,x)):E=h/2,void 0===T&&(T=E);let I=b<O?A(b/O):1,X=C-b<D?S((C-b)/D):1;E=Math.max(.01,E*Math.min(I,X));let Y=(w?t[i]:t[i+1]).vector,k=w?1:g(y,Y),R=null!==k&&k<0;if(g(y,K)<0&&!q||R){M(z,K),f(z,z,E);for(let t=0;t<=1;t+=.07692307692307693)l(L,d,z),P(L,L,d,s*t),G=[L[0],L[1]],W.push(G),a(_,d,z),P(_,_,d,s*-t),Z=[_[0],_[1]],F.push(Z);Q=G,U=Z,R&&(q=!0)}else q=!1,w?(M(z,y),f(z,z,E),W.push(u(d,z)),F.push(o(d,z))):($(z,Y,y,k),M(z,z),f(z,z,E),l(L,d,z),G=[L[0],L[1]],(i<=1||p(Q,G)>V)&&(W.push(G),Q=G),a(_,d,z),Z=[_[0],_[1]],(i<=1||p(U,Z)>V)&&(F.push(Z),U=Z),H=n,K=y)}let J=[t[0].point[0],t[0].point[1]],N=t.length>1?[t[t.length-1].point[0],t[t.length-1].point[1]]:o(t[0].point,[1,1]),tt=[],it=[];if(1===t.length){if(!O&&!D||b)return I(J,T||E)}else{O||D&&1===t.length||(w?tt.push(...X(J,F[0],13)):tt.push(...Y(J,W[0],F[0])));let i=d(function(t){return[-t[0],-t[1]]}(t[t.length-1].vector));D||O&&1===t.length?it.push(N):B?it.push(...k(N,i,E,29)):it.push(...R(N,i,E))}return W.concat(it,F.reverse(),tt)}const B=[0,0];function S(t){return null!=t&&t>=0}function T(t,i={}){let{streamline:s=.5,size:e=16,last:n=!1}=i;if(0===t.length)return[];let r=.15+.85*(1-s),a=Array.isArray(t[0])?t:t.map((({x:t,y:i,pressure:s=.5})=>[t,i,s]));if(2===a.length){let t=a[1];a=a.slice(0,-1);for(let i=1;i<5;i++)a.push(b(a[0],t,i/4))}1===a.length&&(a=[...a,[...o(a[0],h),...a[0].slice(2)]]);let u=[{point:[a[0][0],a[0][1]],pressure:S(a[0][2])?a[0][2]:.25,vector:[...h],distance:0,runningLength:0}],c=!1,f=0,d=u[0],M=a.length-1;for(let t=1;t<a.length;t++){let i=n&&t===M?[a[t][0],a[t][1]]:b(d.point,a[t],r);if(m(d.point,i))continue;let s=y(i,d.point);if(f+=s,t<M&&!c){if(f<e)continue;c=!0}l(B,d.point,i),d={point:i,pressure:S(a[t][2])?a[t][2]:.5,vector:x(B),distance:s,runningLength:f},u.push(d)}return u[0].vector=u[1]?.vector||[0,0],u}function C(t,i={}){return A(T(t,i),i)}t.default=C,t.getStroke=C,t.getStrokeOutlinePoints=A,t.getStrokePoints=T}(r)),r);class a extends h{__class__="KritzelPath";points;d;stroke={light:"none",dark:"none"};strokeWidth;lineSlack=.5;fill;x=0;y=0;height=0;width=0;scale=1;options;isVisible=!0;isDebugInfoVisible=!0;isCompleted=!1;_adjustedPoints=null;get viewBox(){return`0 0 ${this.width} ${this.height}`}constructor(t){super(),this.options=t,this.points=t?.points??[],this.translateX=t?.translateX??0,this.translateY=t?.translateY??0,this.rotation=e.degreesToRadians(t?.rotation??0),this.scale=t?.scale??1,this.strokeWidth=t?.strokeWidth??8,this.fill=t?.fill??{light:"#000000",dark:"#ffffff"},this.d=this.generateSvgPath(),this.updateDimensions()}static create(t,i){const s=new a;return s._core=t,s.id=s.generateId(),s.workspaceId=t.store.state.activeWorkspace.id,s.userId=t.user?.id,s.options=i,s.points=i?.points??[],s.translateX=i?.translateX??0,s.translateY=i?.translateY??0,s.rotation=e.degreesToRadians(i?.rotation??0),s.scale=i?.scale??1,s.strokeWidth=i?.strokeWidth??8,s.fill=i?.fill??{light:"#000000",dark:"#ffffff"},s.opacity=i?.opacity??1,s.zIndex=t.store.currentZIndex,s.d=s.generateSvgPath(),s.updateDimensions(),s}copy(){const t=super.copy();return this.points&&(t.points=this.points.map((t=>[...t]))),t}deserialize(t){const i=super.deserialize(t);return this.d=this.generateSvgPath(),i}resize(t,i,s,h){if(s<=1||h<=1)return;const e=s/this.width,n=h/this.height;if(this.width=s,this.height=h,1===this.points.length){const t=this.points[0],i=Math.max(0,s-this.strokeWidth)/e,r=Math.max(0,h-this.strokeWidth)/n;this.points.push([t[0]+i,t[1]+r])}this.points=this.points.map((([t,i])=>[t*e,i*n])),this.d=this.generateSvgPath(),this.width=Math.max(...this.points.map((t=>t[0])))-Math.min(...this.points.map((t=>t[0])))+this.strokeWidth,this.height=Math.max(...this.points.map((t=>t[1])))-Math.min(...this.points.map((t=>t[1])))+this.strokeWidth,this.x=Math.min(...this.points.map((t=>t[0])))-this.strokeWidth/2,this.y=Math.min(...this.points.map((t=>t[1])))-this.strokeWidth/2,null!==t&&(this.translateX=t),null!==i&&(this.translateY=i),this._adjustedPoints=null,this._core.store.objects.update(this)}rotate(t){this.rotation=t,this._adjustedPoints=null,this._core.store.objects.update(this)}move(t,i,s,h){const e=(i-h)/this._core.store.state.scale;this.translateX+=(t-s)/this._core.store.state.scale,this.translateY+=e,this._adjustedPoints=null,this._core.store.objects.update(this)}hitTest(t,i){const s=this.strokeWidth/this.scale/2;if(null===this._adjustedPoints&&(this._adjustedPoints=this.computeAdjustedPoints()),1===this._adjustedPoints.length){const h=this._adjustedPoints[0];return this.pointToLineSegmentDistance(t,i,h[0],h[1],h[0],h[1])<=s}for(let h=0;h<this._adjustedPoints.length-1;h++){const e=this._adjustedPoints[h],n=this._adjustedPoints[h+1];if(this.pointToLineSegmentDistance(t,i,e[0],e[1],n[0],n[1])<=s)return!0}return!1}hitTestPolygon(t){const i=this.strokeWidth/this.scale/2;null===this._adjustedPoints&&(this._adjustedPoints=this.computeAdjustedPoints());const h=[{x:t.bottomLeft.x,y:t.bottomLeft.y},{x:t.bottomRight.x,y:t.bottomRight.y},{x:t.topRight.x,y:t.topRight.y},{x:t.topLeft.x,y:t.topLeft.y}];for(const[t,i]of this._adjustedPoints)if(s.isPointInPolygon({x:t,y:i},h))return!0;for(const t of h)if(this.hitTest(t.x,t.y))return!0;for(let t=0;t<this._adjustedPoints.length-1;t++){const i={x:this._adjustedPoints[t][0],y:this._adjustedPoints[t][1]},e={x:this._adjustedPoints[t+1][0],y:this._adjustedPoints[t+1][1]};for(let t=0;t<h.length;t++)if(s.intersectLines(i,e,h[t],h[(t+1)%h.length]))return!0}for(let t=0;t<this._adjustedPoints.length-1;t++){const s=this._adjustedPoints[t],e=this._adjustedPoints[t+1];for(let t=0;t<h.length;t++){const n=h[t],r=h[(t+1)%h.length],o=this.pointToLineSegmentDistance(n.x,n.y,s[0],s[1],e[0],e[1]),a=this.pointToLineSegmentDistance(r.x,r.y,s[0],s[1],e[0],e[1]),u=this.pointToLineSegmentDistance(s[0],s[1],n.x,n.y,r.x,r.y),l=this.pointToLineSegmentDistance(e[0],e[1],n.x,n.y,r.x,r.y);if(Math.min(o,a,u,l)<=i)return!0}}return!1}updatePosition(t,i){this.translateX=t,this.translateY=i,this._adjustedPoints=null,this._core.store.objects.update(this)}onAfterUpdate(t){t.includes("strokeWidth")&&(this.d=this.generateSvgPath(),this.updateBoundingBox(),this._adjustedPoints=null)}computeAdjustedPoints(){if(!this.points?.length)return[];const t=this.rotation,i=Math.cos(t),s=Math.sin(t),h=this.points.map((t=>t[0])),e=this.points.map((t=>t[1])),n={x:(Math.min(...h)+Math.max(...h))/2,y:(Math.min(...e)+Math.max(...e))/2},{x:r,y:o}=n;return this.points.map((([t,h])=>{const e=t-r,n=h-o;return[r+e*i-n*s,o+e*s+n*i]})).map((([t,i])=>[Math.abs(t-this.x)/this.scale+this.translateX,Math.abs(i-this.y)/this.scale+this.translateY]))}pointToLineSegmentDistance(t,i,s,h,e,n){const r=e-s,o=n-h,a=r*r+o*o;let u,l,c=-1;0!==a&&(c=((t-s)*r+(i-h)*o)/a),c<0?(u=s,l=h):c>1?(u=e,l=n):(u=s+c*r,l=h+c*o);const f=t-u,d=i-l;return Math.sqrt(f*f+d*d)}updateDimensions(){const t=Math.min(...this.points.map((t=>t[0])))-this.strokeWidth/2,i=Math.min(...this.points.map((t=>t[1])))-this.strokeWidth/2,s=Math.max(...this.points.map((t=>t[0])))+this.strokeWidth/2,h=Math.max(...this.points.map((t=>t[1])))+this.strokeWidth/2;this.width=s-t+this.lineSlack,this.height=h-i+this.lineSlack,this.x=t,this.y=i,this.translateX=(this.x+this.translateX)/this.scale,this.translateY=(this.y+this.translateY)/this.scale}updateBoundingBox(){const t=Math.min(...this.points.map((t=>t[0])))-this.strokeWidth/2,i=Math.min(...this.points.map((t=>t[1])))-this.strokeWidth/2,s=Math.max(...this.points.map((t=>t[0])))+this.strokeWidth/2,h=Math.max(...this.points.map((t=>t[1])))+this.strokeWidth/2;this.width=s-t+this.lineSlack,this.height=h-i+this.lineSlack,this.x=t,this.y=i}generateSvgPath(){const t=this.getStrokeFromPoints(this.points,this.strokeWidth),i=this.points.length?Math.min(...this.points.map((t=>t[0])))-this.strokeWidth/2:0,s=this.points.length?Math.min(...this.points.map((t=>t[1])))-this.strokeWidth/2:0;return this.getSvgPathFromStroke(t,i,s)}getStrokeFromPoints(t,i){return o.getStroke(t,{size:i,thinning:.5,smoothing:.5,streamline:.5,easing:t=>t,simulatePressure:!0,last:!0,start:{cap:!0,taper:0,easing:t=>t},end:{cap:!0,taper:0,easing:t=>t}})}getSvgPathFromStroke(t,i=0,s=0,h=!0){const n=t.length;if(n<4)return"";const r=t[0],o=t[1],a=t[2],u=r[1]-s,l=o[0]-i,c=o[1]-s,f=a[0]-i,d=a[1]-s;let M=`M${(r[0]-i).toFixed(2)},${u.toFixed(2)} Q${l.toFixed(2)},${c.toFixed(2)} ${e.average(l,f).toFixed(2)},${e.average(c,d).toFixed(2)} T`;for(let h=2,r=n-1;h<r;h++){const n=t[h],r=t[h+1],o=n[1]-s,a=r[1]-s;M+=`${e.average(n[0]-i,r[0]-i).toFixed(2)},${e.average(o,a).toFixed(2)} `}return h&&(M+="Z"),M}isLowRes(){if(!this._core)return!1;const t=this._core.store.state.scale;return this.boundingBox.width*t*(this.boundingBox.height*t)<500}getClipPoint(t){const i=this.centerX,s=this.centerY,h=this.strokeWidth/this.scale/2;if(null===this._adjustedPoints&&(this._adjustedPoints=this.computeAdjustedPoints()),this._adjustedPoints.length<1)return null;let e=!0;for(let n=1;n<=32;n++){const r=n/32,o=t.x+(i-t.x)*r,a=t.y+(s-t.y)*r;let u=1/0;if(1===this._adjustedPoints.length){const t=this._adjustedPoints[0],i=o-t[0],s=a-t[1];u=Math.sqrt(i*i+s*s)}else for(let t=0;t<this._adjustedPoints.length-1;t++){const i=this._adjustedPoints[t],s=this._adjustedPoints[t+1],h=this.pointToLineSegmentDistance(o,a,i[0],i[1],s[0],s[1]);h<u&&(u=h)}const l=u<=h;if(e&&l){let e=(n-1)/32,o=r;for(let n=0;n<8;n++){const n=(e+o)/2,r=t.x+(i-t.x)*n,a=t.y+(s-t.y)*n;let u=1/0;if(1===this._adjustedPoints.length){const t=this._adjustedPoints[0],i=r-t[0],s=a-t[1];u=Math.sqrt(i*i+s*s)}else for(let t=0;t<this._adjustedPoints.length-1;t++){const i=this._adjustedPoints[t],s=this._adjustedPoints[t+1],h=this.pointToLineSegmentDistance(r,a,i[0],i[1],s[0],s[1]);h<u&&(u=h)}u<=h?o=n:e=n}const a=(e+o)/2;return{x:t.x+(i-t.x)*a,y:t.y+(s-t.y)*a}}e=!l}return null}}class u extends h{__class__="KritzelLine";startX;startY;endX;endY;controlX;controlY;stroke;strokeWidth;scale=1;options;startAnchor;endAnchor;arrows;isVisible=!0;isDebugInfoVisible=!0;isCompleted=!1;_adjustedPoints=null;_clipInfo=null;get d(){return void 0!==this.controlX&&void 0!==this.controlY?`M ${this.startX} ${this.startY} Q ${this.controlX} ${this.controlY} ${this.endX} ${this.endY}`:`M ${this.startX} ${this.startY} L ${this.endX} ${this.endY}`}get viewBox(){return`${this.x} ${this.y} ${this.width} ${this.height}`}constructor(t){super(),this.options=t,this.startX=t?.startX??0,this.startY=t?.startY??0,this.endX=t?.endX??0,this.endY=t?.endY??0,this.controlX=t?.controlX,this.controlY=t?.controlY,this.translateX=t?.translateX??0,this.translateY=t?.translateY??0,this.rotation=e.degreesToRadians(t?.rotation??0),this.scale=t?.scale??1,this.strokeWidth=t?.strokeWidth??4,this.stroke=t?.stroke??{light:"#000000",dark:"#ffffff"},this.startAnchor=t?.startAnchor,this.endAnchor=t?.endAnchor,this.arrows=t?.arrows,this.updateDimensions()}static create(t,i){const s=new u;return s._core=t,s.id=s.generateId(),s.workspaceId=t.store.state.activeWorkspace.id,s.userId=t.user?.id,s.options=i,s.startX=i?.startX??0,s.startY=i?.startY??0,s.endX=i?.endX??0,s.endY=i?.endY??0,s.controlX=i?.controlX,s.controlY=i?.controlY,s.translateX=i?.translateX??0,s.translateY=i?.translateY??0,s.rotation=e.degreesToRadians(i?.rotation??0),s.scale=i?.scale??1,s.strokeWidth=i?.strokeWidth??4,s.stroke=i?.stroke??{light:"#000000",dark:"#ffffff"},s.opacity=i?.opacity??1,s.startAnchor=i?.startAnchor,s.endAnchor=i?.endAnchor,s.arrows=i?.arrows,s.zIndex=t.store.currentZIndex,s.updateDimensions(),s}resize(t,i,s,h){if(s<=1||h<=1)return;const e=s/this.width,n=h/this.height;this.startX=this.startX*e,this.startY=this.startY*n,this.endX=this.endX*e,this.endY=this.endY*n,void 0!==this.controlX&&void 0!==this.controlY&&(this.controlX=this.controlX*e,this.controlY=this.controlY*n);const{minX:r,minY:o,maxX:a,maxY:u}=this.calculateBoundingBox();this.width=a-r,this.height=u-o,this.x=r,this.y=o,this.translateX=t,this.translateY=i,this._adjustedPoints=null,this._clipInfo=null,this._core.store.objects.update(this),this._core.anchorManager.updateAnchorsForObject(this.id),this.startAnchor&&this._core.anchorManager.updateAnchorsForObject(this.startAnchor.objectId),this.endAnchor&&this._core.anchorManager.updateAnchorsForObject(this.endAnchor.objectId)}rotate(t){this.rotation=t,this._adjustedPoints=null,this._clipInfo=null,this._core.store.objects.update(this)}move(t,i,s,h){const e=(i-h)/this._core.store.state.scale;this.translateX+=(t-s)/this._core.store.state.scale,this.translateY+=e,this.startAnchor&&this._core.anchorManager.updateAnchorsForObject(this.startAnchor.objectId),this.endAnchor&&this._core.anchorManager.updateAnchorsForObject(this.endAnchor.objectId),this._adjustedPoints=null,this._clipInfo=null,this._core.store.objects.update(this)}hitTest(t,i){const s=Math.max(this.strokeWidth,20)/this.scale/2;if(null===this._adjustedPoints&&(this._adjustedPoints=this.computeAdjustedPoints()),void 0!==this.controlX&&void 0!==this.controlY){const h=this.getClipInfo();return this.pointToBezierDistance(t,i,h.start?.t??0,h.end?.t??1)<=s}const h=this.getClipInfo(),e=h.start?[h.start.x,h.start.y]:this._adjustedPoints[0],n=h.end?[h.end.x,h.end.y]:this._adjustedPoints[1];return this.pointToLineSegmentDistance(t,i,e[0],e[1],n[0],n[1])<=s}hitTestPolygon(t){const i=this.strokeWidth/this.scale/2;null===this._adjustedPoints&&(this._adjustedPoints=this.computeAdjustedPoints());const h=this.getClipInfo(),e=[{x:t.bottomLeft.x,y:t.bottomLeft.y},{x:t.bottomRight.x,y:t.bottomRight.y},{x:t.topRight.x,y:t.topRight.y},{x:t.topLeft.x,y:t.topLeft.y}],n=h.start?[h.start.x,h.start.y]:this._adjustedPoints[0],r=h.end?[h.end.x,h.end.y]:this._adjustedPoints[1],o=[n,r];for(const[t,i]of o)if(s.isPointInPolygon({x:t,y:i},e))return!0;for(const t of e)if(this.hitTest(t.x,t.y))return!0;if(void 0!==this.controlX&&void 0!==this.controlY){const t=this._adjustedPoints[0],n=this._adjustedPoints[1],r=this.computeAdjustedControlPoint(),o=h.start?.t??0,a=h.end?.t??1,u=20;for(let h=0;h<=u;h++){const l=o+h/u*(a-o),c=1-l,f=c*c*t[0]+2*c*l*r[0]+l*l*n[0],d=c*c*t[1]+2*c*l*r[1]+l*l*n[1];if(s.isPointInPolygon({x:f,y:d},e))return!0;for(let t=0;t<e.length;t++){const s=e[t],h=e[(t+1)%e.length];if(this.pointToLineSegmentDistance(f,d,s.x,s.y,h.x,h.y)<=i)return!0}}return!1}const a={x:n[0],y:n[1]},u={x:r[0],y:r[1]};for(let t=0;t<e.length;t++){const h=e[t],n=e[(t+1)%e.length];if(s.intersectLines(a,u,h,n))return!0;const r=this.pointToLineSegmentDistance(h.x,h.y,a.x,a.y,u.x,u.y),o=this.pointToLineSegmentDistance(n.x,n.y,a.x,a.y,u.x,u.y),l=this.pointToLineSegmentDistance(a.x,a.y,h.x,h.y,n.x,n.y),c=this.pointToLineSegmentDistance(u.x,u.y,h.x,h.y,n.x,n.y);if(Math.min(r,o,l,c)<=i)return!0}return!1}updatePosition(t,i){this.translateX=t,this.translateY=i,this._adjustedPoints=null,this._clipInfo=null,this._core.store.objects.update(this)}updateEndpoint(t,i,s){"start"===t?(this.startX=i,this.startY=s):(this.endX=i,this.endY=s);const h=this.width,e=this.height,{minX:n,minY:r,maxX:o,maxY:a}=this.calculateBoundingBox(),u=n-this.x,l=r-this.y,c=o-n,f=a-r,d=(c-h)/2,M=(f-e)/2;this.x=n,this.y=r,this.width=c,this.height=f;const g=Math.cos(this.rotation),m=Math.sin(this.rotation),p=u+d,x=l+M,y=p*m+x*g-M;this.translateX+=(p*g-x*m-d)/this.scale,this.translateY+=y/this.scale,this._adjustedPoints=null,this._clipInfo=null,this._core.store.objects.update(this)}updateControlPoint(t,i){this.controlX=t,this.controlY=i;const s=this.width,h=this.height,{minX:e,minY:n,maxX:r,maxY:o}=this.calculateBoundingBox(),a=e-this.x,u=n-this.y,l=r-e,c=o-n,f=(l-s)/2,d=(c-h)/2;this.x=e,this.y=n,this.width=l,this.height=c;const M=Math.cos(this.rotation),g=Math.sin(this.rotation),m=a+f,p=u+d,x=m*g+p*M-d;this.translateX+=(m*M-p*g-f)/this.scale,this.translateY+=x/this.scale,this._adjustedPoints=null,this._clipInfo=null,this._core.store.objects.update(this)}computeAdjustedPoints(){const t=[[this.startX,this.startY],[this.endX,this.endY]],i=this.rotation,s=Math.cos(i),h=Math.sin(i),e=t.map((t=>t[0])),n=t.map((t=>t[1])),r={x:(Math.min(...e)+Math.max(...e))/2,y:(Math.min(...n)+Math.max(...n))/2},{x:o,y:a}=r;return t.map((([t,i])=>{const e=t-o,n=i-a;return[o+e*s-n*h,a+e*h+n*s]})).map((([t,i])=>[(t-this.x)/this.scale+this.translateX,(i-this.y)/this.scale+this.translateY]))}pointToLineSegmentDistance(t,i,s,h,e,n){const r=e-s,o=n-h,a=r*r+o*o;let u,l,c=-1;0!==a&&(c=((t-s)*r+(i-h)*o)/a),c<0?(u=s,l=h):c>1?(u=e,l=n):(u=s+c*r,l=h+c*o);const f=t-u,d=i-l;return Math.sqrt(f*f+d*d)}pointToBezierDistance(t,i,s=0,h=1){null===this._adjustedPoints&&(this._adjustedPoints=this.computeAdjustedPoints());const e=this._adjustedPoints[0],n=this._adjustedPoints[1],r=this.computeAdjustedControlPoint();let o=1/0;for(let a=0;a<=20;a++){const u=s+a/20*(h-s),l=1-u,c=t-(l*l*e[0]+2*l*u*r[0]+u*u*n[0]),f=i-(l*l*e[1]+2*l*u*r[1]+u*u*n[1]),d=Math.sqrt(c*c+f*f);d<o&&(o=d)}return o}getClipInfo(){if(this._clipInfo)return this._clipInfo;const t=this.endAnchor,i={};if(this.startAnchor){const t=this._core.anchorManager.findAnchorTarget(this,"start");if(t){const s=this._core.anchorManager.computeAnchorClipInfo(this,"start",t);s&&(i.start={x:s.worldX,y:s.worldY,t:s.t})}}if(t){const t=this._core.anchorManager.findAnchorTarget(this,"end");if(t){const s=this._core.anchorManager.computeAnchorClipInfo(this,"end",t);s&&(i.end={x:s.worldX,y:s.worldY,t:s.t})}}return this._clipInfo=i,i}computeAdjustedControlPoint(){if(void 0===this.controlX||void 0===this.controlY)return[(this.startX+this.endX)/2,(this.startY+this.endY)/2];const t=this.rotation,i=Math.cos(t),s=Math.sin(t),h=[this.startX,this.endX],e=[this.startY,this.endY],n={x:(Math.min(...h)+Math.max(...h))/2,y:(Math.min(...e)+Math.max(...e))/2},{x:r,y:o}=n,a=this.controlX-r,u=this.controlY-o;return[(r+a*i-u*s-this.x)/this.scale+this.translateX,(o+a*s+u*i-this.y)/this.scale+this.translateY]}get rotatedPolygon(){const t=this.padding,{minX:i,minY:s,maxX:h,maxY:e}=u.calculateBoundingBox(this.startX,this.startY,this.endX,this.endY,this.controlX,this.controlY,this.strokeWidth),n=i-this.x+t,r=s-this.y+t,o=h-this.x+t,a=e-this.y+t,l={x:n,y:r},c={x:o,y:r},f={x:o,y:a},d={x:n,y:a},M=this.totalWidth/2,g=this.totalHeight/2,m=this.rotation,p=Math.cos(m),x=Math.sin(m),y=t=>({x:((t.x-M)*p-(t.y-g)*x+M)/this.scale+this.translateX,y:((t.x-M)*x+(t.y-g)*p+g)/this.scale+this.translateY});return{topLeft:y(l),topRight:y(c),bottomRight:y(f),bottomLeft:y(d)}}static calculateBoundingBox(t,i,s,h,e,n,r){let o=Math.min(t,s),a=Math.min(i,h),u=Math.max(t,s),l=Math.max(i,h);if(void 0!==e&&void 0!==n){const r=t-2*e+s;if(0!==r){const i=(t-e)/r;if(i>0&&i<1){const h=(1-i)*(1-i)*t+2*(1-i)*i*e+i*i*s;o=Math.min(o,h),u=Math.max(u,h)}}const c=i-2*n+h;if(0!==c){const t=(i-n)/c;if(t>0&&t<1){const s=(1-t)*(1-t)*i+2*(1-t)*t*n+t*t*h;a=Math.min(a,s),l=Math.max(l,s)}}}const c=r/2;return{minX:o-c,minY:a-c,maxX:u+c,maxY:l+c}}calculateBoundingBox(){return u.calculateBoundingBox(this.startX,this.startY,this.endX,this.endY,this.controlX,this.controlY,this.strokeWidth)}serialize(){const t=super.serialize();return delete t._adjustedPoints,delete t._clipInfo,t}deserialize(t){const i=super.deserialize(t);return this._adjustedPoints=null,this._clipInfo=null,i}updateDimensions(){const{minX:t,minY:i,maxX:s,maxY:h}=this.calculateBoundingBox();this.width=s-t,this.height=h-i,this.x=t,this.y=i,this.translateX=(this.x+this.translateX)/this.scale,this.translateY=(this.y+this.translateY)/this.scale}get startMarkerId(){return`arrow-start-${this.id}`}get endMarkerId(){return`arrow-end-${this.id}`}getArrowSize(t){const i="start"===t?this.arrows?.start:this.arrows?.end;return i?.size??3*this.strokeWidth}getArrowFill(t){const s="start"===t?this.arrows?.start:this.arrows?.end;return i.resolveThemeColor(s?.fill??this.stroke)}getArrowPath(t="triangle"){switch(t){case"triangle":default:return"M 0 0 L 10 5 L 0 10 z";case"open":return"M 0 0 L 10 5 L 0 10";case"diamond":return"M 0 5 L 5 0 L 10 5 L 5 10 z";case"circle":return"M 5,0 A 5,5 0 1,1 5,10 A 5,5 0 1,1 5,0"}}get hasStartArrow(){return!0===this.arrows?.start?.enabled}get hasEndArrow(){return!0===this.arrows?.end?.enabled}}export{h as K,a,u as b,e as c,s as d}
package/dist/esm/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { H as HocuspocusProvider, a as HocuspocusProviderWebsocket } from './schema.constants-Cphx5M7a.js';
2
- export { N as APP_STATE_MIGRATIONS, A as AssetNotFoundError, P as CURRENT_APP_STATE_SCHEMA_VERSION, Q as CURRENT_WORKSPACE_SCHEMA_VERSION, B as DEFAULT_ASSET_STORAGE_CONFIG, D as DEFAULT_BRUSH_CONFIG, z as DEFAULT_LINE_TOOL_CONFIG, y as DEFAULT_TEXT_CONFIG, G as DE_LOCALE, F as EN_LOCALE, J as FR_LOCALE, I as IndexedDBAssetProvider, L as KritzelAlignment, t as KritzelAnchorManager, r as KritzelAssetResolver, K as KritzelBaseObject, i as KritzelBaseTool, j as KritzelBrushTool, p as KritzelCursorHelper, h as KritzelCustomElement, x as KritzelCustomElementRendererRegistry, l as KritzelEraserTool, f as KritzelGroup, d as KritzelImage, m as KritzelImageTool, w as KritzelLicenseManager, e as KritzelLine, k as KritzelLineTool, v as KritzelLocalizationManager, c as KritzelPath, q as KritzelSelectionTool, g as KritzelShape, o as KritzelShapeTool, b as KritzelText, n as KritzelTextTool, u as KritzelThemeManager, s as KritzelWorkspace, S as ShapeType, W as WORKSPACE_EXPORT_VERSION, O as WORKSPACE_MIGRATIONS, E as darkTheme, C as lightTheme, M as runMigrations } from './schema.constants-Cphx5M7a.js';
1
+ import { H as HocuspocusProvider, a as HocuspocusProviderWebsocket } from './schema.constants-Cv5-yM39.js';
2
+ export { N as APP_STATE_MIGRATIONS, A as AssetNotFoundError, P as CURRENT_APP_STATE_SCHEMA_VERSION, Q as CURRENT_WORKSPACE_SCHEMA_VERSION, B as DEFAULT_ASSET_STORAGE_CONFIG, D as DEFAULT_BRUSH_CONFIG, z as DEFAULT_LINE_TOOL_CONFIG, y as DEFAULT_TEXT_CONFIG, G as DE_LOCALE, F as EN_LOCALE, J as FR_LOCALE, I as IndexedDBAssetProvider, L as KritzelAlignment, t as KritzelAnchorManager, r as KritzelAssetResolver, K as KritzelBaseObject, i as KritzelBaseTool, j as KritzelBrushTool, p as KritzelCursorHelper, h as KritzelCustomElement, x as KritzelCustomElementRendererRegistry, l as KritzelEraserTool, f as KritzelGroup, d as KritzelImage, m as KritzelImageTool, w as KritzelLicenseManager, e as KritzelLine, k as KritzelLineTool, v as KritzelLocalizationManager, c as KritzelPath, q as KritzelSelectionTool, g as KritzelShape, o as KritzelShapeTool, b as KritzelText, n as KritzelTextTool, u as KritzelThemeManager, s as KritzelWorkspace, S as ShapeType, W as WORKSPACE_EXPORT_VERSION, O as WORKSPACE_MIGRATIONS, E as darkTheme, C as lightTheme, M as runMigrations } from './schema.constants-Cv5-yM39.js';
3
3
  import * as Y from 'yjs';
4
4
  import { IndexeddbPersistence } from 'y-indexeddb';
5
5
  import { WebsocketProvider } from 'y-websocket';
@@ -1,5 +1,5 @@
1
1
  import { r as registerInstance, h, H as Host, c as createEvent, g as getElement } from './index-Dhio9uis.js';
2
- import { c as KritzelPath, e as KritzelLine, R as KritzelColorHelper, T as KritzelDevicesHelper, q as KritzelSelectionTool, n as KritzelTextTool, U as KritzelMouseButton, V as KritzelHTMLHelper, X as DEFAULT_STROKE_SIZES, Y as DEFAULT_COLOR_PALETTE, S as ShapeType, D as DEFAULT_BRUSH_CONFIG, j as KritzelBrushTool, l as KritzelEraserTool, z as DEFAULT_LINE_TOOL_CONFIG, k as KritzelLineTool, o as KritzelShapeTool, y as DEFAULT_TEXT_CONFIG, m as KritzelImageTool, L as KritzelAlignment, B as DEFAULT_ASSET_STORAGE_CONFIG, Z as ObjectHelper, _ as ThemeHelper, E as darkTheme, C as lightTheme, $ as KritzelSelectionGroup, a0 as KritzelSelectionBox, a1 as KritzelIconRegistry, a2 as KritzelKeyboardHelper, a3 as KritzelBaseHandler, s as KritzelWorkspace, f as KritzelGroup, h as KritzelCustomElement, d as KritzelImage, g as KritzelShape, b as KritzelText, M as runMigrations, Q as CURRENT_WORKSPACE_SCHEMA_VERSION, O as WORKSPACE_MIGRATIONS, a4 as KritzelClassHelper, P as CURRENT_APP_STATE_SCHEMA_VERSION, N as APP_STATE_MIGRATIONS, p as KritzelCursorHelper, a5 as imageCompression, t as KritzelAnchorManager, u as KritzelThemeManager, v as KritzelLocalizationManager, w as KritzelLicenseManager, r as KritzelAssetResolver, a6 as KritzelEventHelper, W as WORKSPACE_EXPORT_VERSION } from './schema.constants-Cphx5M7a.js';
2
+ import { c as KritzelPath, e as KritzelLine, R as KritzelColorHelper, T as KritzelDevicesHelper, q as KritzelSelectionTool, n as KritzelTextTool, U as KritzelMouseButton, V as KritzelHTMLHelper, X as DEFAULT_STROKE_SIZES, Y as DEFAULT_COLOR_PALETTE, S as ShapeType, D as DEFAULT_BRUSH_CONFIG, j as KritzelBrushTool, l as KritzelEraserTool, z as DEFAULT_LINE_TOOL_CONFIG, k as KritzelLineTool, o as KritzelShapeTool, y as DEFAULT_TEXT_CONFIG, m as KritzelImageTool, L as KritzelAlignment, B as DEFAULT_ASSET_STORAGE_CONFIG, Z as ObjectHelper, _ as ThemeHelper, E as darkTheme, C as lightTheme, $ as KritzelSelectionGroup, a0 as KritzelSelectionBox, a1 as KritzelIconRegistry, a2 as KritzelKeyboardHelper, a3 as KritzelBaseHandler, s as KritzelWorkspace, f as KritzelGroup, h as KritzelCustomElement, d as KritzelImage, g as KritzelShape, b as KritzelText, M as runMigrations, Q as CURRENT_WORKSPACE_SCHEMA_VERSION, O as WORKSPACE_MIGRATIONS, a4 as KritzelClassHelper, P as CURRENT_APP_STATE_SCHEMA_VERSION, N as APP_STATE_MIGRATIONS, p as KritzelCursorHelper, a5 as imageCompression, t as KritzelAnchorManager, u as KritzelThemeManager, v as KritzelLocalizationManager, w as KritzelLicenseManager, r as KritzelAssetResolver, a6 as KritzelEventHelper, W as WORKSPACE_EXPORT_VERSION } from './schema.constants-Cv5-yM39.js';
3
3
  import * as Y from 'yjs';
4
4
  import 'y-indexeddb';
5
5
  import 'y-websocket';
@@ -31428,7 +31428,7 @@ const KritzelPortal = class {
31428
31428
  * This file is auto-generated by the version bump scripts.
31429
31429
  * Do not modify manually.
31430
31430
  */
31431
- const KRITZEL_VERSION = '0.3.36';
31431
+ const KRITZEL_VERSION = '0.3.38';
31432
31432
 
31433
31433
  const kritzelSettingsCss = () => `:host{display:contents}kritzel-dialog{--kritzel-dialog-body-padding:0;--kritzel-dialog-width-large:800px;--kritzel-dialog-height-large:500px}.footer-button{padding:8px 16px;border-radius:6px;cursor:pointer;font-size:14px}.cancel-button{border:1px solid #ebebeb;background:#fff;color:inherit}.cancel-button:hover{background:#f5f5f5}.settings-content{padding:0}.settings-content h3{margin:0 0 16px 0;font-size:18px;font-weight:600;color:var(--kritzel-settings-content-heading-color, #333333)}.settings-content p{margin:0;font-size:14px;color:var(--kritzel-settings-content-text-color, #666666);line-height:1.5}.settings-group{display:flex;flex-direction:column;gap:24px}.settings-item{display:flex;flex-direction:column;gap:8px}.settings-row{display:flex;align-items:center;justify-content:space-between;gap:16px}.settings-label{font-size:14px;font-weight:600;color:var(--kritzel-settings-label-color, #333333);margin:0 0 4px 0}.settings-description{font-size:12px;color:var(--kritzel-settings-description-color, #888888);margin:0;line-height:1.4}.shortcuts-list{display:flex;flex-direction:column;gap:24px}.shortcuts-category{display:flex;flex-direction:column;gap:8px}.shortcuts-category-title{font-size:14px;font-weight:600;color:var(--kritzel-settings-label-color, #333333);margin:0 0 4px 0}.shortcuts-group{display:flex;flex-direction:column;gap:4px}.shortcut-item{display:flex;justify-content:space-between;align-items:center;padding:6px 8px;border-radius:4px;background:var(--kritzel-settings-shortcut-item-bg, rgba(0, 0, 0, 0.02))}.shortcut-label{font-size:14px;color:var(--kritzel-settings-content-text-color, #666666)}.shortcut-key{font-family:monospace;font-size:12px;padding:2px 8px;border-radius:4px;background:var(--kritzel-settings-shortcut-key-bg, #f0f0f0);color:var(--kritzel-settings-shortcut-key-color, #333333);border:1px solid var(--kritzel-settings-shortcut-key-border, #ddd)}`;
31434
31434
 
@@ -15932,11 +15932,18 @@ class KritzelPath extends KritzelBaseObject {
15932
15932
  isCompleted = false;
15933
15933
  _adjustedPoints = null;
15934
15934
  /**
15935
- * Gets the SVG viewBox string based on the path's position and dimensions.
15936
- * @returns The viewBox attribute value in the format "x y width height"
15935
+ * Gets the SVG viewBox string for local (object-relative) rendering.
15936
+ *
15937
+ * The path's `d` string is generated in local coordinates (offset so the
15938
+ * object's top-left origin is at 0,0), so the viewBox always starts at 0,0.
15939
+ * Keeping the SVG's internal coordinates small — independent of the object's
15940
+ * world position — avoids float32 precision loss in the browser's SVG
15941
+ * rasterizer (Skia), which otherwise fails to paint paths whose absolute
15942
+ * world coordinates exceed ~2^24 (e.g. far from the origin at extreme zoom).
15943
+ * @returns The viewBox attribute value in the format "0 0 width height"
15937
15944
  */
15938
15945
  get viewBox() {
15939
- return `${this.x} ${this.y} ${this.width} ${this.height}`;
15946
+ return `0 0 ${this.width} ${this.height}`;
15940
15947
  }
15941
15948
  /**
15942
15949
  * Creates a new KritzelPath instance.
@@ -16001,6 +16008,24 @@ class KritzelPath extends KritzelBaseObject {
16001
16008
  }
16002
16009
  return copiedObject;
16003
16010
  }
16011
+ /**
16012
+ * Restores the path from a serialized object, then regenerates the SVG `d`
16013
+ * string from the restored points.
16014
+ *
16015
+ * Regeneration is required because the `d` string is now emitted in local
16016
+ * (object-relative) coordinates paired with a "0 0 width height" viewBox.
16017
+ * Older persisted paths stored `d` in absolute world coordinates, which
16018
+ * would be inconsistent with the local-coordinate viewBox and fail to
16019
+ * rasterize far from the origin at extreme zoom. Recomputing `d` here makes
16020
+ * both freshly created and previously persisted paths render identically.
16021
+ * @param object - The serialized path data to restore from
16022
+ * @returns This instance cast to type T
16023
+ */
16024
+ deserialize(object) {
16025
+ const result = super.deserialize(object);
16026
+ this.d = this.generateSvgPath();
16027
+ return result;
16028
+ }
16004
16029
  /**
16005
16030
  * Resizes the path to fit within the specified dimensions.
16006
16031
  * Scales all points proportionally and updates the SVG path.
@@ -16276,7 +16301,9 @@ class KritzelPath extends KritzelBaseObject {
16276
16301
  */
16277
16302
  generateSvgPath() {
16278
16303
  const stroke = this.getStrokeFromPoints(this.points, this.strokeWidth);
16279
- return this.getSvgPathFromStroke(stroke);
16304
+ const offsetX = this.points.length ? Math.min(...this.points.map(p => p[0])) - this.strokeWidth / 2 : 0;
16305
+ const offsetY = this.points.length ? Math.min(...this.points.map(p => p[1])) - this.strokeWidth / 2 : 0;
16306
+ return this.getSvgPathFromStroke(stroke, offsetX, offsetY);
16280
16307
  }
16281
16308
  /**
16282
16309
  * Converts raw input points into a smooth stroke outline using perfect-freehand.
@@ -16309,23 +16336,40 @@ class KritzelPath extends KritzelBaseObject {
16309
16336
  /**
16310
16337
  * Converts stroke outline points into an SVG path data string.
16311
16338
  * Uses quadratic bezier curves for smooth rendering.
16339
+ * Coordinates are emitted relative to (offsetX, offsetY) so the resulting
16340
+ * path lives in the object's local coordinate space (paired with a
16341
+ * "0 0 width height" viewBox). This keeps SVG-internal coordinates small
16342
+ * regardless of the object's world position, avoiding float32 rasterizer
16343
+ * precision failures far from the origin.
16312
16344
  * @param points - Array of [x, y] coordinate pairs forming the stroke outline
16345
+ * @param offsetX - X origin to subtract from every coordinate (default 0)
16346
+ * @param offsetY - Y origin to subtract from every coordinate (default 0)
16313
16347
  * @param closed - Whether to close the path with 'Z' command (default: true)
16314
16348
  * @returns SVG path data string with M, Q, and T commands
16315
16349
  */
16316
- getSvgPathFromStroke(points, closed = true) {
16350
+ getSvgPathFromStroke(points, offsetX = 0, offsetY = 0, closed = true) {
16317
16351
  const len = points.length;
16318
16352
  if (len < 4) {
16319
16353
  return ``;
16320
16354
  }
16321
- let a = points[0];
16322
- let b = points[1];
16355
+ const a = points[0];
16356
+ const b = points[1];
16323
16357
  const c = points[2];
16324
- let result = `M${a[0].toFixed(2)},${a[1].toFixed(2)} Q${b[0].toFixed(2)},${b[1].toFixed(2)} ${KritzelMathHelper.average(b[0], c[0]).toFixed(2)},${KritzelMathHelper.average(b[1], c[1]).toFixed(2)} T`;
16358
+ const ax = a[0] - offsetX;
16359
+ const ay = a[1] - offsetY;
16360
+ const bx = b[0] - offsetX;
16361
+ const by = b[1] - offsetY;
16362
+ const cx = c[0] - offsetX;
16363
+ const cy = c[1] - offsetY;
16364
+ let result = `M${ax.toFixed(2)},${ay.toFixed(2)} Q${bx.toFixed(2)},${by.toFixed(2)} ${KritzelMathHelper.average(bx, cx).toFixed(2)},${KritzelMathHelper.average(by, cy).toFixed(2)} T`;
16325
16365
  for (let i = 2, max = len - 1; i < max; i++) {
16326
- a = points[i];
16327
- b = points[i + 1];
16328
- result += `${KritzelMathHelper.average(a[0], b[0]).toFixed(2)},${KritzelMathHelper.average(a[1], b[1]).toFixed(2)} `;
16366
+ const p = points[i];
16367
+ const q = points[i + 1];
16368
+ const px = p[0] - offsetX;
16369
+ const py = p[1] - offsetY;
16370
+ const qx = q[0] - offsetX;
16371
+ const qy = q[1] - offsetY;
16372
+ result += `${KritzelMathHelper.average(px, qx).toFixed(2)},${KritzelMathHelper.average(py, qy).toFixed(2)} `;
16329
16373
  }
16330
16374
  if (closed) {
16331
16375
  result += 'Z';
@@ -1 +1 @@
1
- import{H as a,a as T}from"./p-Cphx5M7a.js";export{N as APP_STATE_MIGRATIONS,A as AssetNotFoundError,P as CURRENT_APP_STATE_SCHEMA_VERSION,Q as CURRENT_WORKSPACE_SCHEMA_VERSION,B as DEFAULT_ASSET_STORAGE_CONFIG,D as DEFAULT_BRUSH_CONFIG,z as DEFAULT_LINE_TOOL_CONFIG,y as DEFAULT_TEXT_CONFIG,G as DE_LOCALE,F as EN_LOCALE,J as FR_LOCALE,I as IndexedDBAssetProvider,L as KritzelAlignment,t as KritzelAnchorManager,r as KritzelAssetResolver,K as KritzelBaseObject,i as KritzelBaseTool,j as KritzelBrushTool,p as KritzelCursorHelper,h as KritzelCustomElement,x as KritzelCustomElementRendererRegistry,l as KritzelEraserTool,f as KritzelGroup,d as KritzelImage,m as KritzelImageTool,w as KritzelLicenseManager,e as KritzelLine,k as KritzelLineTool,v as KritzelLocalizationManager,c as KritzelPath,q as KritzelSelectionTool,g as KritzelShape,o as KritzelShapeTool,b as KritzelText,n as KritzelTextTool,u as KritzelThemeManager,s as KritzelWorkspace,S as ShapeType,W as WORKSPACE_EXPORT_VERSION,O as WORKSPACE_MIGRATIONS,E as darkTheme,C as lightTheme,M as runMigrations}from"./p-Cphx5M7a.js";import*as $ from"yjs";import{IndexeddbPersistence as _}from"y-indexeddb";import{WebsocketProvider as R}from"y-websocket";const U=Math.floor,H=127,V=Number.MAX_SAFE_INTEGER;class X{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Y=()=>new X,Z=t=>{const e=new Uint8Array((t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e})(t));let s=0;for(let i=0;i<t.bufs.length;i++){const n=t.bufs[i];e.set(n,s),s+=n.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},tt=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(2*s),t.cpos=0),t.cbuf[t.cpos++]=e},et=(t,e)=>{for(;e>H;)tt(t,128|H&e),e=U(e/128);tt(t,H&e)},st=(t,e)=>{et(t,e.byteLength),((t,e)=>{const s=t.cbuf.length,i=t.cpos,n=((t,e)=>t<e?t:e)(s-i,e.length),o=e.length-n;t.cbuf.set(e.subarray(0,n),i),t.cpos+=n,o>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(((t,e)=>t>e?t:e)(2*s,o)),t.cbuf.set(e.subarray(n)),t.cpos=o)})(t,e)},it=t=>new Error(t),nt=it("Unexpected end of array"),ot=it("Integer out of Range");class rt{constructor(t){this.arr=t,this.pos=0}}const ct=t=>((t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s})(t,at(t)),at=t=>{let e=0,s=1;const i=t.arr.length;for(;t.pos<i;){const i=t.arr[t.pos++];if(e+=(i&H)*s,s*=128,i<128)return e;if(e>V)throw ot}throw nt};class ht{type="local";doc;channel;_synced=!1;constructor(t,e,s){this.doc=e,this.channel=new BroadcastChannel(t),this.channel.onmessage=t=>{this.handleMessage(t.data)},this.doc.on("update",this.handleDocUpdate),this.broadcastSync(),setTimeout((()=>{this._synced=!0}),100),s?.quiet||console.info(`BroadcastChannel Provider initialized: ${t}`)}handleDocUpdate=(t,e)=>{if(e!==this){const e=Y();et(e,0),st(e,t),this.channel.postMessage(Z(e))}};handleMessage(t){const e=(s=new Uint8Array(t),new rt(s));var s;switch(at(e)){case 0:const t=ct(e);$.applyUpdate(this.doc,t,this);break;case 1:this.broadcastSync();break;case 2:const s=ct(e),i=$.encodeStateAsUpdate(this.doc,s);if(i.length>0){const t=Y();et(t,0),st(t,i),this.channel.postMessage(Z(t))}}}broadcastSync(){const t=Y();et(t,2),st(t,$.encodeStateVector(this.doc)),this.channel.postMessage(Z(t))}async connect(){if(!this._synced)return new Promise((t=>{const e=()=>{this._synced?t():setTimeout(e,50)};e()}))}disconnect(){}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.doc.off("update",this.handleDocUpdate),this.channel.close()}}const lt=new Map;class dt{type="local";doc;cacheKey;isConnected=!1;constructor(t,e,s){this.doc=e,this.cacheKey=s?.name??t}handleUpdate=(t,e)=>{e!==this&&lt.set(this.cacheKey,$.encodeStateAsUpdate(this.doc))};async connect(){if(this.isConnected)return;const t=lt.get(this.cacheKey);t&&$.applyUpdate(this.doc,t,this),this.doc.on("update",this.handleUpdate),this.isConnected=!0}disconnect(){this.isConnected=!1}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.doc.off("update",this.handleUpdate),this.isConnected=!1}static clear(t){void 0!==t?lt.delete(t):lt.clear()}}class ut{type="local";provider;isConnected=!1;constructor(t,e,s){this.provider=new _(s?.name||t,e)}async connect(){if(!this.isConnected)return new Promise((t=>{this.provider.on("synced",(()=>{this.isConnected=!0,t()}))}))}disconnect(){this.isConnected=!1}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1}}class yt{type="network";provider;isConnected=!1;_quiet=!1;get awareness(){return this.provider.awareness}constructor(t,e,s){const i=s?.url||"ws://localhost:1234",n=s?.roomName||t;this.provider=new R(i,n,e,{params:s?.params,protocols:s?.protocols,WebSocketPolyfill:s?.WebSocketPolyfill,awareness:s?.awareness,maxBackoffTime:s?.maxBackoffTime,disableBc:!0}),this._quiet=s?.quiet??!1,this.setupEventListeners(),this._quiet||console.info(`WebSocket Provider initialized: ${i}/${n}`)}static with(t){return{create:(e,s,i)=>{const n=i?{...t,...i}:t;return new yt(e,s,n)}}}setupEventListeners(){this.provider.on("status",(({status:t})=>{"connected"===t?(this.isConnected=!0,this._quiet||console.info("WebSocket connected")):"disconnected"===t&&(this.isConnected=!1,this._quiet||console.info("WebSocket disconnected"))})),this.provider.on("sync",(t=>{t&&!this._quiet&&console.info("WebSocket synced")}))}async connect(){if(!this.isConnected)return new Promise(((t,e)=>{const s=setTimeout((()=>{e(new Error("WebSocket connection timeout"))}),1e4),i=({status:e})=>{"connected"===e&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,t())};this.provider.on("status",i),this.provider.wsconnected&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,t())}))}disconnect(){this.provider&&this.provider.disconnect(),this.isConnected=!1}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1}}class wt{type="network";provider;isConnected=!1;isSynced=!1;usesSharedSocket=!1;isDestroyed=!1;connectTimeout=null;pendingConnectReject=null;connectionTimeoutMs;_connectionStatus="disconnected";visibilityHandler=null;onlineHandler=null;get awareness(){return this.provider.awareness}get connectionStatus(){return this._connectionStatus}static sharedWebSocketProvider=null;constructor(t,e,s){const i=s?.name||t,n=s?.url||"ws://localhost:1234";this.connectionTimeoutMs=s?.connectionTimeout??1e4;const o=s?.websocketProvider||wt.sharedWebSocketProvider,r={};void 0!==s?.delay&&(r.delay=s.delay),void 0!==s?.factor&&(r.factor=s.factor),void 0!==s?.maxAttempts&&(r.maxAttempts=s.maxAttempts),void 0!==s?.minDelay&&(r.minDelay=s.minDelay),void 0!==s?.maxDelay&&(r.maxDelay=s.maxDelay);const c=()=>{this.isDestroyed||(this.isConnected=!0,this._connectionStatus="connected",s?.quiet||console.info(`Hocuspocus connected: ${i}`),s?.onConnect&&s.onConnect())},h=()=>{this.isDestroyed||(this.isConnected=!1,this.isSynced=!1,this._connectionStatus="disconnected",s?.quiet||console.info(`Hocuspocus disconnected: ${i}`),s?.onDisconnect&&s.onDisconnect())},l=()=>{this.isDestroyed||(this.isSynced=!0,this._connectionStatus="synced",s?.quiet||console.info(`Hocuspocus synced: ${i}`),s?.onSynced&&s.onSynced())},d=t=>{this.isDestroyed||("connecting"===t.status&&(this._connectionStatus="connecting"),s?.onStatus&&s.onStatus(t))};if(o){this.usesSharedSocket=!0;const t={websocketProvider:o,name:i,document:e,token:s?.token||null,onStatus:d,onConnect:c,onDisconnect:h,onSynced:l,...r};void 0!==s?.forceSyncInterval&&(t.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(t.onAuthenticationFailed=s.onAuthenticationFailed),this.provider=new a(t),this.provider.attach(),s?.quiet||console.info(`Hocuspocus Provider initialized (multiplexed): ${i}`)}else{this.usesSharedSocket=!1;const t={url:n,name:i,document:e,token:s?.token||null,autoConnect:!1,onStatus:d,onConnect:c,onDisconnect:h,onSynced:l,...r};void 0!==s?.forceSyncInterval&&(t.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(t.onAuthenticationFailed=s.onAuthenticationFailed),s?.WebSocketPolyfill&&(t.WebSocketPolyfill=s.WebSocketPolyfill),this.provider=new a(t),s?.quiet||console.info(`Hocuspocus Provider initialized: ${n}/${i}`)}this.setupBrowserEventListeners()}setupBrowserEventListeners(){"undefined"!=typeof document&&(this.visibilityHandler=()=>{"visible"!==document.visibilityState||this.isConnected||this.isDestroyed||this.provider.connect()},document.addEventListener("visibilitychange",this.visibilityHandler)),"undefined"!=typeof window&&(this.onlineHandler=()=>{this.isConnected||this.isDestroyed||this.provider.connect()},window.addEventListener("online",this.onlineHandler))}removeBrowserEventListeners(){this.visibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.onlineHandler&&"undefined"!=typeof window&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null)}static createSharedWebSocket(t){if(wt.sharedWebSocketProvider)return console.warn("Shared WebSocket already exists. Returning existing instance."),wt.sharedWebSocketProvider;const e={url:t.url};return t.WebSocketPolyfill&&(e.WebSocketPolyfill=t.WebSocketPolyfill),t.onConnect&&(e.onConnect=t.onConnect),t.onDisconnect&&(e.onDisconnect=t.onDisconnect),t.onStatus&&(e.onStatus=t.onStatus),wt.sharedWebSocketProvider=new T(e),console.info(`Shared Hocuspocus WebSocket created: ${t.url}`),wt.sharedWebSocketProvider}static destroySharedWebSocket(){wt.sharedWebSocketProvider&&(wt.sharedWebSocketProvider.destroy(),wt.sharedWebSocketProvider=null,console.info("Shared Hocuspocus WebSocket destroyed"))}static getSharedWebSocket(){return wt.sharedWebSocketProvider}static with(t){return{create:(e,s,i)=>{const n=i?{...t,...i}:t;return new wt(e,s,n)}}}async connect(){if(!this.isSynced&&!this.isDestroyed)return this._connectionStatus="connecting",new Promise(((t,e)=>{this.pendingConnectReject=e,this.connectTimeout=setTimeout((()=>{this.pendingConnectReject=null,this.connectTimeout=null,e(new Error("Hocuspocus connection timeout"))}),this.connectionTimeoutMs);const s=()=>{this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=null),this.pendingConnectReject=null,this.provider.off("synced",s),this.isDestroyed||t()};if(this.provider.on("synced",s),this.provider.isSynced)return this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=null),this.pendingConnectReject=null,this.provider.off("synced",s),void t();this.isConnected||this.usesSharedSocket||this.provider.connect()}))}async reconnect(){return this.disconnect(),this.connect()}disconnect(){this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=null),this.pendingConnectReject&&(this.pendingConnectReject=null),this.provider&&(this.usesSharedSocket?this.provider.detach():this.provider.disconnect()),this.isConnected=!1,this.isSynced=!1,this._connectionStatus="disconnected"}destroy(){this.isDestroyed=!0,this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=null),this.pendingConnectReject&&(this.pendingConnectReject=null),this.removeBrowserEventListeners(),this.provider&&this.provider.destroy(),this.isConnected=!1,this.isSynced=!1,this._connectionStatus="disconnected"}}class pt{type="remote";name="HttpAssetProvider";_options;constructor(t){this._options=t}static with(t){return{create:()=>new pt(t)}}async init(){this._options.quiet||console.info("HttpAssetProvider initialized")}destroy(){}canResolve(t){return!0}async put(t,e){const s=e.id??this.generateUuid(),i={...e,id:s},n=await(this._options.headers?.())??{},o=await this._options.uploadUrl(i),r=this._options.upload??this.defaultUpload;return{id:(await r(o,t,i,n)).id??s,kind:e.kind??"file",mimeType:e.mimeType,size:t.size,createdAt:Date.now(),width:e.width,height:e.height,durationMs:e.durationMs,originalFilename:e.originalFilename}}async resolve(t){return this._options.resolveUrl(t)}async fetch(t){const e=await this._options.resolveUrl(t),s=await(this._options.headers?.())??{},i=await fetch(e,{headers:s});if(!i.ok)throw new Error(`[HttpAssetProvider] Failed to fetch asset ${t}: ${i.status} ${i.statusText}`);return i.blob()}async delete(t){if(!this._options.deleteUrl)return;const e=await this._options.deleteUrl(t),s=await(this._options.headers?.())??{},i=await fetch(e,{method:"DELETE",headers:s});if(!i.ok)throw new Error(`[HttpAssetProvider] Failed to delete asset ${t}: ${i.status} ${i.statusText}`);this._options.quiet||console.info(`HttpAssetProvider: deleted asset ${t}`)}defaultUpload=async(t,e,s,i)=>{const n=new FormData;n.append("metadata",JSON.stringify(s)),n.append("file",e,s.originalFilename||`${s.id}.${this.extensionFromMime(s.mimeType)}`);const o=await fetch(t,{method:"POST",headers:i,body:n});if(!o.ok)throw new Error(`[HttpAssetProvider] Upload failed: ${o.status} ${o.statusText}`);return(o.headers.get("content-type")||"").includes("application/json")?await o.json():{}};extensionFromMime(t){const e=t.indexOf("/");return e>=0?t.slice(e+1):"bin"}generateUuid(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=crypto.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const e=Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}class mt{type="remote";name="PresignedAssetProvider";_options;constructor(t){this._options=t}static with(t){return{create:()=>new mt(t)}}async init(){this._options.quiet||console.info("PresignedAssetProvider initialized")}destroy(){}canResolve(t){return!0}async put(t,e){const s=await this._options.getUploadDescriptor(e),i=s.method??"PUT",n={...s.headers??{}};let o;if(n["Content-Type"]||n["content-type"]||(n["Content-Type"]=e.mimeType),"POST"===i&&s.fields){const e=new FormData;for(const[t,i]of Object.entries(s.fields))e.append(t,i);e.append("file",t),o=e,delete n["Content-Type"],delete n["content-type"]}else o=t;const r=await fetch(s.url,{method:i,headers:n,body:o});if(!r.ok)throw new Error(`[PresignedAssetProvider] Upload failed: ${r.status} ${r.statusText}`);return{id:s.id,kind:e.kind??"file",mimeType:e.mimeType,size:t.size,createdAt:Date.now(),width:e.width,height:e.height,durationMs:e.durationMs,originalFilename:e.originalFilename}}async resolve(t){return this._options.getDownloadUrl(t)}async fetch(t){const e=await this._options.getDownloadUrl(t),s=await fetch(e);if(!s.ok)throw new Error(`[PresignedAssetProvider] Failed to fetch asset ${t}: ${s.status} ${s.statusText}`);return s.blob()}async delete(t){this._options.deleteAsset&&(await this._options.deleteAsset(t),this._options.quiet||console.info(`PresignedAssetProvider: deleted asset ${t}`))}}export{ht as BroadcastSyncProvider,wt as HocuspocusSyncProvider,pt as HttpAssetProvider,dt as InMemorySyncProvider,ut as IndexedDBSyncProvider,mt as PresignedAssetProvider,yt as WebSocketSyncProvider}
1
+ import{H as a,a as T}from"./p-Cv5-yM39.js";export{N as APP_STATE_MIGRATIONS,A as AssetNotFoundError,P as CURRENT_APP_STATE_SCHEMA_VERSION,Q as CURRENT_WORKSPACE_SCHEMA_VERSION,B as DEFAULT_ASSET_STORAGE_CONFIG,D as DEFAULT_BRUSH_CONFIG,z as DEFAULT_LINE_TOOL_CONFIG,y as DEFAULT_TEXT_CONFIG,G as DE_LOCALE,F as EN_LOCALE,J as FR_LOCALE,I as IndexedDBAssetProvider,L as KritzelAlignment,t as KritzelAnchorManager,r as KritzelAssetResolver,K as KritzelBaseObject,i as KritzelBaseTool,j as KritzelBrushTool,p as KritzelCursorHelper,h as KritzelCustomElement,x as KritzelCustomElementRendererRegistry,l as KritzelEraserTool,f as KritzelGroup,d as KritzelImage,m as KritzelImageTool,w as KritzelLicenseManager,e as KritzelLine,k as KritzelLineTool,v as KritzelLocalizationManager,c as KritzelPath,q as KritzelSelectionTool,g as KritzelShape,o as KritzelShapeTool,b as KritzelText,n as KritzelTextTool,u as KritzelThemeManager,s as KritzelWorkspace,S as ShapeType,W as WORKSPACE_EXPORT_VERSION,O as WORKSPACE_MIGRATIONS,E as darkTheme,C as lightTheme,M as runMigrations}from"./p-Cv5-yM39.js";import*as $ from"yjs";import{IndexeddbPersistence as _}from"y-indexeddb";import{WebsocketProvider as R}from"y-websocket";const U=Math.floor,H=127,V=Number.MAX_SAFE_INTEGER;class X{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Y=()=>new X,Z=t=>{const e=new Uint8Array((t=>{let e=t.cpos;for(let s=0;s<t.bufs.length;s++)e+=t.bufs[s].length;return e})(t));let s=0;for(let i=0;i<t.bufs.length;i++){const n=t.bufs[i];e.set(n,s),s+=n.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),s),e},tt=(t,e)=>{const s=t.cbuf.length;t.cpos===s&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(2*s),t.cpos=0),t.cbuf[t.cpos++]=e},et=(t,e)=>{for(;e>H;)tt(t,128|H&e),e=U(e/128);tt(t,H&e)},st=(t,e)=>{et(t,e.byteLength),((t,e)=>{const s=t.cbuf.length,i=t.cpos,n=((t,e)=>t<e?t:e)(s-i,e.length),o=e.length-n;t.cbuf.set(e.subarray(0,n),i),t.cpos+=n,o>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(((t,e)=>t>e?t:e)(2*s,o)),t.cbuf.set(e.subarray(n)),t.cpos=o)})(t,e)},it=t=>new Error(t),nt=it("Unexpected end of array"),ot=it("Integer out of Range");class rt{constructor(t){this.arr=t,this.pos=0}}const ct=t=>((t,e)=>{const s=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,s})(t,at(t)),at=t=>{let e=0,s=1;const i=t.arr.length;for(;t.pos<i;){const i=t.arr[t.pos++];if(e+=(i&H)*s,s*=128,i<128)return e;if(e>V)throw ot}throw nt};class ht{type="local";doc;channel;_synced=!1;constructor(t,e,s){this.doc=e,this.channel=new BroadcastChannel(t),this.channel.onmessage=t=>{this.handleMessage(t.data)},this.doc.on("update",this.handleDocUpdate),this.broadcastSync(),setTimeout((()=>{this._synced=!0}),100),s?.quiet||console.info(`BroadcastChannel Provider initialized: ${t}`)}handleDocUpdate=(t,e)=>{if(e!==this){const e=Y();et(e,0),st(e,t),this.channel.postMessage(Z(e))}};handleMessage(t){const e=(s=new Uint8Array(t),new rt(s));var s;switch(at(e)){case 0:const t=ct(e);$.applyUpdate(this.doc,t,this);break;case 1:this.broadcastSync();break;case 2:const s=ct(e),i=$.encodeStateAsUpdate(this.doc,s);if(i.length>0){const t=Y();et(t,0),st(t,i),this.channel.postMessage(Z(t))}}}broadcastSync(){const t=Y();et(t,2),st(t,$.encodeStateVector(this.doc)),this.channel.postMessage(Z(t))}async connect(){if(!this._synced)return new Promise((t=>{const e=()=>{this._synced?t():setTimeout(e,50)};e()}))}disconnect(){}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.doc.off("update",this.handleDocUpdate),this.channel.close()}}const lt=new Map;class dt{type="local";doc;cacheKey;isConnected=!1;constructor(t,e,s){this.doc=e,this.cacheKey=s?.name??t}handleUpdate=(t,e)=>{e!==this&&lt.set(this.cacheKey,$.encodeStateAsUpdate(this.doc))};async connect(){if(this.isConnected)return;const t=lt.get(this.cacheKey);t&&$.applyUpdate(this.doc,t,this),this.doc.on("update",this.handleUpdate),this.isConnected=!0}disconnect(){this.isConnected=!1}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.doc.off("update",this.handleUpdate),this.isConnected=!1}static clear(t){void 0!==t?lt.delete(t):lt.clear()}}class ut{type="local";provider;isConnected=!1;constructor(t,e,s){this.provider=new _(s?.name||t,e)}async connect(){if(!this.isConnected)return new Promise((t=>{this.provider.on("synced",(()=>{this.isConnected=!0,t()}))}))}disconnect(){this.isConnected=!1}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1}}class yt{type="network";provider;isConnected=!1;_quiet=!1;get awareness(){return this.provider.awareness}constructor(t,e,s){const i=s?.url||"ws://localhost:1234",n=s?.roomName||t;this.provider=new R(i,n,e,{params:s?.params,protocols:s?.protocols,WebSocketPolyfill:s?.WebSocketPolyfill,awareness:s?.awareness,maxBackoffTime:s?.maxBackoffTime,disableBc:!0}),this._quiet=s?.quiet??!1,this.setupEventListeners(),this._quiet||console.info(`WebSocket Provider initialized: ${i}/${n}`)}static with(t){return{create:(e,s,i)=>{const n=i?{...t,...i}:t;return new yt(e,s,n)}}}setupEventListeners(){this.provider.on("status",(({status:t})=>{"connected"===t?(this.isConnected=!0,this._quiet||console.info("WebSocket connected")):"disconnected"===t&&(this.isConnected=!1,this._quiet||console.info("WebSocket disconnected"))})),this.provider.on("sync",(t=>{t&&!this._quiet&&console.info("WebSocket synced")}))}async connect(){if(!this.isConnected)return new Promise(((t,e)=>{const s=setTimeout((()=>{e(new Error("WebSocket connection timeout"))}),1e4),i=({status:e})=>{"connected"===e&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,t())};this.provider.on("status",i),this.provider.wsconnected&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,t())}))}disconnect(){this.provider&&this.provider.disconnect(),this.isConnected=!1}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1}}class wt{type="network";provider;isConnected=!1;isSynced=!1;usesSharedSocket=!1;isDestroyed=!1;connectTimeout=null;pendingConnectReject=null;connectionTimeoutMs;_connectionStatus="disconnected";visibilityHandler=null;onlineHandler=null;get awareness(){return this.provider.awareness}get connectionStatus(){return this._connectionStatus}static sharedWebSocketProvider=null;constructor(t,e,s){const i=s?.name||t,n=s?.url||"ws://localhost:1234";this.connectionTimeoutMs=s?.connectionTimeout??1e4;const o=s?.websocketProvider||wt.sharedWebSocketProvider,r={};void 0!==s?.delay&&(r.delay=s.delay),void 0!==s?.factor&&(r.factor=s.factor),void 0!==s?.maxAttempts&&(r.maxAttempts=s.maxAttempts),void 0!==s?.minDelay&&(r.minDelay=s.minDelay),void 0!==s?.maxDelay&&(r.maxDelay=s.maxDelay);const c=()=>{this.isDestroyed||(this.isConnected=!0,this._connectionStatus="connected",s?.quiet||console.info(`Hocuspocus connected: ${i}`),s?.onConnect&&s.onConnect())},h=()=>{this.isDestroyed||(this.isConnected=!1,this.isSynced=!1,this._connectionStatus="disconnected",s?.quiet||console.info(`Hocuspocus disconnected: ${i}`),s?.onDisconnect&&s.onDisconnect())},l=()=>{this.isDestroyed||(this.isSynced=!0,this._connectionStatus="synced",s?.quiet||console.info(`Hocuspocus synced: ${i}`),s?.onSynced&&s.onSynced())},d=t=>{this.isDestroyed||("connecting"===t.status&&(this._connectionStatus="connecting"),s?.onStatus&&s.onStatus(t))};if(o){this.usesSharedSocket=!0;const t={websocketProvider:o,name:i,document:e,token:s?.token||null,onStatus:d,onConnect:c,onDisconnect:h,onSynced:l,...r};void 0!==s?.forceSyncInterval&&(t.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(t.onAuthenticationFailed=s.onAuthenticationFailed),this.provider=new a(t),this.provider.attach(),s?.quiet||console.info(`Hocuspocus Provider initialized (multiplexed): ${i}`)}else{this.usesSharedSocket=!1;const t={url:n,name:i,document:e,token:s?.token||null,autoConnect:!1,onStatus:d,onConnect:c,onDisconnect:h,onSynced:l,...r};void 0!==s?.forceSyncInterval&&(t.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(t.onAuthenticationFailed=s.onAuthenticationFailed),s?.WebSocketPolyfill&&(t.WebSocketPolyfill=s.WebSocketPolyfill),this.provider=new a(t),s?.quiet||console.info(`Hocuspocus Provider initialized: ${n}/${i}`)}this.setupBrowserEventListeners()}setupBrowserEventListeners(){"undefined"!=typeof document&&(this.visibilityHandler=()=>{"visible"!==document.visibilityState||this.isConnected||this.isDestroyed||this.provider.connect()},document.addEventListener("visibilitychange",this.visibilityHandler)),"undefined"!=typeof window&&(this.onlineHandler=()=>{this.isConnected||this.isDestroyed||this.provider.connect()},window.addEventListener("online",this.onlineHandler))}removeBrowserEventListeners(){this.visibilityHandler&&"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this.onlineHandler&&"undefined"!=typeof window&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null)}static createSharedWebSocket(t){if(wt.sharedWebSocketProvider)return console.warn("Shared WebSocket already exists. Returning existing instance."),wt.sharedWebSocketProvider;const e={url:t.url};return t.WebSocketPolyfill&&(e.WebSocketPolyfill=t.WebSocketPolyfill),t.onConnect&&(e.onConnect=t.onConnect),t.onDisconnect&&(e.onDisconnect=t.onDisconnect),t.onStatus&&(e.onStatus=t.onStatus),wt.sharedWebSocketProvider=new T(e),console.info(`Shared Hocuspocus WebSocket created: ${t.url}`),wt.sharedWebSocketProvider}static destroySharedWebSocket(){wt.sharedWebSocketProvider&&(wt.sharedWebSocketProvider.destroy(),wt.sharedWebSocketProvider=null,console.info("Shared Hocuspocus WebSocket destroyed"))}static getSharedWebSocket(){return wt.sharedWebSocketProvider}static with(t){return{create:(e,s,i)=>{const n=i?{...t,...i}:t;return new wt(e,s,n)}}}async connect(){if(!this.isSynced&&!this.isDestroyed)return this._connectionStatus="connecting",new Promise(((t,e)=>{this.pendingConnectReject=e,this.connectTimeout=setTimeout((()=>{this.pendingConnectReject=null,this.connectTimeout=null,e(new Error("Hocuspocus connection timeout"))}),this.connectionTimeoutMs);const s=()=>{this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=null),this.pendingConnectReject=null,this.provider.off("synced",s),this.isDestroyed||t()};if(this.provider.on("synced",s),this.provider.isSynced)return this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=null),this.pendingConnectReject=null,this.provider.off("synced",s),void t();this.isConnected||this.usesSharedSocket||this.provider.connect()}))}async reconnect(){return this.disconnect(),this.connect()}disconnect(){this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=null),this.pendingConnectReject&&(this.pendingConnectReject=null),this.provider&&(this.usesSharedSocket?this.provider.detach():this.provider.disconnect()),this.isConnected=!1,this.isSynced=!1,this._connectionStatus="disconnected"}destroy(){this.isDestroyed=!0,this.connectTimeout&&(clearTimeout(this.connectTimeout),this.connectTimeout=null),this.pendingConnectReject&&(this.pendingConnectReject=null),this.removeBrowserEventListeners(),this.provider&&this.provider.destroy(),this.isConnected=!1,this.isSynced=!1,this._connectionStatus="disconnected"}}class pt{type="remote";name="HttpAssetProvider";_options;constructor(t){this._options=t}static with(t){return{create:()=>new pt(t)}}async init(){this._options.quiet||console.info("HttpAssetProvider initialized")}destroy(){}canResolve(t){return!0}async put(t,e){const s=e.id??this.generateUuid(),i={...e,id:s},n=await(this._options.headers?.())??{},o=await this._options.uploadUrl(i),r=this._options.upload??this.defaultUpload;return{id:(await r(o,t,i,n)).id??s,kind:e.kind??"file",mimeType:e.mimeType,size:t.size,createdAt:Date.now(),width:e.width,height:e.height,durationMs:e.durationMs,originalFilename:e.originalFilename}}async resolve(t){return this._options.resolveUrl(t)}async fetch(t){const e=await this._options.resolveUrl(t),s=await(this._options.headers?.())??{},i=await fetch(e,{headers:s});if(!i.ok)throw new Error(`[HttpAssetProvider] Failed to fetch asset ${t}: ${i.status} ${i.statusText}`);return i.blob()}async delete(t){if(!this._options.deleteUrl)return;const e=await this._options.deleteUrl(t),s=await(this._options.headers?.())??{},i=await fetch(e,{method:"DELETE",headers:s});if(!i.ok)throw new Error(`[HttpAssetProvider] Failed to delete asset ${t}: ${i.status} ${i.statusText}`);this._options.quiet||console.info(`HttpAssetProvider: deleted asset ${t}`)}defaultUpload=async(t,e,s,i)=>{const n=new FormData;n.append("metadata",JSON.stringify(s)),n.append("file",e,s.originalFilename||`${s.id}.${this.extensionFromMime(s.mimeType)}`);const o=await fetch(t,{method:"POST",headers:i,body:n});if(!o.ok)throw new Error(`[HttpAssetProvider] Upload failed: ${o.status} ${o.statusText}`);return(o.headers.get("content-type")||"").includes("application/json")?await o.json():{}};extensionFromMime(t){const e=t.indexOf("/");return e>=0?t.slice(e+1):"bin"}generateUuid(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=crypto.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const e=Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}class mt{type="remote";name="PresignedAssetProvider";_options;constructor(t){this._options=t}static with(t){return{create:()=>new mt(t)}}async init(){this._options.quiet||console.info("PresignedAssetProvider initialized")}destroy(){}canResolve(t){return!0}async put(t,e){const s=await this._options.getUploadDescriptor(e),i=s.method??"PUT",n={...s.headers??{}};let o;if(n["Content-Type"]||n["content-type"]||(n["Content-Type"]=e.mimeType),"POST"===i&&s.fields){const e=new FormData;for(const[t,i]of Object.entries(s.fields))e.append(t,i);e.append("file",t),o=e,delete n["Content-Type"],delete n["content-type"]}else o=t;const r=await fetch(s.url,{method:i,headers:n,body:o});if(!r.ok)throw new Error(`[PresignedAssetProvider] Upload failed: ${r.status} ${r.statusText}`);return{id:s.id,kind:e.kind??"file",mimeType:e.mimeType,size:t.size,createdAt:Date.now(),width:e.width,height:e.height,durationMs:e.durationMs,originalFilename:e.originalFilename}}async resolve(t){return this._options.getDownloadUrl(t)}async fetch(t){const e=await this._options.getDownloadUrl(t),s=await fetch(e);if(!s.ok)throw new Error(`[PresignedAssetProvider] Failed to fetch asset ${t}: ${s.status} ${s.statusText}`);return s.blob()}async delete(t){this._options.deleteAsset&&(await this._options.deleteAsset(t),this._options.quiet||console.info(`PresignedAssetProvider: deleted asset ${t}`))}}export{ht as BroadcastSyncProvider,wt as HocuspocusSyncProvider,pt as HttpAssetProvider,dt as InMemorySyncProvider,ut as IndexedDBSyncProvider,mt as PresignedAssetProvider,yt as WebSocketSyncProvider}