kritzel-stencil 0.3.24 → 0.3.25
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 +55 -36
- package/dist/cjs/{schema.constants-D8JoUfNc.js → schema.constants-Np7j2Gz4.js} +13 -2
- package/dist/collection/classes/managers/anchor.manager.js +13 -2
- package/dist/collection/classes/managers/clipboard.manager.js +7 -0
- package/dist/collection/components/core/kritzel-engine/kritzel-engine.js +46 -34
- package/dist/collection/constants/version.js +1 -1
- package/dist/components/index.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/p-6_95PFq4.js +9 -0
- package/dist/components/{p-Bz_zj6dQ.js → p-DF0S4FqL.js} +1 -1
- package/dist/esm/index.js +2 -2
- package/dist/esm/kritzel-active-users_45.entry.js +55 -36
- package/dist/esm/{schema.constants-B3IqnD8l.js → schema.constants-1SDhlkfS.js} +13 -2
- package/dist/stencil/index.esm.js +1 -1
- package/dist/stencil/{p-B3IqnD8l.js → p-1SDhlkfS.js} +1 -1
- package/dist/stencil/{p-63bc234f.entry.js → p-7ba7df62.entry.js} +2 -2
- package/dist/stencil/stencil.esm.js +1 -1
- package/dist/types/classes/managers/anchor.manager.d.ts +4 -1
- package/dist/types/constants/version.d.ts +1 -1
- package/package.json +1 -1
- package/dist/components/p-on11Z8cZ.js +0 -9
package/dist/cjs/index.cjs.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var index = require('./index-Xav9JFHg.js');
|
|
4
|
-
var schema_constants = require('./schema.constants-
|
|
4
|
+
var schema_constants = require('./schema.constants-Np7j2Gz4.js');
|
|
5
5
|
var Y = require('yjs');
|
|
6
6
|
require('y-indexeddb');
|
|
7
7
|
require('y-websocket');
|
|
@@ -24157,6 +24157,7 @@ class KritzelClipboardManager {
|
|
|
24157
24157
|
*/
|
|
24158
24158
|
regenerateIdsAndRemapAnchors(topLevel) {
|
|
24159
24159
|
const all = [];
|
|
24160
|
+
const hasOnlyTopLevelLines = topLevel.length > 0 && topLevel.every(object => schema_constants.KritzelClassHelper.isInstanceOf(object, 'KritzelLine'));
|
|
24160
24161
|
const collect = (objects) => {
|
|
24161
24162
|
for (const object of objects) {
|
|
24162
24163
|
all.push(object);
|
|
@@ -24181,9 +24182,15 @@ class KritzelClipboardManager {
|
|
|
24181
24182
|
if (object.startAnchor && idMap.has(object.startAnchor.objectId)) {
|
|
24182
24183
|
object.startAnchor = { objectId: idMap.get(object.startAnchor.objectId) };
|
|
24183
24184
|
}
|
|
24185
|
+
else if (hasOnlyTopLevelLines) {
|
|
24186
|
+
object.startAnchor = undefined;
|
|
24187
|
+
}
|
|
24184
24188
|
if (object.endAnchor && idMap.has(object.endAnchor.objectId)) {
|
|
24185
24189
|
object.endAnchor = { objectId: idMap.get(object.endAnchor.objectId) };
|
|
24186
24190
|
}
|
|
24191
|
+
else if (hasOnlyTopLevelLines) {
|
|
24192
|
+
object.endAnchor = undefined;
|
|
24193
|
+
}
|
|
24187
24194
|
}
|
|
24188
24195
|
}
|
|
24189
24196
|
}
|
|
@@ -29412,7 +29419,11 @@ const KritzelEngine = class {
|
|
|
29412
29419
|
transform: object?.transformationMatrix,
|
|
29413
29420
|
transformOrigin: 'top left',
|
|
29414
29421
|
position: 'absolute',
|
|
29415
|
-
|
|
29422
|
+
// The object wrapper establishes its own stacking context (transform + z-index),
|
|
29423
|
+
// so the selection-line handles inside it cannot escape above the snap/anchor
|
|
29424
|
+
// layers (z-index 9999/9998) rendered later at the origin level. Lift the
|
|
29425
|
+
// selected line's wrapper above those layers so its handles always paint on top.
|
|
29426
|
+
zIndex: this.core.displaySelectionLineUI(object) ? '10001' : object.zIndex.toString(),
|
|
29416
29427
|
pointerEvents: getObjectWrapperPointerEvents(object),
|
|
29417
29428
|
} }, schema_constants.KritzelClassHelper.isInstanceOf(object, 'KritzelPath') && (index.h("svg", { ref: el => el && object.mount(el), xmlns: "http://www.w3.org/2000/svg", style: {
|
|
29418
29429
|
height: object?.totalHeight + 'px',
|
|
@@ -29616,10 +29627,19 @@ const KritzelEngine = class {
|
|
|
29616
29627
|
}
|
|
29617
29628
|
const selectionBorderColor = remoteUserColor ?? (schema_constants.KritzelColorHelper.resolveThemeColor(object.borderColor, currentTheme) || 'var(--kritzel-selection-border-color, #007AFF)');
|
|
29618
29629
|
const selectionHandleStrokeColor = remoteUserColor ?? 'var(--kritzel-selection-handle-stroke-color, #007AFF)';
|
|
29630
|
+
const lineObject = object;
|
|
29631
|
+
const activeSnapCandidate = this.core.store.state.snapCandidate;
|
|
29632
|
+
const isStartHandleSnapped = lineObject.startAnchor != null;
|
|
29633
|
+
const isEndHandleSnapped = lineObject.endAnchor != null;
|
|
29634
|
+
const isStartHandleSnapPreview = activeSnapCandidate?.endpoint === 'start';
|
|
29635
|
+
const isEndHandleSnapPreview = activeSnapCandidate?.endpoint === 'end';
|
|
29636
|
+
const isStartHandleHighlighted = isStartHandleSnapped || isStartHandleSnapPreview;
|
|
29637
|
+
const isEndHandleHighlighted = isEndHandleSnapped || isEndHandleSnapPreview;
|
|
29638
|
+
const selectionOverlayZIndex = this.core.displaySelectionLineUI(object) ? '10000' : (object.zIndex + 1).toString();
|
|
29619
29639
|
const handleScale = object.scale ?? 1;
|
|
29620
29640
|
const { canRenderResizeHandles, canRenderRotationHandle } = this.getSelectionHandleCapabilities(object);
|
|
29621
29641
|
return (index.h("svg", { xmlns: "http://www.w3.org/2000/svg", style: {
|
|
29622
|
-
zIndex:
|
|
29642
|
+
zIndex: selectionOverlayZIndex,
|
|
29623
29643
|
height: object?.totalHeight.toString(),
|
|
29624
29644
|
width: object?.totalWidth.toString(),
|
|
29625
29645
|
left: '0',
|
|
@@ -29710,7 +29730,7 @@ const KritzelEngine = class {
|
|
|
29710
29730
|
strokeLinecap: 'round',
|
|
29711
29731
|
fill: 'none',
|
|
29712
29732
|
} })), !this.isSelecting && !isRemoteSelection && (index.h("g", { class: "selection-line-handles", style: { pointerEvents: 'auto' } }, index.h("circle", { class: "selection-line-handle start", cx: object.startX - object.x, cy: object.startY - object.y, r: `${((baseHandleSize - 1) * object.scale) / this.core.store.state?.scale}`, style: {
|
|
29713
|
-
fill: 'var(--kritzel-selection-handle-color, #000000)',
|
|
29733
|
+
fill: isStartHandleHighlighted ? selectionHandleStrokeColor : 'var(--kritzel-selection-handle-color, #000000)',
|
|
29714
29734
|
stroke: selectionHandleStrokeColor,
|
|
29715
29735
|
strokeWidth: `calc(2px * ${object.scale} / ${this.core.store.state?.scale})`,
|
|
29716
29736
|
paintOrder: 'fill',
|
|
@@ -29734,7 +29754,7 @@ const KritzelEngine = class {
|
|
|
29734
29754
|
fill: 'transparent',
|
|
29735
29755
|
paintOrder: 'fill',
|
|
29736
29756
|
} }), index.h("circle", { class: "selection-line-handle end", cx: object.endX - object.x, cy: object.endY - object.y, r: `${((baseHandleSize - 1) * object.scale) / this.core.store.state?.scale}`, style: {
|
|
29737
|
-
fill: 'var(--kritzel-selection-handle-color, #000000)',
|
|
29757
|
+
fill: isEndHandleHighlighted ? selectionHandleStrokeColor : 'var(--kritzel-selection-handle-color, #000000)',
|
|
29738
29758
|
stroke: selectionHandleStrokeColor,
|
|
29739
29759
|
strokeWidth: `calc(2px * ${object.scale} / ${this.core.store.state?.scale})`,
|
|
29740
29760
|
paintOrder: 'fill',
|
|
@@ -29744,6 +29764,34 @@ const KritzelEngine = class {
|
|
|
29744
29764
|
} })))))));
|
|
29745
29765
|
})()));
|
|
29746
29766
|
}), (() => {
|
|
29767
|
+
const data = this.core.anchorManager.getSnapIndicatorRenderData();
|
|
29768
|
+
if (!data)
|
|
29769
|
+
return null;
|
|
29770
|
+
return (index.h("svg", { xmlns: "http://www.w3.org/2000/svg", class: "snap-indicator", style: {
|
|
29771
|
+
position: 'absolute',
|
|
29772
|
+
left: '0',
|
|
29773
|
+
top: '0',
|
|
29774
|
+
width: '1px',
|
|
29775
|
+
height: '1px',
|
|
29776
|
+
pointerEvents: 'none',
|
|
29777
|
+
zIndex: '9999',
|
|
29778
|
+
overflow: 'visible',
|
|
29779
|
+
} }, index.h("g", null, data.snapLinePath ? (index.h("path", { d: data.snapLinePath, fill: "none", style: {
|
|
29780
|
+
stroke: 'var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))',
|
|
29781
|
+
strokeWidth: data.lineStrokeWidth,
|
|
29782
|
+
strokeDasharray: data.dashArray,
|
|
29783
|
+
strokeLinecap: 'round',
|
|
29784
|
+
} })) : (data.edgeX !== undefined &&
|
|
29785
|
+
data.edgeY !== undefined && (index.h("line", { x1: data.edgeX, y1: data.edgeY, x2: data.centerX, y2: data.centerY, style: {
|
|
29786
|
+
stroke: 'var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))',
|
|
29787
|
+
strokeWidth: data.lineStrokeWidth,
|
|
29788
|
+
strokeDasharray: data.dashArray,
|
|
29789
|
+
strokeLinecap: 'round',
|
|
29790
|
+
} }))), index.h("circle", { cx: data.centerX, cy: data.centerY, r: data.indicatorRadius, style: {
|
|
29791
|
+
fill: 'var(--kritzel-snap-indicator-fill, rgba(59, 130, 246, 0.3))',
|
|
29792
|
+
strokeWidth: data.indicatorStrokeWidth,
|
|
29793
|
+
} }))));
|
|
29794
|
+
})(), (() => {
|
|
29747
29795
|
const data = this.core.anchorManager.getAnchorLinesRenderData();
|
|
29748
29796
|
if (!data)
|
|
29749
29797
|
return null;
|
|
@@ -29768,7 +29816,7 @@ const KritzelEngine = class {
|
|
|
29768
29816
|
strokeDasharray: data.dashArray,
|
|
29769
29817
|
strokeLinecap: 'round',
|
|
29770
29818
|
} })), index.h("circle", { cx: data.startAnchorViz.centerX, cy: data.startAnchorViz.centerY, r: data.indicatorRadius, style: {
|
|
29771
|
-
fill: 'var(--kritzel-snap-indicator-fill, rgba(
|
|
29819
|
+
fill: 'var(--kritzel-snap-indicator-fill, rgba(59, 130, 246, 0.3))',
|
|
29772
29820
|
stroke: 'var(--kritzel-snap-indicator-stroke, #007bff)',
|
|
29773
29821
|
strokeWidth: data.indicatorStrokeWidth,
|
|
29774
29822
|
} }))), data.endAnchorViz && (index.h("g", { class: "anchor-line-end" }, data.endAnchorViz.pathD ? (index.h("path", { d: data.endAnchorViz.pathD, style: {
|
|
@@ -29787,35 +29835,6 @@ const KritzelEngine = class {
|
|
|
29787
29835
|
stroke: 'var(--kritzel-snap-indicator-stroke, #007bff)',
|
|
29788
29836
|
strokeWidth: data.indicatorStrokeWidth,
|
|
29789
29837
|
} })))));
|
|
29790
|
-
})(), (() => {
|
|
29791
|
-
const data = this.core.anchorManager.getSnapIndicatorRenderData();
|
|
29792
|
-
if (!data)
|
|
29793
|
-
return null;
|
|
29794
|
-
return (index.h("svg", { xmlns: "http://www.w3.org/2000/svg", class: "snap-indicator", style: {
|
|
29795
|
-
position: 'absolute',
|
|
29796
|
-
left: '0',
|
|
29797
|
-
top: '0',
|
|
29798
|
-
width: '1px',
|
|
29799
|
-
height: '1px',
|
|
29800
|
-
pointerEvents: 'none',
|
|
29801
|
-
zIndex: '9999',
|
|
29802
|
-
overflow: 'visible',
|
|
29803
|
-
} }, index.h("g", null, data.snapLinePath ? (index.h("path", { d: data.snapLinePath, fill: "none", style: {
|
|
29804
|
-
stroke: 'var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))',
|
|
29805
|
-
strokeWidth: data.lineStrokeWidth,
|
|
29806
|
-
strokeDasharray: data.dashArray,
|
|
29807
|
-
strokeLinecap: 'round',
|
|
29808
|
-
} })) : (data.edgeX !== undefined &&
|
|
29809
|
-
data.edgeY !== undefined && (index.h("line", { x1: data.edgeX, y1: data.edgeY, x2: data.centerX, y2: data.centerY, style: {
|
|
29810
|
-
stroke: 'var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))',
|
|
29811
|
-
strokeWidth: data.lineStrokeWidth,
|
|
29812
|
-
strokeDasharray: data.dashArray,
|
|
29813
|
-
strokeLinecap: 'round',
|
|
29814
|
-
} }))), index.h("circle", { cx: data.centerX, cy: data.centerY, r: data.indicatorRadius, style: {
|
|
29815
|
-
fill: 'var(--kritzel-snap-indicator-fill, rgba(59, 130, 246, 0.3))',
|
|
29816
|
-
stroke: 'var(--kritzel-snap-indicator-stroke, #007bff)',
|
|
29817
|
-
strokeWidth: data.indicatorStrokeWidth,
|
|
29818
|
-
} }))));
|
|
29819
29838
|
})()), this.core.store.state.isContextMenuVisible && (index.h("kritzel-context-menu", { class: "context-menu", ref: el => (this.contextMenuElement = el ?? null), items: this.core.store.state.contextMenuItems, objects: this.core.store.selectionGroup?.objects || [], style: {
|
|
29820
29839
|
position: 'absolute',
|
|
29821
29840
|
left: `${this.core.store.state.contextMenuX}px`,
|
|
@@ -31227,7 +31246,7 @@ const KritzelPortal = class {
|
|
|
31227
31246
|
* This file is auto-generated by the version bump scripts.
|
|
31228
31247
|
* Do not modify manually.
|
|
31229
31248
|
*/
|
|
31230
|
-
const KRITZEL_VERSION = '0.3.
|
|
31249
|
+
const KRITZEL_VERSION = '0.3.25';
|
|
31231
31250
|
|
|
31232
31251
|
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)}`;
|
|
31233
31252
|
|
|
@@ -27968,7 +27968,10 @@ class KritzelAnchorManager {
|
|
|
27968
27968
|
// Snap Detection
|
|
27969
27969
|
// ============================================
|
|
27970
27970
|
/**
|
|
27971
|
-
* Finds
|
|
27971
|
+
* Finds an object that can be snapped to when the cursor is sufficiently close to its center.
|
|
27972
|
+
* Snap is only triggered when the cursor is inside the object's bounds AND within 1/5 of the
|
|
27973
|
+
* shorter side from the center, so snapping activates only as the user approaches the center
|
|
27974
|
+
* and releases quickly as they move away.
|
|
27972
27975
|
* Returns null if no suitable snap target is found.
|
|
27973
27976
|
*
|
|
27974
27977
|
* @param worldX - X coordinate in world space
|
|
@@ -27997,7 +28000,15 @@ class KritzelAnchorManager {
|
|
|
27997
28000
|
const polygon = object.rotatedPolygon;
|
|
27998
28001
|
const points = [polygon.topLeft, polygon.topRight, polygon.bottomRight, polygon.bottomLeft];
|
|
27999
28002
|
if (KritzelGeometryHelper.isPointInPolygon({ x: worldX, y: worldY }, points)) {
|
|
28000
|
-
//
|
|
28003
|
+
// Only snap when the cursor is near the object's center (within 1/5 of the shorter side)
|
|
28004
|
+
const snapRadius = Math.min(object.width, object.height) / 5;
|
|
28005
|
+
const dx = worldX - object.centerX;
|
|
28006
|
+
const dy = worldY - object.centerY;
|
|
28007
|
+
const distanceToCenter = Math.sqrt(dx * dx + dy * dy);
|
|
28008
|
+
if (distanceToCenter > snapRadius) {
|
|
28009
|
+
continue;
|
|
28010
|
+
}
|
|
28011
|
+
// If inside and close enough to center, check if this object is "above" the current best target
|
|
28001
28012
|
if (object.zIndex > highestZIndex) {
|
|
28002
28013
|
highestZIndex = object.zIndex;
|
|
28003
28014
|
bestTarget = {
|
|
@@ -199,7 +199,10 @@ export class KritzelAnchorManager {
|
|
|
199
199
|
// Snap Detection
|
|
200
200
|
// ============================================
|
|
201
201
|
/**
|
|
202
|
-
* Finds
|
|
202
|
+
* Finds an object that can be snapped to when the cursor is sufficiently close to its center.
|
|
203
|
+
* Snap is only triggered when the cursor is inside the object's bounds AND within 1/5 of the
|
|
204
|
+
* shorter side from the center, so snapping activates only as the user approaches the center
|
|
205
|
+
* and releases quickly as they move away.
|
|
203
206
|
* Returns null if no suitable snap target is found.
|
|
204
207
|
*
|
|
205
208
|
* @param worldX - X coordinate in world space
|
|
@@ -228,7 +231,15 @@ export class KritzelAnchorManager {
|
|
|
228
231
|
const polygon = object.rotatedPolygon;
|
|
229
232
|
const points = [polygon.topLeft, polygon.topRight, polygon.bottomRight, polygon.bottomLeft];
|
|
230
233
|
if (KritzelGeometryHelper.isPointInPolygon({ x: worldX, y: worldY }, points)) {
|
|
231
|
-
//
|
|
234
|
+
// Only snap when the cursor is near the object's center (within 1/5 of the shorter side)
|
|
235
|
+
const snapRadius = Math.min(object.width, object.height) / 5;
|
|
236
|
+
const dx = worldX - object.centerX;
|
|
237
|
+
const dy = worldY - object.centerY;
|
|
238
|
+
const distanceToCenter = Math.sqrt(dx * dx + dy * dy);
|
|
239
|
+
if (distanceToCenter > snapRadius) {
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
// If inside and close enough to center, check if this object is "above" the current best target
|
|
232
243
|
if (object.zIndex > highestZIndex) {
|
|
233
244
|
highestZIndex = object.zIndex;
|
|
234
245
|
bestTarget = {
|
|
@@ -103,6 +103,7 @@ export class KritzelClipboardManager {
|
|
|
103
103
|
*/
|
|
104
104
|
regenerateIdsAndRemapAnchors(topLevel) {
|
|
105
105
|
const all = [];
|
|
106
|
+
const hasOnlyTopLevelLines = topLevel.length > 0 && topLevel.every(object => KritzelClassHelper.isInstanceOf(object, 'KritzelLine'));
|
|
106
107
|
const collect = (objects) => {
|
|
107
108
|
for (const object of objects) {
|
|
108
109
|
all.push(object);
|
|
@@ -127,9 +128,15 @@ export class KritzelClipboardManager {
|
|
|
127
128
|
if (object.startAnchor && idMap.has(object.startAnchor.objectId)) {
|
|
128
129
|
object.startAnchor = { objectId: idMap.get(object.startAnchor.objectId) };
|
|
129
130
|
}
|
|
131
|
+
else if (hasOnlyTopLevelLines) {
|
|
132
|
+
object.startAnchor = undefined;
|
|
133
|
+
}
|
|
130
134
|
if (object.endAnchor && idMap.has(object.endAnchor.objectId)) {
|
|
131
135
|
object.endAnchor = { objectId: idMap.get(object.endAnchor.objectId) };
|
|
132
136
|
}
|
|
137
|
+
else if (hasOnlyTopLevelLines) {
|
|
138
|
+
object.endAnchor = undefined;
|
|
139
|
+
}
|
|
133
140
|
}
|
|
134
141
|
}
|
|
135
142
|
}
|
|
@@ -2155,7 +2155,11 @@ export class KritzelEngine {
|
|
|
2155
2155
|
transform: object?.transformationMatrix,
|
|
2156
2156
|
transformOrigin: 'top left',
|
|
2157
2157
|
position: 'absolute',
|
|
2158
|
-
|
|
2158
|
+
// The object wrapper establishes its own stacking context (transform + z-index),
|
|
2159
|
+
// so the selection-line handles inside it cannot escape above the snap/anchor
|
|
2160
|
+
// layers (z-index 9999/9998) rendered later at the origin level. Lift the
|
|
2161
|
+
// selected line's wrapper above those layers so its handles always paint on top.
|
|
2162
|
+
zIndex: this.core.displaySelectionLineUI(object) ? '10001' : object.zIndex.toString(),
|
|
2159
2163
|
pointerEvents: getObjectWrapperPointerEvents(object),
|
|
2160
2164
|
} }, KritzelClassHelper.isInstanceOf(object, 'KritzelPath') && (h("svg", { ref: el => el && object.mount(el), xmlns: "http://www.w3.org/2000/svg", style: {
|
|
2161
2165
|
height: object?.totalHeight + 'px',
|
|
@@ -2359,10 +2363,19 @@ export class KritzelEngine {
|
|
|
2359
2363
|
}
|
|
2360
2364
|
const selectionBorderColor = remoteUserColor ?? (KritzelColorHelper.resolveThemeColor(object.borderColor, currentTheme) || 'var(--kritzel-selection-border-color, #007AFF)');
|
|
2361
2365
|
const selectionHandleStrokeColor = remoteUserColor ?? 'var(--kritzel-selection-handle-stroke-color, #007AFF)';
|
|
2366
|
+
const lineObject = object;
|
|
2367
|
+
const activeSnapCandidate = this.core.store.state.snapCandidate;
|
|
2368
|
+
const isStartHandleSnapped = lineObject.startAnchor != null;
|
|
2369
|
+
const isEndHandleSnapped = lineObject.endAnchor != null;
|
|
2370
|
+
const isStartHandleSnapPreview = activeSnapCandidate?.endpoint === 'start';
|
|
2371
|
+
const isEndHandleSnapPreview = activeSnapCandidate?.endpoint === 'end';
|
|
2372
|
+
const isStartHandleHighlighted = isStartHandleSnapped || isStartHandleSnapPreview;
|
|
2373
|
+
const isEndHandleHighlighted = isEndHandleSnapped || isEndHandleSnapPreview;
|
|
2374
|
+
const selectionOverlayZIndex = this.core.displaySelectionLineUI(object) ? '10000' : (object.zIndex + 1).toString();
|
|
2362
2375
|
const handleScale = object.scale ?? 1;
|
|
2363
2376
|
const { canRenderResizeHandles, canRenderRotationHandle } = this.getSelectionHandleCapabilities(object);
|
|
2364
2377
|
return (h("svg", { xmlns: "http://www.w3.org/2000/svg", style: {
|
|
2365
|
-
zIndex:
|
|
2378
|
+
zIndex: selectionOverlayZIndex,
|
|
2366
2379
|
height: object?.totalHeight.toString(),
|
|
2367
2380
|
width: object?.totalWidth.toString(),
|
|
2368
2381
|
left: '0',
|
|
@@ -2453,7 +2466,7 @@ export class KritzelEngine {
|
|
|
2453
2466
|
strokeLinecap: 'round',
|
|
2454
2467
|
fill: 'none',
|
|
2455
2468
|
} })), !this.isSelecting && !isRemoteSelection && (h("g", { class: "selection-line-handles", style: { pointerEvents: 'auto' } }, h("circle", { class: "selection-line-handle start", cx: object.startX - object.x, cy: object.startY - object.y, r: `${((baseHandleSize - 1) * object.scale) / this.core.store.state?.scale}`, style: {
|
|
2456
|
-
fill: 'var(--kritzel-selection-handle-color, #000000)',
|
|
2469
|
+
fill: isStartHandleHighlighted ? selectionHandleStrokeColor : 'var(--kritzel-selection-handle-color, #000000)',
|
|
2457
2470
|
stroke: selectionHandleStrokeColor,
|
|
2458
2471
|
strokeWidth: `calc(2px * ${object.scale} / ${this.core.store.state?.scale})`,
|
|
2459
2472
|
paintOrder: 'fill',
|
|
@@ -2477,7 +2490,7 @@ export class KritzelEngine {
|
|
|
2477
2490
|
fill: 'transparent',
|
|
2478
2491
|
paintOrder: 'fill',
|
|
2479
2492
|
} }), h("circle", { class: "selection-line-handle end", cx: object.endX - object.x, cy: object.endY - object.y, r: `${((baseHandleSize - 1) * object.scale) / this.core.store.state?.scale}`, style: {
|
|
2480
|
-
fill: 'var(--kritzel-selection-handle-color, #000000)',
|
|
2493
|
+
fill: isEndHandleHighlighted ? selectionHandleStrokeColor : 'var(--kritzel-selection-handle-color, #000000)',
|
|
2481
2494
|
stroke: selectionHandleStrokeColor,
|
|
2482
2495
|
strokeWidth: `calc(2px * ${object.scale} / ${this.core.store.state?.scale})`,
|
|
2483
2496
|
paintOrder: 'fill',
|
|
@@ -2487,6 +2500,34 @@ export class KritzelEngine {
|
|
|
2487
2500
|
} })))))));
|
|
2488
2501
|
})()));
|
|
2489
2502
|
}), (() => {
|
|
2503
|
+
const data = this.core.anchorManager.getSnapIndicatorRenderData();
|
|
2504
|
+
if (!data)
|
|
2505
|
+
return null;
|
|
2506
|
+
return (h("svg", { xmlns: "http://www.w3.org/2000/svg", class: "snap-indicator", style: {
|
|
2507
|
+
position: 'absolute',
|
|
2508
|
+
left: '0',
|
|
2509
|
+
top: '0',
|
|
2510
|
+
width: '1px',
|
|
2511
|
+
height: '1px',
|
|
2512
|
+
pointerEvents: 'none',
|
|
2513
|
+
zIndex: '9999',
|
|
2514
|
+
overflow: 'visible',
|
|
2515
|
+
} }, h("g", null, data.snapLinePath ? (h("path", { d: data.snapLinePath, fill: "none", style: {
|
|
2516
|
+
stroke: 'var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))',
|
|
2517
|
+
strokeWidth: data.lineStrokeWidth,
|
|
2518
|
+
strokeDasharray: data.dashArray,
|
|
2519
|
+
strokeLinecap: 'round',
|
|
2520
|
+
} })) : (data.edgeX !== undefined &&
|
|
2521
|
+
data.edgeY !== undefined && (h("line", { x1: data.edgeX, y1: data.edgeY, x2: data.centerX, y2: data.centerY, style: {
|
|
2522
|
+
stroke: 'var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))',
|
|
2523
|
+
strokeWidth: data.lineStrokeWidth,
|
|
2524
|
+
strokeDasharray: data.dashArray,
|
|
2525
|
+
strokeLinecap: 'round',
|
|
2526
|
+
} }))), h("circle", { cx: data.centerX, cy: data.centerY, r: data.indicatorRadius, style: {
|
|
2527
|
+
fill: 'var(--kritzel-snap-indicator-fill, rgba(59, 130, 246, 0.3))',
|
|
2528
|
+
strokeWidth: data.indicatorStrokeWidth,
|
|
2529
|
+
} }))));
|
|
2530
|
+
})(), (() => {
|
|
2490
2531
|
const data = this.core.anchorManager.getAnchorLinesRenderData();
|
|
2491
2532
|
if (!data)
|
|
2492
2533
|
return null;
|
|
@@ -2511,7 +2552,7 @@ export class KritzelEngine {
|
|
|
2511
2552
|
strokeDasharray: data.dashArray,
|
|
2512
2553
|
strokeLinecap: 'round',
|
|
2513
2554
|
} })), h("circle", { cx: data.startAnchorViz.centerX, cy: data.startAnchorViz.centerY, r: data.indicatorRadius, style: {
|
|
2514
|
-
fill: 'var(--kritzel-snap-indicator-fill, rgba(
|
|
2555
|
+
fill: 'var(--kritzel-snap-indicator-fill, rgba(59, 130, 246, 0.3))',
|
|
2515
2556
|
stroke: 'var(--kritzel-snap-indicator-stroke, #007bff)',
|
|
2516
2557
|
strokeWidth: data.indicatorStrokeWidth,
|
|
2517
2558
|
} }))), data.endAnchorViz && (h("g", { class: "anchor-line-end" }, data.endAnchorViz.pathD ? (h("path", { d: data.endAnchorViz.pathD, style: {
|
|
@@ -2530,35 +2571,6 @@ export class KritzelEngine {
|
|
|
2530
2571
|
stroke: 'var(--kritzel-snap-indicator-stroke, #007bff)',
|
|
2531
2572
|
strokeWidth: data.indicatorStrokeWidth,
|
|
2532
2573
|
} })))));
|
|
2533
|
-
})(), (() => {
|
|
2534
|
-
const data = this.core.anchorManager.getSnapIndicatorRenderData();
|
|
2535
|
-
if (!data)
|
|
2536
|
-
return null;
|
|
2537
|
-
return (h("svg", { xmlns: "http://www.w3.org/2000/svg", class: "snap-indicator", style: {
|
|
2538
|
-
position: 'absolute',
|
|
2539
|
-
left: '0',
|
|
2540
|
-
top: '0',
|
|
2541
|
-
width: '1px',
|
|
2542
|
-
height: '1px',
|
|
2543
|
-
pointerEvents: 'none',
|
|
2544
|
-
zIndex: '9999',
|
|
2545
|
-
overflow: 'visible',
|
|
2546
|
-
} }, h("g", null, data.snapLinePath ? (h("path", { d: data.snapLinePath, fill: "none", style: {
|
|
2547
|
-
stroke: 'var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))',
|
|
2548
|
-
strokeWidth: data.lineStrokeWidth,
|
|
2549
|
-
strokeDasharray: data.dashArray,
|
|
2550
|
-
strokeLinecap: 'round',
|
|
2551
|
-
} })) : (data.edgeX !== undefined &&
|
|
2552
|
-
data.edgeY !== undefined && (h("line", { x1: data.edgeX, y1: data.edgeY, x2: data.centerX, y2: data.centerY, style: {
|
|
2553
|
-
stroke: 'var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))',
|
|
2554
|
-
strokeWidth: data.lineStrokeWidth,
|
|
2555
|
-
strokeDasharray: data.dashArray,
|
|
2556
|
-
strokeLinecap: 'round',
|
|
2557
|
-
} }))), h("circle", { cx: data.centerX, cy: data.centerY, r: data.indicatorRadius, style: {
|
|
2558
|
-
fill: 'var(--kritzel-snap-indicator-fill, rgba(59, 130, 246, 0.3))',
|
|
2559
|
-
stroke: 'var(--kritzel-snap-indicator-stroke, #007bff)',
|
|
2560
|
-
strokeWidth: data.indicatorStrokeWidth,
|
|
2561
|
-
} }))));
|
|
2562
2574
|
})()), this.core.store.state.isContextMenuVisible && (h("kritzel-context-menu", { class: "context-menu", ref: el => (this.contextMenuElement = el ?? null), items: this.core.store.state.contextMenuItems, objects: this.core.store.selectionGroup?.objects || [], style: {
|
|
2563
2575
|
position: 'absolute',
|
|
2564
2576
|
left: `${this.core.store.state.contextMenuX}px`,
|
package/dist/components/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{g as getAssetPath,r as render,s as setAssetPath,a as setNonce,b as setPlatformOptions}from"./p-B43upypT.js";export{K as KritzelBaseObject,b as KritzelLine,a as KritzelPath}from"./p-BNu3Akp5.js";export{A as AssetNotFoundError,I as IndexedDBAssetProvider,g as KritzelAssetResolver,d as KritzelBaseTool,b as KritzelGroup,a as KritzelImage,f as KritzelSelectionTool,c as KritzelShape,K as KritzelText,e as KritzelTextTool,S as ShapeType}from"./p-B5XGjTLd.js";export{A as APP_STATE_MIGRATIONS,D as DE_LOCALE,E as EN_LOCALE,F as FR_LOCALE,k as KritzelAlignment,g as KritzelAnchorManager,a as KritzelBrushTool,f as KritzelCursorHelper,K as KritzelCustomElement,j as KritzelCustomElementRendererRegistry,c as KritzelEraserTool,d as KritzelImageTool,i as KritzelLicenseManager,b as KritzelLineTool,h as KritzelLocalizationManager,e as KritzelShapeTool,W as WORKSPACE_MIGRATIONS,r as runMigrations}from"./p-on11Z8cZ.js";import*as t from"yjs";import{IndexeddbPersistence as n}from"y-indexeddb";import{WebsocketProvider as o}from"y-websocket";import{H as m,a as u}from"./kritzel-editor.js";export{d as DEFAULT_ASSET_STORAGE_CONFIG,D as DEFAULT_BRUSH_CONFIG,c as DEFAULT_LINE_TOOL_CONFIG,b as DEFAULT_TEXT_CONFIG,KritzelEditor,defineCustomElement as defineCustomElementKritzelEditor}from"./kritzel-editor.js";export{K as KritzelWorkspace,W as WORKSPACE_EXPORT_VERSION}from"./p-DhMlShij.js";export{K as KritzelThemeManager,d as darkTheme,l as lightTheme}from"./p-CpzicliK.js";export{C as CURRENT_APP_STATE_SCHEMA_VERSION,a as CURRENT_WORKSPACE_SCHEMA_VERSION}from"./p-CW-VyJgK.js";export{KritzelActiveUsers,defineCustomElement as defineCustomElementKritzelActiveUsers}from"./kritzel-active-users.js";export{KritzelAvatar,defineCustomElement as defineCustomElementKritzelAvatar}from"./kritzel-avatar.js";export{KritzelAwarenessCursors,defineCustomElement as defineCustomElementKritzelAwarenessCursors}from"./kritzel-awareness-cursors.js";export{KritzelBackToContent,defineCustomElement as defineCustomElementKritzelBackToContent}from"./kritzel-back-to-content.js";export{KritzelBrushStyle,defineCustomElement as defineCustomElementKritzelBrushStyle}from"./kritzel-brush-style.js";export{KritzelButton,defineCustomElement as defineCustomElementKritzelButton}from"./kritzel-button.js";export{KritzelColor,defineCustomElement as defineCustomElementKritzelColor}from"./kritzel-color.js";export{KritzelColorPalette,defineCustomElement as defineCustomElementKritzelColorPalette}from"./kritzel-color-palette.js";export{KritzelContextMenu,defineCustomElement as defineCustomElementKritzelContextMenu}from"./kritzel-context-menu.js";export{KritzelControls,defineCustomElement as defineCustomElementKritzelControls}from"./kritzel-controls.js";export{KritzelCurrentUser,defineCustomElement as defineCustomElementKritzelCurrentUser}from"./kritzel-current-user.js";export{KritzelCurrentUserDialog,defineCustomElement as defineCustomElementKritzelCurrentUserDialog}from"./kritzel-current-user-dialog.js";export{KritzelCursorTrail,defineCustomElement as defineCustomElementKritzelCursorTrail}from"./kritzel-cursor-trail.js";export{KritzelDialog,defineCustomElement as defineCustomElementKritzelDialog}from"./kritzel-dialog.js";export{KritzelDropdown,defineCustomElement as defineCustomElementKritzelDropdown}from"./kritzel-dropdown.js";export{KritzelEngine,defineCustomElement as defineCustomElementKritzelEngine}from"./kritzel-engine.js";export{KritzelExport,defineCustomElement as defineCustomElementKritzelExport}from"./kritzel-export.js";export{KritzelFont,defineCustomElement as defineCustomElementKritzelFont}from"./kritzel-font.js";export{KritzelFontFamily,defineCustomElement as defineCustomElementKritzelFontFamily}from"./kritzel-font-family.js";export{KritzelFontSize,defineCustomElement as defineCustomElementKritzelFontSize}from"./kritzel-font-size.js";export{KritzelIcon,defineCustomElement as defineCustomElementKritzelIcon}from"./kritzel-icon.js";export{KritzelInput,defineCustomElement as defineCustomElementKritzelInput}from"./kritzel-input.js";export{KritzelLineEndings,defineCustomElement as defineCustomElementKritzelLineEndings}from"./kritzel-line-endings.js";export{KritzelLoginDialog,defineCustomElement as defineCustomElementKritzelLoginDialog}from"./kritzel-login-dialog.js";export{KritzelMasterDetail,defineCustomElement as defineCustomElementKritzelMasterDetail}from"./kritzel-master-detail.js";export{KritzelMenu,defineCustomElement as defineCustomElementKritzelMenu}from"./kritzel-menu.js";export{KritzelMenuItem,defineCustomElement as defineCustomElementKritzelMenuItem}from"./kritzel-menu-item.js";export{KritzelMoreMenu,defineCustomElement as defineCustomElementKritzelMoreMenu}from"./kritzel-more-menu.js";export{KritzelNotificationCard,defineCustomElement as defineCustomElementKritzelNotificationCard}from"./kritzel-notification-card.js";export{KritzelNumericInput,defineCustomElement as defineCustomElementKritzelNumericInput}from"./kritzel-numeric-input.js";export{KritzelOpacitySlider,defineCustomElement as defineCustomElementKritzelOpacitySlider}from"./kritzel-opacity-slider.js";export{KritzelPillTabs,defineCustomElement as defineCustomElementKritzelPillTabs}from"./kritzel-pill-tabs.js";export{KritzelPortal,defineCustomElement as defineCustomElementKritzelPortal}from"./kritzel-portal.js";export{KritzelSettings,defineCustomElement as defineCustomElementKritzelSettings}from"./kritzel-settings.js";export{KritzelShapeFill,defineCustomElement as defineCustomElementKritzelShapeFill}from"./kritzel-shape-fill.js";export{KritzelShareDialog,defineCustomElement as defineCustomElementKritzelShareDialog}from"./kritzel-share-dialog.js";export{KritzelSlideToggle,defineCustomElement as defineCustomElementKritzelSlideToggle}from"./kritzel-slide-toggle.js";export{KritzelSplitButton,defineCustomElement as defineCustomElementKritzelSplitButton}from"./kritzel-split-button.js";export{KritzelStrokeSize,defineCustomElement as defineCustomElementKritzelStrokeSize}from"./kritzel-stroke-size.js";export{KritzelToolConfig,defineCustomElement as defineCustomElementKritzelToolConfig}from"./kritzel-tool-config.js";export{KritzelTooltip,defineCustomElement as defineCustomElementKritzelTooltip}from"./kritzel-tooltip.js";export{KritzelUtilityPanel,defineCustomElement as defineCustomElementKritzelUtilityPanel}from"./kritzel-utility-panel.js";export{KritzelWatermark,defineCustomElement as defineCustomElementKritzelWatermark}from"./kritzel-watermark.js";export{KritzelWorkspaceManager,defineCustomElement as defineCustomElementKritzelWorkspaceManager}from"./kritzel-workspace-manager.js";export{KritzelZoomPanel,defineCustomElement as defineCustomElementKritzelZoomPanel}from"./kritzel-zoom-panel.js";const z=Math.floor,p=127,y=Number.MAX_SAFE_INTEGER;class w{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const x=()=>new w,T=e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let s=0;s<e.bufs.length;s++)t+=e.bufs[s].length;return t})(e));let s=0;for(let i=0;i<e.bufs.length;i++){const n=e.bufs[i];t.set(n,s),s+=n.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),s),t},P=(e,t)=>{const s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*s),e.cpos=0),e.cbuf[e.cpos++]=t},v=(e,t)=>{for(;t>p;)P(e,128|p&t),t=z(t/128);P(e,p&t)},M=(e,t)=>{v(e,t.byteLength),((e,t)=>{const s=e.cbuf.length,i=e.cpos,n=((e,t)=>e<t?e:t)(s-i,t.length),o=t.length-n;e.cbuf.set(t.subarray(0,n),i),e.cpos+=n,o>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(((e,t)=>e>t?e:t)(2*s,o)),e.cbuf.set(t.subarray(n)),e.cpos=o)})(e,t)},U=e=>Error(e),_=U("Unexpected end of array"),O=U("Integer out of Range");class L{constructor(e){this.arr=e,this.pos=0}}const R=e=>((e,t)=>{const s=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,s})(e,$(e)),$=e=>{let t=0,s=1;const i=e.arr.length;for(;e.pos<i;){const i=e.arr[e.pos++];if(t+=(i&p)*s,s*=128,i<128)return t;if(t>y)throw O}throw _};class B{type="local";doc;channel;_synced=!1;constructor(e,t,s){this.doc=t,this.channel=new BroadcastChannel(e),this.channel.onmessage=e=>{this.handleMessage(e.data)},this.doc.on("update",this.handleDocUpdate),this.broadcastSync(),setTimeout((()=>{this._synced=!0}),100),s?.quiet||console.info("BroadcastChannel Provider initialized: "+e)}handleDocUpdate=(e,t)=>{if(t!==this){const t=x();v(t,0),M(t,e),this.channel.postMessage(T(t))}};handleMessage(e){const s=(e=>new L(e))(new Uint8Array(e));switch($(s)){case 0:const e=R(s);t.applyUpdate(this.doc,e,this);break;case 1:this.broadcastSync();break;case 2:const i=R(s),n=t.encodeStateAsUpdate(this.doc,i);if(n.length>0){const e=x();v(e,0),M(e,n),this.channel.postMessage(T(e))}}}broadcastSync(){const e=x();v(e,2),M(e,t.encodeStateVector(this.doc)),this.channel.postMessage(T(e))}async connect(){if(!this._synced)return new Promise((e=>{const t=()=>{this._synced?e():setTimeout(t,50)};t()}))}disconnect(){}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.doc.off("update",this.handleDocUpdate),this.channel.close()}}const N=new Map;class H{type="local";doc;cacheKey;isConnected=!1;constructor(e,t,s){this.doc=t,this.cacheKey=s?.name??e}handleUpdate=(e,s)=>{s!==this&&N.set(this.cacheKey,t.encodeStateAsUpdate(this.doc))};async connect(){if(this.isConnected)return;const e=N.get(this.cacheKey);e&&t.applyUpdate(this.doc,e,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(e){void 0!==e?N.delete(e):N.clear()}}class G{type="local";provider;isConnected=!1;constructor(e,t,s){this.provider=new n(s?.name||e,t)}async connect(){if(!this.isConnected)return new Promise((e=>{this.provider.on("synced",(()=>{this.isConnected=!0,e()}))}))}disconnect(){this.isConnected=!1}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1}}class V{type="network";provider;isConnected=!1;_quiet=!1;get awareness(){return this.provider.awareness}constructor(e,t,s){const i=s?.url||"ws://localhost:1234",n=s?.roomName||e;this.provider=new o(i,n,t,{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(e){return{create:(t,s,i)=>{const n=i?{...e,...i}:e;return new V(t,s,n)}}}setupEventListeners(){this.provider.on("status",(({status:e})=>{"connected"===e?(this.isConnected=!0,this._quiet||console.info("WebSocket connected")):"disconnected"===e&&(this.isConnected=!1,this._quiet||console.info("WebSocket disconnected"))})),this.provider.on("sync",(e=>{e&&!this._quiet&&console.info("WebSocket synced")}))}async connect(){if(!this.isConnected)return new Promise(((e,t)=>{const s=setTimeout((()=>{t(Error("WebSocket connection timeout"))}),1e4),i=({status:t})=>{"connected"===t&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,e())};this.provider.on("status",i),this.provider.wsconnected&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,e())}))}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 Z{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(e,t,s){const i=s?.name||e,n=s?.url||"ws://localhost:1234";this.connectionTimeoutMs=s?.connectionTimeout??1e4;const o=s?.websocketProvider||Z.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 l=()=>{this.isDestroyed||(this.isConnected=!0,this._connectionStatus="connected",s?.quiet||console.info("Hocuspocus connected: "+i),s?.onConnect&&s.onConnect())},a=()=>{this.isDestroyed||(this.isConnected=!1,this.isSynced=!1,this._connectionStatus="disconnected",s?.quiet||console.info("Hocuspocus disconnected: "+i),s?.onDisconnect&&s.onDisconnect())},c=()=>{this.isDestroyed||(this.isSynced=!0,this._connectionStatus="synced",s?.quiet||console.info("Hocuspocus synced: "+i),s?.onSynced&&s.onSynced())},d=e=>{this.isDestroyed||("connecting"===e.status&&(this._connectionStatus="connecting"),s?.onStatus&&s.onStatus(e))};if(o){this.usesSharedSocket=!0;const e={websocketProvider:o,name:i,document:t,token:s?.token||null,onStatus:d,onConnect:l,onDisconnect:a,onSynced:c,...r};void 0!==s?.forceSyncInterval&&(e.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(e.onAuthenticationFailed=s.onAuthenticationFailed),this.provider=new m(e),this.provider.attach(),s?.quiet||console.info("Hocuspocus Provider initialized (multiplexed): "+i)}else{this.usesSharedSocket=!1;const e={url:n,name:i,document:t,token:s?.token||null,autoConnect:!1,onStatus:d,onConnect:l,onDisconnect:a,onSynced:c,...r};void 0!==s?.forceSyncInterval&&(e.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(e.onAuthenticationFailed=s.onAuthenticationFailed),s?.WebSocketPolyfill&&(e.WebSocketPolyfill=s.WebSocketPolyfill),this.provider=new m(e),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(e){if(Z.sharedWebSocketProvider)return console.warn("Shared WebSocket already exists. Returning existing instance."),Z.sharedWebSocketProvider;const t={url:e.url};return e.WebSocketPolyfill&&(t.WebSocketPolyfill=e.WebSocketPolyfill),e.onConnect&&(t.onConnect=e.onConnect),e.onDisconnect&&(t.onDisconnect=e.onDisconnect),e.onStatus&&(t.onStatus=e.onStatus),Z.sharedWebSocketProvider=new u(t),console.info("Shared Hocuspocus WebSocket created: "+e.url),Z.sharedWebSocketProvider}static destroySharedWebSocket(){Z.sharedWebSocketProvider&&(Z.sharedWebSocketProvider.destroy(),Z.sharedWebSocketProvider=null,console.info("Shared Hocuspocus WebSocket destroyed"))}static getSharedWebSocket(){return Z.sharedWebSocketProvider}static with(e){return{create:(t,s,i)=>{const n=i?{...e,...i}:e;return new Z(t,s,n)}}}async connect(){if(!this.isSynced&&!this.isDestroyed)return this._connectionStatus="connecting",new Promise(((e,t)=>{this.pendingConnectReject=t,this.connectTimeout=setTimeout((()=>{this.pendingConnectReject=null,this.connectTimeout=null,t(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||e()};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 e();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 X{type="remote";name="HttpAssetProvider";_options;constructor(e){this._options=e}static with(e){return{create:()=>new X(e)}}async init(){this._options.quiet||console.info("HttpAssetProvider initialized")}destroy(){}canResolve(e){return!0}async put(e,t){const s=t.id??this.generateUuid(),i={...t,id:s},n=await(this._options.headers?.())??{},o=await this._options.uploadUrl(i),r=this._options.upload??this.defaultUpload;return{id:(await r(o,e,i,n)).id??s,kind:t.kind??"file",mimeType:t.mimeType,size:e.size,createdAt:Date.now(),width:t.width,height:t.height,durationMs:t.durationMs,originalFilename:t.originalFilename}}async resolve(e){return this._options.resolveUrl(e)}async fetch(e){const t=await this._options.resolveUrl(e),s=await(this._options.headers?.())??{},i=await fetch(t,{headers:s});if(!i.ok)throw Error(`[HttpAssetProvider] Failed to fetch asset ${e}: ${i.status} ${i.statusText}`);return i.blob()}async delete(e){if(!this._options.deleteUrl)return;const t=await this._options.deleteUrl(e),s=await(this._options.headers?.())??{},i=await fetch(t,{method:"DELETE",headers:s});if(!i.ok)throw Error(`[HttpAssetProvider] Failed to delete asset ${e}: ${i.status} ${i.statusText}`);this._options.quiet||console.info("HttpAssetProvider: deleted asset "+e)}defaultUpload=async(e,t,s,i)=>{const n=new FormData;n.append("metadata",JSON.stringify(s)),n.append("file",t,s.originalFilename||`${s.id}.${this.extensionFromMime(s.mimeType)}`);const o=await fetch(e,{method:"POST",headers:i,body:n});if(!o.ok)throw Error(`[HttpAssetProvider] Upload failed: ${o.status} ${o.statusText}`);return(o.headers.get("content-type")||"").includes("application/json")?await o.json():{}};extensionFromMime(e){const t=e.indexOf("/");return t>=0?e.slice(t+1):"bin"}generateUuid(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}class J{type="remote";name="PresignedAssetProvider";_options;constructor(e){this._options=e}static with(e){return{create:()=>new J(e)}}async init(){this._options.quiet||console.info("PresignedAssetProvider initialized")}destroy(){}canResolve(e){return!0}async put(e,t){const s=await this._options.getUploadDescriptor(t),i=s.method??"PUT",n={...s.headers??{}};let o;if(n["Content-Type"]||n["content-type"]||(n["Content-Type"]=t.mimeType),"POST"===i&&s.fields){const t=new FormData;for(const[e,i]of Object.entries(s.fields))t.append(e,i);t.append("file",e),o=t,delete n["Content-Type"],delete n["content-type"]}else o=e;const r=await fetch(s.url,{method:i,headers:n,body:o});if(!r.ok)throw Error(`[PresignedAssetProvider] Upload failed: ${r.status} ${r.statusText}`);return{id:s.id,kind:t.kind??"file",mimeType:t.mimeType,size:e.size,createdAt:Date.now(),width:t.width,height:t.height,durationMs:t.durationMs,originalFilename:t.originalFilename}}async resolve(e){return this._options.getDownloadUrl(e)}async fetch(e){const t=await this._options.getDownloadUrl(e),s=await fetch(t);if(!s.ok)throw Error(`[PresignedAssetProvider] Failed to fetch asset ${e}: ${s.status} ${s.statusText}`);return s.blob()}async delete(e){this._options.deleteAsset&&(await this._options.deleteAsset(e),this._options.quiet||console.info("PresignedAssetProvider: deleted asset "+e))}}export{B as BroadcastSyncProvider,Z as HocuspocusSyncProvider,X as HttpAssetProvider,H as InMemorySyncProvider,G as IndexedDBSyncProvider,J as PresignedAssetProvider,V as WebSocketSyncProvider}
|
|
1
|
+
export{g as getAssetPath,r as render,s as setAssetPath,a as setNonce,b as setPlatformOptions}from"./p-B43upypT.js";export{K as KritzelBaseObject,b as KritzelLine,a as KritzelPath}from"./p-BNu3Akp5.js";export{A as AssetNotFoundError,I as IndexedDBAssetProvider,g as KritzelAssetResolver,d as KritzelBaseTool,b as KritzelGroup,a as KritzelImage,f as KritzelSelectionTool,c as KritzelShape,K as KritzelText,e as KritzelTextTool,S as ShapeType}from"./p-B5XGjTLd.js";export{A as APP_STATE_MIGRATIONS,D as DE_LOCALE,E as EN_LOCALE,F as FR_LOCALE,k as KritzelAlignment,g as KritzelAnchorManager,a as KritzelBrushTool,f as KritzelCursorHelper,K as KritzelCustomElement,j as KritzelCustomElementRendererRegistry,c as KritzelEraserTool,d as KritzelImageTool,i as KritzelLicenseManager,b as KritzelLineTool,h as KritzelLocalizationManager,e as KritzelShapeTool,W as WORKSPACE_MIGRATIONS,r as runMigrations}from"./p-6_95PFq4.js";import*as t from"yjs";import{IndexeddbPersistence as n}from"y-indexeddb";import{WebsocketProvider as o}from"y-websocket";import{H as m,a as u}from"./kritzel-editor.js";export{d as DEFAULT_ASSET_STORAGE_CONFIG,D as DEFAULT_BRUSH_CONFIG,c as DEFAULT_LINE_TOOL_CONFIG,b as DEFAULT_TEXT_CONFIG,KritzelEditor,defineCustomElement as defineCustomElementKritzelEditor}from"./kritzel-editor.js";export{K as KritzelWorkspace,W as WORKSPACE_EXPORT_VERSION}from"./p-DhMlShij.js";export{K as KritzelThemeManager,d as darkTheme,l as lightTheme}from"./p-CpzicliK.js";export{C as CURRENT_APP_STATE_SCHEMA_VERSION,a as CURRENT_WORKSPACE_SCHEMA_VERSION}from"./p-CW-VyJgK.js";export{KritzelActiveUsers,defineCustomElement as defineCustomElementKritzelActiveUsers}from"./kritzel-active-users.js";export{KritzelAvatar,defineCustomElement as defineCustomElementKritzelAvatar}from"./kritzel-avatar.js";export{KritzelAwarenessCursors,defineCustomElement as defineCustomElementKritzelAwarenessCursors}from"./kritzel-awareness-cursors.js";export{KritzelBackToContent,defineCustomElement as defineCustomElementKritzelBackToContent}from"./kritzel-back-to-content.js";export{KritzelBrushStyle,defineCustomElement as defineCustomElementKritzelBrushStyle}from"./kritzel-brush-style.js";export{KritzelButton,defineCustomElement as defineCustomElementKritzelButton}from"./kritzel-button.js";export{KritzelColor,defineCustomElement as defineCustomElementKritzelColor}from"./kritzel-color.js";export{KritzelColorPalette,defineCustomElement as defineCustomElementKritzelColorPalette}from"./kritzel-color-palette.js";export{KritzelContextMenu,defineCustomElement as defineCustomElementKritzelContextMenu}from"./kritzel-context-menu.js";export{KritzelControls,defineCustomElement as defineCustomElementKritzelControls}from"./kritzel-controls.js";export{KritzelCurrentUser,defineCustomElement as defineCustomElementKritzelCurrentUser}from"./kritzel-current-user.js";export{KritzelCurrentUserDialog,defineCustomElement as defineCustomElementKritzelCurrentUserDialog}from"./kritzel-current-user-dialog.js";export{KritzelCursorTrail,defineCustomElement as defineCustomElementKritzelCursorTrail}from"./kritzel-cursor-trail.js";export{KritzelDialog,defineCustomElement as defineCustomElementKritzelDialog}from"./kritzel-dialog.js";export{KritzelDropdown,defineCustomElement as defineCustomElementKritzelDropdown}from"./kritzel-dropdown.js";export{KritzelEngine,defineCustomElement as defineCustomElementKritzelEngine}from"./kritzel-engine.js";export{KritzelExport,defineCustomElement as defineCustomElementKritzelExport}from"./kritzel-export.js";export{KritzelFont,defineCustomElement as defineCustomElementKritzelFont}from"./kritzel-font.js";export{KritzelFontFamily,defineCustomElement as defineCustomElementKritzelFontFamily}from"./kritzel-font-family.js";export{KritzelFontSize,defineCustomElement as defineCustomElementKritzelFontSize}from"./kritzel-font-size.js";export{KritzelIcon,defineCustomElement as defineCustomElementKritzelIcon}from"./kritzel-icon.js";export{KritzelInput,defineCustomElement as defineCustomElementKritzelInput}from"./kritzel-input.js";export{KritzelLineEndings,defineCustomElement as defineCustomElementKritzelLineEndings}from"./kritzel-line-endings.js";export{KritzelLoginDialog,defineCustomElement as defineCustomElementKritzelLoginDialog}from"./kritzel-login-dialog.js";export{KritzelMasterDetail,defineCustomElement as defineCustomElementKritzelMasterDetail}from"./kritzel-master-detail.js";export{KritzelMenu,defineCustomElement as defineCustomElementKritzelMenu}from"./kritzel-menu.js";export{KritzelMenuItem,defineCustomElement as defineCustomElementKritzelMenuItem}from"./kritzel-menu-item.js";export{KritzelMoreMenu,defineCustomElement as defineCustomElementKritzelMoreMenu}from"./kritzel-more-menu.js";export{KritzelNotificationCard,defineCustomElement as defineCustomElementKritzelNotificationCard}from"./kritzel-notification-card.js";export{KritzelNumericInput,defineCustomElement as defineCustomElementKritzelNumericInput}from"./kritzel-numeric-input.js";export{KritzelOpacitySlider,defineCustomElement as defineCustomElementKritzelOpacitySlider}from"./kritzel-opacity-slider.js";export{KritzelPillTabs,defineCustomElement as defineCustomElementKritzelPillTabs}from"./kritzel-pill-tabs.js";export{KritzelPortal,defineCustomElement as defineCustomElementKritzelPortal}from"./kritzel-portal.js";export{KritzelSettings,defineCustomElement as defineCustomElementKritzelSettings}from"./kritzel-settings.js";export{KritzelShapeFill,defineCustomElement as defineCustomElementKritzelShapeFill}from"./kritzel-shape-fill.js";export{KritzelShareDialog,defineCustomElement as defineCustomElementKritzelShareDialog}from"./kritzel-share-dialog.js";export{KritzelSlideToggle,defineCustomElement as defineCustomElementKritzelSlideToggle}from"./kritzel-slide-toggle.js";export{KritzelSplitButton,defineCustomElement as defineCustomElementKritzelSplitButton}from"./kritzel-split-button.js";export{KritzelStrokeSize,defineCustomElement as defineCustomElementKritzelStrokeSize}from"./kritzel-stroke-size.js";export{KritzelToolConfig,defineCustomElement as defineCustomElementKritzelToolConfig}from"./kritzel-tool-config.js";export{KritzelTooltip,defineCustomElement as defineCustomElementKritzelTooltip}from"./kritzel-tooltip.js";export{KritzelUtilityPanel,defineCustomElement as defineCustomElementKritzelUtilityPanel}from"./kritzel-utility-panel.js";export{KritzelWatermark,defineCustomElement as defineCustomElementKritzelWatermark}from"./kritzel-watermark.js";export{KritzelWorkspaceManager,defineCustomElement as defineCustomElementKritzelWorkspaceManager}from"./kritzel-workspace-manager.js";export{KritzelZoomPanel,defineCustomElement as defineCustomElementKritzelZoomPanel}from"./kritzel-zoom-panel.js";const z=Math.floor,p=127,y=Number.MAX_SAFE_INTEGER;class w{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const x=()=>new w,T=e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let s=0;s<e.bufs.length;s++)t+=e.bufs[s].length;return t})(e));let s=0;for(let i=0;i<e.bufs.length;i++){const n=e.bufs[i];t.set(n,s),s+=n.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),s),t},P=(e,t)=>{const s=e.cbuf.length;e.cpos===s&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*s),e.cpos=0),e.cbuf[e.cpos++]=t},v=(e,t)=>{for(;t>p;)P(e,128|p&t),t=z(t/128);P(e,p&t)},M=(e,t)=>{v(e,t.byteLength),((e,t)=>{const s=e.cbuf.length,i=e.cpos,n=((e,t)=>e<t?e:t)(s-i,t.length),o=t.length-n;e.cbuf.set(t.subarray(0,n),i),e.cpos+=n,o>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(((e,t)=>e>t?e:t)(2*s,o)),e.cbuf.set(t.subarray(n)),e.cpos=o)})(e,t)},U=e=>Error(e),_=U("Unexpected end of array"),O=U("Integer out of Range");class L{constructor(e){this.arr=e,this.pos=0}}const R=e=>((e,t)=>{const s=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,s})(e,$(e)),$=e=>{let t=0,s=1;const i=e.arr.length;for(;e.pos<i;){const i=e.arr[e.pos++];if(t+=(i&p)*s,s*=128,i<128)return t;if(t>y)throw O}throw _};class B{type="local";doc;channel;_synced=!1;constructor(e,t,s){this.doc=t,this.channel=new BroadcastChannel(e),this.channel.onmessage=e=>{this.handleMessage(e.data)},this.doc.on("update",this.handleDocUpdate),this.broadcastSync(),setTimeout((()=>{this._synced=!0}),100),s?.quiet||console.info("BroadcastChannel Provider initialized: "+e)}handleDocUpdate=(e,t)=>{if(t!==this){const t=x();v(t,0),M(t,e),this.channel.postMessage(T(t))}};handleMessage(e){const s=(e=>new L(e))(new Uint8Array(e));switch($(s)){case 0:const e=R(s);t.applyUpdate(this.doc,e,this);break;case 1:this.broadcastSync();break;case 2:const i=R(s),n=t.encodeStateAsUpdate(this.doc,i);if(n.length>0){const e=x();v(e,0),M(e,n),this.channel.postMessage(T(e))}}}broadcastSync(){const e=x();v(e,2),M(e,t.encodeStateVector(this.doc)),this.channel.postMessage(T(e))}async connect(){if(!this._synced)return new Promise((e=>{const t=()=>{this._synced?e():setTimeout(t,50)};t()}))}disconnect(){}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.doc.off("update",this.handleDocUpdate),this.channel.close()}}const N=new Map;class H{type="local";doc;cacheKey;isConnected=!1;constructor(e,t,s){this.doc=t,this.cacheKey=s?.name??e}handleUpdate=(e,s)=>{s!==this&&N.set(this.cacheKey,t.encodeStateAsUpdate(this.doc))};async connect(){if(this.isConnected)return;const e=N.get(this.cacheKey);e&&t.applyUpdate(this.doc,e,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(e){void 0!==e?N.delete(e):N.clear()}}class G{type="local";provider;isConnected=!1;constructor(e,t,s){this.provider=new n(s?.name||e,t)}async connect(){if(!this.isConnected)return new Promise((e=>{this.provider.on("synced",(()=>{this.isConnected=!0,e()}))}))}disconnect(){this.isConnected=!1}async reconnect(){return this.disconnect(),this.connect()}destroy(){this.provider&&this.provider.destroy(),this.isConnected=!1}}class V{type="network";provider;isConnected=!1;_quiet=!1;get awareness(){return this.provider.awareness}constructor(e,t,s){const i=s?.url||"ws://localhost:1234",n=s?.roomName||e;this.provider=new o(i,n,t,{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(e){return{create:(t,s,i)=>{const n=i?{...e,...i}:e;return new V(t,s,n)}}}setupEventListeners(){this.provider.on("status",(({status:e})=>{"connected"===e?(this.isConnected=!0,this._quiet||console.info("WebSocket connected")):"disconnected"===e&&(this.isConnected=!1,this._quiet||console.info("WebSocket disconnected"))})),this.provider.on("sync",(e=>{e&&!this._quiet&&console.info("WebSocket synced")}))}async connect(){if(!this.isConnected)return new Promise(((e,t)=>{const s=setTimeout((()=>{t(Error("WebSocket connection timeout"))}),1e4),i=({status:t})=>{"connected"===t&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,e())};this.provider.on("status",i),this.provider.wsconnected&&(clearTimeout(s),this.provider.off("status",i),this.isConnected=!0,e())}))}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 X{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(e,t,s){const i=s?.name||e,n=s?.url||"ws://localhost:1234";this.connectionTimeoutMs=s?.connectionTimeout??1e4;const o=s?.websocketProvider||X.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 l=()=>{this.isDestroyed||(this.isConnected=!0,this._connectionStatus="connected",s?.quiet||console.info("Hocuspocus connected: "+i),s?.onConnect&&s.onConnect())},a=()=>{this.isDestroyed||(this.isConnected=!1,this.isSynced=!1,this._connectionStatus="disconnected",s?.quiet||console.info("Hocuspocus disconnected: "+i),s?.onDisconnect&&s.onDisconnect())},c=()=>{this.isDestroyed||(this.isSynced=!0,this._connectionStatus="synced",s?.quiet||console.info("Hocuspocus synced: "+i),s?.onSynced&&s.onSynced())},d=e=>{this.isDestroyed||("connecting"===e.status&&(this._connectionStatus="connecting"),s?.onStatus&&s.onStatus(e))};if(o){this.usesSharedSocket=!0;const e={websocketProvider:o,name:i,document:t,token:s?.token||null,onStatus:d,onConnect:l,onDisconnect:a,onSynced:c,...r};void 0!==s?.forceSyncInterval&&(e.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(e.onAuthenticationFailed=s.onAuthenticationFailed),this.provider=new m(e),this.provider.attach(),s?.quiet||console.info("Hocuspocus Provider initialized (multiplexed): "+i)}else{this.usesSharedSocket=!1;const e={url:n,name:i,document:t,token:s?.token||null,autoConnect:!1,onStatus:d,onConnect:l,onDisconnect:a,onSynced:c,...r};void 0!==s?.forceSyncInterval&&(e.forceSyncInterval=s.forceSyncInterval),s?.onAuthenticationFailed&&(e.onAuthenticationFailed=s.onAuthenticationFailed),s?.WebSocketPolyfill&&(e.WebSocketPolyfill=s.WebSocketPolyfill),this.provider=new m(e),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(e){if(X.sharedWebSocketProvider)return console.warn("Shared WebSocket already exists. Returning existing instance."),X.sharedWebSocketProvider;const t={url:e.url};return e.WebSocketPolyfill&&(t.WebSocketPolyfill=e.WebSocketPolyfill),e.onConnect&&(t.onConnect=e.onConnect),e.onDisconnect&&(t.onDisconnect=e.onDisconnect),e.onStatus&&(t.onStatus=e.onStatus),X.sharedWebSocketProvider=new u(t),console.info("Shared Hocuspocus WebSocket created: "+e.url),X.sharedWebSocketProvider}static destroySharedWebSocket(){X.sharedWebSocketProvider&&(X.sharedWebSocketProvider.destroy(),X.sharedWebSocketProvider=null,console.info("Shared Hocuspocus WebSocket destroyed"))}static getSharedWebSocket(){return X.sharedWebSocketProvider}static with(e){return{create:(t,s,i)=>{const n=i?{...e,...i}:e;return new X(t,s,n)}}}async connect(){if(!this.isSynced&&!this.isDestroyed)return this._connectionStatus="connecting",new Promise(((e,t)=>{this.pendingConnectReject=t,this.connectTimeout=setTimeout((()=>{this.pendingConnectReject=null,this.connectTimeout=null,t(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||e()};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 e();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 q{type="remote";name="HttpAssetProvider";_options;constructor(e){this._options=e}static with(e){return{create:()=>new q(e)}}async init(){this._options.quiet||console.info("HttpAssetProvider initialized")}destroy(){}canResolve(e){return!0}async put(e,t){const s=t.id??this.generateUuid(),i={...t,id:s},n=await(this._options.headers?.())??{},o=await this._options.uploadUrl(i),r=this._options.upload??this.defaultUpload;return{id:(await r(o,e,i,n)).id??s,kind:t.kind??"file",mimeType:t.mimeType,size:e.size,createdAt:Date.now(),width:t.width,height:t.height,durationMs:t.durationMs,originalFilename:t.originalFilename}}async resolve(e){return this._options.resolveUrl(e)}async fetch(e){const t=await this._options.resolveUrl(e),s=await(this._options.headers?.())??{},i=await fetch(t,{headers:s});if(!i.ok)throw Error(`[HttpAssetProvider] Failed to fetch asset ${e}: ${i.status} ${i.statusText}`);return i.blob()}async delete(e){if(!this._options.deleteUrl)return;const t=await this._options.deleteUrl(e),s=await(this._options.headers?.())??{},i=await fetch(t,{method:"DELETE",headers:s});if(!i.ok)throw Error(`[HttpAssetProvider] Failed to delete asset ${e}: ${i.status} ${i.statusText}`);this._options.quiet||console.info("HttpAssetProvider: deleted asset "+e)}defaultUpload=async(e,t,s,i)=>{const n=new FormData;n.append("metadata",JSON.stringify(s)),n.append("file",t,s.originalFilename||`${s.id}.${this.extensionFromMime(s.mimeType)}`);const o=await fetch(e,{method:"POST",headers:i,body:n});if(!o.ok)throw Error(`[HttpAssetProvider] Upload failed: ${o.status} ${o.statusText}`);return(o.headers.get("content-type")||"").includes("application/json")?await o.json():{}};extensionFromMime(e){const t=e.indexOf("/");return t>=0?e.slice(t+1):"bin"}generateUuid(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=crypto.getRandomValues(new Uint8Array(16));e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}}class J{type="remote";name="PresignedAssetProvider";_options;constructor(e){this._options=e}static with(e){return{create:()=>new J(e)}}async init(){this._options.quiet||console.info("PresignedAssetProvider initialized")}destroy(){}canResolve(e){return!0}async put(e,t){const s=await this._options.getUploadDescriptor(t),i=s.method??"PUT",n={...s.headers??{}};let o;if(n["Content-Type"]||n["content-type"]||(n["Content-Type"]=t.mimeType),"POST"===i&&s.fields){const t=new FormData;for(const[e,i]of Object.entries(s.fields))t.append(e,i);t.append("file",e),o=t,delete n["Content-Type"],delete n["content-type"]}else o=e;const r=await fetch(s.url,{method:i,headers:n,body:o});if(!r.ok)throw Error(`[PresignedAssetProvider] Upload failed: ${r.status} ${r.statusText}`);return{id:s.id,kind:t.kind??"file",mimeType:t.mimeType,size:e.size,createdAt:Date.now(),width:t.width,height:t.height,durationMs:t.durationMs,originalFilename:t.originalFilename}}async resolve(e){return this._options.getDownloadUrl(e)}async fetch(e){const t=await this._options.getDownloadUrl(e),s=await fetch(t);if(!s.ok)throw Error(`[PresignedAssetProvider] Failed to fetch asset ${e}: ${s.status} ${s.statusText}`);return s.blob()}async delete(e){this._options.deleteAsset&&(await this._options.deleteAsset(e),this._options.quiet||console.info("PresignedAssetProvider: deleted asset "+e))}}export{B as BroadcastSyncProvider,X as HocuspocusSyncProvider,q as HttpAssetProvider,H as InMemorySyncProvider,G as IndexedDBSyncProvider,J as PresignedAssetProvider,V as WebSocketSyncProvider}
|