@r2digisolutions/components 0.24.2 → 0.24.4

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.
@@ -335,6 +335,7 @@
335
335
  flush
336
336
  clipContent={layer.kind === 'text' || layer.kind === 'sticky' ? !textAuto : true}
337
337
  handleStyle="canva"
338
+ snapMode="live"
338
339
  hugContent={textAuto}
339
340
  hugMaxWidth={layer.textMaxWidth ?? 0}
340
341
  resizeEdges={textAuto ? [...TEXT_RESIZE_EDGES] : undefined}
@@ -332,14 +332,15 @@
332
332
  const gridOverlayStyle = $derived.by(() => {
333
333
  const cell = Math.max(4, cellSize);
334
334
  const major = cell * 5;
335
- const fine = 'color-mix(in oklab, #0f172a 18%, transparent)';
336
- const bold = 'color-mix(in oklab, #0f172a 32%, transparent)';
335
+ const line = 1 / Math.max(0.05, scale);
336
+ const fine = 'color-mix(in oklab, #0f172a 28%, transparent)';
337
+ const bold = 'color-mix(in oklab, #0f172a 48%, transparent)';
337
338
  return [
338
339
  `background-image:`,
339
- `linear-gradient(to right, ${fine} 1px, transparent 1px),`,
340
- `linear-gradient(to bottom, ${fine} 1px, transparent 1px),`,
341
- `linear-gradient(to right, ${bold} 1px, transparent 1px),`,
342
- `linear-gradient(to bottom, ${bold} 1px, transparent 1px);`,
340
+ `linear-gradient(to right, ${fine} ${line}px, transparent ${line}px),`,
341
+ `linear-gradient(to bottom, ${fine} ${line}px, transparent ${line}px),`,
342
+ `linear-gradient(to right, ${bold} ${line}px, transparent ${line}px),`,
343
+ `linear-gradient(to bottom, ${bold} ${line}px, transparent ${line}px);`,
343
344
  `background-size:${cell}px ${cell}px, ${cell}px ${cell}px, ${major}px ${major}px, ${major}px ${major}px;`
344
345
  ].join('');
345
346
  });
@@ -1358,14 +1359,6 @@
1358
1359
  <div class="inset-0 absolute" style:background-color={doc.background}></div>
1359
1360
  </div>
1360
1361
 
