@widgetic/canvas 0.5.28 → 0.5.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.
@@ -887,6 +887,130 @@
887
887
  canvas.requestRenderAll();
888
888
  }
889
889
  }
890
+
891
+ /** Screenshot of every shape on the board, cropped to their bounds. */
892
+ export async function captureCanvasSketch(): Promise<string> {
893
+ if (!canvas) return '';
894
+ // Do not discard an ActiveSelection: Fabric 6 empties it on deselect.
895
+ // Selection handles sit on the upper canvas, so toDataURL leaves them out.
896
+ const objects = canvas.getObjects().filter((object: any) => object.visible !== false && !object.excludeFromExport);
897
+ if (objects.length === 0) return '';
898
+ let left = Infinity;
899
+ let top = Infinity;
900
+ let right = -Infinity;
901
+ let bottom = -Infinity;
902
+ for (const object of objects) {
903
+ const bounds = object.getBoundingRect();
904
+ left = Math.min(left, bounds.left);
905
+ top = Math.min(top, bounds.top);
906
+ right = Math.max(right, bounds.left + bounds.width);
907
+ bottom = Math.max(bottom, bounds.top + bounds.height);
908
+ }
909
+ if (!Number.isFinite(left) || right <= left || bottom <= top) return '';
910
+ skipGroupIdleOutline = true;
911
+ skipTextPlaceholder = true;
912
+ try {
913
+ canvas.renderAll();
914
+ const dataUrl = canvas.toDataURL({
915
+ format: 'png',
916
+ multiplier: 2,
917
+ left: Math.floor(left),
918
+ top: Math.floor(top),
919
+ width: Math.max(1, Math.ceil(right - left)),
920
+ height: Math.max(1, Math.ceil(bottom - top)),
921
+ });
922
+ canvasLog('Canvas sketch captured', { shapes: objects.length, bytes: dataUrl.length });
923
+ return dataUrl;
924
+ } catch (captureError) {
925
+ console.error('Canvas: captureCanvasSketch failed', captureError);
926
+ return '';
927
+ } finally {
928
+ skipGroupIdleOutline = false;
929
+ skipTextPlaceholder = false;
930
+ canvas.requestRenderAll();
931
+ }
932
+ }
933
+
934
+ /**
935
+ * Turn the whole board into one WidgetShape. A board that is already only
936
+ * this widget is left as it is.
937
+ */
938
+ export async function absorbCanvasSketchIntoWidget(
939
+ widgetId: string,
940
+ screenshotDataUrl: string
941
+ ): Promise<string | null> {
942
+ if (!canvas || !widgetId) return null;
943
+ try {
944
+ canvas.discardActiveObject();
945
+ } catch (discardError) {
946
+ console.warn('Canvas: discard before sketch absorb failed', discardError);
947
+ }
948
+ const objects = canvas.getObjects().filter((object: any) => !object.excludeFromExport);
949
+ // A text-only prompt has nothing to absorb. The live preview still needs a
950
+ // frame, so the board gets the same placeholder a shape would have had.
951
+ if (objects.length === 0) {
952
+ canvasLog('Canvas: empty board, placing a preview frame', widgetId.substring(0, 8));
953
+ return addWidgetShape(widgetId, undefined, 0, 1, screenshotDataUrl || null);
954
+ }
955
+ const alreadyThisWidget = objects.every((object: any) => object._isWidgetImage && object._widgetId === widgetId);
956
+ if (alreadyThisWidget) {
957
+ return (objects[0] as any)._objectId ?? null;
958
+ }
959
+ let left = Infinity;
960
+ let top = Infinity;
961
+ let right = -Infinity;
962
+ let bottom = -Infinity;
963
+ for (const object of objects) {
964
+ const bounds = object.getBoundingRect();
965
+ left = Math.min(left, bounds.left);
966
+ top = Math.min(top, bounds.top);
967
+ right = Math.max(right, bounds.left + bounds.width);
968
+ bottom = Math.max(bottom, bounds.top + bounds.height);
969
+ }
970
+ const bounds = {
971
+ left: Number.isFinite(left) ? left : 80,
972
+ top: Number.isFinite(top) ? top : 80,
973
+ width: Math.max(120, right - left),
974
+ height: Math.max(80, bottom - top),
975
+ };
976
+ for (const object of objects) canvas.remove(object);
977
+ const widgetImage = createImagePlaceholder({
978
+ left: bounds.left,
979
+ top: bounds.top,
980
+ width: bounds.width,
981
+ height: bounds.height,
982
+ }) as any;
983
+ upgradeToWidgetShape(widgetImage);
984
+ clearWidgetShapeDefaultBorder(widgetImage);
985
+ lockWidgetShapeBodyDrag(widgetImage);
986
+ const newObjectId = `widget_img_${Date.now()}`;
987
+ widgetImage._objectId = newObjectId;
988
+ widgetImage._customType = 'image';
989
+ widgetImage._widgetId = widgetId;
990
+ widgetImage._imageUrl = screenshotDataUrl;
991
+ widgetImage._hasImage = !!screenshotDataUrl;
992
+ widgetImage._originalFilename = 'widget-screenshot.png';
993
+ canvas.add(widgetImage);
994
+ if (screenshotDataUrl) {
995
+ const image = new Image();
996
+ image.onload = () => {
997
+ widgetImage._imageElement = image;
998
+ widgetImage._originalAspectRatio = image.width / image.height;
999
+ widgetImage.dirty = true;
1000
+ canvas?.requestRenderAll();
1001
+ takeHistorySnapshot();
1002
+ };
1003
+ image.onerror = () => {
1004
+ console.error('Canvas: Failed to load canvas sketch into WidgetShape');
1005
+ };
1006
+ image.src = screenshotDataUrl;
1007
+ }
1008
+ canvas.setActiveObject(widgetImage);
1009
+ selectedObject = widgetImage;
1010
+ canvas.requestRenderAll();
1011
+ canvasLog('Canvas sketch absorbed into one WidgetShape', { widgetId, objectId: newObjectId });
1012
+ return newObjectId;
1013
+ }
890
1014
 
