kritzel-stencil 0.0.164 → 0.0.166
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.
- package/dist/cjs/{default-line-tool.config-DJMYrkSu.js → default-line-tool.config-BNBO4I1t.js} +59 -36
- package/dist/cjs/default-line-tool.config-BNBO4I1t.js.map +1 -0
- package/dist/cjs/index.cjs.js +1 -1
- package/dist/cjs/kritzel-color_22.cjs.entry.js +17 -8
- package/dist/collection/classes/core/core.class.js +9 -0
- package/dist/collection/classes/core/core.class.js.map +1 -1
- package/dist/collection/classes/objects/line.class.js +4 -3
- package/dist/collection/classes/objects/line.class.js.map +1 -1
- package/dist/collection/classes/objects/selection-group.class.js +4 -1
- package/dist/collection/classes/objects/selection-group.class.js.map +1 -1
- package/dist/collection/classes/tools/brush-tool.class.js +45 -30
- package/dist/collection/classes/tools/brush-tool.class.js.map +1 -1
- package/dist/collection/classes/tools/selection-tool.class.js +4 -0
- package/dist/collection/classes/tools/selection-tool.class.js.map +1 -1
- package/dist/collection/components/core/kritzel-engine/kritzel-engine.js +7 -7
- package/dist/collection/components/core/kritzel-engine/kritzel-engine.js.map +1 -1
- package/dist/components/index.js +3 -3
- package/dist/components/kritzel-controls.js +1 -1
- package/dist/components/kritzel-editor.js +3 -3
- package/dist/components/kritzel-engine.js +1 -1
- package/dist/components/{p-Dz2XHHqa.js → p-Bwv1dxAB.js} +47 -32
- package/dist/components/{p-Dz2XHHqa.js.map → p-Bwv1dxAB.js.map} +1 -1
- package/dist/components/{p-DzUUppVL.js → p-CIXaR1a8.js} +31 -14
- package/dist/components/p-CIXaR1a8.js.map +1 -0
- package/dist/components/{p-tp96UZ0l.js → p-CRtmNOp1.js} +3 -3
- package/dist/components/{p-tp96UZ0l.js.map → p-CRtmNOp1.js.map} +1 -1
- package/dist/esm/{default-line-tool.config-C35P3XfD.js → default-line-tool.config-DJ488kil.js} +59 -36
- package/dist/{cjs/default-line-tool.config-DJMYrkSu.js.map → esm/default-line-tool.config-DJ488kil.js.map} +1 -1
- package/dist/esm/index.js +2 -2
- package/dist/esm/kritzel-color_22.entry.js +17 -8
- package/dist/stencil/index.esm.js +1 -1
- package/dist/stencil/{p-3e2b5c42.entry.js → p-3df115ed.entry.js} +3 -3
- package/dist/stencil/p-3df115ed.entry.js.map +1 -0
- package/dist/stencil/p-DJ488kil.js +2 -0
- package/dist/stencil/p-DJ488kil.js.map +1 -0
- package/dist/stencil/stencil.esm.js +1 -1
- package/dist/types/classes/objects/selection-group.class.d.ts +1 -0
- package/dist/types/classes/tools/brush-tool.class.d.ts +1 -0
- package/package.json +1 -1
- package/dist/components/p-DzUUppVL.js.map +0 -1
- package/dist/esm/default-line-tool.config-C35P3XfD.js.map +0 -1
- package/dist/stencil/p-3e2b5c42.entry.js.map +0 -1
- package/dist/stencil/p-C35P3XfD.js +0 -2
- package/dist/stencil/p-C35P3XfD.js.map +0 -1
package/dist/esm/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { w as writeVarUint, a as writeVarUint8Array, t as toUint8Array, r as readVarUint, b as readVarUint8Array, e as encodeStateAsUpdate, c as applyUpdate, d as encodeStateVector, f as createEncoder, g as createDecoder, s as setIfUndefined, h as create, i as fromBase64, v as varStorage, j as toBase64, o as onChange, k as createUint8ArrayFromArrayBuffer, l as offChange, m as readVarString, O as Observable, n as floor, p as getUnixTime, q as equalityDeep, u as writeVarString, x as map, y as ObservableV2, z as length, A as isNode, B as min, C as pow, H as HocuspocusProvider, D as HocuspocusProviderWebsocket } from './default-line-tool.config-
|
|
2
|
-
export { V as DEFAULT_BRUSH_CONFIG, X as DEFAULT_LINE_TOOL_CONFIG, W as DEFAULT_TEXT_CONFIG, R as IndexedDBSyncProvider, U as KritzelAnchorManager, S as KritzelAppStateMap, I as KritzelBrushTool, P as KritzelCursorHelper, L as KritzelEraserTool, F as KritzelImage, M as KritzelImageTool, G as KritzelLine, J as KritzelLineTool, E as KritzelPath, Q as KritzelSelectionTool, K as KritzelText, N as KritzelTextTool, T as KritzelWorkspace } from './default-line-tool.config-
|
|
1
|
+
import { w as writeVarUint, a as writeVarUint8Array, t as toUint8Array, r as readVarUint, b as readVarUint8Array, e as encodeStateAsUpdate, c as applyUpdate, d as encodeStateVector, f as createEncoder, g as createDecoder, s as setIfUndefined, h as create, i as fromBase64, v as varStorage, j as toBase64, o as onChange, k as createUint8ArrayFromArrayBuffer, l as offChange, m as readVarString, O as Observable, n as floor, p as getUnixTime, q as equalityDeep, u as writeVarString, x as map, y as ObservableV2, z as length, A as isNode, B as min, C as pow, H as HocuspocusProvider, D as HocuspocusProviderWebsocket } from './default-line-tool.config-DJ488kil.js';
|
|
2
|
+
export { V as DEFAULT_BRUSH_CONFIG, X as DEFAULT_LINE_TOOL_CONFIG, W as DEFAULT_TEXT_CONFIG, R as IndexedDBSyncProvider, U as KritzelAnchorManager, S as KritzelAppStateMap, I as KritzelBrushTool, P as KritzelCursorHelper, L as KritzelEraserTool, F as KritzelImage, M as KritzelImageTool, G as KritzelLine, J as KritzelLineTool, E as KritzelPath, Q as KritzelSelectionTool, K as KritzelText, N as KritzelTextTool, T as KritzelWorkspace } from './default-line-tool.config-DJ488kil.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* BroadcastChannel sync provider for cross-tab synchronization
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as registerInstance, h, H as Host, c as createEvent, g as getElement } from './index-SGde3HXB.js';
|
|
2
|
-
import { Y as KritzelDevicesHelper, I as KritzelBrushTool, N as KritzelTextTool, Z as KritzelMouseButton, _ as KritzelBaseObject, $ as Schema, a0 as schema, a1 as addListNodes, a2 as EditorView, a3 as EditorState, a4 as keymap, a5 as TextSelection, a6 as KritzelKeyboardHelper, a7 as KritzelToolRegistry, a8 as KritzelGeometryHelper, a9 as baseKeymap, aa as KritzelBaseTool, ab as KritzelEventHelper, Q as KritzelSelectionTool, V as DEFAULT_BRUSH_CONFIG, X as DEFAULT_LINE_TOOL_CONFIG, J as KritzelLineTool, L as KritzelEraserTool, W as DEFAULT_TEXT_CONFIG, M as KritzelImageTool, T as KritzelWorkspace, ac as KritzelIconRegistry, ad as KritzelBaseHandler, ae as KritzelSelectionBox, af as KritzelSelectionGroup, F as KritzelImage, K as KritzelText, G as KritzelLine, E as KritzelPath, ag as Doc, ah as DEFAULT_SYNC_CONFIG, ai as UndoManager, P as KritzelCursorHelper, S as KritzelAppStateMap, U as KritzelAnchorManager, aj as ObjectHelper, ak as KritzelClassHelper } from './default-line-tool.config-
|
|
2
|
+
import { Y as KritzelDevicesHelper, I as KritzelBrushTool, N as KritzelTextTool, Z as KritzelMouseButton, _ as KritzelBaseObject, $ as Schema, a0 as schema, a1 as addListNodes, a2 as EditorView, a3 as EditorState, a4 as keymap, a5 as TextSelection, a6 as KritzelKeyboardHelper, a7 as KritzelToolRegistry, a8 as KritzelGeometryHelper, a9 as baseKeymap, aa as KritzelBaseTool, ab as KritzelEventHelper, Q as KritzelSelectionTool, V as DEFAULT_BRUSH_CONFIG, X as DEFAULT_LINE_TOOL_CONFIG, J as KritzelLineTool, L as KritzelEraserTool, W as DEFAULT_TEXT_CONFIG, M as KritzelImageTool, T as KritzelWorkspace, ac as KritzelIconRegistry, ad as KritzelBaseHandler, ae as KritzelSelectionBox, af as KritzelSelectionGroup, F as KritzelImage, K as KritzelText, G as KritzelLine, E as KritzelPath, ag as Doc, ah as DEFAULT_SYNC_CONFIG, ai as UndoManager, P as KritzelCursorHelper, S as KritzelAppStateMap, U as KritzelAnchorManager, aj as ObjectHelper, ak as KritzelClassHelper } from './default-line-tool.config-DJ488kil.js';
|
|
3
3
|
|
|
4
4
|
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
|
5
5
|
|
|
@@ -19889,6 +19889,9 @@ class KritzelCore {
|
|
|
19889
19889
|
const workspaces = this.loadWorkspacesFromAppState();
|
|
19890
19890
|
// Find most recently updated workspace or use provided/fallback
|
|
19891
19891
|
const mostRecentWorkspace = workspaces.length > 0 ? [...workspaces].sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())[0] : null;
|
|
19892
|
+
// Check localStorage for last active workspace
|
|
19893
|
+
const lastActiveWorkspaceId = localStorage.getItem('kritzel-active-workspace-id');
|
|
19894
|
+
const lastActiveWorkspace = lastActiveWorkspaceId ? workspaces.find(w => w.id === lastActiveWorkspaceId) : null;
|
|
19892
19895
|
let activeWorkspace;
|
|
19893
19896
|
if (workspace) {
|
|
19894
19897
|
// Use provided workspace
|
|
@@ -19900,6 +19903,10 @@ class KritzelCore {
|
|
|
19900
19903
|
this.saveWorkspaceToAppState(activeWorkspace);
|
|
19901
19904
|
}
|
|
19902
19905
|
}
|
|
19906
|
+
else if (lastActiveWorkspace) {
|
|
19907
|
+
// Use last active workspace from localStorage
|
|
19908
|
+
activeWorkspace = lastActiveWorkspace;
|
|
19909
|
+
}
|
|
19903
19910
|
else if (mostRecentWorkspace) {
|
|
19904
19911
|
// Use most recent workspace
|
|
19905
19912
|
activeWorkspace = mostRecentWorkspace;
|
|
@@ -19910,6 +19917,8 @@ class KritzelCore {
|
|
|
19910
19917
|
activeWorkspace._core = this;
|
|
19911
19918
|
this.saveWorkspaceToAppState(activeWorkspace);
|
|
19912
19919
|
}
|
|
19920
|
+
// Save active workspace ID to localStorage
|
|
19921
|
+
localStorage.setItem('kritzel-active-workspace-id', activeWorkspace.id);
|
|
19913
19922
|
// Destroy old ObjectMap if switching workspaces
|
|
19914
19923
|
if (this._store.state.objects && this._store.state.objects.isReady) {
|
|
19915
19924
|
this._store.state.objects.destroy();
|
|
@@ -20827,16 +20836,16 @@ const KritzelEngine = class {
|
|
|
20827
20836
|
pointerEvents: this.core.store.state.isScaling ? 'none' : 'auto',
|
|
20828
20837
|
} }, h("svg", { xmlns: "http://www.w3.org/2000/svg", id: object.id, class: "object", style: {
|
|
20829
20838
|
zIndex: object.zIndex.toString(),
|
|
20830
|
-
height: object?.totalHeight
|
|
20831
|
-
width: object?.totalWidth
|
|
20839
|
+
height: object?.totalHeight + 'px',
|
|
20840
|
+
width: object?.totalWidth + 'px',
|
|
20832
20841
|
left: '0',
|
|
20833
20842
|
top: '0',
|
|
20834
20843
|
position: 'absolute',
|
|
20835
|
-
transform: `rotate(${object.rotationDegrees}deg)
|
|
20836
|
-
transformOrigin: `${object.totalWidth / 2}px ${object.totalHeight / 2}px
|
|
20844
|
+
transform: object.rotationDegrees !== 0 ? `rotate(${object.rotationDegrees}deg)` : undefined,
|
|
20845
|
+
transformOrigin: object.rotationDegrees !== 0 ? `${object.totalWidth / 2}px ${object.totalHeight / 2}px` : undefined,
|
|
20837
20846
|
opacity: object.markedForRemoval ? '0.5' : object.opacity.toString(),
|
|
20838
20847
|
pointerEvents: object.markedForRemoval ? 'none' : 'auto',
|
|
20839
|
-
} }, KritzelClassHelper.isInstanceOf(object, 'KritzelPath') && (h("svg", { ref: el => object.mount(el), xmlns: "http://www.w3.org/2000/svg", style: { overflow: 'visible' }, viewBox: object?.viewBox }, h("path", { d: object?.d, fill: object.fill, stroke: object?.stroke, "shape-rendering": object.isLowRes() ? 'optimizeSpeed' : 'auto' }))), KritzelClassHelper.isInstanceOf(object, 'KritzelLine') && (h("svg", { ref: el => object.mount(el), xmlns: "http://www.w3.org/2000/svg", style: { overflow: 'visible' }, viewBox: object?.viewBox }, h("defs", null, object.hasStartArrow && (h("marker", { id: object.startMarkerId, markerWidth: object.getArrowSize('start'), markerHeight: object.getArrowSize('start'), refX: 0, refY: object.getArrowSize('start') / 2, orient: "auto-start-reverse", markerUnits: "userSpaceOnUse" }, h("path", { d: object.getArrowPath(object.arrows?.start?.style), fill: object.getArrowFill('start'), transform: `scale(${object.getArrowSize('start') / 10})` }))), object.hasEndArrow && (h("marker", { id: object.endMarkerId, markerWidth: object.getArrowSize('end'), markerHeight: object.getArrowSize('end'), refX: 0, refY: object.getArrowSize('end') / 2, orient: "auto", markerUnits: "userSpaceOnUse" }, h("path", { d: object.getArrowPath(object.arrows?.end?.style), fill: object.getArrowFill('end'), transform: `scale(${object.getArrowSize('end') / 10})` })))), h("path", { d: this.core.anchorManager.computeClippedLinePath(object), fill: "none", stroke: object?.stroke, "stroke-width": object?.strokeWidth, "stroke-linecap": "round", "marker-start": object.hasStartArrow ? `url(#${object.startMarkerId})` : undefined, "marker-end": object.hasEndArrow ? `url(#${object.endMarkerId})` : undefined }))), h("foreignObject", { x: "0", y: "0", width: object.totalWidth.toString(), height: object.totalHeight.toString(), style: {
|
|
20848
|
+
} }, KritzelClassHelper.isInstanceOf(object, 'KritzelPath') && (h("svg", { ref: el => object.mount(el), xmlns: "http://www.w3.org/2000/svg", style: { overflow: 'visible' }, viewBox: object?.viewBox }, h("path", { d: object?.d, fill: object.fill, stroke: object?.stroke, "shape-rendering": object.isLowRes() ? 'optimizeSpeed' : 'auto' }))), KritzelClassHelper.isInstanceOf(object, 'KritzelLine') && (h("svg", { ref: el => object.mount(el), xmlns: "http://www.w3.org/2000/svg", style: { overflow: 'visible' }, viewBox: object?.viewBox }, h("defs", null, object.hasStartArrow && (h("marker", { id: object.startMarkerId, markerWidth: object.getArrowSize('start'), markerHeight: object.getArrowSize('start'), refX: 0, refY: object.getArrowSize('start') / 2, orient: "auto-start-reverse", markerUnits: "userSpaceOnUse" }, h("path", { d: object.getArrowPath(object.arrows?.start?.style), fill: object.getArrowFill('start'), transform: `scale(${object.getArrowSize('start') / 10})` }))), object.hasEndArrow && (h("marker", { id: object.endMarkerId, markerWidth: object.getArrowSize('end'), markerHeight: object.getArrowSize('end'), refX: 0, refY: object.getArrowSize('end') / 2, orient: "auto", markerUnits: "userSpaceOnUse" }, h("path", { d: object.getArrowPath(object.arrows?.end?.style), fill: object.getArrowFill('end'), transform: `scale(${object.getArrowSize('end') / 10})` })))), h("path", { d: this.core.anchorManager.computeClippedLinePath(object), fill: "none", stroke: "transparent", "stroke-width": Math.max(object?.strokeWidth || 0, 10), "stroke-linecap": "round" }), h("path", { d: this.core.anchorManager.computeClippedLinePath(object), fill: "none", stroke: object?.stroke, "stroke-width": object?.strokeWidth, "stroke-linecap": "round", "marker-start": object.hasStartArrow ? `url(#${object.startMarkerId})` : undefined, "marker-end": object.hasEndArrow ? `url(#${object.endMarkerId})` : undefined }))), h("foreignObject", { x: "0", y: "0", width: object.totalWidth.toString(), height: object.totalHeight.toString(), style: {
|
|
20840
20849
|
minHeight: '0',
|
|
20841
20850
|
minWidth: '0',
|
|
20842
20851
|
backgroundColor: object.backgroundColor,
|
|
@@ -21066,7 +21075,7 @@ const KritzelEngine = class {
|
|
|
21066
21075
|
stroke: 'var(--kritzel-snap-indicator-stroke, #3b82f6)',
|
|
21067
21076
|
strokeWidth: data.indicatorStrokeWidth,
|
|
21068
21077
|
} }))));
|
|
21069
|
-
})()), this.core.store.state.isContextMenuVisible && (h("kritzel-context-menu", { key: '
|
|
21078
|
+
})()), this.core.store.state.isContextMenuVisible && (h("kritzel-context-menu", { key: '70aefa0f3cf33036edb455dbe75448d2521e6dc9', class: "context-menu", ref: el => (this.contextMenuElement = el), items: this.core.store.state.contextMenuItems, objects: this.core.store.selectionGroup?.objects || [], style: {
|
|
21070
21079
|
position: 'fixed',
|
|
21071
21080
|
left: `${this.core.store.state.contextMenuX}px`,
|
|
21072
21081
|
top: `${this.core.store.state.contextMenuY}px`,
|
|
@@ -21077,7 +21086,7 @@ const KritzelEngine = class {
|
|
|
21077
21086
|
y: (-this.core.store.state.translateY + this.core.store.state.contextMenuY) / this.core.store.state.scale,
|
|
21078
21087
|
}, this.core.store.selectionGroup?.objects);
|
|
21079
21088
|
this.hideContextMenu();
|
|
21080
|
-
}, onClose: () => this.hideContextMenu() })), this.core.store.state?.activeTool instanceof KritzelEraserTool && !this.core.store.state.isScaling && h("kritzel-cursor-trail", { key: '
|
|
21089
|
+
}, onClose: () => this.hideContextMenu() })), this.core.store.state?.activeTool instanceof KritzelEraserTool && !this.core.store.state.isScaling && h("kritzel-cursor-trail", { key: '68106a187ca81a38a819f1d52895b2858a8a28cb', core: this.core })));
|
|
21081
21090
|
}
|
|
21082
21091
|
static get watchers() { return {
|
|
21083
21092
|
"workspace": ["onWorkspaceChange"],
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{w as s,a as t,t as e,r as i,b as n,e as o,c,d as a,f as h,g as r,s as l,h as d,i as u,v as f,j as p,o as m,k as y,l as w,m as k,O as b,n as v,p as g,q as z,u as C,x as $,y as x,z as B,A as H,B as A,C as D,H as O,D as _}from"./p-C35P3XfD.js";export{V as DEFAULT_BRUSH_CONFIG,X as DEFAULT_LINE_TOOL_CONFIG,W as DEFAULT_TEXT_CONFIG,R as IndexedDBSyncProvider,U as KritzelAnchorManager,S as KritzelAppStateMap,I as KritzelBrushTool,P as KritzelCursorHelper,L as KritzelEraserTool,F as KritzelImage,M as KritzelImageTool,G as KritzelLine,J as KritzelLineTool,E as KritzelPath,Q as KritzelSelectionTool,K as KritzelText,N as KritzelTextTool,T as KritzelWorkspace}from"./p-C35P3XfD.js";class j{doc;channel;_synced=false;constructor(s,t,e){this.doc=t;this.channel=new BroadcastChannel(s);this.channel.onmessage=s=>{this.handleMessage(s.data)};this.doc.on("update",this.handleDocUpdate);this.broadcastSync();setTimeout((()=>{this._synced=true}),100);console.info(`BroadcastChannel Provider initialized: ${s}`)}handleDocUpdate=(i,n)=>{if(n!==this){const n=h();s(n,0);t(n,i);this.channel.postMessage(e(n))}};handleMessage(a){const l=r(new Uint8Array(a));const d=i(l);switch(d){case 0:const i=n(l);c(this.doc,i,this);break;case 1:this.broadcastSync();break;case 2:const a=n(l);const r=o(this.doc,a);if(r.length>0){const i=h();s(i,0);t(i,r);this.channel.postMessage(e(i))}break}}broadcastSync(){const i=h();s(i,2);t(i,a(this.doc));this.channel.postMessage(e(i))}async connect(){if(this._synced){return}return new Promise((s=>{const t=()=>{if(this._synced){s()}else{setTimeout(t,50)}};t()}))}disconnect(){}destroy(){this.doc.off("update",this.handleDocUpdate);this.channel.close()}}const q=new Map;class Y{constructor(s){this.room=s;this.onmessage=null;this._onChange=t=>t.key===s&&this.onmessage!==null&&this.onmessage({data:u(t.newValue||"")});m(this._onChange)}postMessage(s){f.setItem(this.room,p(y(s)))}close(){w(this._onChange)}}const Z=typeof BroadcastChannel==="undefined"?Y:BroadcastChannel;const ss=s=>l(q,s,(()=>{const t=d();const e=new Z(s);e.onmessage=s=>t.forEach((t=>t(s.data,"broadcastchannel")));return{bc:e,subs:t}}));const ts=(s,t)=>{ss(s).subs.add(t);return t};const es=(s,t)=>{const e=ss(s);const i=e.subs.delete(t);if(i&&e.subs.size===0){e.bc.close();q.delete(s)}return i};const is=(s,t,e=null)=>{const i=ss(s);i.bc.postMessage(t);i.subs.forEach((s=>s(t,e)))};const ns=0;const os=1;const cs=2;const as=(e,i)=>{s(e,ns);const n=a(i);t(e,n)};const hs=(e,i,n)=>{s(e,os);t(e,o(i,n))};const rs=(s,t,e)=>hs(t,e,n(s));const ls=(s,t,e)=>{try{c(t,n(s),e)}catch(s){console.error("Caught error while handling a Yjs update",s)}};const ds=(e,i)=>{s(e,cs);t(e,i)};const us=ls;const fs=(s,t,e,n)=>{const o=i(s);switch(o){case ns:rs(s,t,e);break;case os:ls(s,e,n);break;case cs:us(s,e,n);break;default:throw new Error("Unknown message type")}return o};const ps=0;const ms=(s,t,e)=>{switch(i(s)){case ps:e(t,k(s))}};const ys=3e4;class Ss extends b{constructor(s){super();this.doc=s;this.clientID=s.clientID;this.states=new Map;this.meta=new Map;this._checkInterval=setInterval((()=>{const s=g();if(this.getLocalState()!==null&&ys/2<=s-this.meta.get(this.clientID).lastUpdated){this.setLocalState(this.getLocalState())}const t=[];this.meta.forEach(((e,i)=>{if(i!==this.clientID&&ys<=s-e.lastUpdated&&this.states.has(i)){t.push(i)}}));if(t.length>0){ws(this,t,"timeout")}}),v(ys/10));s.on("destroy",(()=>{this.destroy()}));this.setLocalState({})}destroy(){this.emit("destroy",[this]);this.setLocalState(null);super.destroy();clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(s){const t=this.clientID;const e=this.meta.get(t);const i=e===undefined?0:e.clock+1;const n=this.states.get(t);if(s===null){this.states.delete(t)}else{this.states.set(t,s)}this.meta.set(t,{clock:i,lastUpdated:g()});const o=[];const c=[];const a=[];const h=[];if(s===null){h.push(t)}else if(n==null){if(s!=null){o.push(t)}}else{c.push(t);if(!z(n,s)){a.push(t)}}if(o.length>0||a.length>0||h.length>0){this.emit("change",[{added:o,updated:a,removed:h},"local"])}this.emit("update",[{added:o,updated:c,removed:h},"local"])}setLocalStateField(s,t){const e=this.getLocalState();if(e!==null){this.setLocalState({...e,[s]:t})}}getStates(){return this.states}}const ws=(s,t,e)=>{const i=[];for(let e=0;e<t.length;e++){const n=t[e];if(s.states.has(n)){s.states.delete(n);if(n===s.clientID){const t=s.meta.get(n);s.meta.set(n,{clock:t.clock+1,lastUpdated:g()})}i.push(n)}}if(i.length>0){s.emit("change",[{added:[],updated:[],removed:i},e]);s.emit("update",[{added:[],updated:[],removed:i},e])}};const ks=(t,i,n=t.states)=>{const o=i.length;const c=h();s(c,o);for(let e=0;e<o;e++){const o=i[e];const a=n.get(o)||null;const h=t.meta.get(o).clock;s(c,o);s(c,h);C(c,JSON.stringify(a))}return e(c)};const bs=(s,t,e)=>{const n=r(t);const o=g();const c=[];const a=[];const h=[];const l=[];const d=i(n);for(let t=0;t<d;t++){const t=i(n);let e=i(n);const r=JSON.parse(k(n));const d=s.meta.get(t);const u=s.states.get(t);const f=d===undefined?0:d.clock;if(f<e||f===e&&r===null&&s.states.has(t)){if(r===null){if(t===s.clientID&&s.getLocalState()!=null){e++}else{s.states.delete(t)}}else{s.states.set(t,r)}s.meta.set(t,{clock:e,lastUpdated:o});if(d===undefined&&r!==null){c.push(t)}else if(d!==undefined&&r===null){l.push(t)}else if(r!==null){if(!z(r,u)){h.push(t)}a.push(t)}}}if(c.length>0||h.length>0||l.length>0){s.emit("change",[{added:c,updated:h,removed:l},e])}if(c.length>0||a.length>0||l.length>0){s.emit("update",[{added:c,updated:a,removed:l},e])}};const Ts=s=>$(s,((s,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(s)}`)).join("&");const vs=0;const gs=3;const zs=1;const Cs=2;const Ws=[];Ws[vs]=(t,e,i,n,o)=>{s(t,vs);const c=fs(e,t,i.doc,i);if(n&&c===os&&!i.synced){i.synced=true}};Ws[gs]=(e,i,n,o,c)=>{s(e,zs);t(e,ks(n.awareness,Array.from(n.awareness.getStates().keys())))};Ws[zs]=(s,t,e,i,o)=>{bs(e.awareness,n(t),e)};Ws[Cs]=(s,t,e,i,n)=>{ms(t,e.doc,((s,t)=>Ps(e,t)))};const Is=3e4;const Ps=(s,t)=>console.warn(`Permission denied to access ${s.url}.\n${t}`);const $s=(s,t,e)=>{const n=r(t);const o=h();const c=i(n);const a=s.messageHandlers[c];if(a){a(o,n,s,e,c)}else{console.error("Unable to compute message")}return o};const Us=(s,t,e)=>{if(t===s.ws){s.emit("connection-close",[e,s]);s.ws=null;t.close();s.wsconnecting=false;if(s.wsconnected){s.wsconnected=false;s.synced=false;ws(s.awareness,Array.from(s.awareness.getStates().keys()).filter((t=>t!==s.doc.clientID)),s);s.emit("status",[{status:"disconnected"}])}else{s.wsUnsuccessfulReconnects++}setTimeout(xs,A(D(2,s.wsUnsuccessfulReconnects)*100,s.maxBackoffTime),s)}};const xs=i=>{if(i.shouldConnect&&i.ws===null){const n=new i._WS(i.url,i.protocols);n.binaryType="arraybuffer";i.ws=n;i.wsconnecting=true;i.wsconnected=false;i.synced=false;n.onmessage=s=>{i.wsLastMessageReceived=g();const t=$s(i,new Uint8Array(s.data),true);if(B(t)>1){n.send(e(t))}};n.onerror=s=>{i.emit("connection-error",[s,i])};n.onclose=s=>{Us(i,n,s)};n.onopen=()=>{i.wsLastMessageReceived=g();i.wsconnecting=false;i.wsconnected=true;i.wsUnsuccessfulReconnects=0;i.emit("status",[{status:"connected"}]);const o=h();s(o,vs);as(o,i.doc);n.send(e(o));if(i.awareness.getLocalState()!==null){const o=h();s(o,zs);t(o,ks(i.awareness,[i.doc.clientID]));n.send(e(o))}};i.emit("status",[{status:"connecting"}])}};const Ks=(s,t)=>{const e=s.ws;if(s.wsconnected&&e&&e.readyState===e.OPEN){e.send(t)}if(s.bcconnected){is(s.bcChannel,t,s)}};class Bs extends x{constructor(i,n,o,{connect:c=true,awareness:a=new Ss(o),params:r={},protocols:l=[],WebSocketPolyfill:d=WebSocket,resyncInterval:u=-1,maxBackoffTime:f=2500,disableBc:p=false}={}){super();while(i[i.length-1]==="/"){i=i.slice(0,i.length-1)}this.serverUrl=i;this.bcChannel=i+"/"+n;this.maxBackoffTime=f;this.params=r;this.protocols=l;this.roomname=n;this.doc=o;this._WS=d;this.awareness=a;this.wsconnected=false;this.wsconnecting=false;this.bcconnected=false;this.disableBc=p;this.wsUnsuccessfulReconnects=0;this.messageHandlers=Ws.slice();this._synced=false;this.ws=null;this.wsLastMessageReceived=0;this.shouldConnect=c;this._resyncInterval=0;if(u>0){this._resyncInterval=setInterval((()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const t=h();s(t,vs);as(t,o);this.ws.send(e(t))}}),u)}this._bcSubscriber=(s,t)=>{if(t!==this){const t=$s(this,new Uint8Array(s),false);if(B(t)>1){is(this.bcChannel,e(t),this)}}};this._updateHandler=(t,i)=>{if(i!==this){const i=h();s(i,vs);ds(i,t);Ks(this,e(i))}};this.doc.on("update",this._updateHandler);this._awarenessUpdateHandler=({added:i,updated:n,removed:o},c)=>{const r=i.concat(n).concat(o);const l=h();s(l,zs);t(l,ks(a,r));Ks(this,e(l))};this._exitHandler=()=>{ws(this.awareness,[o.clientID],"app closed")};if(H&&typeof process!=="undefined"){process.on("exit",this._exitHandler)}a.on("update",this._awarenessUpdateHandler);this._checkInterval=setInterval((()=>{if(this.wsconnected&&Is<g()-this.wsLastMessageReceived){Us(this,this.ws,null)}}),Is/10);if(c){this.connect()}}get url(){const s=Ts(this.params);return this.serverUrl+"/"+this.roomname+(s.length===0?"":"?"+s)}get synced(){return this._synced}set synced(s){if(this._synced!==s){this._synced=s;this.emit("synced",[s]);this.emit("sync",[s])}}destroy(){if(this._resyncInterval!==0){clearInterval(this._resyncInterval)}clearInterval(this._checkInterval);this.disconnect();if(H&&typeof process!=="undefined"){process.off("exit",this._exitHandler)}this.awareness.off("update",this._awarenessUpdateHandler);this.doc.off("update",this._updateHandler);super.destroy()}connectBc(){if(this.disableBc){return}if(!this.bcconnected){ts(this.bcChannel,this._bcSubscriber);this.bcconnected=true}const i=h();s(i,vs);as(i,this.doc);is(this.bcChannel,e(i),this);const n=h();s(n,vs);hs(n,this.doc);is(this.bcChannel,e(n),this);const o=h();s(o,gs);is(this.bcChannel,e(o),this);const c=h();s(c,zs);t(c,ks(this.awareness,[this.doc.clientID]));is(this.bcChannel,e(c),this)}disconnectBc(){const i=h();s(i,zs);t(i,ks(this.awareness,[this.doc.clientID],new Map));Ks(this,e(i));if(this.bcconnected){es(this.bcChannel,this._bcSubscriber);this.bcconnected=false}}disconnect(){this.shouldConnect=false;this.disconnectBc();if(this.ws!==null){Us(this,this.ws,null)}}connect(){this.shouldConnect=true;if(!this.wsconnected&&this.ws===null){xs(this);this.connectBc()}}}class Hs{provider;isConnected=false;constructor(s,t,e){const i=e?.url||"ws://localhost:1234";const n=e?.roomName||s;this.provider=new Bs(i,n,t,{params:e?.params,protocols:e?.protocols,WebSocketPolyfill:e?.WebSocketPolyfill,awareness:e?.awareness,maxBackoffTime:e?.maxBackoffTime,disableBc:true});this.setupEventListeners();console.info(`WebSocket Provider initialized: ${i}/${n}`)}static with(s){return{create:(t,e)=>new Hs(t,e,s)}}setupEventListeners(){this.provider.on("status",(({status:s})=>{if(s==="connected"){this.isConnected=true;console.info("WebSocket connected")}else if(s==="disconnected"){this.isConnected=false;console.info("WebSocket disconnected")}}));this.provider.on("sync",(s=>{if(s){console.info("WebSocket synced")}}))}async connect(){if(this.isConnected){return}return new Promise(((s,t)=>{const e=setTimeout((()=>{t(new Error("WebSocket connection timeout"))}),1e4);const i=({status:t})=>{if(t==="connected"){clearTimeout(e);this.provider.off("status",i);this.isConnected=true;s()}};this.provider.on("status",i);if(this.provider.wsconnected){clearTimeout(e);this.provider.off("status",i);this.isConnected=true;s()}}))}disconnect(){if(this.provider){this.provider.disconnect()}this.isConnected=false}destroy(){if(this.provider){this.provider.destroy()}this.isConnected=false}}class Ls{provider;isConnected=false;isSynced=false;usesSharedSocket=false;static sharedWebSocketProvider=null;constructor(s,t,e){const i=e?.name||s;const n=e?.url||"ws://localhost:1234";const o=e?.websocketProvider||Ls.sharedWebSocketProvider;if(o){this.usesSharedSocket=true;const s={websocketProvider:o,name:i,document:t,token:e?.token||null,onConnect:()=>{this.isConnected=true;if(!e?.quiet){console.info(`Hocuspocus connected: ${i}`)}if(e?.onConnect){e.onConnect()}},onDisconnect:()=>{this.isConnected=false;this.isSynced=false;if(!e?.quiet){console.info(`Hocuspocus disconnected: ${i}`)}if(e?.onDisconnect){e.onDisconnect()}},onSynced:()=>{this.isSynced=true;if(!e?.quiet){console.info(`Hocuspocus synced: ${i}`)}if(e?.onSynced){e.onSynced()}}};if(e?.forceSyncInterval!==undefined){s.forceSyncInterval=e.forceSyncInterval}if(e?.onAuthenticationFailed){s.onAuthenticationFailed=e.onAuthenticationFailed}if(e?.onStatus){s.onStatus=e.onStatus}this.provider=new O(s);this.provider.attach();if(!e?.quiet){console.info(`Hocuspocus Provider initialized (multiplexed): ${i}`)}}else{this.usesSharedSocket=false;const s={url:n,name:i,document:t,token:e?.token||null,onConnect:()=>{this.isConnected=true;if(!e?.quiet){console.info(`Hocuspocus connected: ${i}`)}if(e?.onConnect){e.onConnect()}},onDisconnect:()=>{this.isConnected=false;this.isSynced=false;if(!e?.quiet){console.info(`Hocuspocus disconnected: ${i}`)}if(e?.onDisconnect){e.onDisconnect()}},onSynced:()=>{this.isSynced=true;if(!e?.quiet){console.info(`Hocuspocus synced: ${i}`)}if(e?.onSynced){e.onSynced()}}};if(e?.forceSyncInterval!==undefined){s.forceSyncInterval=e.forceSyncInterval}if(e?.onAuthenticationFailed){s.onAuthenticationFailed=e.onAuthenticationFailed}if(e?.onStatus){s.onStatus=e.onStatus}if(e?.WebSocketPolyfill){s.WebSocketPolyfill=e.WebSocketPolyfill}this.provider=new O(s);if(!e?.quiet){console.info(`Hocuspocus Provider initialized: ${n}/${i}`)}}}static createSharedWebSocket(s){if(Ls.sharedWebSocketProvider){console.warn("Shared WebSocket already exists. Returning existing instance.");return Ls.sharedWebSocketProvider}const t={url:s.url};if(s.WebSocketPolyfill){t.WebSocketPolyfill=s.WebSocketPolyfill}if(s.onConnect){t.onConnect=s.onConnect}if(s.onDisconnect){t.onDisconnect=s.onDisconnect}if(s.onStatus){t.onStatus=s.onStatus}Ls.sharedWebSocketProvider=new _(t);console.info(`Shared Hocuspocus WebSocket created: ${s.url}`);return Ls.sharedWebSocketProvider}static destroySharedWebSocket(){if(Ls.sharedWebSocketProvider){Ls.sharedWebSocketProvider.destroy();Ls.sharedWebSocketProvider=null;console.info("Shared Hocuspocus WebSocket destroyed")}}static getSharedWebSocket(){return Ls.sharedWebSocketProvider}static with(s){return{create:(t,e)=>new Ls(t,e,s)}}async connect(){if(this.isSynced){return}return new Promise(((s,t)=>{const e=setTimeout((()=>{t(new Error("Hocuspocus connection timeout"))}),1e4);const i=()=>{clearTimeout(e);this.provider.off("synced",i);s()};this.provider.on("synced",i);if(this.provider.isSynced){clearTimeout(e);this.provider.off("synced",i);s();return}if(!this.isConnected&&!this.usesSharedSocket){this.provider.connect()}}))}disconnect(){if(this.provider){if(this.usesSharedSocket){this.provider.detach()}else{this.provider.disconnect()}}this.isConnected=false;this.isSynced=false}destroy(){if(this.provider){this.provider.destroy()}this.isConnected=false;this.isSynced=false}}export{j as BroadcastSyncProvider,Ls as HocuspocusSyncProvider,Hs as WebSocketSyncProvider};
|
|
1
|
+
import{w as s,a as t,t as e,r as i,b as n,e as o,c,d as a,f as h,g as r,s as l,h as d,i as u,v as f,j as p,o as m,k as y,l as w,m as k,O as b,n as v,p as g,q as z,u as $,x as C,y as x,z as B,A as H,B as A,C as D,H as O,D as _}from"./p-DJ488kil.js";export{V as DEFAULT_BRUSH_CONFIG,X as DEFAULT_LINE_TOOL_CONFIG,W as DEFAULT_TEXT_CONFIG,R as IndexedDBSyncProvider,U as KritzelAnchorManager,S as KritzelAppStateMap,I as KritzelBrushTool,P as KritzelCursorHelper,L as KritzelEraserTool,F as KritzelImage,M as KritzelImageTool,G as KritzelLine,J as KritzelLineTool,E as KritzelPath,Q as KritzelSelectionTool,K as KritzelText,N as KritzelTextTool,T as KritzelWorkspace}from"./p-DJ488kil.js";class j{doc;channel;_synced=false;constructor(s,t,e){this.doc=t;this.channel=new BroadcastChannel(s);this.channel.onmessage=s=>{this.handleMessage(s.data)};this.doc.on("update",this.handleDocUpdate);this.broadcastSync();setTimeout((()=>{this._synced=true}),100);console.info(`BroadcastChannel Provider initialized: ${s}`)}handleDocUpdate=(i,n)=>{if(n!==this){const n=h();s(n,0);t(n,i);this.channel.postMessage(e(n))}};handleMessage(a){const l=r(new Uint8Array(a));const d=i(l);switch(d){case 0:const i=n(l);c(this.doc,i,this);break;case 1:this.broadcastSync();break;case 2:const a=n(l);const r=o(this.doc,a);if(r.length>0){const i=h();s(i,0);t(i,r);this.channel.postMessage(e(i))}break}}broadcastSync(){const i=h();s(i,2);t(i,a(this.doc));this.channel.postMessage(e(i))}async connect(){if(this._synced){return}return new Promise((s=>{const t=()=>{if(this._synced){s()}else{setTimeout(t,50)}};t()}))}disconnect(){}destroy(){this.doc.off("update",this.handleDocUpdate);this.channel.close()}}const q=new Map;class Y{constructor(s){this.room=s;this.onmessage=null;this._onChange=t=>t.key===s&&this.onmessage!==null&&this.onmessage({data:u(t.newValue||"")});m(this._onChange)}postMessage(s){f.setItem(this.room,p(y(s)))}close(){w(this._onChange)}}const Z=typeof BroadcastChannel==="undefined"?Y:BroadcastChannel;const ss=s=>l(q,s,(()=>{const t=d();const e=new Z(s);e.onmessage=s=>t.forEach((t=>t(s.data,"broadcastchannel")));return{bc:e,subs:t}}));const ts=(s,t)=>{ss(s).subs.add(t);return t};const es=(s,t)=>{const e=ss(s);const i=e.subs.delete(t);if(i&&e.subs.size===0){e.bc.close();q.delete(s)}return i};const is=(s,t,e=null)=>{const i=ss(s);i.bc.postMessage(t);i.subs.forEach((s=>s(t,e)))};const ns=0;const os=1;const cs=2;const as=(e,i)=>{s(e,ns);const n=a(i);t(e,n)};const hs=(e,i,n)=>{s(e,os);t(e,o(i,n))};const rs=(s,t,e)=>hs(t,e,n(s));const ls=(s,t,e)=>{try{c(t,n(s),e)}catch(s){console.error("Caught error while handling a Yjs update",s)}};const ds=(e,i)=>{s(e,cs);t(e,i)};const us=ls;const fs=(s,t,e,n)=>{const o=i(s);switch(o){case ns:rs(s,t,e);break;case os:ls(s,e,n);break;case cs:us(s,e,n);break;default:throw new Error("Unknown message type")}return o};const ps=0;const ms=(s,t,e)=>{switch(i(s)){case ps:e(t,k(s))}};const ys=3e4;class Ss extends b{constructor(s){super();this.doc=s;this.clientID=s.clientID;this.states=new Map;this.meta=new Map;this._checkInterval=setInterval((()=>{const s=g();if(this.getLocalState()!==null&&ys/2<=s-this.meta.get(this.clientID).lastUpdated){this.setLocalState(this.getLocalState())}const t=[];this.meta.forEach(((e,i)=>{if(i!==this.clientID&&ys<=s-e.lastUpdated&&this.states.has(i)){t.push(i)}}));if(t.length>0){ws(this,t,"timeout")}}),v(ys/10));s.on("destroy",(()=>{this.destroy()}));this.setLocalState({})}destroy(){this.emit("destroy",[this]);this.setLocalState(null);super.destroy();clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(s){const t=this.clientID;const e=this.meta.get(t);const i=e===undefined?0:e.clock+1;const n=this.states.get(t);if(s===null){this.states.delete(t)}else{this.states.set(t,s)}this.meta.set(t,{clock:i,lastUpdated:g()});const o=[];const c=[];const a=[];const h=[];if(s===null){h.push(t)}else if(n==null){if(s!=null){o.push(t)}}else{c.push(t);if(!z(n,s)){a.push(t)}}if(o.length>0||a.length>0||h.length>0){this.emit("change",[{added:o,updated:a,removed:h},"local"])}this.emit("update",[{added:o,updated:c,removed:h},"local"])}setLocalStateField(s,t){const e=this.getLocalState();if(e!==null){this.setLocalState({...e,[s]:t})}}getStates(){return this.states}}const ws=(s,t,e)=>{const i=[];for(let e=0;e<t.length;e++){const n=t[e];if(s.states.has(n)){s.states.delete(n);if(n===s.clientID){const t=s.meta.get(n);s.meta.set(n,{clock:t.clock+1,lastUpdated:g()})}i.push(n)}}if(i.length>0){s.emit("change",[{added:[],updated:[],removed:i},e]);s.emit("update",[{added:[],updated:[],removed:i},e])}};const ks=(t,i,n=t.states)=>{const o=i.length;const c=h();s(c,o);for(let e=0;e<o;e++){const o=i[e];const a=n.get(o)||null;const h=t.meta.get(o).clock;s(c,o);s(c,h);$(c,JSON.stringify(a))}return e(c)};const bs=(s,t,e)=>{const n=r(t);const o=g();const c=[];const a=[];const h=[];const l=[];const d=i(n);for(let t=0;t<d;t++){const t=i(n);let e=i(n);const r=JSON.parse(k(n));const d=s.meta.get(t);const u=s.states.get(t);const f=d===undefined?0:d.clock;if(f<e||f===e&&r===null&&s.states.has(t)){if(r===null){if(t===s.clientID&&s.getLocalState()!=null){e++}else{s.states.delete(t)}}else{s.states.set(t,r)}s.meta.set(t,{clock:e,lastUpdated:o});if(d===undefined&&r!==null){c.push(t)}else if(d!==undefined&&r===null){l.push(t)}else if(r!==null){if(!z(r,u)){h.push(t)}a.push(t)}}}if(c.length>0||h.length>0||l.length>0){s.emit("change",[{added:c,updated:h,removed:l},e])}if(c.length>0||a.length>0||l.length>0){s.emit("update",[{added:c,updated:a,removed:l},e])}};const Ts=s=>C(s,((s,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(s)}`)).join("&");const vs=0;const gs=3;const zs=1;const Ws=2;const Is=[];Is[vs]=(t,e,i,n,o)=>{s(t,vs);const c=fs(e,t,i.doc,i);if(n&&c===os&&!i.synced){i.synced=true}};Is[gs]=(e,i,n,o,c)=>{s(e,zs);t(e,ks(n.awareness,Array.from(n.awareness.getStates().keys())))};Is[zs]=(s,t,e,i,o)=>{bs(e.awareness,n(t),e)};Is[Ws]=(s,t,e,i,n)=>{ms(t,e.doc,((s,t)=>Cs(e,t)))};const $s=3e4;const Cs=(s,t)=>console.warn(`Permission denied to access ${s.url}.\n${t}`);const Us=(s,t,e)=>{const n=r(t);const o=h();const c=i(n);const a=s.messageHandlers[c];if(a){a(o,n,s,e,c)}else{console.error("Unable to compute message")}return o};const xs=(s,t,e)=>{if(t===s.ws){s.emit("connection-close",[e,s]);s.ws=null;t.close();s.wsconnecting=false;if(s.wsconnected){s.wsconnected=false;s.synced=false;ws(s.awareness,Array.from(s.awareness.getStates().keys()).filter((t=>t!==s.doc.clientID)),s);s.emit("status",[{status:"disconnected"}])}else{s.wsUnsuccessfulReconnects++}setTimeout(Ks,A(D(2,s.wsUnsuccessfulReconnects)*100,s.maxBackoffTime),s)}};const Ks=i=>{if(i.shouldConnect&&i.ws===null){const n=new i._WS(i.url,i.protocols);n.binaryType="arraybuffer";i.ws=n;i.wsconnecting=true;i.wsconnected=false;i.synced=false;n.onmessage=s=>{i.wsLastMessageReceived=g();const t=Us(i,new Uint8Array(s.data),true);if(B(t)>1){n.send(e(t))}};n.onerror=s=>{i.emit("connection-error",[s,i])};n.onclose=s=>{xs(i,n,s)};n.onopen=()=>{i.wsLastMessageReceived=g();i.wsconnecting=false;i.wsconnected=true;i.wsUnsuccessfulReconnects=0;i.emit("status",[{status:"connected"}]);const o=h();s(o,vs);as(o,i.doc);n.send(e(o));if(i.awareness.getLocalState()!==null){const o=h();s(o,zs);t(o,ks(i.awareness,[i.doc.clientID]));n.send(e(o))}};i.emit("status",[{status:"connecting"}])}};const Ps=(s,t)=>{const e=s.ws;if(s.wsconnected&&e&&e.readyState===e.OPEN){e.send(t)}if(s.bcconnected){is(s.bcChannel,t,s)}};class Bs extends x{constructor(i,n,o,{connect:c=true,awareness:a=new Ss(o),params:r={},protocols:l=[],WebSocketPolyfill:d=WebSocket,resyncInterval:u=-1,maxBackoffTime:f=2500,disableBc:p=false}={}){super();while(i[i.length-1]==="/"){i=i.slice(0,i.length-1)}this.serverUrl=i;this.bcChannel=i+"/"+n;this.maxBackoffTime=f;this.params=r;this.protocols=l;this.roomname=n;this.doc=o;this._WS=d;this.awareness=a;this.wsconnected=false;this.wsconnecting=false;this.bcconnected=false;this.disableBc=p;this.wsUnsuccessfulReconnects=0;this.messageHandlers=Is.slice();this._synced=false;this.ws=null;this.wsLastMessageReceived=0;this.shouldConnect=c;this._resyncInterval=0;if(u>0){this._resyncInterval=setInterval((()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const t=h();s(t,vs);as(t,o);this.ws.send(e(t))}}),u)}this._bcSubscriber=(s,t)=>{if(t!==this){const t=Us(this,new Uint8Array(s),false);if(B(t)>1){is(this.bcChannel,e(t),this)}}};this._updateHandler=(t,i)=>{if(i!==this){const i=h();s(i,vs);ds(i,t);Ps(this,e(i))}};this.doc.on("update",this._updateHandler);this._awarenessUpdateHandler=({added:i,updated:n,removed:o},c)=>{const r=i.concat(n).concat(o);const l=h();s(l,zs);t(l,ks(a,r));Ps(this,e(l))};this._exitHandler=()=>{ws(this.awareness,[o.clientID],"app closed")};if(H&&typeof process!=="undefined"){process.on("exit",this._exitHandler)}a.on("update",this._awarenessUpdateHandler);this._checkInterval=setInterval((()=>{if(this.wsconnected&&$s<g()-this.wsLastMessageReceived){xs(this,this.ws,null)}}),$s/10);if(c){this.connect()}}get url(){const s=Ts(this.params);return this.serverUrl+"/"+this.roomname+(s.length===0?"":"?"+s)}get synced(){return this._synced}set synced(s){if(this._synced!==s){this._synced=s;this.emit("synced",[s]);this.emit("sync",[s])}}destroy(){if(this._resyncInterval!==0){clearInterval(this._resyncInterval)}clearInterval(this._checkInterval);this.disconnect();if(H&&typeof process!=="undefined"){process.off("exit",this._exitHandler)}this.awareness.off("update",this._awarenessUpdateHandler);this.doc.off("update",this._updateHandler);super.destroy()}connectBc(){if(this.disableBc){return}if(!this.bcconnected){ts(this.bcChannel,this._bcSubscriber);this.bcconnected=true}const i=h();s(i,vs);as(i,this.doc);is(this.bcChannel,e(i),this);const n=h();s(n,vs);hs(n,this.doc);is(this.bcChannel,e(n),this);const o=h();s(o,gs);is(this.bcChannel,e(o),this);const c=h();s(c,zs);t(c,ks(this.awareness,[this.doc.clientID]));is(this.bcChannel,e(c),this)}disconnectBc(){const i=h();s(i,zs);t(i,ks(this.awareness,[this.doc.clientID],new Map));Ps(this,e(i));if(this.bcconnected){es(this.bcChannel,this._bcSubscriber);this.bcconnected=false}}disconnect(){this.shouldConnect=false;this.disconnectBc();if(this.ws!==null){xs(this,this.ws,null)}}connect(){this.shouldConnect=true;if(!this.wsconnected&&this.ws===null){Ks(this);this.connectBc()}}}class Hs{provider;isConnected=false;constructor(s,t,e){const i=e?.url||"ws://localhost:1234";const n=e?.roomName||s;this.provider=new Bs(i,n,t,{params:e?.params,protocols:e?.protocols,WebSocketPolyfill:e?.WebSocketPolyfill,awareness:e?.awareness,maxBackoffTime:e?.maxBackoffTime,disableBc:true});this.setupEventListeners();console.info(`WebSocket Provider initialized: ${i}/${n}`)}static with(s){return{create:(t,e)=>new Hs(t,e,s)}}setupEventListeners(){this.provider.on("status",(({status:s})=>{if(s==="connected"){this.isConnected=true;console.info("WebSocket connected")}else if(s==="disconnected"){this.isConnected=false;console.info("WebSocket disconnected")}}));this.provider.on("sync",(s=>{if(s){console.info("WebSocket synced")}}))}async connect(){if(this.isConnected){return}return new Promise(((s,t)=>{const e=setTimeout((()=>{t(new Error("WebSocket connection timeout"))}),1e4);const i=({status:t})=>{if(t==="connected"){clearTimeout(e);this.provider.off("status",i);this.isConnected=true;s()}};this.provider.on("status",i);if(this.provider.wsconnected){clearTimeout(e);this.provider.off("status",i);this.isConnected=true;s()}}))}disconnect(){if(this.provider){this.provider.disconnect()}this.isConnected=false}destroy(){if(this.provider){this.provider.destroy()}this.isConnected=false}}class Ls{provider;isConnected=false;isSynced=false;usesSharedSocket=false;static sharedWebSocketProvider=null;constructor(s,t,e){const i=e?.name||s;const n=e?.url||"ws://localhost:1234";const o=e?.websocketProvider||Ls.sharedWebSocketProvider;if(o){this.usesSharedSocket=true;const s={websocketProvider:o,name:i,document:t,token:e?.token||null,onConnect:()=>{this.isConnected=true;if(!e?.quiet){console.info(`Hocuspocus connected: ${i}`)}if(e?.onConnect){e.onConnect()}},onDisconnect:()=>{this.isConnected=false;this.isSynced=false;if(!e?.quiet){console.info(`Hocuspocus disconnected: ${i}`)}if(e?.onDisconnect){e.onDisconnect()}},onSynced:()=>{this.isSynced=true;if(!e?.quiet){console.info(`Hocuspocus synced: ${i}`)}if(e?.onSynced){e.onSynced()}}};if(e?.forceSyncInterval!==undefined){s.forceSyncInterval=e.forceSyncInterval}if(e?.onAuthenticationFailed){s.onAuthenticationFailed=e.onAuthenticationFailed}if(e?.onStatus){s.onStatus=e.onStatus}this.provider=new O(s);this.provider.attach();if(!e?.quiet){console.info(`Hocuspocus Provider initialized (multiplexed): ${i}`)}}else{this.usesSharedSocket=false;const s={url:n,name:i,document:t,token:e?.token||null,onConnect:()=>{this.isConnected=true;if(!e?.quiet){console.info(`Hocuspocus connected: ${i}`)}if(e?.onConnect){e.onConnect()}},onDisconnect:()=>{this.isConnected=false;this.isSynced=false;if(!e?.quiet){console.info(`Hocuspocus disconnected: ${i}`)}if(e?.onDisconnect){e.onDisconnect()}},onSynced:()=>{this.isSynced=true;if(!e?.quiet){console.info(`Hocuspocus synced: ${i}`)}if(e?.onSynced){e.onSynced()}}};if(e?.forceSyncInterval!==undefined){s.forceSyncInterval=e.forceSyncInterval}if(e?.onAuthenticationFailed){s.onAuthenticationFailed=e.onAuthenticationFailed}if(e?.onStatus){s.onStatus=e.onStatus}if(e?.WebSocketPolyfill){s.WebSocketPolyfill=e.WebSocketPolyfill}this.provider=new O(s);if(!e?.quiet){console.info(`Hocuspocus Provider initialized: ${n}/${i}`)}}}static createSharedWebSocket(s){if(Ls.sharedWebSocketProvider){console.warn("Shared WebSocket already exists. Returning existing instance.");return Ls.sharedWebSocketProvider}const t={url:s.url};if(s.WebSocketPolyfill){t.WebSocketPolyfill=s.WebSocketPolyfill}if(s.onConnect){t.onConnect=s.onConnect}if(s.onDisconnect){t.onDisconnect=s.onDisconnect}if(s.onStatus){t.onStatus=s.onStatus}Ls.sharedWebSocketProvider=new _(t);console.info(`Shared Hocuspocus WebSocket created: ${s.url}`);return Ls.sharedWebSocketProvider}static destroySharedWebSocket(){if(Ls.sharedWebSocketProvider){Ls.sharedWebSocketProvider.destroy();Ls.sharedWebSocketProvider=null;console.info("Shared Hocuspocus WebSocket destroyed")}}static getSharedWebSocket(){return Ls.sharedWebSocketProvider}static with(s){return{create:(t,e)=>new Ls(t,e,s)}}async connect(){if(this.isSynced){return}return new Promise(((s,t)=>{const e=setTimeout((()=>{t(new Error("Hocuspocus connection timeout"))}),1e4);const i=()=>{clearTimeout(e);this.provider.off("synced",i);s()};this.provider.on("synced",i);if(this.provider.isSynced){clearTimeout(e);this.provider.off("synced",i);s();return}if(!this.isConnected&&!this.usesSharedSocket){this.provider.connect()}}))}disconnect(){if(this.provider){if(this.usesSharedSocket){this.provider.detach()}else{this.provider.disconnect()}}this.isConnected=false;this.isSynced=false}destroy(){if(this.provider){this.provider.destroy()}this.isConnected=false;this.isSynced=false}}export{j as BroadcastSyncProvider,Ls as HocuspocusSyncProvider,Hs as WebSocketSyncProvider};
|
|
2
2
|
//# sourceMappingURL=index.esm.js.map
|