1361
- {#if showGrid}
1362
- <div
1363
- class="inset-0 pointer-events-none absolute z-100 overflow-hidden"
1364
- style={gridOverlayStyle}
1365
- aria-hidden="true"
1366
- ></div>
1367
- {/if}
1368
-
1369
1362
  <div class={['inset-0 absolute overflow-visible', drawMode && 'pointer-events-none']}>
1370
1363
  {#each sorted as layer, paintIndex (layer.id)}
1371
1364
  {#if effectivelyVisible.has(layer.id)}
@@ -1493,6 +1486,7 @@
1493
1486
  showChrome={false}
1494
1487
  flush
1495
1488
  handleStyle="canva"
1489
+ snapMode="live"
1496
1490
  handlesVisible={true}
1497
1491
  raiseOnSelect={false}
1498
1492
  stackIndex={999999}
@@ -1580,6 +1574,14 @@
1580
1574
  {/if}
1581
1575
  {/each}
1582
1576
  </div>
1577
+ {#if showGrid}
1578
+ <div
1579
+ class="pointer-events-none absolute inset-0 overflow-hidden"
1580
+ style:z-index="2000000"
1581
+ style={gridOverlayStyle}
1582
+ aria-hidden="true"
1583
+ ></div>
1584
+ {/if}
1583
1585
  </div>
1584
1586
  </div>
1585
1587
  </div>
@@ -1600,13 +1602,14 @@
1600
1602
  <div
1601
1603
  data-guide={guide.id}
1602
1604
  class={[
1603
- 'absolute z-40',
1605
+ 'absolute',
1604
1606
  guide.orientation === 'vertical'
1605
1607
  ? 'w-2 -translate-x-1/2 cursor-col-resize'
1606
1608
  : 'h-2 -translate-y-1/2 cursor-row-resize',
1607
1609
  locked && 'cursor-default',
1608
1610
  hiding && 'opacity-0'
1609
1611
  ]}
1612
+ style:z-index="2100000"
1610
1613
  style:left={guide.orientation === 'vertical'
1611
1614
  ? `${RULER_LEFT + tickX(guide.position)}px`
1612
1615
  : `${originX}px`}
@@ -161,6 +161,8 @@
161
161
  }: WidgetFrameProps = $props();
162
162
 
163
163
  const canvas = getContext<WidgetCanvasContext | undefined>(WIDGET_CANVAS_CONTEXT);
164
+ /** Document pixels per screen pixel, so chrome stays the same size when the artboard is zoomed. */
165
+ const ui = $derived(1 / Math.max(0.05, canvas?.scale || 1));
164
166
 
165
167
  let mode = $state<'move' | 'resize' | null>(null);
166
168
  let rotating = $state(false);
@@ -647,7 +649,7 @@
647
649
  !isCanva && showChrome && 'rounded-xl border-border bg-surface-elevated overflow-hidden border',
648
650
  !isCanva && !showChrome && 'bg-transparent',
649
651
  isCanva && 'bg-transparent',
650
- canvaBorder && 'outline outline-2 outline-[#3b82f6]',
652
+ canvaBorder && 'outline outline-[#3b82f6]',
651
653
  freeform ? 'shadow-md absolute' : 'relative',
652
654
  isCanva && 'shadow-none',
653
655
  mode === 'move' && 'cursor-grabbing opacity-95',
@@ -656,6 +658,7 @@
656
658
  frameClassName
657
659
  ]}
658
660
  style={rootStyle}
661
+ style:outline-width={canvaBorder ? `${2 * ui}px` : undefined}
659
662
  onpointerdown={(e) => {
660
663
  bringToFront();
661
664
  if (!showChrome && freeform && draggable && e.button === 0) {
@@ -814,14 +817,21 @@
814
817
 
815
818
  {#if isCanva && mode === 'resize'}
816
819
  <div
817
- class="rounded-md bg-neutral-900 px-2 py-1 font-medium text-white top-0 shadow-md pointer-events-none absolute left-1/2 z-30 -translate-x-1/2 -translate-y-[calc(100%+8px)] text-[11px] whitespace-nowrap"
820
+ class="rounded-md bg-neutral-900 font-medium text-white top-0 shadow-md pointer-events-none absolute left-1/2 z-30 whitespace-nowrap"
821
+ style:padding="{4 * ui}px {8 * ui}px"
822
+ style:font-size="{11 * ui}px"
823
+ style:transform="translate(-50%, calc(-100% - {8 * ui}px))"
818
824
  >
819
825
  {Math.round(rect.w)} × {Math.round(hugContent && hugLiveH > 0 ? hugLiveH : rect.h)}
820
826
  </div>
821
827
  {/if}
822
828
  {#if isCanva && rotating}
823
829
  <div
824
- class="rounded-md bg-neutral-900 px-2 py-1 font-medium text-white mt-8 shadow-md pointer-events-none absolute top-full left-1/2 z-30 -translate-x-1/2 text-[11px] whitespace-nowrap"
830
+ class="rounded-md bg-neutral-900 font-medium text-white shadow-md pointer-events-none absolute top-full left-1/2 z-30 whitespace-nowrap"
831
+ style:margin-top="{32 * ui}px"
832
+ style:padding="{4 * ui}px {8 * ui}px"
833
+ style:font-size="{11 * ui}px"
834
+ style:transform="translateX(-50%)"
825
835
  >
826
836
  {Math.round(rotation)}°
827
837
  </div>
@@ -832,6 +842,9 @@
832
842
  <div
833
843
  data-resize-handle
834
844
  class={[edgeAccent, h.class]}
845
+ style:width={isCanva ? `${12 * ui}px` : undefined}
846
+ style:height={isCanva ? `${12 * ui}px` : undefined}
847
+ style:border-width={isCanva ? `${2 * ui}px` : undefined}
835
848
  role="separator"
836
849
  aria-orientation={h.edge === 'e' || h.edge === 'w' ? 'vertical' : 'horizontal'}
837
850
  aria-label={`Resize ${title ?? 'widget'} (${h.edge})`}
@@ -841,13 +854,19 @@
841
854
 
842
855
  {#if isCanva && onrotation}
843
856
  <div
844
- class="h-3 pointer-events-none absolute top-full left-1/2 z-20 w-px -translate-x-1/2 bg-[#3b82f6]"
857
+ class="pointer-events-none absolute top-full left-1/2 z-20 -translate-x-1/2 bg-[#3b82f6]"
858
+ style:width="{Math.max(1, ui)}px"
859
+ style:height="{12 * ui}px"
845
860
  ></div>
846
861
  <div
847
862
  class={[
848
863
  edgeAccent,
849
- 'mt-3 h-6 w-6 top-full left-1/2 z-20 flex -translate-x-1/2 cursor-grab items-center justify-center active:cursor-grabbing'
864
+ 'top-full left-1/2 z-20 flex -translate-x-1/2 cursor-grab items-center justify-center active:cursor-grabbing'
850
865
  ]}
866
+ style:width="{24 * ui}px"
867
+ style:height="{24 * ui}px"
868
+ style:margin-top="{12 * ui}px"
869
+ style:border-width="{2 * ui}px"
851
870
  role="slider"
852
871
  tabindex="0"
853
872
  aria-label="Rotar"
@@ -870,7 +889,7 @@
870
889
  }
871
890
  }}
872
891
  >
873
- <RotateCw class="h-3 w-3 text-[#3b82f6]" />
892
+ <RotateCw width={12 * ui} height={12 * ui} class="text-[#3b82f6]" />
874
893
  </div>
875
894
  {/if}
876
895
  {#if !isCanva}
@@ -46,7 +46,7 @@ declare const meta: {
46
46
  headline: string;
47
47
  fullHeight: true;
48
48
  asideSide: "left";
49
- mobileHero: true;
49
+ mobileHero: false;
50
50
  formVariant: "card";
51
51
  formAlign: "center";
52
52
  preview: "desktop";
@@ -32,7 +32,7 @@ const meta = {
32
32
  headline: 'Sign in to continue',
33
33
  fullHeight: true,
34
34
  asideSide: 'left',
35
- mobileHero: true,
35
+ mobileHero: false,
36
36
  formVariant: 'card',
37
37
  formAlign: 'center',
38
38
  preview: 'desktop'
@@ -22,7 +22,10 @@
22
22
  fillParent?: boolean;
23
23
  /** Desktop marketing panel placement */
24
24
  asideSide?: AuthAsideSide;
25
- /** Compact gradient hero on small screens */
25
+ /**
26
+ * Compact gradient hero above the form on small screens.
27
+ * Off by default: mobile shows only the form column (the card carries the brand).
28
+ */
26
29
  mobileHero?: boolean;
27
30
  highlights?: string[];
28
31
  class?: string;
@@ -41,7 +44,7 @@
41
44
  fullHeight = true,
42
45
  fillParent = false,
43
46
  asideSide = 'left',
44
- mobileHero = true,
47
+ mobileHero = false,
45
48
  highlights = [
46
49
  'Reusable atoms, molecules, and page templates',
47
50
  'Consistent tokens across product surfaces',
@@ -174,19 +177,6 @@
174
177
  <div class="lg:hidden shrink-0">
175
178
  {@render marketingPanel(true)}
176
179
  </div>
177
- {:else}
178
- <div class="px-5 pt-6 lg:hidden shrink-0 text-center">
179
- <BrandMark
180
- name={brand}
181
- {logoSrc}
182
- {monochrome}
183
- href={brandHref}
184
- showName
185
- size="md"
186
- class="justify-center"
187
- />
188
- <p class="mt-2 text-sm text-muted">{tagline}</p>
189
- </div>
190
180
  {/if}
191
181
 
192
182
  <!-- Form column: true center in remaining space -->
@@ -17,7 +17,10 @@ interface AuthShellProps {
17
17
  fillParent?: boolean;
18
18
  /** Desktop marketing panel placement */
19
19
  asideSide?: AuthAsideSide;
20
- /** Compact gradient hero on small screens */
20
+ /**
21
+ * Compact gradient hero above the form on small screens.
22
+ * Off by default: mobile shows only the form column (the card carries the brand).
23
+ */
21
24
  mobileHero?: boolean;
22
25
  highlights?: string[];
23
26
  class?: string;
@@ -11,7 +11,7 @@
11
11
  headline = 'Sign in to continue',
12
12
  fullHeight = true,
13
13
  asideSide = 'left' as AuthAsideSide,
14
- mobileHero = true,
14
+ mobileHero = false,
15
15
  formVariant = 'card' as LoginFormVariant,
16
16
  formAlign = 'center' as 'center' | 'start',
17
17
  preview = 'desktop' as 'desktop' | 'mobile' | 'compact'
@@ -22,6 +22,7 @@
22
22
  } from '../../molecules/DropdownMenu/DropdownMenu.svelte';
23
23
  import {
24
24
  CANVAS_PRESETS,
25
+ INSTAGRAM_GRID_PRESET_ID,
25
26
  alignLayerRect,
26
27
  applyTextAutoSize,
27
28
  createCanvasGuide,
@@ -29,6 +30,7 @@
29
30
  createPathFromDocPoints,
30
31
  defaultSlotFromRect,
31
32
  emptyCanvasDocument,
33
+ instagramGridGuides,
32
34
  migrateCanvasDocument,
33
35
  presetIdForSize,
34
36
  type CanvasAlign,
@@ -135,6 +137,14 @@
135
137
  * `edit` is the full canvas: panels, menu and component search.
136
138
  */
137
139
  mode?: 'edit' | 'frame';
140
+ /** Hide the built-in menu when the host already has one. */
141
+ showMenu?: boolean;
142
+ showGrid?: boolean;
143
+ showGuides?: boolean;
144
+ snap?: boolean;
145
+ showSidebar?: boolean;
146
+ showInspector?: boolean;
147
+ stageFrame?: 'edit' | 'desktop' | 'tablet' | 'mobile';
138
148
  class?: string;
139
149
  onchange?: (doc: CanvasDocument) => void;
140
150
  onassetschange?: (assets: MediaAsset[]) => void;
@@ -150,6 +160,13 @@
150
160
  assets = $bindable<MediaAsset[]>([]),
151
161
  zoom = $bindable(1),
152
162
  mode = 'edit',
163
+ showMenu = true,
164
+ showGrid = $bindable(false),
165
+ showGuides = $bindable(true),
166
+ snap = $bindable(true),
167
+ showSidebar = $bindable(true),
168
+ showInspector = $bindable(true),
169
+ stageFrame = $bindable<'edit' | 'desktop' | 'tablet' | 'mobile'>('edit'),
153
170
  class: className = '',
154
171
  onchange,
155
172
  onassetschange,
@@ -166,14 +183,8 @@
166
183
  let selectedIds = $state<string[]>([]);
167
184
  let editingTextId = $state<string | null>(null);
168
185
  let frameBoot = false;
169
- let showSidebar = $state(true);
170
- let showInspector = $state(true);
171
186
  let assetsSize = $state(58);
172
187
  let sidebarTab = $state<'elements' | 'uploads' | 'widgets'>('elements');
173
- let showGrid = $state(false);
174
- let stageFrame = $state<'edit' | 'desktop' | 'tablet' | 'mobile'>('edit');
175
- let showGuides = $state(true);
176
- let snap = $state(true);
177
188
  let cellSize = $state(8);
178
189
  let drawMode = $state(false);
179
190
  let ctxOpen = $state(false);
@@ -731,6 +742,17 @@
731
742
  if (editingWidgetId) return;
732
743
  const preset = CANVAS_PRESETS.find((p) => p.id === id);
733
744
  if (!preset) return;
745
+ if (id === INSTAGRAM_GRID_PRESET_ID) {
746
+ emit({
747
+ ...value,
748
+ width: preset.width,
749
+ height: preset.height,
750
+ guides: instagramGridGuides(),
751
+ guidesLocked: true
752
+ });
753
+ zoom = 0.25;
754
+ return;
755
+ }
734
756
  emit({ ...value, width: preset.width, height: preset.height });
735
757
  zoom = 1;
736
758
  }
@@ -1213,7 +1235,7 @@
1213
1235
  <svelte:window onkeydowncapture={handleKeydown} />
1214
1236
 
1215
1237
  <div class={['min-h-0 relative flex h-full flex-col', className]}>
1216
- {#if mode !== 'frame'}
1238
+ {#if mode !== 'frame' && showMenu}
1217
1239
  <Menubar items={menuItems} onselect={onMenu} />
1218
1240
  {/if}
1219
1241
  <header
@@ -1238,7 +1260,8 @@
1238
1260
  <span class="text-sm font-semibold text-primary sm:inline hidden">Canvas</span>
1239
1261
  <Select
1240
1262
  size="sm"
1241
- class="w-44"
1263
+ class="min-w-72"
1264
+ listboxMinWidth={320}
1242
1265
  options={presetOptions}
1243
1266
  value={presetValue}
1244
1267
  onchange={(id) => {
@@ -10,6 +10,14 @@ interface CanvasEditorProps {
10
10
  * `edit` is the full canvas: panels, menu and component search.
11
11
  */
12
12
  mode?: 'edit' | 'frame';
13
+ /** Hide the built-in menu when the host already has one. */
14
+ showMenu?: boolean;
15
+ showGrid?: boolean;
16
+ showGuides?: boolean;
17
+ snap?: boolean;
18
+ showSidebar?: boolean;
19
+ showInspector?: boolean;
20
+ stageFrame?: 'edit' | 'desktop' | 'tablet' | 'mobile';
13
21
  class?: string;
14
22
  onchange?: (doc: CanvasDocument) => void;
15
23
  onassetschange?: (assets: MediaAsset[]) => void;
@@ -19,6 +27,6 @@ interface CanvasEditorProps {
19
27
  blob?: Blob;
20
28
  }) => void;
21
29
  }
22
- declare const CanvasEditor: import("svelte").Component<CanvasEditorProps, {}, "value" | "zoom" | "assets">;
30
+ declare const CanvasEditor: import("svelte").Component<CanvasEditorProps, {}, "value" | "zoom" | "showGrid" | "snap" | "assets" | "showGuides" | "showSidebar" | "showInspector" | "stageFrame">;
23
31
  type CanvasEditor = ReturnType<typeof CanvasEditor>;
24
32
  export default CanvasEditor;
@@ -49,7 +49,7 @@
49
49
  'Ship auth, dashboards, and marketing faster'
50
50
  ],
51
51
  asideSide = 'left',
52
- mobileHero = true,
52
+ mobileHero = false,
53
53
  fullHeight = true,
54
54
  fillParent = false,
55
55
  loading = false,
package/dist/index.d.ts CHANGED
@@ -874,7 +874,7 @@ export { msToPx, pxToMs, pxPerMsFromZoom, snapMs, clampMs, formatTimecode, ticks
874
874
  export type { TimeTick, TimeTickLevel } from './utils/mediaTime.js';
875
875
  export type { MediaAsset, MediaAssetKind, MediaClip, MediaClipAlign, MediaClipRect, MediaClipResettableField, MediaClipRectAxis, MediaTransitionPlayback, MediaTrack, MediaTrackKind } from './utils/mediaTracks.js';
876
876
  export { uid, createMediaClip, createMediaTrack, createMediaAsset, clipDurationMs, moveClip, trimClipStart, trimClipEnd, isClipActiveAt, findClipAt, updateClipInTracks, removeClipFromTracks, removeClipsFromTracks, splitClipAt, splitClipsAt, duplicateClipInTracks, mergeClipsInTracks, canMergeMediaClips, moveClipsByDelta, findClipById, nextTrackName, reorderTracks, moveTrack, removeTrack, removeTracks, defaultOverlayRect, defaultMediaClipRect, resolveClipRect, alignClipRect, alignMediaRect, clipHasSpatialRect, isMediaClipFieldModified, resetMediaClipField, findTransitionAt, transitionLayerStyle, transitionDipOverlay, resolvePreviewOpacity, resolveClipOpacity, MEDIA_CLIP_DEFAULTS, kindFromFile, probeMediaSrc } from './utils/mediaTracks.js';
877
- export { emptyCanvasDocument, createCanvasLayer, createCanvasGuide, createPathFromDocPoints, rebakePathLayer, pathPointsToDoc, reorderCanvasLayers, updateCanvasLayer, updateCanvasLayers, alignLayerRect, snapLayerRect, snapRectToGuides, migrateCanvasDocument, defaultSlotFromRect, rectFromSlot, ensureLayerSlot, canvasLayerFieldDefault, isCanvasFieldModified, resetCanvasField, applyTextAutoSize, CANVAS_PRESETS, COVER_ARTBOARD, coverDocumentFromImage, persistCoverDocument, hydrateCoverDocument, canvasLayerFilter, mediaContentBox, presetIdForSize } from './utils/canvasDocument.js';
877
+ export { emptyCanvasDocument, createCanvasLayer, createCanvasGuide, createPathFromDocPoints, rebakePathLayer, pathPointsToDoc, reorderCanvasLayers, updateCanvasLayer, updateCanvasLayers, alignLayerRect, snapLayerRect, snapRectToGuides, migrateCanvasDocument, defaultSlotFromRect, rectFromSlot, ensureLayerSlot, canvasLayerFieldDefault, isCanvasFieldModified, resetCanvasField, applyTextAutoSize, CANVAS_PRESETS, INSTAGRAM_GRID_PRESET_ID, INSTAGRAM_GRID, instagramGridGuides, emptyInstagramGridDocument, COVER_ARTBOARD, coverDocumentFromImage, persistCoverDocument, hydrateCoverDocument, canvasLayerFilter, mediaContentBox, presetIdForSize } from './utils/canvasDocument.js';
878
878
  export type { CanvasDocument, CanvasLayer, CanvasLayerKind, CanvasLayerRect, CanvasPoint, CanvasObjectFit, CanvasTextAlign, CanvasResettableField, CanvasAlign, CanvasFontStyle, CanvasTextDecoration, CanvasGuide, CanvasGuideOrientation, CanvasAnchors, CanvasSlot, CanvasExposedProp, CanvasWidgetDefinition } from './utils/canvasDocument.js';
879
879
  export { isContainerKind, canHaveChildren, getChildren, getDescendantIds, getSubtreeIds, getAncestors, enclosingGroupId, isEffectivelyVisible, isEffectivelyLocked, isLayoutPositionLocked, isLayoutSizeLocked, selectionAncestorIds, LAYOUT_POSITION_KINDS, LAYOUT_SIZE_KINDS, paintTransformForLayer, isDescendant, canReparent, ANCHOR_PRESETS, resolveSlotRect, slotFromLocalRect, translateSlot, stepAxis, computeAbsoluteRects, absoluteRectFor, reparentLayer, wrapSelection, groupLayers, ungroupLayers, layerFromAbsoluteRect, fitGroupsToChildren, scaleSubtreeAbsolute, scaleSelectionAbsolute, shouldAutoSizeChildren, topLevelSelectedIds, translateSelectionAbsolute, unionAbsRect, clampDeltaToKeepUnion, selectedAncestorId, deleteSubtree, duplicateSubtree, reorderSiblings, clipPathForLayer, scrollBoxOverflow, scrollBarMetrics, applyScrollBoxOffsets } from './utils/canvasHierarchy.js';
880
880
  export { createWidgetDefinition, createWidgetFromSelection, placeWidgetInstance, resolveWidgetInstance, flattenLayersWithWidgets, breakWidgetInstance, updateWidgetDefinition, deleteWidgetDefinition, renameWidgetDefinition, duplicateWidgetDefinition, syncInstanceSizesToDefinition, setExposedProp, isPropExposed, getExposedProp, getExposedFieldDefault, resolveExposedPropValue, groupExposedPropsByLayer, setInstanceOverride, getNamedSlotsFromDefinition, listFillableSlotsForInstance } from './utils/canvasWidget.js';
package/dist/index.js CHANGED
@@ -593,7 +593,7 @@ export { queryStringToGroup, groupToQueryString, groupToFilterItems, removeRuleF
593
593
  export { emptyBlogDocument, createBlock, createComponentBlock, serializeBlogDocument, parseBlogDocument, registerBlogComponent, unregisterBlogComponent, getBlogComponent, listBlogComponents, clearBlogComponentRegistry, NATIVE_BLOCK_TYPES, defaultDataForType, blogWidthClass, blogAlignClass, blogAspectPadding } from './utils/blogDocument.js';
594
594
  export { msToPx, pxToMs, pxPerMsFromZoom, snapMs, clampMs, formatTimecode, ticksForDuration, snapStepForZoom } from './utils/mediaTime.js';
595
595
  export { uid, createMediaClip, createMediaTrack, createMediaAsset, clipDurationMs, moveClip, trimClipStart, trimClipEnd, isClipActiveAt, findClipAt, updateClipInTracks, removeClipFromTracks, removeClipsFromTracks, splitClipAt, splitClipsAt, duplicateClipInTracks, mergeClipsInTracks, canMergeMediaClips, moveClipsByDelta, findClipById, nextTrackName, reorderTracks, moveTrack, removeTrack, removeTracks, defaultOverlayRect, defaultMediaClipRect, resolveClipRect, alignClipRect, alignMediaRect, clipHasSpatialRect, isMediaClipFieldModified, resetMediaClipField, findTransitionAt, transitionLayerStyle, transitionDipOverlay, resolvePreviewOpacity, resolveClipOpacity, MEDIA_CLIP_DEFAULTS, kindFromFile, probeMediaSrc } from './utils/mediaTracks.js';
596
- export { emptyCanvasDocument, createCanvasLayer, createCanvasGuide, createPathFromDocPoints, rebakePathLayer, pathPointsToDoc, reorderCanvasLayers, updateCanvasLayer, updateCanvasLayers, alignLayerRect, snapLayerRect, snapRectToGuides, migrateCanvasDocument, defaultSlotFromRect, rectFromSlot, ensureLayerSlot, canvasLayerFieldDefault, isCanvasFieldModified, resetCanvasField, applyTextAutoSize, CANVAS_PRESETS, COVER_ARTBOARD, coverDocumentFromImage, persistCoverDocument, hydrateCoverDocument, canvasLayerFilter, mediaContentBox, presetIdForSize } from './utils/canvasDocument.js';
596
+ export { emptyCanvasDocument, createCanvasLayer, createCanvasGuide, createPathFromDocPoints, rebakePathLayer, pathPointsToDoc, reorderCanvasLayers, updateCanvasLayer, updateCanvasLayers, alignLayerRect, snapLayerRect, snapRectToGuides, migrateCanvasDocument, defaultSlotFromRect, rectFromSlot, ensureLayerSlot, canvasLayerFieldDefault, isCanvasFieldModified, resetCanvasField, applyTextAutoSize, CANVAS_PRESETS, INSTAGRAM_GRID_PRESET_ID, INSTAGRAM_GRID, instagramGridGuides, emptyInstagramGridDocument, COVER_ARTBOARD, coverDocumentFromImage, persistCoverDocument, hydrateCoverDocument, canvasLayerFilter, mediaContentBox, presetIdForSize } from './utils/canvasDocument.js';
597
597
  export { isContainerKind, canHaveChildren, getChildren, getDescendantIds, getSubtreeIds, getAncestors, enclosingGroupId, isEffectivelyVisible, isEffectivelyLocked, isLayoutPositionLocked, isLayoutSizeLocked, selectionAncestorIds, LAYOUT_POSITION_KINDS, LAYOUT_SIZE_KINDS, paintTransformForLayer, isDescendant, canReparent, ANCHOR_PRESETS, resolveSlotRect, slotFromLocalRect, translateSlot, stepAxis, computeAbsoluteRects, absoluteRectFor, reparentLayer, wrapSelection, groupLayers, ungroupLayers, layerFromAbsoluteRect, fitGroupsToChildren, scaleSubtreeAbsolute, scaleSelectionAbsolute, shouldAutoSizeChildren, topLevelSelectedIds, translateSelectionAbsolute, unionAbsRect, clampDeltaToKeepUnion, selectedAncestorId, deleteSubtree, duplicateSubtree, reorderSiblings, clipPathForLayer, scrollBoxOverflow, scrollBarMetrics, applyScrollBoxOffsets } from './utils/canvasHierarchy.js';
598
598
  export { createWidgetDefinition, createWidgetFromSelection, placeWidgetInstance, resolveWidgetInstance, flattenLayersWithWidgets, breakWidgetInstance, updateWidgetDefinition, deleteWidgetDefinition, renameWidgetDefinition, duplicateWidgetDefinition, syncInstanceSizesToDefinition, setExposedProp, isPropExposed, getExposedProp, getExposedFieldDefault, resolveExposedPropValue, groupExposedPropsByLayer, setInstanceOverride, getNamedSlotsFromDefinition, listFillableSlotsForInstance } from './utils/canvasWidget.js';
599
599
  export { createCanvasHistory, pushCanvasHistory, undoCanvasHistory, redoCanvasHistory, serializeCanvasDoc, parseCanvasDoc } from './utils/canvasHistory.js';
@@ -236,6 +236,17 @@ export declare function canvasLayerFilter(layer: {
236
236
  contrast?: number;
237
237
  saturate?: number;
238
238
  }): string | undefined;
239
+ /** Instagram puzzle feed: 3 columns × 1080 and 3 rows × 1350 (4:5 tiles). */
240
+ export declare const INSTAGRAM_GRID_PRESET_ID = "ig-grid-3x3";
241
+ export declare const INSTAGRAM_GRID: {
242
+ readonly id: "ig-grid-3x3";
243
+ readonly cols: 3;
244
+ readonly rows: 3;
245
+ readonly cellWidth: 1080;
246
+ readonly cellHeight: 1350;
247
+ readonly width: 3240;
248
+ readonly height: 4050;
249
+ };
239
250
  export declare const CANVAS_PRESETS: readonly [{
240
251
  readonly id: "cover";
241
252
  readonly label: "Cover · 1800×600";
@@ -261,6 +272,11 @@ export declare const CANVAS_PRESETS: readonly [{
261
272
  readonly label: "Story · 1080×1920";
262
273
  readonly width: 1080;
263
274
  readonly height: 1920;
275
+ }, {
276
+ readonly id: "ig-grid-3x3";
277
+ readonly label: "Instagram 3×3 · 3240×4050";
278
+ readonly width: 3240;
279
+ readonly height: 4050;
264
280
  }, {
265
281
  readonly id: "landscape";
266
282
  readonly label: "Landscape · 1600×900";
@@ -282,6 +298,9 @@ export declare const CANVAS_PRESETS: readonly [{
282
298
  readonly width: 1600;
283
299
  readonly height: 900;
284
300
  }];
301
+ /** Locked cut lines between the nine Instagram tiles. */
302
+ export declare function instagramGridGuides(): CanvasGuide[];
303
+ export declare function emptyInstagramGridDocument(): CanvasDocument;
285
304
  export declare function presetIdForSize(width: number, height: number): string;
286
305
  /** Build a path layer from absolute document points. */
287
306
  export declare function createPathFromDocPoints(docPoints: {
@@ -498,17 +498,54 @@ export function canvasLayerFilter(layer) {
498
498
  parts.push(`saturate(${layer.saturate}%)`);
499
499
  return parts.length ? parts.join(' ') : undefined;
500
500
  }
501
+ /** Instagram puzzle feed: 3 columns × 1080 and 3 rows × 1350 (4:5 tiles). */
502
+ export const INSTAGRAM_GRID_PRESET_ID = 'ig-grid-3x3';
503
+ export const INSTAGRAM_GRID = {
504
+ id: INSTAGRAM_GRID_PRESET_ID,
505
+ cols: 3,
506
+ rows: 3,
507
+ cellWidth: 1080,
508
+ cellHeight: 1350,
509
+ width: 3240,
510
+ height: 4050
511
+ };
501
512
  export const CANVAS_PRESETS = [
502
513
  { id: 'cover', label: 'Cover · 1800×600', width: 1800, height: 600 },
503
514
  { id: 'hd', label: 'HD · 1280×720', width: 1280, height: 720 },
504
515
  { id: 'fhd', label: 'Full HD · 1920×1080', width: 1920, height: 1080 },
505
516
  { id: 'square', label: 'Instagram · 1080×1080', width: 1080, height: 1080 },
506
517
  { id: 'story', label: 'Story · 1080×1920', width: 1080, height: 1920 },
518
+ {
519
+ id: INSTAGRAM_GRID_PRESET_ID,
520
+ label: 'Instagram 3×3 · 3240×4050',
521
+ width: INSTAGRAM_GRID.width,
522
+ height: INSTAGRAM_GRID.height
523
+ },
507
524
  { id: 'landscape', label: 'Landscape · 1600×900', width: 1600, height: 900 },
508
525
  { id: 'presentation', label: 'Presentation · 1920×1080', width: 1920, height: 1080 },
509
526
  { id: 'a4', label: 'A4 · 794×1123', width: 794, height: 1123 },
510
527
  { id: 'twitter', label: 'X Post · 1600×900', width: 1600, height: 900 }
511
528
  ];
529
+ /** Locked cut lines between the nine Instagram tiles. */
530
+ export function instagramGridGuides() {
531
+ const guides = [];
532
+ for (let col = 1; col < INSTAGRAM_GRID.cols; col++) {
533
+ guides.push(createCanvasGuide('vertical', col * INSTAGRAM_GRID.cellWidth, { locked: true }));
534
+ }
535
+ for (let row = 1; row < INSTAGRAM_GRID.rows; row++) {
536
+ guides.push(createCanvasGuide('horizontal', row * INSTAGRAM_GRID.cellHeight, { locked: true }));
537
+ }
538
+ return guides;
539
+ }
540
+ export function emptyInstagramGridDocument() {
541
+ return emptyCanvasDocument({
542
+ width: INSTAGRAM_GRID.width,
543
+ height: INSTAGRAM_GRID.height,
544
+ background: '#0b1f3a',
545
+ guides: instagramGridGuides(),
546
+ guidesLocked: true
547
+ });
548
+ }
512
549
  export function presetIdForSize(width, height) {
513
550
  const match = CANVAS_PRESETS.find((p) => p.width === width && p.height === height);
514
551
  return match?.id ?? 'custom';
@@ -1,13 +1,16 @@
1
1
  /**
2
- * Minimal QR Code encoder (byte mode, ECC level M).
3
- * Generates a boolean matrix suitable for SVG rendering. No external deps.
2
+ * QR Code encoder (byte mode, ECC level M, versions 1–40). No external deps.
3
+ * Follows ISO/IEC 18004: block interleaving, version info, format info and
4
+ * mask selection by penalty score, so the output is scannable by any reader.
4
5
  */
6
+ type Matrix = boolean[][];
5
7
  /** Returns a square boolean matrix (true = dark module). */
6
- export declare function encodeQR(text: string): boolean[][];
7
- export declare function qrToSvgPath(matrix: boolean[][], cell?: number): string;
8
+ export declare function encodeQR(text: string): Matrix;
9
+ export declare function qrToSvgPath(matrix: Matrix, cell?: number): string;
8
10
  /**
9
11
  * Clears a centered square so a logo can sit in empty modules
10
12
  * instead of covering data. `ratio` is hole size relative to matrix (0–1).
11
13
  * Returns a shallow-cloned matrix.
12
14
  */
13
- export declare function punchLogoHole(matrix: boolean[][], ratio?: number): boolean[][];
15
+ export declare function punchLogoHole(matrix: Matrix, ratio?: number): Matrix;
16
+ export {};
package/dist/utils/qr.js CHANGED
@@ -1,268 +1,354 @@
1
1
  /**
2
- * Minimal QR Code encoder (byte mode, ECC level M).
3
- * Generates a boolean matrix suitable for SVG rendering. No external deps.
2
+ * QR Code encoder (byte mode, ECC level M, versions 1–40). No external deps.
3
+ * Follows ISO/IEC 18004: block interleaving, version info, format info and
4
+ * mask selection by penalty score, so the output is scannable by any reader.
4
5
  */
5
- const ECC_CODEWORDS_PER_BLOCK = {
6
- 1: 10,
7
- 2: 16,
8
- 3: 26,
9
- 4: 18,
10
- 5: 24,
11
- 6: 16,
12
- 7: 18,
13
- 8: 22,
14
- 9: 22,
15
- 10: 26
16
- };
17
- const DATA_CODEWORDS = {
18
- 1: 16,
19
- 2: 28,
20
- 3: 44,
21
- 4: 64,
22
- 5: 86,
23
- 6: 108,
24
- 7: 124,
25
- 8: 154,
26
- 9: 182,
27
- 10: 216
28
- };
29
- const ALIGNMENT = {
30
- 1: [],
31
- 2: [6, 18],
32
- 3: [6, 22],
33
- 4: [6, 26],
34
- 5: [6, 30],
35
- 6: [6, 34],
36
- 7: [6, 22, 38],
37
- 8: [6, 24, 42],
38
- 9: [6, 26, 46],
39
- 10: [6, 28, 50]
40
- };
41
- function gfMul(x, y) {
42
- if (x === 0 || y === 0)
43
- return 0;
44
- return EXP[(LOG[x] + LOG[y]) % 255];
6
+ const ECL_M_FORMAT_BITS = 0;
7
+ /** ECC codewords per block, level M, versions 1..40. */
8
+ const ECC_PER_BLOCK_M = [
9
+ 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28,
10
+ 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28
11
+ ];
12
+ /** Number of ECC blocks, level M, versions 1..40. */
13
+ const NUM_BLOCKS_M = [
14
+ 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26,
15
+ 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49
16
+ ];
17
+ function sizeOf(version) {
18
+ return version * 4 + 17;
45
19
  }
46
- const EXP = new Array(512);
47
- const LOG = new Array(256);
48
- (() => {
49
- let x = 1;
50
- for (let i = 0; i < 255; i++) {
51
- EXP[i] = x;
52
- LOG[x] = i;
53
- x <<= 1;
54
- if (x & 0x100)
55
- x ^= 0x11d;
20
+ function numRawDataModules(version) {
21
+ let result = (16 * version + 128) * version + 64;
22
+ if (version >= 2) {
23
+ const numAlign = Math.floor(version / 7) + 2;
24
+ result -= (25 * numAlign - 10) * numAlign - 55;
25
+ if (version >= 7)
26
+ result -= 36;
56
27
  }
57
- for (let i = 255; i < 512; i++)
58
- EXP[i] = EXP[i - 255];
59
- })();
60
- function rsGenerator(n) {
61
- let g = [1];
62
- for (let i = 0; i < n; i++) {
63
- const next = new Array(g.length + 1).fill(0);
64
- for (let j = 0; j < g.length; j++) {
65
- next[j] ^= g[j];
66
- next[j + 1] ^= gfMul(g[j], EXP[i]);
28
+ return result;
29
+ }
30
+ function numDataCodewords(version) {
31
+ return (Math.floor(numRawDataModules(version) / 8) -
32
+ ECC_PER_BLOCK_M[version - 1] * NUM_BLOCKS_M[version - 1]);
33
+ }
34
+ function charCountBits(version) {
35
+ return version <= 9 ? 8 : 16;
36
+ }
37
+ function chooseVersion(byteLen) {
38
+ for (let v = 1; v <= 40; v++) {
39
+ const bitsNeeded = 4 + charCountBits(v) + byteLen * 8;
40
+ if (bitsNeeded <= numDataCodewords(v) * 8)
41
+ return v;
42
+ }
43
+ throw new Error('QR payload too long');
44
+ }
45
+ function alignmentPositions(version) {
46
+ if (version === 1)
47
+ return [];
48
+ const numAlign = Math.floor(version / 7) + 2;
49
+ const size = sizeOf(version);
50
+ const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (numAlign * 2 - 2)) * 2;
51
+ const result = [6];
52
+ for (let pos = size - 7; result.length < numAlign; pos -= step)
53
+ result.splice(1, 0, pos);
54
+ return result;
55
+ }
56
+ // ---------- Reed–Solomon over GF(2^8), polynomial 0x11D ----------
57
+ function gfMul(x, y) {
58
+ let z = 0;
59
+ for (let i = 7; i >= 0; i--) {
60
+ z = (z << 1) ^ ((z >>> 7) * 0x11d);
61
+ z ^= ((y >>> i) & 1) * x;
62
+ }
63
+ return z & 0xff;
64
+ }
65
+ function rsDivisor(degree) {
66
+ const result = new Array(degree).fill(0);
67
+ result[degree - 1] = 1;
68
+ let root = 1;
69
+ for (let i = 0; i < degree; i++) {
70
+ for (let j = 0; j < result.length; j++) {
71
+ result[j] = gfMul(result[j], root);
72
+ if (j + 1 < result.length)
73
+ result[j] ^= result[j + 1];
67
74
  }
68
- g = next;
75
+ root = gfMul(root, 0x02);
69
76
  }
70
- return g;
77
+ return result;
71
78
  }
72
- function rsEncode(data, ecLen) {
73
- const gen = rsGenerator(ecLen);
74
- const res = new Array(ecLen).fill(0);
79
+ function rsRemainder(data, divisor) {
80
+ const result = new Array(divisor.length).fill(0);
75
81
  for (const b of data) {
76
- const factor = b ^ res[0];
77
- res.shift();
78
- res.push(0);
79
- for (let i = 0; i < ecLen; i++)
80
- res[i] ^= gfMul(gen[i + 1] ?? 0, factor);
82
+ const factor = b ^ result.shift();
83
+ result.push(0);
84
+ for (let i = 0; i < divisor.length; i++)
85
+ result[i] ^= gfMul(divisor[i], factor);
81
86
  }
82
- return res;
87
+ return result;
83
88
  }
84
- function bitBuffer() {
89
+ // ---------- Data segment ----------
90
+ function buildCodewords(bytes, version) {
91
+ const capacityBits = numDataCodewords(version) * 8;
85
92
  const bits = [];
86
- return {
87
- put(val, len) {
88
- for (let i = len - 1; i >= 0; i--)
89
- bits.push((val >>> i) & 1);
90
- },
91
- toBytes() {
92
- const out = [];
93
- for (let i = 0; i < bits.length; i += 8) {
94
- let b = 0;
95
- for (let j = 0; j < 8; j++)
96
- b = (b << 1) | (bits[i + j] ?? 0);
97
- out.push(b);
98
- }
99
- return out;
100
- },
101
- get length() {
102
- return bits.length;
103
- }
93
+ const put = (val, len) => {
94
+ for (let i = len - 1; i >= 0; i--)
95
+ bits.push((val >>> i) & 1);
104
96
  };
105
- }
106
- function chooseVersion(byteLen) {
107
- for (let v = 1; v <= 10; v++) {
108
- const capacity = DATA_CODEWORDS[v] - 3; // mode+len overhead approx for short
109
- const bitsNeeded = 4 + (v <= 9 ? 8 : 16) + byteLen * 8 + 4;
110
- const maxBits = DATA_CODEWORDS[v] * 8;
111
- if (bitsNeeded <= maxBits && byteLen <= capacity + 2)
112
- return v;
97
+ put(0b0100, 4);
98
+ put(bytes.length, charCountBits(version));
99
+ for (const b of bytes)
100
+ put(b, 8);
101
+ put(0, Math.min(4, capacityBits - bits.length));
102
+ while (bits.length % 8 !== 0)
103
+ bits.push(0);
104
+ for (let pad = 0xec; bits.length < capacityBits; pad ^= 0xec ^ 0x11)
105
+ put(pad, 8);
106
+ const data = [];
107
+ for (let i = 0; i < bits.length; i += 8) {
108
+ let b = 0;
109
+ for (let j = 0; j < 8; j++)
110
+ b = (b << 1) | bits[i + j];
111
+ data.push(b);
113
112
  }
114
- return 10;
113
+ return data;
115
114
  }
116
- function sizeOf(version) {
117
- return version * 4 + 17;
115
+ function addEccAndInterleave(data, version) {
116
+ const numBlocks = NUM_BLOCKS_M[version - 1];
117
+ const eccLen = ECC_PER_BLOCK_M[version - 1];
118
+ const rawCodewords = Math.floor(numRawDataModules(version) / 8);
119
+ const numShortBlocks = numBlocks - (rawCodewords % numBlocks);
120
+ const shortBlockLen = Math.floor(rawCodewords / numBlocks);
121
+ const blocks = [];
122
+ const divisor = rsDivisor(eccLen);
123
+ let offset = 0;
124
+ for (let i = 0; i < numBlocks; i++) {
125
+ const len = shortBlockLen - eccLen + (i < numShortBlocks ? 0 : 1);
126
+ const dat = data.slice(offset, offset + len);
127
+ offset += len;
128
+ const ecc = rsRemainder(dat, divisor);
129
+ if (i < numShortBlocks)
130
+ dat.push(0);
131
+ blocks.push(dat.concat(ecc));
132
+ }
133
+ const result = [];
134
+ for (let i = 0; i < blocks[0].length; i++) {
135
+ blocks.forEach((block, j) => {
136
+ if (i !== shortBlockLen - eccLen || j >= numShortBlocks)
137
+ result.push(block[i]);
138
+ });
139
+ }
140
+ return result;
118
141
  }
119
- function placeFinder(mod, r, c) {
120
- for (let y = -1; y <= 7; y++) {
121
- for (let x = -1; x <= 7; x++) {
122
- const rr = r + y;
123
- const cc = c + x;
124
- if (rr < 0 || cc < 0 || rr >= mod.length || cc >= mod.length)
142
+ // ---------- Matrix drawing ----------
143
+ function drawFunctionPatterns(version, mod, fn) {
144
+ const size = mod.length;
145
+ const set = (x, y, dark) => {
146
+ mod[y][x] = dark;
147
+ fn[y][x] = true;
148
+ };
149
+ for (let i = 0; i < size; i++) {
150
+ set(6, i, i % 2 === 0);
151
+ set(i, 6, i % 2 === 0);
152
+ }
153
+ const finder = (cx, cy) => {
154
+ for (let dy = -4; dy <= 4; dy++) {
155
+ for (let dx = -4; dx <= 4; dx++) {
156
+ const dist = Math.max(Math.abs(dx), Math.abs(dy));
157
+ const x = cx + dx;
158
+ const y = cy + dy;
159
+ if (x >= 0 && x < size && y >= 0 && y < size)
160
+ set(x, y, dist !== 2 && dist !== 4);
161
+ }
162
+ }
163
+ };
164
+ finder(3, 3);
165
+ finder(size - 4, 3);
166
+ finder(3, size - 4);
167
+ const aligns = alignmentPositions(version);
168
+ const last = aligns.length - 1;
169
+ for (let i = 0; i < aligns.length; i++) {
170
+ for (let j = 0; j < aligns.length; j++) {
171
+ if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0))
125
172
  continue;
126
- const inFinder = x >= 0 && x <= 6 && y >= 0 && y <= 6;
127
- const onBorder = x === 0 || x === 6 || y === 0 || y === 6;
128
- const inCore = x >= 2 && x <= 4 && y >= 2 && y <= 4;
129
- if (inFinder)
130
- mod[rr][cc] = onBorder || inCore;
131
- else
132
- mod[rr][cc] = false;
173
+ for (let dy = -2; dy <= 2; dy++) {
174
+ for (let dx = -2; dx <= 2; dx++) {
175
+ set(aligns[i] + dx, aligns[j] + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
176
+ }
177
+ }
133
178
  }
134
179
  }
180
+ drawFormatBits(0, mod, fn);
181
+ drawVersion(version, mod, fn);
182
+ }
183
+ function drawFormatBits(mask, mod, fn) {
184
+ const size = mod.length;
185
+ const data = (ECL_M_FORMAT_BITS << 3) | mask;
186
+ let rem = data;
187
+ for (let i = 0; i < 10; i++)
188
+ rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
189
+ const bits = ((data << 10) | rem) ^ 0x5412;
190
+ const bit = (i) => ((bits >>> i) & 1) !== 0;
191
+ const set = (x, y, dark) => {
192
+ mod[y][x] = dark;
193
+ fn[y][x] = true;
194
+ };
195
+ for (let i = 0; i <= 5; i++)
196
+ set(8, i, bit(i));
197
+ set(8, 7, bit(6));
198
+ set(8, 8, bit(7));
199
+ set(7, 8, bit(8));
200
+ for (let i = 9; i < 15; i++)
201
+ set(14 - i, 8, bit(i));
202
+ for (let i = 0; i < 8; i++)
203
+ set(size - 1 - i, 8, bit(i));
204
+ for (let i = 8; i < 15; i++)
205
+ set(8, size - 15 + i, bit(i));
206
+ set(8, size - 8, true);
207
+ }
208
+ function drawVersion(version, mod, fn) {
209
+ if (version < 7)
210
+ return;
211
+ const size = mod.length;
212
+ let rem = version;
213
+ for (let i = 0; i < 12; i++)
214
+ rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
215
+ const bits = (version << 12) | rem;
216
+ for (let i = 0; i < 18; i++) {
217
+ const dark = ((bits >>> i) & 1) !== 0;
218
+ const a = size - 11 + (i % 3);
219
+ const b = Math.floor(i / 3);
220
+ mod[b][a] = dark;
221
+ fn[b][a] = true;
222
+ mod[a][b] = dark;
223
+ fn[a][b] = true;
224
+ }
135
225
  }
136
- function placeAlignment(mod, r, c) {
137
- for (let y = -2; y <= 2; y++) {
138
- for (let x = -2; x <= 2; x++) {
139
- mod[r + y][c + x] = Math.max(Math.abs(x), Math.abs(y)) !== 1;
226
+ function drawCodewords(codewords, mod, fn) {
227
+ const size = mod.length;
228
+ let i = 0;
229
+ const total = codewords.length * 8;
230
+ for (let right = size - 1; right >= 1; right -= 2) {
231
+ if (right === 6)
232
+ right = 5;
233
+ for (let vert = 0; vert < size; vert++) {
234
+ for (let j = 0; j < 2; j++) {
235
+ const x = right - j;
236
+ const upward = ((right + 1) & 2) === 0;
237
+ const y = upward ? size - 1 - vert : vert;
238
+ if (!fn[y][x] && i < total) {
239
+ mod[y][x] = ((codewords[i >>> 3] >>> (7 - (i & 7))) & 1) !== 0;
240
+ i++;
241
+ }
242
+ }
140
243
  }
141
244
  }
142
245
  }
143
- function maskFn(mask, r, c) {
246
+ function maskBit(mask, x, y) {
144
247
  switch (mask) {
145
248
  case 0:
146
- return (r + c) % 2 === 0;
249
+ return (x + y) % 2 === 0;
147
250
  case 1:
148
- return r % 2 === 0;
251
+ return y % 2 === 0;
149
252
  case 2:
150
- return c % 3 === 0;
253
+ return x % 3 === 0;
151
254
  case 3:
152
- return (r + c) % 3 === 0;
255
+ return (x + y) % 3 === 0;
153
256
  case 4:
154
- return (Math.floor(r / 2) + Math.floor(c / 3)) % 2 === 0;
257
+ return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
155
258
  case 5:
156
- return ((r * c) % 2) + ((r * c) % 3) === 0;
259
+ return ((x * y) % 2) + ((x * y) % 3) === 0;
157
260
  case 6:
158
- return (((r * c) % 2) + ((r * c) % 3)) % 2 === 0;
261
+ return (((x * y) % 2) + ((x * y) % 3)) % 2 === 0;
159
262
  default:
160
- return (((r + c) % 2) + ((r * c) % 3)) % 2 === 0;
263
+ return (((x + y) % 2) + ((x * y) % 3)) % 2 === 0;
161
264
  }
162
265
  }
163
- /** Returns a square boolean matrix (true = dark module). */
164
- export function encodeQR(text) {
165
- const bytes = Array.from(new TextEncoder().encode(text));
166
- const version = chooseVersion(bytes.length);
167
- const size = sizeOf(version);
168
- const dataCapacity = DATA_CODEWORDS[version];
169
- const ecLen = ECC_CODEWORDS_PER_BLOCK[version];
170
- const buf = bitBuffer();
171
- buf.put(0b0100, 4); // byte mode
172
- buf.put(bytes.length, version <= 9 ? 8 : 16);
173
- for (const b of bytes)
174
- buf.put(b, 8);
175
- buf.put(0, Math.min(4, dataCapacity * 8 - buf.length));
176
- while (buf.length % 8 !== 0)
177
- buf.put(0, 1);
178
- const data = buf.toBytes();
179
- const pad = [0xec, 0x11];
180
- let pi = 0;
181
- while (data.length < dataCapacity)
182
- data.push(pad[pi++ % 2]);
183
- const ec = rsEncode(data.slice(0, dataCapacity), ecLen);
184
- const codewords = [...data.slice(0, dataCapacity), ...ec];
185
- const mod = Array.from({ length: size }, () => Array(size).fill(null));
186
- placeFinder(mod, 0, 0);
187
- placeFinder(mod, 0, size - 7);
188
- placeFinder(mod, size - 7, 0);
189
- for (let i = 8; i < size - 8; i++) {
190
- if (mod[6][i] === null)
191
- mod[6][i] = i % 2 === 0;
192
- if (mod[i][6] === null)
193
- mod[i][6] = i % 2 === 0;
194
- }
195
- const aligns = ALIGNMENT[version];
196
- for (const r of aligns) {
197
- for (const c of aligns) {
198
- if (mod[r][c] !== null)
199
- continue;
200
- placeAlignment(mod, r, c);
266
+ function applyMask(mask, mod, fn) {
267
+ const size = mod.length;
268
+ for (let y = 0; y < size; y++) {
269
+ for (let x = 0; x < size; x++) {
270
+ if (!fn[y][x] && maskBit(mask, x, y))
271
+ mod[y][x] = !mod[y][x];
201
272
  }
202
273
  }
203
- // format info reserved
204
- for (let i = 0; i < 9; i++) {
205
- if (mod[8][i] === null)
206
- mod[8][i] = false;
207
- if (mod[i][8] === null)
208
- mod[i][8] = false;
209
- }
210
- for (let i = 0; i < 8; i++) {
211
- if (mod[8][size - 1 - i] === null)
212
- mod[8][size - 1 - i] = false;
213
- if (mod[size - 1 - i][8] === null)
214
- mod[size - 1 - i][8] = false;
215
- }
216
- mod[size - 8][8] = true;
217
- const bits = [];
218
- for (const cw of codewords) {
219
- for (let i = 7; i >= 0; i--)
220
- bits.push((cw >> i) & 1);
274
+ }
275
+ function penaltyScore(mod) {
276
+ const size = mod.length;
277
+ let result = 0;
278
+ let dark = 0;
279
+ for (let y = 0; y < size; y++) {
280
+ let runColor = false;
281
+ let runX = 0;
282
+ for (let x = 0; x < size; x++) {
283
+ if (mod[y][x] === runColor) {
284
+ runX++;
285
+ if (runX === 5)
286
+ result += 3;
287
+ else if (runX > 5)
288
+ result++;
289
+ }
290
+ else {
291
+ runColor = mod[y][x];
292
+ runX = 1;
293
+ }
294
+ if (mod[y][x])
295
+ dark++;
296
+ }
221
297
  }
222
- let bitIndex = 0;
223
- let direction = -1;
224
- for (let col = size - 1; col > 0; col -= 2) {
225
- if (col === 6)
226
- col = 5;
227
- for (let i = 0; i < size; i++) {
228
- const row = direction < 0 ? size - 1 - i : i;
229
- for (let c = 0; c < 2; c++) {
230
- const cc = col - c;
231
- if (mod[row][cc] !== null)
232
- continue;
233
- mod[row][cc] = bits[bitIndex++] === 1;
298
+ for (let x = 0; x < size; x++) {
299
+ let runColor = false;
300
+ let runY = 0;
301
+ for (let y = 0; y < size; y++) {
302
+ if (mod[y][x] === runColor) {
303
+ runY++;
304
+ if (runY === 5)
305
+ result += 3;
306
+ else if (runY > 5)
307
+ result++;
308
+ }
309
+ else {
310
+ runColor = mod[y][x];
311
+ runY = 1;
234
312
  }
235
313
  }
236
- direction *= -1;
237
314
  }
238
- const mask = 0;
239
- const out = Array.from({ length: size }, () => Array(size).fill(false));
240
- for (let r = 0; r < size; r++) {
241
- for (let c = 0; c < size; c++) {
242
- const dark = !!mod[r][c];
243
- out[r][c] = maskFn(mask, r, c) ? !dark : dark;
315
+ for (let y = 0; y < size - 1; y++) {
316
+ for (let x = 0; x < size - 1; x++) {
317
+ const c = mod[y][x];
318
+ if (c === mod[y][x + 1] && c === mod[y + 1][x] && c === mod[y + 1][x + 1])
319
+ result += 3;
244
320
  }
245
321
  }
246
- // Write simplified format bits (ECC M + mask 0) — hardcoded BCH for 0b00100 << 10 etc.
247
- const format = 0b101010000010010; // common format for M / mask0 approximation
248
- for (let i = 0; i < 15; i++) {
249
- const bit = ((format >> i) & 1) === 1;
250
- // vertical near finder
251
- if (i < 6)
252
- out[i][8] = bit;
253
- else if (i < 8)
254
- out[i + 1][8] = bit;
255
- else
256
- out[size - 15 + i][8] = bit;
257
- // horizontal
258
- if (i < 8)
259
- out[8][size - 1 - i] = bit;
260
- else if (i < 9)
261
- out[8][15 - i] = bit;
262
- else
263
- out[8][14 - i] = bit;
322
+ const total = size * size;
323
+ const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
324
+ result += k * 10;
325
+ return result;
326
+ }
327
+ /** Returns a square boolean matrix (true = dark module). */
328
+ export function encodeQR(text) {
329
+ const bytes = Array.from(new TextEncoder().encode(text));
330
+ const version = chooseVersion(bytes.length);
331
+ const size = sizeOf(version);
332
+ const codewords = addEccAndInterleave(buildCodewords(bytes, version), version);
333
+ const mod = Array.from({ length: size }, () => Array(size).fill(false));
334
+ const fn = Array.from({ length: size }, () => Array(size).fill(false));
335
+ drawFunctionPatterns(version, mod, fn);
336
+ drawCodewords(codewords, mod, fn);
337
+ let bestMask = 0;
338
+ let bestScore = Number.POSITIVE_INFINITY;
339
+ for (let mask = 0; mask < 8; mask++) {
340
+ applyMask(mask, mod, fn);
341
+ drawFormatBits(mask, mod, fn);
342
+ const score = penaltyScore(mod);
343
+ if (score < bestScore) {
344
+ bestScore = score;
345
+ bestMask = mask;
346
+ }
347
+ applyMask(mask, mod, fn);
264
348
  }
265
- return out;
349
+ applyMask(bestMask, mod, fn);
350
+ drawFormatBits(bestMask, mod, fn);
351
+ return mod;
266
352
  }
267
353
  export function qrToSvgPath(matrix, cell = 1) {
268
354
  const parts = [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@r2digisolutions/components",
3
- "version": "0.24.2",
3
+ "version": "0.24.4",
4
4
  "private": false,
5
5
  "description": "R2DigiSolutions Svelte 5 component library — Atomic Design, Tailwind 4, Light/Dark mode",
6
6
  "license": "MIT",