891
1015
  // Extract metadata from object for onObjectClick callback
892
1016
  function extractObjectMetadata(target: any): Record<string, any> {
@@ -2748,12 +2872,15 @@
2748
2872
  upgradeToImageShape(obj);
2749
2873
  if ((obj as any)._isWidgetImage) {
2750
2874
  lockWidgetShapeBodyDrag(obj);
2751
- if ((obj as any)._isPrimaryWidget) {
2875
+ applyWidgetShapeChrome(obj);
2876
+ if ((obj as any)._isPrimaryWidget && advancedFeatures) {
2752
2877
  obj.set({
2753
2878
  stroke: PRIMARY_WIDGET_STROKE,
2754
2879
  strokeWidth: PRIMARY_WIDGET_STROKE_WIDTH,
2755
2880
  strokeDashArray: null,
2756
2881
  });
2882
+ } else if (!advancedFeatures) {
2883
+ obj.set({ stroke: 'transparent', strokeWidth: 0, strokeDashArray: null });
2757
2884
  }
2758
2885
  }
2759
2886
  canvasLog('Canvas: object:added — upgraded image shape for', (obj as any)._objectId || 'image');
@@ -6589,6 +6716,39 @@
6589
6716
  refreshTextShapeChrome();
6590
6717
  }
6591
6718
 
6719
+ /**
6720
+ * Simple canvas: corner handles stay. Rotate and the mid-edge scales do not.
6721
+ * Advanced turns those handles back on.
6722
+ */
6723
+ function applyWidgetShapeChrome(obj: any) {
6724
+ if (!obj?._isWidgetImage || typeof obj.setControlsVisibility !== 'function') return;
6725
+ obj.setControlsVisibility({
6726
+ ml: !!advancedFeatures,
6727
+ mr: !!advancedFeatures,
6728
+ mt: !!advancedFeatures,
6729
+ mb: !!advancedFeatures,
6730
+ mtr: !!advancedFeatures,
6731
+ tl: true,
6732
+ tr: true,
6733
+ bl: true,
6734
+ br: true,
6735
+ });
6736
+ }
6737
+
6738
+ function refreshWidgetShapeChrome() {
6739
+ if (!canvas) return;
6740
+ for (const obj of canvas.getObjects()) applyWidgetShapeChrome(obj);
6741
+ const primary = canvas.getObjects().find((object: any) => object._isWidgetImage && object._isPrimaryWidget) as any;
6742
+ applyPrimaryWidgetStrokes(primary?._widgetId ?? null);
6743
+ canvas.requestRenderAll();
6744
+ }
6745
+
6746
+ let widgetChromeAdvanced: boolean | null = null;
6747
+ $: if (canvas && widgetChromeAdvanced !== advancedFeatures) {
6748
+ widgetChromeAdvanced = advancedFeatures;
6749
+ refreshWidgetShapeChrome();
6750
+ }
6751
+
6592
6752
  /** Fold a uniform scale into fontSize so the glyphs are redrawn, not stretched. */
6593
6753
  function bakeTextboxScaleIntoFont(tb: any) {
6594
6754
  if (!tb || tb.type !== 'textbox' || tb._bakingTextScale) return;
@@ -8493,7 +8653,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
8493
8653
  if (!anyObj._isWidgetImage) continue;
8494
8654
  const isPrimary = !!(primaryWidgetId && anyObj._widgetId === primaryWidgetId);
8495
8655
  anyObj._isPrimaryWidget = isPrimary;
8496
- if (isPrimary) {
8656
+ if (isPrimary && advancedFeatures) {
8497
8657
  obj.set({
8498
8658
  stroke: PRIMARY_WIDGET_STROKE,
8499
8659
  strokeWidth: PRIMARY_WIDGET_STROKE_WIDTH,
@@ -12721,10 +12881,11 @@ function checkAndAddNewShapeToFrame(shape: any) {
12721
12881
  />
12722
12882
 
12723
12883
  {#if canvas && widgetSelectionLayerTarget}
12724
- <WidgetSelectionLayer fabricCanvas={canvas} target={widgetSelectionLayerTarget} />
12884
+ <WidgetSelectionLayer fabricCanvas={canvas} target={widgetSelectionLayerTarget} {advancedFeatures} />
12725
12885
  {/if}
12726
12886
 
12727
- <!-- Preserve the panel wrapper and dismissal state throughout selection changes. -->
12887
+ <!-- Props and Convert stay in the code. The simple canvas hides them until Advanced is on. -->
12888
+ {#if advancedFeatures}
12728
12889
  <PropsPanel
12729
12890
  {selectedObject}
12730
12891
  {wireframeMode}
@@ -12790,6 +12951,7 @@ function checkAndAddNewShapeToFrame(shape: any) {
12790
12951
  onWidthChange={updateSelectedWidth}
12791
12952
  onHeightChange={updateSelectedHeight}
12792
12953
  />
12954
+ {/if}
12793
12955
 
12794
12956
  <!-- Custom Context Menu (shown on right-click) -->
12795
12957
  <ContextMenu
@@ -68,6 +68,8 @@ declare const Canvas: $$__sveltets_2_IsomorphicComponent<{
68
68
  */ locale?: string | null;
69
69
  messages?: Readonly<Record<string, unknown>> | null;
70
70
  shapeFillColor?: () => string;
71
+ captureCanvasSketch?: () => Promise<string>;
72
+ absorbCanvasSketchIntoWidget?: (widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
71
73
  deselectAll?: () => void;
72
74
  duplicateSelectedObjects?: () => Promise<void>;
73
75
  deleteSelectedObjects?: () => Promise<void>;
@@ -164,6 +166,8 @@ declare const Canvas: $$__sveltets_2_IsomorphicComponent<{
164
166
  [evt: string]: CustomEvent<any>;
165
167
  }, {}, {
166
168
  shapeFillColor: () => string;
169
+ captureCanvasSketch: () => Promise<string>;
170
+ absorbCanvasSketchIntoWidget: (widgetId: string, screenshotDataUrl: string) => Promise<string | null>;
167
171
  deselectAll: () => void;
168
172
  duplicateSelectedObjects: () => Promise<void>;
169
173
  deleteSelectedObjects: () => Promise<void>;
@@ -75,7 +75,7 @@
75
75
  /** Draw-to-place: activates library shape tool so user clicks-and-drags to size it. */
76
76
  export let onSelectLibraryShapeTool: (shapeKey: string, pathData: string) => void = () => {};
77
77
 
78
- /** Extra tools (undo/redo/lock). Code stays; UI is gated. */
78
+ /** Extra tools (undo, redo, lock, shapes). Arrow stays on the simple bar. */
79
79
  export let advancedFeatures: boolean = false;
80
80
  /**
81
81
  * When true (default) and advancedFeatures is on, Frame / Image / Video sit on the toolbar.
@@ -106,6 +106,8 @@
106
106
  // When a library shape was last selected, store its info for the trigger button
107
107
  let lastSelectedLibraryShape: LibraryShape | null = null;
108
108
  let shapesDropdownOpen = false;
109
+ // The shapes menu is part of the advanced toolbar. Close it when that mode turns off.
110
+ $: if (!advancedFeatures) shapesDropdownOpen = false;
109
111
  let shapesDropdownNeedsScroll = false;
110
112
  // DEV FLAG: when true the dropdown stays open after selecting a shape so
111
113
  // multiple shapes can be placed in a row. Set to false for production.
@@ -483,7 +485,6 @@
483
485
  so dropdowns and tooltips are rendered as siblings OUTSIDE this div -->
484
486
  <div class="tools-ct flex flex-row">
485
487
  {#if advancedFeatures}
486
- <!-- ── Utility cluster: Undo, Redo, Hand, Lock | Divider ── -->
487
488
  <Tooltip text={$t('canvas.tool.undoTitle')}>
488
489
  <div class="disabled-tooltip-wrap">
489
490
  <button
@@ -682,7 +683,8 @@
682
683
  </Tooltip>
683
684
  {/if}
684
685
 
685
- <!-- Shapes: tldraw-style split — left activates tool, right opens dropdown. Always available. -->
686
+ <!-- Shapes: tldraw-style split — left activates tool, right opens dropdown. Advanced only. -->
687
+ {#if advancedFeatures}
686
688
  <div class="shapes-split-ct" bind:this={dropdownTriggerEl}>
687
689
  <Tooltip text={dropdownButtonTooltip}>
688
690
  <button
@@ -713,6 +715,7 @@
713
715
  </button>
714
716
  </Tooltip>
715
717
  </div>
718
+ {/if}
716
719
  </div>
717
720
  </div>
718
721
 
@@ -45,7 +45,7 @@ declare const CanvasToolbar: $$__sveltets_2_IsomorphicComponent<{
45
45
  /** Passed by Canvas.svelte but never read here — export const keeps the
46
46
  * init-set contract without the unused-reactive warning. */ onInsertLibraryShape?: (shapeKey: string, pathData: string) => void;
47
47
  /** Draw-to-place: activates library shape tool so user clicks-and-drags to size it. */ onSelectLibraryShapeTool?: (shapeKey: string, pathData: string) => void;
48
- /** Extra tools (undo/redo/lock). Code stays; UI is gated. */ advancedFeatures?: boolean;
48
+ /** Extra tools (undo, redo, lock, shapes). Arrow stays on the simple bar. */ advancedFeatures?: boolean;
49
49
  /**
50
50
  * When true (default) and advancedFeatures is on, Frame / Image / Video sit on the toolbar.
51
51
  * When false, they leave the bar and appear under More Shapes → Media Shapes.
@@ -4,7 +4,7 @@
4
4
  import { Portal } from '@widgetic/design-system';
5
5
  import { canvasWarn } from './canvasLogger';
6
6
 
7
- let { fabricCanvas, target, class: className = '', style = '' }: { fabricCanvas: Canvas; target: string; class?: string; style?: string } = $props();
7
+ let { fabricCanvas, target, advancedFeatures = true, class: className = '', style = '' }: { fabricCanvas: Canvas; target: string; advancedFeatures?: boolean; class?: string; style?: string } = $props();
8
8
  let drawingCanvas: HTMLCanvasElement | null = null;
9
9
  function captureDrawingCanvas(node: HTMLCanvasElement) {
10
10
  drawingCanvas = node;
@@ -76,8 +76,8 @@
76
76
  const retina = fabricCanvas.getRetinaScaling();
77
77
  context.setTransform(retina, 0, 0, retina, 0, 0);
78
78
  // Red primary stroke is part of the object, not the selection border.
79
- // Paint it with the same viewport/object matrices above the HTML preview.
80
- if ((selected as any)._isPrimaryWidget && selected.strokeWidth) {
79
+ // The simple canvas hides it. Advanced paints it above the HTML preview.
80
+ if (advancedFeatures && (selected as any)._isPrimaryWidget && selected.strokeWidth) {
81
81
  context.save();
82
82
  context.transform(...fabricCanvas.viewportTransform);
83
83
  context.transform(...selected.calcTransformMatrix());
@@ -93,14 +93,24 @@
93
93
  // Fabric's internal control geometry (oCoords/controls) isn't on the
94
94
  // public FabricObject type; this layer re-renders it as hit regions.
95
95
  const sel = selected as any;
96
+ const hiddenWhenSimple = new Set(['ml', 'mr', 'mt', 'mb', 'mtr']);
96
97
  controls = Object.entries(sel.oCoords || {}).flatMap(([key, position]: [string, any]) => {
97
98
  const control = sel.controls[key];
99
+ if (!advancedFeatures && hiddenWhenSimple.has(key)) return [];
98
100
  if (!sel.hasControls || !control?.getVisibility(sel, key)) return [];
99
101
  const points = position.corner;
100
102
  return [{ key, points: ['tl', 'tr', 'br', 'bl'].map(corner => `${points[corner].x * scaleX},${points[corner].y * scaleY}`).join(' '), cursor: control.cursorStyleHandler({}, control, sel) }];
101
103
  });
102
104
  }
103
105
 
106
+ // The board flips Advanced after this layer is already mounted. Repaint once
107
+ // the flag has landed, so a render that raced the prop does not leave the
108
+ // rotate handle or the red stroke up.
109
+ $effect(() => {
110
+ void advancedFeatures;
111
+ if (drawingCanvas) redraw();
112
+ });
113
+
104
114
  onMount(() => {
105
115
  let animationFrame = 0;
106
116
  function scheduleRedraw() {
@@ -2,6 +2,7 @@ import type { Canvas } from 'fabric';
2
2
  type $$ComponentProps = {
3
3
  fabricCanvas: Canvas;
4
4
  target: string;
5
+ advancedFeatures?: boolean;
5
6
  class?: string;
6
7
  style?: string;
7
8
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@widgetic/canvas",
3
- "version": "0.5.28",
3
+ "version": "0.5.29",
4
4
  "license": "SEE LICENSE IN LICENSE",
5
5
  "type": "module",
6
6
  "svelte": "./dist/index.js",