kritzel-stencil 0.3.27 → 0.3.29
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/index.cjs.js +1 -1
- package/dist/cjs/kritzel-active-users_45.cjs.entry.js +8 -2
- package/dist/cjs/{schema.constants-9v4Edzoe.js → schema.constants-TiseVL4a.js} +14 -1
- package/dist/collection/classes/objects/selection-group.class.js +14 -1
- package/dist/collection/classes/structures/object-map.structure.js +6 -0
- package/dist/collection/constants/version.js +1 -1
- package/dist/components/index.js +1 -1
- package/dist/components/kritzel-controls.js +1 -1
- package/dist/components/kritzel-editor.js +1 -1
- package/dist/components/kritzel-engine.js +1 -1
- package/dist/components/kritzel-settings.js +1 -1
- package/dist/components/kritzel-tool-config.js +1 -1
- package/dist/components/{p-G3xSPZ0x.js → p-B0g_ls7F.js} +1 -1
- package/dist/components/{p-DXYkgNAO.js → p-BC7jWR_G.js} +1 -1
- package/dist/components/{p-ioK7ttPL.js → p-BqR6dXX-.js} +2 -2
- package/dist/components/{p-BmKYyPpl.js → p-CPnjRgkl.js} +1 -1
- package/dist/components/{p-CRKezkZU.js → p-pCB0JKlD.js} +1 -1
- package/dist/esm/index.js +2 -2
- package/dist/esm/kritzel-active-users_45.entry.js +8 -2
- package/dist/esm/{schema.constants-BT66X_r5.js → schema.constants-7ayQfjzt.js} +14 -1
- package/dist/stencil/index.esm.js +1 -1
- package/dist/stencil/{p-BT66X_r5.js → p-7ayQfjzt.js} +1 -1
- package/dist/stencil/p-d6a79b4c.entry.js +9 -0
- package/dist/stencil/stencil.esm.js +1 -1
- package/dist/types/classes/objects/selection-group.class.d.ts +1 -0
- package/dist/types/constants/version.d.ts +1 -1
- package/package.json +1 -1
- package/dist/stencil/p-9ca04088.entry.js +0 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
import{p as e,H as t,c as s,h as i,d as o,t as r}from"./p-B43upypT.js";import{f as n,e as l}from"./p-
|
|
1
|
+
import{p as e,H as t,c as s,h as i,d as o,t as r}from"./p-B43upypT.js";import{f as n,e as l}from"./p-CPnjRgkl.js";import{a}from"./p-CpzicliK.js";import{d as h}from"./p-C4-Som48.js";import{d as p}from"./p-CO0eEzos.js";import{d as c}from"./p-Df3BwVGy.js";import{d}from"./p-BX-nQAyH.js";import{d as m}from"./p-JhOYwUOj.js";import{d as f}from"./p-Cb5YwXbC.js";import{d as u}from"./p-CdR76C4L.js";import{d as g}from"./p-CXpv9Rxe.js";import{d as z}from"./p-CdkNxxut.js";import{d as y}from"./p-BFYtCsZu.js";import{d as k}from"./p-C1jg5IQi.js";class C{static getToolConfig(e){switch(e?.toolType){case"selection":return"getToolConfig"in e&&"function"==typeof e.getToolConfig?e.getToolConfig():null;case"brush":return{type:"brush",colorProperty:"color",sizeProperty:"size",opacityProperty:"opacity",paletteSource:"palette",sizesSource:"sizes",controls:[{type:"stroke-size",propertyName:"size"}]};case"line":return{type:"line",colorProperty:"color",sizeProperty:"size",opacityProperty:"opacity",paletteSource:"palette",sizesSource:"sizes",controls:[{type:"stroke-size",propertyName:"size"},{type:"line-endings",propertyName:"arrows",additionalProps:{}}]};case"shape":return{type:"shape",colorProperty:"strokeColor",sizeProperty:"strokeWidth",opacityProperty:"opacity",paletteSource:"palette",sizesSource:"sizes",controls:[{type:"stroke-size",propertyName:"strokeWidth"},{type:"shape-fill",propertyName:"fillColor",additionalProps:{}}]};case"text":return{type:"text",colorProperty:"fontColor",sizeProperty:"fontSize",opacityProperty:"opacity",paletteSource:"palette",sizesSource:"sizes",controls:[{type:"font-size",propertyName:"fontSize",additionalProps:{}},{type:"font-family",propertyName:"fontFamily"}]};default:return null}}}const x=e(class extends t{constructor(e){super(),!1!==e&&this.__registerHost(),this.__attachShadow(),this.toolChange=s(this,"toolChange"),this.displayValuesChange=s(this,"displayValuesChange")}tool;handleToolChange(e,t){const s=C.getToolConfig(e);if(t&&e&&"shape"===s?.type){const i=C.getToolConfig(t);"shape"===i?.type&&[s.colorProperty,s.sizeProperty,s.opacityProperty,"fillColor"].forEach((s=>{s&&void 0!==t[s]&&(e[s]=t[s])}))}this.config=s,this.config&&(this.updatePalette(),this.updateSizes(),this.currentOpacity=e[this.config.opacityProperty]??1,this.emitDisplayValues())}isExpanded=!1;theme;engine;terms={};handleSelectionChangeBound=this.handleSelectionChange.bind(this);onThemeChange(){this.emitDisplayValues()}handleEngineChange(e,t){t&&t.removeEventListener("objectsSelectionChange",this.handleSelectionChangeBound),e&&e.addEventListener("objectsSelectionChange",this.handleSelectionChangeBound)}toolChange;displayValuesChange;config;palette=[];sizes=[];currentOpacity=1;updateTrigger=0;handleSelectionChange(){this.tool instanceof n&&(this.config=C.getToolConfig(this.tool),this.config&&(this.updatePalette(),this.updateSizes(),this.currentOpacity=this.tool[this.config.opacityProperty]??1,this.emitDisplayValues()))}disconnectedCallback(){this.engine&&this.engine.removeEventListener("objectsSelectionChange",this.handleSelectionChangeBound)}componentWillLoad(){this.config=C.getToolConfig(this.tool),this.config&&(this.updatePalette(),this.updateSizes(),this.currentOpacity=this.tool[this.config.opacityProperty]??1,this.emitDisplayValues()),this.engine&&this.engine.addEventListener("objectsSelectionChange",this.handleSelectionChangeBound)}emitDisplayValues(){if(!this.config)return;const e=this.tool[this.config.sizeProperty],t={color:a.applyOpacity(this.tool[this.config.colorProperty],this.currentOpacity,this.theme),size:e};this.tool instanceof l&&(t.fontFamily=this.tool.fontFamily),this.displayValuesChange.emit(t)}updatePalette(){this.config&&(this.palette="none"===this.config.paletteSource?[]:this.tool.palette||[])}updateSizes(){this.config&&(this.sizes="none"===this.config.sizesSource?[]:this.tool.sizes||[])}handleToggleExpand=()=>{this.isExpanded=!this.isExpanded};handleColorChange=e=>{if(this.tool[this.config.colorProperty]=e.detail,"shape"===this.config.type||"selection"===this.config.type){const t=this.tool;("string"==typeof t.fillColor?"transparent"===t.fillColor:"transparent"===t.fillColor.light&&"transparent"===t.fillColor.dark)||(t.fillColor=e.detail)}this.emitDisplayValues(),this.toolChange.emit(this.tool),this.updateTrigger++};handleSizeChange=e=>{this.tool[this.config.sizeProperty]=e.detail,this.emitDisplayValues(),this.toolChange.emit(this.tool),this.updateTrigger++};handleOpacityChange=e=>{this.tool[this.config.opacityProperty]=e.detail,this.currentOpacity=e.detail,this.emitDisplayValues(),this.toolChange.emit(this.tool)};handlePropertyChange=(e,t)=>{if("shape"!==this.config.type&&"selection"!==this.config.type||"fillColor"!==e)this.tool[e]=t,"fontFamily"===e&&this.emitDisplayValues();else{const e="filled"===t?this.tool[this.config.colorProperty]:{light:"transparent",dark:"transparent"};this.tool.fillColor=e,"filled"===t&&(this.tool[this.config.colorProperty]=e)}this.toolChange.emit(this.tool),this.updateTrigger++};getShapeFillValue(){const e=this.tool.fillColor;return("string"==typeof e?"transparent"===e:"transparent"===e.light&&"transparent"===e.dark)?"transparent":"filled"}renderControl(e){const t=this.tool[e.propertyName];switch(e.type){case"stroke-size":return i("kritzel-stroke-size",{key:e.type,sizes:this.sizes,selectedSize:t,onSizeChange:this.handleSizeChange});case"font-size":return i("kritzel-font-size",{key:e.type,sizes:this.sizes,selectedSize:t,fontFamily:this.tool.fontFamily,onSizeChange:this.handleSizeChange});case"line-endings":return i("kritzel-line-endings",{key:e.type,value:t,onValueChange:t=>this.handlePropertyChange(e.propertyName,t.detail)});case"shape-fill":return i("kritzel-shape-fill",{key:e.type,value:this.getShapeFillValue(),onValueChange:t=>this.handlePropertyChange(e.propertyName,t.detail)});case"font-family":return i("kritzel-font-family",{key:e.type,selectedFontFamily:t,onFontFamilyChange:t=>this.handlePropertyChange(e.propertyName,t.detail)});default:return null}}render(){if(!this.config)return null;const e=this.palette.length>6||"text"===this.config.type,t=this.palette.length>0,s=this.config.controls.find((e=>"stroke-size"===e.type||"font-size"===e.type)),r=this.config.controls.filter((e=>"stroke-size"!==e.type&&"font-size"!==e.type));return i(o,null,i("div",{style:{display:"flex",flexDirection:"row",gap:"8px",width:"100%"}},i("div",{style:{display:"flex",flexDirection:"column",gap:"12px",flex:"1"}},t&&i("kritzel-color-palette",{colors:this.palette,selectedColor:this.tool[this.config.colorProperty],isExpanded:this.isExpanded,isOpaque:!0,opacity:this.currentOpacity,theme:this.theme,onColorChange:this.handleColorChange}),s&&this.renderControl(s),i("kritzel-opacity-slider",{value:this.tool[this.config.opacityProperty],previewColor:this.tool[this.config.colorProperty],onValueChange:this.handleOpacityChange}),r.map((e=>[i("div",{class:"divider"}),this.renderControl(e)]))),e&&i("div",{style:{display:"flex",alignItems:"flex-start"}},i("button",{class:"expand-toggle",onClick:this.handleToggleExpand,title:this.isExpanded?this.terms["toolConfig.collapse"]??"Collapse":this.terms["toolConfig.expand"]??"Expand"},i("kritzel-icon",{name:this.isExpanded?"chevron-up":"chevron-down"})))))}static get watchers(){return{tool:[{handleToolChange:0}],theme:[{onThemeChange:0}],engine:[{handleEngineChange:0}]}}static get style(){return".expand-toggle{background:none;border:none;cursor:var(--kritzel-global-pointer-cursor, pointer);padding:0;margin:0;display:flex;align-items:center;justify-content:center;width:32px;height:32px;color:var(--kritzel-icon-color, currentColor);transition:transform 0.2s ease}.expand-toggle:hover{opacity:0.7}.expand-toggle:focus{outline:none}.expand-toggle:focus-visible{outline:2px solid var(--kritzel-focus-color, #007acc);outline-offset:2px}.expand-toggle:active{transform:scale(0.95)}.divider{height:1px;background-color:var(--kritzel-divider-color, #e0e0e0);margin:4px 0;width:100%}"}},[513,"kritzel-tool-config",{tool:[1040],isExpanded:[1028,"is-expanded"],theme:[1],engine:[16],terms:[16],config:[32],palette:[32],sizes:[32],currentOpacity:[32],updateTrigger:[32]},void 0,{tool:[{handleToolChange:0}],theme:[{onThemeChange:0}],engine:[{handleEngineChange:0}]}]);function b(){"undefined"!=typeof customElements&&["kritzel-tool-config","kritzel-color","kritzel-color-palette","kritzel-dropdown","kritzel-font","kritzel-font-family","kritzel-font-size","kritzel-icon","kritzel-line-endings","kritzel-opacity-slider","kritzel-shape-fill","kritzel-stroke-size"].forEach((e=>{switch(e){case"kritzel-tool-config":customElements.get(r(e))||customElements.define(r(e),x);break;case"kritzel-color":customElements.get(r(e))||h();break;case"kritzel-color-palette":customElements.get(r(e))||p();break;case"kritzel-dropdown":customElements.get(r(e))||c();break;case"kritzel-font":customElements.get(r(e))||d();break;case"kritzel-font-family":customElements.get(r(e))||m();break;case"kritzel-font-size":customElements.get(r(e))||f();break;case"kritzel-icon":customElements.get(r(e))||u();break;case"kritzel-line-endings":customElements.get(r(e))||g();break;case"kritzel-opacity-slider":customElements.get(r(e))||z();break;case"kritzel-shape-fill":customElements.get(r(e))||y();break;case"kritzel-stroke-size":customElements.get(r(e))||k()}}))}export{C as K,x as a,b as d}
|
package/dist/esm/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { H as HocuspocusProvider, a as HocuspocusProviderWebsocket } from './schema.constants-
|
|
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-
|
|
1
|
+
import { H as HocuspocusProvider, a as HocuspocusProviderWebsocket } from './schema.constants-7ayQfjzt.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-7ayQfjzt.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-
|
|
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-7ayQfjzt.js';
|
|
3
3
|
import * as Y from 'yjs';
|
|
4
4
|
import 'y-indexeddb';
|
|
5
5
|
import 'y-websocket';
|
|
@@ -22488,6 +22488,12 @@ class KritzelObjectMap {
|
|
|
22488
22488
|
});
|
|
22489
22489
|
// Delete objects from local map
|
|
22490
22490
|
objectsToDelete.forEach(objectId => {
|
|
22491
|
+
const existingObject = this._idMap.get(objectId);
|
|
22492
|
+
if (existingObject instanceof KritzelSelectionGroup) {
|
|
22493
|
+
// Remote deletion of a selection group must also clear the transient
|
|
22494
|
+
// selection flags it had applied to its children locally.
|
|
22495
|
+
existingObject.deselectAllChildren?.();
|
|
22496
|
+
}
|
|
22491
22497
|
this.quadtree.remove(o => o.id === objectId);
|
|
22492
22498
|
this._idMap.delete(objectId);
|
|
22493
22499
|
});
|
|
@@ -31229,7 +31235,7 @@ const KritzelPortal = class {
|
|
|
31229
31235
|
* This file is auto-generated by the version bump scripts.
|
|
31230
31236
|
* Do not modify manually.
|
|
31231
31237
|
*/
|
|
31232
|
-
const KRITZEL_VERSION = '0.3.
|
|
31238
|
+
const KRITZEL_VERSION = '0.3.29';
|
|
31233
31239
|
|
|
31234
31240
|
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)}`;
|
|
31235
31241
|
|
|
@@ -20734,6 +20734,17 @@ class KritzelSelectionGroup extends KritzelBaseObject {
|
|
|
20734
20734
|
child.isSelected = shouldBeSelected;
|
|
20735
20735
|
}
|
|
20736
20736
|
}
|
|
20737
|
+
shouldSyncChildSelectionState() {
|
|
20738
|
+
const localClientId = this._core.store.objects?.localClientId ?? null;
|
|
20739
|
+
if (localClientId != null && this.clientId != null) {
|
|
20740
|
+
return this.clientId === localClientId;
|
|
20741
|
+
}
|
|
20742
|
+
const localUserId = this._core.user?.id ?? null;
|
|
20743
|
+
if (localUserId != null && this.userId != null) {
|
|
20744
|
+
return this.userId === localUserId;
|
|
20745
|
+
}
|
|
20746
|
+
return this.userId == null;
|
|
20747
|
+
}
|
|
20737
20748
|
/**
|
|
20738
20749
|
* Gets the number of objects in the selection group.
|
|
20739
20750
|
* @returns The count of selected objects
|
|
@@ -20979,7 +20990,9 @@ class KritzelSelectionGroup extends KritzelBaseObject {
|
|
|
20979
20990
|
if (object.unchangedObjectSnapshots) {
|
|
20980
20991
|
this.unchangedObjectSnapshots = new Map(Object.entries(object.unchangedObjectSnapshots));
|
|
20981
20992
|
}
|
|
20982
|
-
this.
|
|
20993
|
+
if (this.shouldSyncChildSelectionState()) {
|
|
20994
|
+
this.syncChildSelectionState(this.objects);
|
|
20995
|
+
}
|
|
20983
20996
|
return this;
|
|
20984
20997
|
}
|
|
20985
20998
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{H as a,a as T}from"./p-BT66X_r5.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-BT66X_r5.js";import*as $ from"yjs";import{IndexeddbPersistence as _}from"y-indexeddb";import{WebsocketProvider as R}from"y-websocket";const U=Math.floor,H=127,X=Number.MAX_SAFE_INTEGER;class V{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Y=()=>new V,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>X)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&<.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-7ayQfjzt.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-7ayQfjzt.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&<.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}
|