Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(v0.3): canva-exact selection chrome, groups, context menu, marquee, topbar context toolbar, color menu, zoom dropdown, expanded elements & uploads

Ashiq Hussain Mirfbed65d2274c
diff --git a/src/app/globals.css b/src/app/globals.css
index bb9c5fd..d7fb2ae 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -149,11 +149,212 @@
--cv-text-3: rgba(255, 255, 255, 0.55);
--cv-border: rgba(255, 255, 255, 0.09);
+ /* v0.3 interaction tokens — measured on canva.com 2026-09-03 */
+ --cv-selection: #7630d7; /* element selection border — real rgb(118,48,215) */
+ --cv-guide: #9954ff; /* alignment guide lines — real rgb(153,84,255) */
+ --cv-menu: #121319; /* context menu / dropdown surface */
+ --cv-menu-item: #1a1b22; /* menu item hover */
+ --cv-slider-fill: #7630d7; /* popover slider fill */
+
/* gradients */
--cv-grad-bar: linear-gradient(90deg, #02c0cc 0%, #7b2ff7 100%);
--cv-grad-brand: linear-gradient(120deg, #02c0cc 0%, #7630d7 55%, #ff5c8a 100%);
}
+/* ── v0.3 shared component classes ─────────────────────────── */
+
+/* canva-style context menu (244px, items 32px, 13px, r10) */
+.cv-menu {
+ position: fixed;
+ z-index: 80;
+ min-width: 224px;
+ max-width: 244px;
+ background: var(--cv-menu);
+ border: 1px solid rgba(255, 255, 255, 0.09);
+ border-radius: 10px;
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
+ padding: 4px;
+ animation: cv-pop-in 0.12s ease-out;
+}
+.cv-menu-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ height: 32px;
+ padding: 0 10px;
+ border-radius: 6px;
+ color: var(--cv-text);
+ font-size: 13px;
+ font-weight: 500;
+ text-align: left;
+ transition: background 0.1s ease;
+}
+.cv-menu-item:hover, .cv-menu-item:focus-visible {
+ background: rgba(255, 255, 255, 0.08);
+ outline: none;
+}
+.cv-menu-item .cv-menu-kbd {
+ margin-left: auto;
+ font-size: 11px;
+ color: var(--cv-text-3);
+ font-family: var(--font-geist-mono), monospace;
+}
+.cv-menu-sep {
+ height: 1px;
+ background: rgba(255, 255, 255, 0.08);
+ margin: 4px 8px;
+}
+.cv-menu-item-danger { color: #ff8080; }
+.cv-menu-item-danger:hover { background: rgba(255, 90, 90, 0.12); }
+
+/* 32px contextual toolbar button (canva r10) */
+.cv-tbtn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ height: 32px;
+ min-width: 32px;
+ padding: 0 6px;
+ border-radius: 10px;
+ color: var(--cv-text);
+ font-size: 14px;
+ font-weight: 600;
+ transition: background 0.12s ease, color 0.12s ease;
+ flex-shrink: 0;
+}
+.cv-tbtn:hover { background: rgba(255, 255, 255, 0.1); }
+.cv-tbtn:active { background: rgba(255, 255, 255, 0.16); }
+.cv-tbtn[data-active="true"] { background: rgba(255, 255, 255, 0.18); color: #fff; }
+.cv-tbtn[data-dim="true"] { color: var(--cv-text-3); }
+.cv-tbtn:disabled { opacity: 0.4; pointer-events: none; }
+
+/* popover panels (spacing / transparency / position) */
+.cv-pop {
+ position: absolute;
+ z-index: 60;
+ background: #1e1f26;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 14px;
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5);
+ padding: 14px;
+ min-width: 232px;
+ animation: cv-pop-in 0.14s ease-out;
+}
+
+/* canva-style slider: purple fill + white circular handle */
+.cv-slider {
+ -webkit-appearance: none;
+ appearance: none;
+ height: 4px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.14);
+ outline: none;
+ cursor: pointer;
+}
+.cv-slider::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: #fff;
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
+ cursor: grab;
+ border: none;
+}
+.cv-slider::-moz-range-thumb {
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: #fff;
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4);
+ border: none;
+ cursor: grab;
+}
+
+/* tooltip (canva: ~45×28, delayed, dark) */
+.cv-tip {
+ position: fixed;
+ z-index: 90;
+ background: #0f1015;
+ color: #fff;
+ font-size: 12px;
+ font-weight: 500;
+ padding: 4px 8px;
+ border-radius: 6px;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
+ pointer-events: none;
+ white-space: nowrap;
+ animation: cv-pop-in 0.1s ease-out;
+}
+
+/* circular swatch (canva color menu) */
+.cv-swatch {
+ border-radius: 50%;
+ border: 2px solid transparent;
+ transition: transform 0.12s ease, border-color 0.12s ease;
+ cursor: pointer;
+}
+.cv-swatch:hover { transform: scale(1.12); border-color: rgba(255, 255, 255, 0.4); }
+.cv-swatch[data-selected="true"] { border-color: #fff; transform: scale(1.08); }
+
+@keyframes cv-pop-in {
+ from { opacity: 0; transform: translateY(4px) scale(0.98); }
+ to { opacity: 1; transform: translateY(0) scale(1); }
+}
+
+/* skeleton shimmer (canva loading state) */
+.cv-skeleton {
+ position: relative;
+ overflow: hidden;
+ background: rgba(255, 255, 255, 0.06);
+ border-radius: 10px;
+}
+.cv-skeleton::after {
+ content: "";
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.08), transparent);
+ animation: cv-shimmer 1.4s infinite;
+}
+@keyframes cv-shimmer {
+ from { transform: translateX(-100%); }
+ to { transform: translateX(100%); }
+}
+
+/* toast (canva-style bottom center) */
+.cv-toast {
+ position: fixed;
+ left: 50%;
+ bottom: 24px;
+ transform: translateX(-50%);
+ z-index: 95;
+ background: #26272f;
+ color: #fff;
+ font-size: 13px;
+ font-weight: 500;
+ padding: 10px 16px;
+ border-radius: 10px;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ animation: cv-toast-in 0.22s cubic-bezier(0.22, 1, 0.36, 1);
+}
+@keyframes cv-toast-in {
+ from { opacity: 0; transform: translateX(-50%) translateY(12px); }
+ to { opacity: 1; transform: translateX(-50%) translateY(0); }
+}
+
+/* focus-visible ring for a11y (subtle canva-style) */
+:where(button, a, input, select, [tabindex]):focus-visible {
+ outline: 2px solid rgba(118, 48, 215, 0.85);
+ outline-offset: 2px;
+}
+
.font-sans {
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
}
diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsx
index 107fde5..dd4de5a 100644
--- a/src/components/editor/Editor.tsx
+++ b/src/components/editor/Editor.tsx
@@ -7,7 +7,7 @@ import { useAppStore } from '@/store/app-store'
import { useEditorStore, type PanelId } from '@/store/editor-store'
import { TopBar } from './TopBar'
import { LeftRail } from './LeftRail'
-import { PropertiesBar } from './PropertiesBar'
+import { ContextToolbar } from './PropertiesBar'
import { PageBar } from './PageBar'
import { ZoomControls } from './ZoomControls'
import { PreviewOverlay } from './PreviewOverlay'
@@ -47,9 +47,16 @@ const SHORTCUTS: [string, string][] = [
['Ctrl + S', 'Save design'],
['Ctrl + D', 'Duplicate selection'],
['Ctrl + C / X / V', 'Copy / cut / paste elements'],
+ ['Ctrl + G / Ctrl + Shift + G', 'Group / ungroup selection'],
+ ['Ctrl + A', 'Select all elements'],
+ ['Ctrl + L', 'Lock / unlock selection'],
+ ['Ctrl + ] / [', 'Bring forward / send backward'],
+ ['Shift + Ctrl + ] / [', 'Bring to front / send to back'],
['Delete / Backspace', 'Delete selection'],
['Arrows (+ Shift ×10)', 'Nudge selection'],
['+ / −', 'Zoom in / out'],
+ ['Space + drag', 'Pan the canvas'],
+ ['Drag on empty canvas', 'Marquee (box) select'],
['Double-click text', 'Edit text'],
['Escape', 'Deselect / close'],
['Ctrl + mouse wheel', 'Zoom at cursor'],
@@ -67,6 +74,7 @@ export default function Editor() {
const version = useEditorStore((s) => s.version)
const isMobile = useIsMobile()
const [shortcutsOpen, setShortcutsOpen] = useState(false)
+ const selectedIds = useEditorStore((s) => s.selectedIds)
const loadedRef = useRef(false)
@@ -181,6 +189,29 @@ export default function Editor() {
state.pasteClipboard()
return
}
+ if (mod && e.key.toLowerCase() === 'g') {
+ e.preventDefault()
+ if (e.shiftKey) state.ungroupSelection()
+ else state.groupSelection()
+ return
+ }
+ if (mod && e.key.toLowerCase() === 'a') {
+ e.preventDefault()
+ const els = state.pages[state.currentPage].elements.filter((el) => !el.locked)
+ state.setSelection(els.map((el) => el.id))
+ return
+ }
+ if (mod && e.key.toLowerCase() === 'l') {
+ e.preventDefault()
+ const hasLocked = state.pages[state.currentPage].elements.some((el) => state.selectedIds.includes(el.id) && el.locked)
+ state.setLock(state.selectedIds, !hasLocked)
+ return
+ }
+ if (mod && (e.key === ']' || e.key === '[')) {
+ e.preventDefault()
+ for (const id of state.selectedIds) state.moveLayer(id, e.key === ']' ? (e.shiftKey ? 'front' : 'up') : (e.shiftKey ? 'back' : 'down'))
+ return
+ }
if (e.key === 'Delete' || e.key === 'Backspace') {
if (state.selectedIds.length) {
e.preventDefault()
@@ -212,6 +243,38 @@ export default function Editor() {
return () => window.removeEventListener('keydown', onKey)
}, [save])
+ // ── drag & drop image files onto the canvas ───────────────
+ useEffect(() => {
+ const onDragOver = (e: DragEvent) => {
+ if (e.dataTransfer?.types.includes('Files')) {
+ e.preventDefault()
+ e.dataTransfer.dropEffect = 'copy'
+ }
+ }
+ const onDrop = async (e: DragEvent) => {
+ const files = e.dataTransfer?.files
+ if (!files?.length) return
+ e.preventDefault()
+ const images = Array.from(files).filter((f) => f.type.startsWith('image/'))
+ if (!images.length) return
+ const { addImageFromFile } = await import('./add-element')
+ let ok = 0
+ for (const file of images) {
+ try {
+ await addImageFromFile(file)
+ ok += 1
+ } catch { /* ignore */ }
+ }
+ if (ok) toast({ title: `${ok} image${ok > 1 ? 's' : ''} added` })
+ }
+ window.addEventListener('dragover', onDragOver)
+ window.addEventListener('drop', onDrop)
+ return () => {
+ window.removeEventListener('dragover', onDragOver)
+ window.removeEventListener('drop', onDrop)
+ }
+ }, [])
+
// ── render panel ───────────────────────────────────────────
const renderPanel = () => {
switch (panel) {
@@ -264,13 +327,19 @@ export default function Editor() {
{/* canvas workspace */}
<main className="flex-1 relative min-w-0 min-h-0" aria-label="Design canvas">
- <PropertiesBar />
<CanvasStage />
<PageBar />
<ZoomControls />
</main>
</div>
+ {/* mobile contextual action bar (canva mobile: bottom bar on selection) */}
+ {isMobile && selectedIds.length > 0 && (
+ <div className="fixed inset-x-0 bottom-14 z-40">
+ <ContextToolbar variant="mobile" />
+ </div>
+ )}
+
{/* mobile rail */}
<div className="md:hidden border-t border-white/[0.07]">
<LeftRail vertical={false} />
diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsx
index 90a274c..3c2781f 100644
--- a/src/components/editor/PropertiesBar.tsx
+++ b/src/components/editor/PropertiesBar.tsx
@@ -1,160 +1,48 @@
'use client'
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
import {
- Bold,
- Italic,
- Underline,
- Strikethrough,
- AlignLeft,
- AlignCenter,
- AlignRight,
- Trash2,
- Copy,
- Lock,
- LockOpen,
- Droplets,
- Plus,
- Minus,
- AlignStartVertical,
- AlignCenterVertical,
- AlignEndVertical,
- AlignStartHorizontal,
- AlignCenterHorizontal,
- AlignEndHorizontal,
- CornerDownRight,
- ArrowLeftRight,
- MoveDiagonal,
- Wand2,
+ Bold, Italic, Underline, Strikethrough, CaseUpper, AlignLeft, AlignCenter, AlignRight,
+ AlignJustify, Minus, Plus, LetterText, Percent, Sparkles, Move, CopyPlus, Trash2,
+ Group, Ungroup, ArrowUpToLine, ArrowDownToLine, BringToFront, SendToBack,
+ AlignVerticalJustifyStart, AlignVerticalJustifyCenter, AlignVerticalJustifyEnd,
+ AlignHorizontalJustifyStart, AlignHorizontalJustifyCenter, AlignHorizontalJustifyEnd,
+ FlipHorizontal, FlipVertical, Sun, Contrast, Palette, RotateCcw, Replace, Lock, LockOpen,
+ Layers, SquareDashed,
} from 'lucide-react'
import { useEditorStore, selectedElements, currentPageData } from '@/store/editor-store'
-import { FONTS } from '@/lib/editor-utils'
-import { ColorPicker } from './panels/color-picker'
-import { Button } from '@/components/ui/button'
-import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
-import { Slider } from '@/components/ui/slider'
+import type { ImageElement, LineElement, ShapeElement, StickerElement, TextElement, AnyElement } from '@/lib/types'
+import { isGroup } from '@/lib/types'
+import { TEXT_EFFECTS } from '@/lib/types'
import { cn } from '@/lib/utils'
-import type { AnyElement, TextElement, ShapeElement, LineElement, ImageElement, StickerElement } from '@/lib/types'
-import { TEXT_EFFECTS, type TextEffect } from '@/lib/types'
+import { FontDropdown } from './toolbar/FontDropdown'
+import { ColorMenu } from './toolbar/ColorMenu'
+import { ToolbarPopover, SliderRow, IconTile } from './toolbar/popover-kit'
-function ToolButton({
- onClick,
- active,
- title,
- children,
-}: {
- onClick?: () => void
- active?: boolean
- title: string
- children: React.ReactNode
-}) {
- return (
- <button
- onClick={onClick}
- title={title}
- aria-label={title}
- className={cn(
- 'h-8 min-w-8 px-1.5 rounded-lg flex items-center justify-center transition-colors',
- active ? 'bg-[#7630D7] text-white' : 'text-white/75 hover:bg-white/10 hover:text-white'
- )}
- >
- {children}
- </button>
- )
-}
-
-function Divider() {
- return <span className="h-5 w-px bg-white/15 mx-1 shrink-0" aria-hidden="true" />
-}
-
-function NumberStepper({
- value,
- onCommit,
- min = 1,
- max = 800,
- suffix,
- title,
-}: {
- value: number
- onCommit: (v: number) => void
- min?: number
- max?: number
- suffix?: string
- title: string
-}) {
- const [draft, setDraft] = useState(String(value))
-
- // resync when the value changes externally
- useEffect(() => {
- setDraft(String(value))
- }, [value])
-
- const commit = (raw: string) => {
- const n = parseInt(raw, 10)
- if (Number.isFinite(n)) onCommit(Math.min(max, Math.max(min, n)))
- else setDraft(String(value))
- }
-
- return (
- <div className="flex items-center rounded-lg border border-white/12 h-8 bg-white/[0.06]" title={title}>
- <button className="h-full px-1.5 text-white/70 hover:text-white" aria-label="Decrease" onClick={() => commit(String(value - 1))}>
- <Minus size={12} />
- </button>
- <input
- value={draft}
- onChange={(e) => setDraft(e.target.value.replace(/[^\d]/g, ''))}
- onBlur={() => commit(draft)}
- onKeyDown={(e) => e.key === 'Enter' && commit(draft)}
- className="w-11 text-center text-xs font-semibold text-white outline-none bg-transparent"
- inputMode="numeric"
- aria-label={title}
- />
- {suffix && <span className="text-[10px] text-white/50 pr-1">{suffix}</span>}
- <button className="h-full px-1.5 text-white/70 hover:text-white" aria-label="Increase" onClick={() => commit(String(value + 1))}>
- <Plus size={12} />
- </button>
- </div>
- )
-}
+const ALIGN_ICONS = {
+ left: AlignLeft,
+ center: AlignCenter,
+ right: AlignRight,
+ justify: AlignJustify,
+} as const
-function OpacityControl({ opacity, onCommit }: { opacity: number; onCommit: (v: number) => void }) {
- const [local, setLocal] = useState(opacity)
- return (
- <Popover>
- <PopoverTrigger asChild>
- <ToolButton title="Transparency">
- <span className="relative flex items-center justify-center">
- <Droplets size={15} />
- </span>
- </ToolButton>
- </PopoverTrigger>
- <PopoverContent className="w-52 p-3 bg-[#16181D] border-white/10 text-white">
- <div className="flex items-center justify-between text-xs font-medium">
- <span>Transparency</span>
- <span>{Math.round(local * 100)}%</span>
- </div>
- <Slider
- value={[Math.round(local * 100)]}
- min={5}
- max={100}
- step={1}
- onValueChange={(v) => {
- const o = v[0] / 100
- setLocal(o)
- onCommit(o)
- }}
- className="mt-2"
- />
- </PopoverContent>
- </Popover>
- )
+const EFFECT_PREVIEW: Record<string, React.CSSProperties> = {
+ none: {},
+ shadow: { textShadow: '2px 3px 4px rgba(0,0,0,0.7)' },
+ lift: { textShadow: '0 4px 0 rgba(0,0,0,0.75)' },
+ glow: { textShadow: '0 0 10px rgba(255,255,255,0.9)' },
+ hollow: { color: 'transparent', WebkitTextStroke: '0.8px #fff' },
+ outline: { WebkitTextStroke: '0.7px #fff' },
+ background: { background: '#EFEFEF', color: '#7630D7', padding: '2px 6px', borderRadius: 4 },
+ splice: { textShadow: '0 -2px 0 rgba(255,255,255,0.4), 0 2px 0 rgba(255,255,255,0.4)' },
+ neon: { textShadow: '0 0 6px #7630D7, 0 0 14px #7630D7, 0 0 22px #9954FF' },
+ echo: { textShadow: '4px 4px 0 rgba(255,255,255,0.35)' },
}
-export function PropertiesBar() {
+/** canva-style contextual toolbar. Desktop: rendered inside the topbar row. Mobile: bottom bar. */
+export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'mobile' }) {
const state = useEditorStore()
const sel = selectedElements(state)
- const page = currentPageData(state)
-
if (sel.length === 0) return null
const ids = sel.map((e) => e.id)
@@ -163,297 +51,419 @@ export function PropertiesBar() {
const first = sel[0]
const isMulti = sel.length > 1
- const allText = sel.every((e) => e.type === 'text')
-
- // align actions (multi-select): relative to page
- const alignSelection = (mode: 'left' | 'cx' | 'right' | 'top' | 'cy' | 'bottom') => {
- state.pushHistory()
- const pages = state.pages.map((p, i) => {
- if (i !== state.currentPage) return p
- return {
- ...p,
- elements: p.elements.map((el) => {
- if (!ids.includes(el.id)) return el
- switch (mode) {
- case 'left': return { ...el, x: 0 }
- case 'cx': return { ...el, x: (state.width - el.width) / 2 }
- case 'right': return { ...el, x: state.width - el.width }
- case 'top': return { ...el, y: 0 }
- case 'cy': return { ...el, y: (state.height - el.height) / 2 }
- case 'bottom': return { ...el, y: state.height - el.height }
- }
- }),
- }
- })
- useEditorStore.setState({ pages })
- }
-
const text = first.type === 'text' ? (first as TextElement) : null
const shape = ['rect', 'ellipse', 'triangle', 'star', 'path'].includes(first.type) ? (first as ShapeElement) : null
const line = first.type === 'line' ? (first as LineElement) : null
const image = first.type === 'image' ? (first as ImageElement) : null
const sticker = first.type === 'sticker' ? (first as StickerElement) : null
+ const group = first.type === 'group' ? first : null
+
+ const canGroup = isMulti
+ const canUngroup = sel.some((e) => isGroup(e))
+
+ const isTopbar = variant === 'topbar'
return (
- <div className="absolute top-3 left-1/2 -translate-x-1/2 z-30 max-w-[calc(100%-2rem)]">
- <div className="flex items-center gap-0.5 rounded-2xl bg-[#1D1F26]/95 backdrop-blur border border-white/10 shadow-xl shadow-black/50 px-2 py-1.5 overflow-x-auto cv-scroll-dark">
- {isMulti ? (
- <>
- <span className="text-xs font-medium text-white/60 px-1.5 shrink-0">{sel.length} selected</span>
- <Divider />
- <ToolButton title="Align left" onClick={() => alignSelection('left')}><AlignStartVertical size={15} /></ToolButton>
- <ToolButton title="Align centers" onClick={() => alignSelection('cx')}><AlignCenterVertical size={15} /></ToolButton>
- <ToolButton title="Align right" onClick={() => alignSelection('right')}><AlignEndVertical size={15} /></ToolButton>
- <ToolButton title="Align top" onClick={() => alignSelection('top')}><AlignStartHorizontal size={15} /></ToolButton>
- <ToolButton title="Align middles" onClick={() => alignSelection('cy')}><AlignCenterHorizontal size={15} /></ToolButton>
- <ToolButton title="Align bottom" onClick={() => alignSelection('bottom')}><AlignEndHorizontal size={15} /></ToolButton>
- </>
- ) : text ? (
- <>
- {/* font family */}
- <div className="shrink-0">
- <select
- value={text.fontFamily}
- onChange={(e) => update(ids, { fontFamily: e.target.value })}
- className="h-8 rounded-lg border border-white/12 bg-white/[0.06] text-white px-2 text-xs font-semibold outline-none cursor-pointer max-w-[130px] truncate [color-scheme:dark]"
- style={{ fontFamily: text.fontFamily }}
- aria-label="Font family"
- >
- {FONTS.map((f) => (
- <option key={f.family} value={f.family} style={{ fontFamily: f.family }}>
- {f.label}
- </option>
- ))}
- </select>
- </div>
- <NumberStepper
- value={text.fontSize}
- onCommit={(v) => update(ids, { fontSize: v })}
+ <div
+ className={cn(
+ 'flex items-center gap-0.5 min-w-0 overflow-x-auto cv-scroll-dark',
+ isTopbar ? 'h-14 items-center px-1' : 'h-14 items-center px-2 bg-[#16181D] border-t border-white/[0.09]'
+ )}
+ aria-label="Selected element common controls"
+ style={{ scrollbarWidth: 'none' }}
+ >
+ {/* ── multi-select ─────────────────────────────────────── */}
+ {isMulti ? (
+ <>
+ <span className="text-[12px] font-semibold text-white/85 px-2 shrink-0">{sel.length} selected</span>
+ <TBtn onClick={() => state.groupSelection()} disabled={!canGroup} title="Group (Ctrl+G)" ariaLabel="Group">
+ <Group size={15} />
+ </TBtn>
+ <TBtn onClick={() => state.ungroupSelection()} disabled={!canUngroup} title="Ungroup (Ctrl+Shift+G)" ariaLabel="Ungroup">
+ <Ungroup size={15} />
+ </TBtn>
+ <Divider />
+ <PositionPopover ids={ids} count={sel.length} />
+ <Divider />
+ <TBtn onClick={() => state.duplicateSelection()} title="Duplicate (Ctrl+D)" ariaLabel="Duplicate">
+ <CopyPlus size={15} />
+ </TBtn>
+ <TBtn onClick={() => state.deleteSelection()} title="Delete (Del)" ariaLabel="Delete" danger>
+ <Trash2 size={15} />
+ </TBtn>
+ </>
+ ) : text ? (
+ <>
+ <FontDropdown value={text.fontFamily} onChange={(f) => update(ids, { fontFamily: f })} />
+ {/* size stepper */}
+ <div className="flex items-center shrink-0">
+ <TBtn onClick={() => update(ids, { fontSize: Math.max(6, text.fontSize - 2) })} title="Decrease font size" ariaLabel="Decrease font size" className="!rounded-r-none">
+ <Minus size={14} />
+ </TBtn>
+ <input
+ type="number"
+ value={Math.round(text.fontSize)}
min={6}
max={400}
- title="Font size"
+ onChange={(e) => { const v = Number(e.target.value); if (v >= 6 && v <= 400) updateLive(ids, { fontSize: v }) }}
+ onBlur={() => update(ids, { fontSize: text.fontSize })}
+ className="h-8 w-10 bg-white/[0.06] border-y border-white/10 text-white text-[12px] text-center outline-none focus:border-[#7630D7] [color-scheme:dark]"
+ aria-label="Font size"
/>
- <Divider />
- <ToolButton title="Bold" active={text.bold} onClick={() => update(ids, { bold: !text.bold })}><Bold size={14} /></ToolButton>
- <ToolButton title="Italic" active={text.italic} onClick={() => update(ids, { italic: !text.italic })}><Italic size={14} /></ToolButton>
- <ToolButton title="Underline" active={text.underline} onClick={() => update(ids, { underline: !text.underline })}><Underline size={14} /></ToolButton>
- <ToolButton title="Strikethrough" active={text.strike} onClick={() => update(ids, { strike: !text.strike })}><Strikethrough size={14} /></ToolButton>
- <Divider />
- <ColorPicker
- value={text.fill}
- onChange={(c, committed) => (committed ? update(ids, { fill: c }) : updateLive(ids, { fill: c }))}
- label="Text color"
- />
- <Divider />
- <ToolButton title="Align left" active={text.align === 'left'} onClick={() => update(ids, { align: 'left' })}><AlignLeft size={14} /></ToolButton>
- <ToolButton title="Align center" active={text.align === 'center'} onClick={() => update(ids, { align: 'center' })}><AlignCenter size={14} /></ToolButton>
- <ToolButton title="Align right" active={text.align === 'right'} onClick={() => update(ids, { align: 'right' })}><AlignRight size={14} /></ToolButton>
- <Divider />
- <SpacingControl
- letterSpacing={text.letterSpacing}
- lineHeight={text.lineHeight}
- onChangeLetter={(v) => update(ids, { letterSpacing: v })}
- onChangeLine={(v) => update(ids, { lineHeight: v })}
- />
- <EffectsControl effect={text.effect ?? 'none'} onChange={(fx) => update(ids, { effect: fx })} />
- </>
- ) : shape ? (
- <>
- <ColorPicker
- value={shape.fill}
- onChange={(c, committed) => (committed ? update(ids, { fill: c }) : updateLive(ids, { fill: c }))}
- label="Fill color"
- />
- <ColorPicker
- value={shape.stroke}
- onChange={(c, committed) => (committed ? update(ids, { stroke: c }) : updateLive(ids, { stroke: c }))}
- label="Stroke color"
- />
- <NumberStepper value={shape.strokeWidth} onCommit={(v) => update(ids, { strokeWidth: v })} min={0} max={80} title="Stroke width" />
- {first.type === 'rect' && (
- <NumberStepper value={shape.cornerRadius} onCommit={(v) => update(ids, { cornerRadius: v })} min={0} max={400} title="Corner radius" />
+ <TBtn onClick={() => update(ids, { fontSize: Math.min(400, text.fontSize + 2) })} title="Increase font size" ariaLabel="Increase font size" className="!rounded-l-none">
+ <Plus size={14} />
+ </TBtn>
+ </div>
+
+ <ColorMenu value={text.fill} onChange={(c, committed) => committed ? update(ids, { fill: c }) : updateLive(ids, { fill: c })} title="Text colour" />
+
+ <TBtn onClick={() => update(ids, { bold: !text.bold })} dataActive={text.bold} title="Bold" ariaLabel="Bold">
+ <Bold size={14} />
+ </TBtn>
+ <TBtn onClick={() => update(ids, { italic: !text.italic })} dataActive={text.italic} title="Italic" ariaLabel="Italic">
+ <Italic size={14} />
+ </TBtn>
+ <TBtn onClick={() => update(ids, { underline: !text.underline })} dataActive={text.underline} title="Underline" ariaLabel="Underline">
+ <Underline size={14} />
+ </TBtn>
+ <TBtn onClick={() => update(ids, { strike: !text.strike })} dataActive={text.strike} title="Strikethrough" ariaLabel="Strikethrough">
+ <Strikethrough size={14} />
+ </TBtn>
+ <TBtn onClick={() => update(ids, { uppercase: !text.uppercase })} dataActive={text.uppercase} title="Uppercase" ariaLabel="Uppercase">
+ <CaseUpper size={14} />
+ </TBtn>
+
+ {/* alignment */}
+ <ToolbarPopover
+ trigger={(open) => (
+ <button className="cv-tbtn" data-active={open} aria-label="Toggle text alignment" title="Text alignment">
+ {(() => { const I = ALIGN_ICONS[text.align] ?? AlignLeft; return <I size={14} /> })()}
+ </button>
)}
- </>
- ) : line ? (
- <>
- <ColorPicker
- value={line.stroke}
- onChange={(c, committed) => (committed ? update(ids, { stroke: c }) : updateLive(ids, { stroke: c }))}
- label="Line color"
- />
- <NumberStepper value={line.strokeWidth} onCommit={(v) => update(ids, { strokeWidth: v })} min={1} max={60} title="Line weight" />
- <ToolButton title="Dashed" active={line.dashed} onClick={() => update(ids, { dashed: !line.dashed })}>
- <ArrowLeftRight size={14} className="opacity-60" />
- </ToolButton>
- <ToolButton title="Start arrow" active={line.arrowStart} onClick={() => update(ids, { arrowStart: !line.arrowStart })}>
- <CornerDownRight size={14} className="-scale-x-100" />
- </ToolButton>
- <ToolButton title="End arrow" active={line.arrowEnd} onClick={() => update(ids, { arrowEnd: !line.arrowEnd })}>
- <CornerDownRight size={14} />
- </ToolButton>
- </>
- ) : sticker ? (
- <>
- <NumberStepper value={sticker.fontSize} onCommit={(v) => update(ids, { fontSize: v })} min={12} max={600} title="Sticker size" />
- </>
- ) : image ? (
- <>
- <NumberStepper value={image.radius} onCommit={(v) => update(ids, { radius: v })} min={0} max={500} title="Corner radius" />
- </>
- ) : null}
+ >
+ <div className="grid grid-cols-2 gap-1 w-[150px]">
+ {(['left', 'center', 'right', 'justify'] as const).map((a) => {
+ const I = ALIGN_ICONS[a]
+ return (
+ <button
+ key={a}
+ onClick={() => update(ids, { align: a })}
+ className={cn('flex items-center justify-center gap-1.5 h-8 rounded-lg text-[11px] font-medium capitalize', text.align === a ? 'bg-white/[0.16] text-white' : 'text-white/75 hover:bg-white/[0.08]')}
+ >
+ <I size={13} /> <span className="w-[42px] text-left">{a}</span>
+ </button>
+ )
+ })}
+ </div>
+ </ToolbarPopover>
- {/* common controls */}
- {!isMulti && <Divider />}
- {!isMulti && <ShadowControl element={first} />}
- {!isMulti && <OpacityControl opacity={first.opacity} onCommit={(v) => update(ids, { opacity: v })} />}
- <Divider />
- {!isMulti && (
- <ToolButton
- title={first.locked ? 'Unlock' : 'Lock'}
- active={first.locked}
- onClick={() => state.setLock(ids, !first.locked)}
+ {/* spacing */}
+ <ToolbarPopover
+ trigger={(open) => (
+ <button className="cv-tbtn" data-active={open} aria-label="Advanced settings" title="Letter & line spacing">
+ <LetterText size={14} />
+ </button>
+ )}
>
- {first.locked ? <Lock size={14} /> : <LockOpen size={14} />}
- </ToolButton>
- )}
- <ToolButton title="Duplicate" onClick={() => state.duplicateSelection()}>
- <Copy size={14} />
- </ToolButton>
- <ToolButton title="Delete" onClick={() => state.deleteSelection()}>
- <Trash2 size={14} className="text-red-500" />
- </ToolButton>
- </div>
+ <SliderRow label="Letter spacing" value={text.letterSpacing} min={-10} max={80} step={1} onChange={(v) => updateLive(ids, { letterSpacing: v })} onCommit={() => update(ids, { letterSpacing: text.letterSpacing })} />
+ <SliderRow label="Line spacing" value={text.lineHeight} min={0.6} max={3} step={0.05} onChange={(v) => updateLive(ids, { lineHeight: v })} onCommit={() => update(ids, { lineHeight: text.lineHeight })} format={(v) => `${v.toFixed(2)}×`} />
+ </ToolbarPopover>
+
+ {/* transparency */}
+ <ToolbarPopover
+ trigger={(open) => (
+ <button className="cv-tbtn" data-active={open} aria-label="Transparency" title="Transparency">
+ <Percent size={14} />
+ </button>
+ )}
+ >
+ <SliderRow label="Transparency" value={Math.round(text.opacity * 100)} min={0} max={100} step={1}
+ onChange={(v) => updateLive(ids, { opacity: v / 100 })}
+ onCommit={() => update(ids, { opacity: text.opacity })}
+ format={(v) => `${100 - v}% transparent`} />
+ </ToolbarPopover>
+
+ {/* effects */}
+ <ToolbarPopover width={264} trigger={(open) => (
+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Effects" title="Effects">
+ <Sparkles size={14} /> <span className="text-[12px] hidden lg:inline">Effects</span>
+ </button>
+ )}>
+ <div className="text-[12px] font-bold text-white/90 mb-2">Text effects</div>
+ <div className="grid grid-cols-3 gap-1.5">
+ {TEXT_EFFECTS.map((fx) => (
+ <button
+ key={fx.id}
+ onClick={() => update(ids, { effect: fx.id })}
+ className={cn(
+ 'flex flex-col items-center justify-center rounded-lg py-2 gap-1 border transition-colors',
+ text.effect === fx.id ? 'bg-white/[0.14] border-white/30' : 'border-white/[0.09] hover:bg-white/[0.07]'
+ )}
+ aria-label={`Effect ${fx.label}`}
+ >
+ <span className="text-[19px] leading-none text-white" style={{ fontFamily: 'Poppins', ...EFFECT_PREVIEW[fx.id] }}>Ag</span>
+ <span className="text-[9.5px] text-white/65 font-medium">{fx.label}</span>
+ </button>
+ ))}
+ </div>
+ {text.effect === 'background' && (
+ <div className="mt-2.5 border-t border-white/[0.08] pt-2.5">
+ <div className="text-[11px] text-white/60 mb-1.5 font-medium">Background block</div>
+ <div className="flex flex-wrap gap-1.5">
+ {['#EFEFEF', '#7630D7', '#00C4CC', '#FF5C8A', '#1F2226', '#FFE066'].map((c) => (
+ <button key={c} className="cv-swatch h-6 w-6" style={{ background: c }} onClick={() => update(ids, { effectBackground: c })} data-selected={text.effectBackground === c} aria-label={`Background ${c}`} />
+ ))}
+ </div>
+ </div>
+ )}
+ </ToolbarPopover>
+
+ <Divider />
+ <PositionPopover ids={ids} count={1} element={first} />
+ </>
+ ) : shape || group || sticker || line ? (
+ <>
+ {shape && (
+ <>
+ <ColorMenu value={shape.fill} onChange={(c, committed) => committed ? update(ids, { fill: c }) : updateLive(ids, { fill: c })} title="Fill" />
+ {/* border colour + width */}
+ <ToolbarPopover trigger={(open) => (
+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Border" title="Border">
+ <SquareDashed size={14} /> <span className="text-[12px] hidden lg:inline">Border</span>
+ </button>
+ )}>
+ <div className="text-[12px] font-bold text-white/90 mb-2">Border</div>
+ <div className="flex items-center gap-2 mb-2">
+ <span className="text-[11px] text-white/60">Colour</span>
+ <ColorMenu value={shape.stroke === 'transparent' ? '#FFFFFF' : shape.stroke} onChange={(c, committed) => committed ? update(ids, { stroke: c, strokeWidth: shape.strokeWidth || 4 }) : updateLive(ids, { stroke: c, strokeWidth: shape.strokeWidth || 4 })} title="Border colour" />
+ </div>
+ <SliderRow label="Width" value={shape.strokeWidth} min={0} max={40} step={1} onChange={(v) => updateLive(ids, { strokeWidth: v })} onCommit={() => update(ids, { strokeWidth: shape.strokeWidth })} />
+ {shape.type === 'rect' && <SliderRow label="Corner radius" value={shape.cornerRadius} min={0} max={Math.round(shape.width / 2)} step={1} onChange={(v) => updateLive(ids, { cornerRadius: v })} onCommit={() => update(ids, { cornerRadius: shape.cornerRadius })} />}
+ </ToolbarPopover>
+ </>
+ )}
+ {line && (
+ <>
+ <ColorMenu value={line.stroke} onChange={(c, committed) => committed ? update(ids, { stroke: c }) : updateLive(ids, { stroke: c })} title="Line colour" />
+ <ToolbarPopover trigger={(open) => (
+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Line style" title="Line style">
+ <Minus size={14} /> <span className="text-[12px] hidden lg:inline">Style</span>
+ </button>
+ )}>
+ <SliderRow label="Thickness" value={line.strokeWidth} min={1} max={40} step={1} onChange={(v) => updateLive(ids, { strokeWidth: v })} onCommit={() => update(ids, { strokeWidth: line.strokeWidth })} />
+ <label className="flex items-center justify-between text-[12px] text-white/80 mb-2.5 cursor-pointer">
+ Dashed
+ <input type="checkbox" checked={line.dashed} onChange={(e) => update(ids, { dashed: e.target.checked })} className="accent-[#7630D7]" />
+ </label>
+ <div className="flex gap-1.5">
+ <TBtn onClick={() => update(ids, { arrowEnd: !line.arrowEnd })} dataActive={line.arrowEnd} title="Arrow end" ariaLabel="Arrow end">→</TBtn>
+ <TBtn onClick={() => update(ids, { arrowStart: !line.arrowStart })} dataActive={line.arrowStart} title="Arrow start" ariaLabel="Arrow start">←</TBtn>
+ </div>
+ </ToolbarPopover>
+ </>
+ )}
+ {sticker && (
+ <SliderRowMini label="Size" value={sticker.fontSize} min={24} max={320} onChange={(v) => updateLive(ids, { fontSize: v, width: v * 1.3, height: v * 1.3 })} onCommit={() => update(ids, { fontSize: sticker.fontSize })} />
+ )}
+ {group && (
+ <span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5">
+ <Layers size={13} /> Group
+ </span>
+ )}
+ <ToolbarPopover trigger={(open) => (
+ <button className="cv-tbtn" data-active={open} aria-label="Transparency" title="Transparency">
+ <Percent size={14} />
+ </button>
+ )}>
+ <SliderRow label="Transparency" value={Math.round(first.opacity * 100)} min={0} max={100} step={1}
+ onChange={(v) => updateLive(ids, { opacity: v / 100 })}
+ onCommit={() => update(ids, { opacity: first.opacity })}
+ format={(v) => `${100 - v}% transparent`} />
+ </ToolbarPopover>
+ <Divider />
+ <PositionPopover ids={ids} count={1} element={first} />
+ </>
+ ) : image ? (
+ <>
+ <ImageAdjustPopover el={image} ids={ids} />
+ <Divider />
+ <ColorMenu value="#FFFFFF" onChange={() => undefined} title="Filter tint (soon)" />
+ <ToolbarPopover trigger={(open) => (
+ <button className="cv-tbtn" data-active={open} aria-label="Transparency" title="Transparency">
+ <Percent size={14} />
+ </button>
+ )}>
+ <SliderRow label="Transparency" value={Math.round(image.opacity * 100)} min={0} max={100} step={1}
+ onChange={(v) => updateLive(ids, { opacity: v / 100 })}
+ onCommit={() => update(ids, { opacity: image.opacity })}
+ format={(v) => `${100 - v}% transparent`} />
+ </ToolbarPopover>
+ <Divider />
+ <PositionPopover ids={ids} count={1} element={first} />
+ </>
+ ) : null}
</div>
)
}
-function SpacingControl({
- letterSpacing,
- lineHeight,
- onChangeLetter,
- onChangeLine,
-}: {
- letterSpacing: number
- lineHeight: number
- onChangeLetter: (v: number) => void
- onChangeLine: (v: number) => void
-}) {
+/** canva position popover: arrange 2×2 + align 6 + advanced W/H/X/Y/rotate */
+function PositionPopover({ ids, count, element }: { ids: string[]; count: number; element?: AnyElement }) {
+ const store = useEditorStore()
+ const el = element ?? selectedElements(store)[0]
+
+ const [ratio, setRatio] = useState(false)
+ const W = el?.width ?? 0
+ const H = el?.height ?? 0
+
+ const setSize = (w: number, h: number) => {
+ store.updateElements(ids, { width: Math.max(4, Math.round(w)), height: Math.max(4, Math.round(h)) })
+ }
+
return (
- <Popover>
- <PopoverTrigger asChild>
- <ToolButton title="Letter & line spacing">
- <MoveDiagonal size={14} />
- </ToolButton>
- </PopoverTrigger>
- <PopoverContent className="w-56 p-3 bg-[#16181D] border-white/10 text-white">
- <div className="flex items-center justify-between text-xs font-medium">
- <span>Letter spacing</span>
- <span>{letterSpacing.toFixed(0)}px</span>
+ <ToolbarPopover
+ width={252}
+ trigger={(open) => (
+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Position" title="Position, layer ordering & size">
+ <Move size={14} /> <span className="text-[12px] hidden lg:inline">Position</span>
+ </button>
+ )}
+ >
+ {/* arrange 2×2 */}
+ <div className="grid grid-cols-2 gap-1 mb-2.5">
+ <IconTile icon={<ArrowUpToLine size={15} />} label="Forward" onClick={() => ids.forEach((id) => store.moveLayer(id, 'up'))} />
+ <IconTile icon={<ArrowDownToLine size={15} />} label="Backward" onClick={() => ids.forEach((id) => store.moveLayer(id, 'down'))} />
+ <IconTile icon={<BringToFront size={15} />} label="To front" onClick={() => ids.forEach((id) => store.moveLayer(id, 'front'))} />
+ <IconTile icon={<SendToBack size={15} />} label="To back" onClick={() => ids.forEach((id) => store.moveLayer(id, 'back'))} />
+ </div>
+
+ <div className="border-t border-white/[0.08] pt-2 mb-2.5">
+ <div className="text-[10px] font-semibold text-white/45 uppercase tracking-wide mb-1.5">Align to page</div>
+ <div className="grid grid-cols-3 gap-1">
+ <IconTile icon={<AlignVerticalJustifyStart size={15} />} label="Top" onClick={() => store.alignElements(ids, 'top')} />
+ <IconTile icon={<AlignVerticalJustifyCenter size={15} />} label="Middle" onClick={() => store.alignElements(ids, 'cy')} />
+ <IconTile icon={<AlignVerticalJustifyEnd size={15} />} label="Bottom" onClick={() => store.alignElements(ids, 'bottom')} />
+ <IconTile icon={<AlignHorizontalJustifyStart size={15} />} label="Left" onClick={() => store.alignElements(ids, 'left')} />
+ <IconTile icon={<AlignHorizontalJustifyCenter size={15} />} label="Centre" onClick={() => store.alignElements(ids, 'cx')} />
+ <IconTile icon={<AlignHorizontalJustifyEnd size={15} />} label="Right" onClick={() => store.alignElements(ids, 'right')} />
</div>
- <Slider value={[letterSpacing]} min={-10} max={40} step={1} onValueChange={(v) => onChangeLetter(v[0])} className="mt-2" />
- <div className="flex items-center justify-between text-xs font-medium mt-4">
- <span>Line height</span>
- <span>{lineHeight.toFixed(2)}</span>
+ </div>
+
+ {count === 1 && el && (
+ <div className="border-t border-white/[0.08] pt-2">
+ <div className="text-[10px] font-semibold text-white/45 uppercase tracking-wide mb-1.5">Advanced</div>
+ <div className="grid grid-cols-3 gap-1.5 mb-1.5">
+ <NumField label="W" value={W} onCommit={(v) => setSize(ratio ? v * (H / W) : v, ratio ? v * (H / W) : H)} />
+ <NumField label="H" value={H} onCommit={(v) => setSize(ratio ? v * (W / H) : W, ratio ? v * (W / H) : v)} />
+ <button
+ className="flex flex-col items-center justify-center gap-0.5 rounded-lg border border-white/10 text-white/75 hover:bg-white/[0.09] text-[10px] font-medium py-1"
+ onClick={() => setRatio(!ratio)}
+ title="Lock aspect ratio"
+ >
+ <Lock size={12} className={ratio ? 'text-[#7630D7]' : 'opacity-50'} />
+ Ratio
+ </button>
+ </div>
+ <div className="grid grid-cols-3 gap-1.5">
+ <NumField label="X" value={Math.round(el.x)} onCommit={(v) => store.updateElements(ids, { x: Math.round(v) })} />
+ <NumField label="Y" value={Math.round(el.y)} onCommit={(v) => store.updateElements(ids, { y: Math.round(v) })} />
+ <NumField label="Rotate" value={Math.round(el.rotation)} suffix="°" onCommit={(v) => store.updateElements(ids, { rotation: ((v % 360) + 360) % 360 })} />
+ </div>
</div>
- <Slider value={[lineHeight * 100]} min={80} max={250} step={5} onValueChange={(v) => onChangeLine(v[0] / 100)} className="mt-2" />
- </PopoverContent>
- </Popover>
+ )}
+ </ToolbarPopover>
)
}
-function ShadowControl({ element }: { element: AnyElement }) {
+/** image adjustments popover (canva "Edit image" lite) */
+function ImageAdjustPopover({ el, ids }: { el: ImageElement; ids: string[] }) {
const update = useEditorStore((s) => s.updateElements)
- const enabled = element.shadow?.enabled ?? false
- const setShadow = (patch: Partial<typeof element.shadow>) => {
- update([element.id], { shadow: { ...element.shadow, ...patch } })
- }
+ const updateLive = useEditorStore((s) => s.updateElementsLive)
return (
- <Popover>
- <PopoverTrigger asChild>
- <ToolButton title="Shadow" active={enabled}>
- <svg viewBox="0 0 24 24" className="h-[15px] w-[15px]" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
- <path d="M12 3v9" />
- <path d="M12 12c0 4-3 6-6.5 6A5.5 5.5 0 0 1 12 12z" fill="currentColor" fillOpacity={enabled ? 0.35 : 0.12} />
- </svg>
- </ToolButton>
- </PopoverTrigger>
- <PopoverContent className="w-56 p-3 bg-[#16181D] border-white/10 text-white">
- <label className="flex items-center justify-between text-xs font-medium cursor-pointer">
- <span>Shadow</span>
- <input type="checkbox" checked={enabled} onChange={(e) => setShadow({ enabled: e.target.checked })} className="accent-[#00C4CC]" />
- </label>
- {enabled && (
- <>
- <div className="flex items-center justify-between text-xs font-medium mt-3">
- <span>Blur</span>
- <span>{element.shadow.blur}px</span>
- </div>
- <Slider value={[element.shadow.blur]} min={0} max={60} step={1} onValueChange={(v) => setShadow({ blur: v[0] })} className="mt-2" />
- <div className="flex items-center justify-between text-xs font-medium mt-2">
- <span>Offset Y</span>
- <span>{element.shadow.offsetY}px</span>
- </div>
- <Slider value={[element.shadow.offsetY]} min={-40} max={40} step={1} onValueChange={(v) => setShadow({ offsetY: v[0], offsetX: 0 })} className="mt-2" />
- <div className="mt-3 flex items-center gap-2">
- <span className="text-xs font-medium">Color</span>
- <ColorPicker
- value={element.shadow.color}
- onChange={(c) => setShadow({ color: c })}
- label="Shadow color"
- />
- </div>
- </>
- )}
- </PopoverContent>
- </Popover>
+ <ToolbarPopover
+ width={252}
+ trigger={(open) => (
+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Adjust image" title="Adjust image">
+ <Sun size={14} /> <span className="text-[12px] hidden lg:inline">Adjust</span>
+ </button>
+ )}
+ >
+ <SliderRow label="Brightness" value={el.brightness ?? 0} min={-100} max={100} step={1} onChange={(v) => updateLive(ids, { brightness: v })} onCommit={() => update(ids, { brightness: el.brightness ?? 0 })} />
+ <SliderRow label="Contrast" value={el.contrast ?? 0} min={-100} max={100} step={1} onChange={(v) => updateLive(ids, { contrast: v })} onCommit={() => update(ids, { contrast: el.contrast ?? 0 })} />
+ <SliderRow label="Saturation" value={el.saturation ?? 0} min={-100} max={100} step={1} onChange={(v) => updateLive(ids, { saturation: v })} onCommit={() => update(ids, { saturation: el.saturation ?? 0 })} />
+ <div className="flex gap-1.5 mt-1 border-t border-white/[0.08] pt-2.5">
+ <TBtn onClick={() => update(ids, { flipH: !el.flipH })} dataActive={el.flipH} title="Flip horizontal" ariaLabel="Flip horizontal"><FlipHorizontal size={14} /></TBtn>
+ <TBtn onClick={() => update(ids, { flipV: !el.flipV })} dataActive={el.flipV} title="Flip vertical" ariaLabel="Flip vertical"><FlipVertical size={14} /></TBtn>
+ <TBtn onClick={() => update(ids, { brightness: 0, contrast: 0, saturation: 0 })} title="Reset adjustments" ariaLabel="Reset adjustments"><RotateCcw size={14} /></TBtn>
+ <TBtn onClick={() => useEditorStore.getState().setPanel('uploads')} title="Replace image" ariaLabel="Replace image"><Replace size={14} /></TBtn>
+ </div>
+ </ToolbarPopover>
)
}
-/** Canva-style text effects: None / Shadow / Lift / Hollow / Neon / Echo */
-function EffectsControl({ effect, onChange }: { effect: TextEffect; onChange: (fx: TextEffect) => void }) {
+function SliderRowMini({ label, value, min, max, onChange, onCommit }: { label: string; value: number; min: number; max: number; onChange: (v: number) => void; onCommit: () => void }) {
return (
- <Popover>
- <PopoverTrigger asChild>
- <ToolButton title="Effects" active={effect !== 'none'}>
- <Wand2 size={14} />
- </ToolButton>
- </PopoverTrigger>
- <PopoverContent className="w-64 p-3 bg-[#16181D] border-white/10 text-white">
- <div className="text-xs font-bold uppercase tracking-wide text-white/50 mb-2">Text effects</div>
- <div className="grid grid-cols-3 gap-2">
- {TEXT_EFFECTS.map((fx) => (
- <button
- key={fx.id}
- onClick={() => onChange(fx.id)}
- className={cn(
- 'rounded-xl border px-2 py-2.5 text-center transition-colors',
- effect === fx.id ? 'border-[#7630D7] bg-[#7630D7]/25' : 'border-white/10 bg-white/[0.04] hover:border-white/30'
- )}
- aria-pressed={effect === fx.id}
- >
- <span
- className="block text-[15px] font-bold leading-tight"
- style={
- fx.id === 'shadow'
- ? { textShadow: '0 3px 5px rgba(0,0,0,0.5)' }
- : fx.id === 'lift'
- ? { textShadow: '0 4px 0 rgba(0,0,0,0.55)' }
- : fx.id === 'hollow'
- ? { WebkitTextStroke: '1px #fff', color: 'transparent' }
- : fx.id === 'neon'
- ? { textShadow: '0 0 10px #02C0CC, 0 0 20px #02C0CC' }
- : fx.id === 'echo'
- ? { textShadow: '3px 3px 0 rgba(255,255,255,0.4)' }
- : undefined
- }
- >
- Aa
- </span>
- <span className="block text-[10px] mt-1 text-white/70">{fx.label}</span>
- </button>
- ))}
- </div>
- </PopoverContent>
- </Popover>
+ <div className="flex items-center gap-2 px-2 shrink-0 w-[150px]">
+ <span className="text-[11px] text-white/60 w-8">{label}</span>
+ <input
+ type="range"
+ className="cv-slider w-full"
+ style={{ background: `linear-gradient(to right, #7630D7 ${((value - min) / (max - min)) * 100}%, rgba(255,255,255,0.14) ${((value - min) / (max - min)) * 100}%)` }}
+ min={min}
+ max={max}
+ value={value}
+ onChange={(e) => onChange(Number(e.target.value))}
+ onPointerUp={onCommit}
+ aria-label={label}
+ />
+ </div>
+ )
+}
+
+function NumField({ label, value, onCommit, suffix }: { label: string; value: number; onCommit: (v: number) => void; suffix?: string }) {
+ const [v, setV] = useState(String(value))
+ const [editing, setEditing] = useState(false)
+ if (!editing && String(value) !== v) setV(String(value))
+ return (
+ <label className="flex flex-col items-center gap-0.5">
+ <span className="text-[9px] text-white/40 font-medium">{label}</span>
+ <span className="relative w-full">
+ <input
+ value={v}
+ onFocus={() => setEditing(true)}
+ onChange={(e) => setV(e.target.value)}
+ onBlur={() => { setEditing(false); const n = Number(v); if (!Number.isNaN(n)) onCommit(n) }}
+ onKeyDown={(e) => { if (e.key === 'Enter') (e.target as HTMLInputElement).blur() }}
+ className="h-7 w-full rounded-lg bg-white/[0.07] border border-white/10 px-1 text-[11px] text-white text-center outline-none focus:border-[#7630D7] [color-scheme:dark]"
+ aria-label={label}
+ />
+ {suffix && <span className="absolute right-1.5 top-1/2 -translate-y-1/2 text-[9px] text-white/35 pointer-events-none">{suffix}</span>}
+ </span>
+ </label>
)
}
+
+function TBtn({ children, onClick, title, ariaLabel, disabled, danger, className, dataActive }: {
+ children: React.ReactNode
+ onClick?: () => void
+ title?: string
+ ariaLabel: string
+ disabled?: boolean
+ danger?: boolean
+ className?: string
+ dataActive?: boolean
+}) {
+ return (
+ <button
+ onClick={onClick}
+ disabled={disabled}
+ title={title}
+ aria-label={ariaLabel}
+ data-active={dataActive ? 'true' : undefined}
+ className={cn('cv-tbtn', danger && 'hover:bg-[#ff5a5a]/15 hover:text-[#ff8080]', className)}
+ >
+ {children}
+ </button>
+ )
+}
+
+const Divider = () => <span className="w-px h-5 bg-white/15 mx-1 shrink-0" />
diff --git a/src/components/editor/TopBar.tsx b/src/components/editor/TopBar.tsx
index c8c40e7..74b4679 100644
--- a/src/components/editor/TopBar.tsx
+++ b/src/components/editor/TopBar.tsx
@@ -5,11 +5,12 @@ import { Home, MessageCircle, Play, Share2, ChevronDown, Undo2, Redo2, Download,
import { useAppStore } from '@/store/app-store'
import { useEditorStore } from '@/store/editor-store'
import { Button } from '@/components/ui/button'
-import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { cn } from '@/lib/utils'
import { ExportDialog } from './ExportDialog'
import { ResizeDialog } from './ResizeDialog'
import { ShareDialog } from './ShareDialog'
+import { ContextToolbar } from './PropertiesBar'
/** Canva-2026 editor topbar: 56px cyan→purple gradient, white text, File/Resize/Editing left, Preview/Share right. */
export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; onShortcuts: () => void }) {
@@ -27,6 +28,7 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o
const setEditingMode = useEditorStore((s) => s.setEditingMode)
const setPreviewOpen = useEditorStore((s) => s.setPreviewOpen)
const setPanel = useEditorStore((s) => s.setPanel)
+ const selectedIds = useEditorStore((s) => s.selectedIds)
const [exportOpen, setExportOpen] = useState(false)
const [resizeOpen, setResizeOpen] = useState(false)
@@ -34,12 +36,22 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o
const item = 'h-10 px-3 rounded-xl text-white/95 hover:bg-white/15 transition-colors text-sm font-semibold flex items-center gap-1.5 select-none'
+ // canva behaviour: an element selection replaces the topbar middle section with the context toolbar
+ const hasSelection = selectedIds.length > 0
+
return (
<header className="h-14 cv-topbar-gradient flex items-center gap-1 px-2 sm:px-3 z-40 shrink-0 shadow-[0_1px_0_rgba(0,0,0,0.15)]">
<Button variant="ghost" size="icon" className="rounded-full text-white hover:bg-white/15 hover:text-white shrink-0" onClick={goDashboard} aria-label="Back to home" title="Home">
<Home size={19} />
</Button>
+ {hasSelection ? (
+ /* context toolbar occupies the middle (desktop only; mobile gets the bottom bar) */
+ <div className="hidden md:flex flex-1 min-w-0 overflow-hidden">
+ <ContextToolbar />
+ </div>
+ ) : (
+ <>
{/* File menu */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -119,6 +131,8 @@ export function TopBar({ onSave, onShortcuts }: { onSave: () => Promise<void>; o
) : null}
</span>
</div>
+ </>
+ )}
<div className="ml-auto flex items-center gap-0.5 sm:gap-1 shrink-0">
<Button variant="ghost" size="icon" className="rounded-lg text-white hover:bg-white/15 hover:text-white" onClick={undo} disabled={!canUndo} aria-label="Undo" title="Undo (Ctrl+Z)">
diff --git a/src/components/editor/ZoomControls.tsx b/src/components/editor/ZoomControls.tsx
index 2cf4775..e14767c 100644
--- a/src/components/editor/ZoomControls.tsx
+++ b/src/components/editor/ZoomControls.tsx
@@ -1,42 +1,107 @@
'use client'
-import { ZoomIn, ZoomOut, Maximize } from 'lucide-react'
+import { useState } from 'react'
+import { ZoomIn, ZoomOut, Maximize, Check, ChevronsUpDown, Scan } from 'lucide-react'
import { useEditorStore } from '@/store/editor-store'
import { canvasBridge } from './canvas/canvas-bridge'
+import { cn } from '@/lib/utils'
+const PRESETS = [300, 200, 125, 100, 75, 50, 25, 10]
+
+/** canva-style zoom bar: − [percent ▾] + fit — dropdown = 128px listbox, 40px items */
export function ZoomControls() {
const zoom = useEditorStore((s) => s.zoom)
const zoomIn = useEditorStore((s) => s.zoomIn)
const zoomOut = useEditorStore((s) => s.zoomOut)
- const resetZoom = useEditorStore((s) => s.resetZoom)
+ const setZoom = useEditorStore((s) => s.setZoom)
+ const fitToScreen = useEditorStore((s) => s.fitToScreen)
+ const [open, setOpen] = useState(false)
const percent = Math.round(zoom * 100)
+ const isFit = Math.abs(zoom - 1) < 0.001 || percent === 100
+
+ const applyPreset = (p: number) => {
+ setZoom(p / 100)
+ setOpen(false)
+ }
+
+ const doFill = () => {
+ // Fill = zoom page to cover the viewport height
+ const vp = useEditorStore.getState().viewport
+ const { width, height } = useEditorStore.getState()
+ if (vp.height > 50) {
+ setZoom(Math.max(0.05, (vp.height - 60) / height))
+ } else {
+ setZoom(1)
+ }
+ void width
+ setOpen(false)
+ }
return (
<div className="absolute bottom-3 right-3 z-30 flex items-center gap-0.5 rounded-xl bg-[#1D1F26]/95 backdrop-blur border border-white/10 shadow-xl shadow-black/40 px-1 py-1">
- <button className="h-8 w-8 rounded-lg flex items-center justify-center text-white/75 hover:bg-white/10 hover:text-white" onClick={zoomOut} aria-label="Zoom out" title="Zoom out">
- <ZoomOut size={15} />
+ <button className="h-10 w-10 rounded-xl flex items-center justify-center text-white/75 hover:bg-white/10 hover:text-white" onClick={zoomOut} aria-label="Zoom out" title="Zoom out">
+ <ZoomOut size={16} />
</button>
<button
- className="h-8 min-w-12 px-1 rounded-lg text-xs font-semibold text-white/85 hover:bg-white/10 hover:text-white"
- onClick={resetZoom}
- aria-label="Reset zoom to 100%"
- title="Reset zoom"
+ className="h-10 min-w-[64px] px-2 rounded-xl text-[13px] font-semibold text-white/90 hover:bg-white/10 flex items-center justify-center gap-1"
+ onClick={() => setOpen(!open)}
+ aria-label="Zoom options"
+ aria-expanded={open}
+ aria-haspopup="listbox"
+ title="Zoom options"
>
- {percent}%
+ {percent}% <ChevronsUpDown size={11} className="opacity-50" />
</button>
- <button className="h-8 w-8 rounded-lg flex items-center justify-center text-white/75 hover:bg-white/10 hover:text-white" onClick={zoomIn} aria-label="Zoom in" title="Zoom in">
- <ZoomIn size={15} />
+ <button className="h-10 w-10 rounded-xl flex items-center justify-center text-white/75 hover:bg-white/10 hover:text-white" onClick={zoomIn} aria-label="Zoom in" title="Zoom in">
+ <ZoomIn size={16} />
</button>
<span className="h-5 w-px bg-white/15 mx-0.5" aria-hidden="true" />
<button
- className="h-8 w-8 rounded-lg flex items-center justify-center text-white/75 hover:bg-white/10 hover:text-white"
- onClick={() => canvasBridge.fitToScreen?.()}
+ className="h-10 w-10 rounded-xl flex items-center justify-center text-white/75 hover:bg-white/10 hover:text-white"
+ onClick={() => canvasBridge.fitToScreen?.() ?? fitToScreen()}
aria-label="Fit to screen"
title="Fit to screen"
>
- <Maximize size={15} />
+ <Maximize size={16} />
</button>
+
+ {open && (
+ <>
+ <div className="fixed inset-0 z-[70]" onClick={() => setOpen(false)} onContextMenu={(e) => { e.preventDefault(); setOpen(false) }} />
+ <div
+ className="cv-menu !min-w-[128px] !max-w-[128px] !p-1.5"
+ role="listbox"
+ aria-label="Zoom level"
+ style={{ right: 12, bottom: 56, left: 'auto', top: 'auto' }}
+ >
+ {PRESETS.map((p) => (
+ <button
+ key={p}
+ role="option"
+ aria-selected={percent === p}
+ className={cn('cv-menu-item !h-10 !justify-between', percent === p && 'bg-white/[0.08]')}
+ onClick={() => applyPreset(p)}
+ >
+ {p}%
+ {percent === p && <Check size={13} className="text-white/80" />}
+ </button>
+ ))}
+ <div className="cv-menu-sep" />
+ <button
+ role="option"
+ className="cv-menu-item !h-10 !justify-between"
+ onClick={() => { canvasBridge.fitToScreen?.() ?? fitToScreen(); setOpen(false) }}
+ >
+ <span className="flex items-center gap-2"><Scan size={13} /> Fit</span>
+ {isFit && <Check size={13} className="text-white/80" />}
+ </button>
+ <button role="option" className="cv-menu-item !h-10" onClick={doFill}>
+ Fill
+ </button>
+ </div>
+ </>
+ )}
</div>
)
}
diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.ts
index 606e4d2..2aef1b4 100644
--- a/src/components/editor/add-element.ts
+++ b/src/components/editor/add-element.ts
@@ -120,3 +120,63 @@ export function addImageFromFile(file: File): Promise<void> {
reader.readAsDataURL(file)
})
}
+
+/** replace the src of the currently selected image element (canva "Replace") */
+export function replaceSelectedImage(src: string, naturalWidth: number, naturalHeight: number) {
+ const state = useEditorStore.getState()
+ const sel = state.pages[state.currentPage].elements.filter((e) => state.selectedIds.includes(e.id) && e.type === 'image')
+ if (!sel.length) {
+ addImageFromSrc(src, naturalWidth, naturalHeight)
+ return
+ }
+ for (const el of sel) {
+ const im = el as import('@/lib/types').ImageElement
+ // keep the box, refit aspect if it distorts more than 15%
+ const boxRatio = im.width / im.height
+ const imgRatio = naturalWidth / naturalHeight
+ let { width, height } = im
+ if (Math.abs(boxRatio - imgRatio) / imgRatio > 0.15) {
+ const refit = Math.min(im.width / naturalWidth, im.height / naturalHeight)
+ width = Math.round(naturalWidth * refit)
+ height = Math.round(naturalHeight * refit)
+ }
+ state.updateElements([im.id], { src, naturalWidth, naturalHeight, width, height })
+ }
+}
+
+/** load a File → {src, w, h} without touching the canvas */
+export function readImageFile(file: File): Promise<{ src: string; w: number; h: number }> {
+ return new Promise((resolve, reject) => {
+ if (!file.type.startsWith('image/')) {
+ reject(new Error('Not an image'))
+ return
+ }
+ const reader = new FileReader()
+ reader.onload = () => {
+ const src = String(reader.result)
+ const img = new window.Image()
+ img.onload = () => resolve({ src, w: img.naturalWidth, h: img.naturalHeight })
+ img.onerror = () => resolve({ src, w: 500, h: 500 })
+ img.src = src
+ }
+ reader.onerror = () => reject(new Error('read failed'))
+ reader.readAsDataURL(file)
+ })
+}
+
+/** add an image dropped at a page position */
+export function addImageAt(src: string, naturalWidth: number, naturalHeight: number, x: number, y: number) {
+ const state = useEditorStore.getState()
+ const maxW = state.width * 0.7
+ const scale = Math.min(maxW / naturalWidth, 1)
+ const w = Math.round(naturalWidth * scale)
+ const h = Math.round(naturalHeight * scale)
+ state.addElement(
+ createImageElement(src, naturalWidth, naturalHeight, {
+ x: Math.max(0, Math.round(x - w / 2)),
+ y: Math.max(0, Math.round(y - h / 2)),
+ width: w,
+ height: h,
+ })
+ )
+}
diff --git a/src/components/editor/canvas/CanvasStage.tsx b/src/components/editor/canvas/CanvasStage.tsx
index e223cf0..d7f7510 100644
--- a/src/components/editor/canvas/CanvasStage.tsx
+++ b/src/components/editor/canvas/CanvasStage.tsx
@@ -10,8 +10,11 @@ import { canvasBridge } from './canvas-bridge'
import { ElementNode } from './element-node'
import type { TextElement } from '@/lib/types'
import { createStrokeElement } from '@/lib/types'
+import { CanvasContextMenu, type ContextMenuState } from './context-menu'
-const GUIDE_COLOR = '#FF33AA'
+/** canva-measured tokens */
+const GUIDE_COLOR = '#9954FF' // rgb(153,84,255) — measured 2026-09-03
+const SELECTION_COLOR = '#7630D7' // rgb(118,48,215) — measured
export default function CanvasStage() {
const containerRef = useRef<HTMLDivElement>(null)
@@ -26,7 +29,10 @@ export default function CanvasStage() {
const height = useEditorStore((s) => s.height)
const zoom = useEditorStore((s) => s.zoom)
const setZoom = useEditorStore((s) => s.setZoom)
+ const setViewport = useEditorStore((s) => s.setViewport)
const clearSelection = useEditorStore((s) => s.clearSelection)
+ const setSelection = useEditorStore((s) => s.setSelection)
+ const selectToggle = useEditorStore((s) => s.selectToggle)
const selectedIds = useEditorStore((s) => s.selectedIds)
const tool = useEditorStore((s) => s.tool)
const drawColor = useEditorStore((s) => s.drawColor)
@@ -40,7 +46,12 @@ export default function CanvasStage() {
const [editValue, setEditValue] = useState('')
/** freehand draft: [x0,y0,x1,y1,…] in page coords */
const [draft, setDraft] = useState<number[] | null>(null)
+ /** marquee draft in PAGE coords */
+ const [marquee, setMarquee] = useState<{ x0: number; y0: number; x1: number; y1: number } | null>(null)
+ const [ctxMenu, setCtxMenu] = useState<ContextMenuState | null>(null)
const drawingRef = useRef(false)
+ const marqueeRef = useRef(false)
+ const spaceRef = useRef(false)
const interactive = editingMode === 'editing' && tool === 'select'
@@ -64,6 +75,35 @@ export default function CanvasStage() {
return () => ro.disconnect()
}, [])
+ // report viewport size to the store (zoom menu "Fit")
+ useEffect(() => {
+ setViewport({ width: containerSize.w, height: containerSize.h })
+ }, [containerSize, setViewport])
+
+ // ── space key tracking (space+drag = pan) ──────────────────
+ useEffect(() => {
+ const down = (e: KeyboardEvent) => {
+ if (e.code === 'Space') {
+ const target = e.target as HTMLElement
+ if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) return
+ spaceRef.current = true
+ containerRef.current?.style.setProperty('cursor', 'grab')
+ }
+ }
+ const up = (e: KeyboardEvent) => {
+ if (e.code === 'Space') {
+ spaceRef.current = false
+ if (!panGestureRef.current?.active) containerRef.current?.style.setProperty('cursor', 'default')
+ }
+ }
+ window.addEventListener('keydown', down)
+ window.addEventListener('keyup', up)
+ return () => {
+ window.removeEventListener('keydown', down)
+ window.removeEventListener('keyup', up)
+ }
+ }, [])
+
// ── fit to screen ──────────────────────────────────────────
const fitToScreen = useCallback(() => {
if (containerSize.w < 50 || containerSize.h < 50) return
@@ -146,27 +186,6 @@ export default function CanvasStage() {
}
}, [refreshTransformer])
- // transformer visual scale compensation
- useEffect(() => {
- const tr = trRef.current
- if (!tr) return
- tr.setAttrs({
- anchorSize: 11 / zoom,
- anchorStrokeWidth: 1.5 / zoom,
- anchorCornerRadius: 12 / zoom,
- rotateAnchorOffset: 28 / zoom,
- borderWidth: 1.5 / zoom,
- padding: 5 / zoom,
- anchorStroke: '#00C4CC',
- anchorFill: '#FFFFFF',
- borderStroke: '#00C4CC',
- rotateEnabled: true,
- keepRatio: true,
- flipEnabled: false,
- })
- tr.forceUpdate()
- }, [zoom, selectedIds, pages])
-
// ── node registry ──────────────────────────────────────────
const registerNode = useCallback((id: string, node: Konva.Node | null) => {
if (node) nodesRef.current.set(id, node)
@@ -200,6 +219,7 @@ export default function CanvasStage() {
const p = currentPageData(state)
const el = p.elements.find((e) => e.id === id)
if (!el || el.type !== 'text' || el.locked) return
+ // if the text lives inside a group, edit via double-click is disabled for simplicity
state.pushHistory()
setEditingTextId(id)
setEditValue((el as TextElement).text)
@@ -222,7 +242,7 @@ export default function CanvasStage() {
)
}, [editingTextId, editValue])
- // ── empty-area pan (mouse + single touch) ──────────────────
+ // ── empty-area pan (space+drag / middle-mouse / touch) ─────
const beginPan = (clientX: number, clientY: number) => {
panGestureRef.current = { active: true, startX: clientX, startY: clientY, baseX: pan.x, baseY: pan.y }
containerRef.current?.style.setProperty('cursor', 'grabbing')
@@ -239,6 +259,28 @@ export default function CanvasStage() {
containerRef.current?.style.setProperty('cursor', 'default')
}
+ // ── marquee helpers (page coords) ──────────────────────────
+ const pagePoint = (clientX: number, clientY: number) => {
+ const container = containerRef.current?.getBoundingClientRect()
+ if (!container) return null
+ return {
+ x: (clientX - container.left - pan.x) / zoom,
+ y: (clientY - container.top - pan.y) / zoom,
+ }
+ }
+
+ const selectInMarquee = (a: { x0: number; y0: number; x1: number; y1: number }) => {
+ const x = Math.min(a.x0, a.x1), y = Math.min(a.y0, a.y1)
+ const w = Math.abs(a.x1 - a.x0), h = Math.abs(a.y1 - a.y0)
+ if (w < 4 && h < 4) return
+ const hits = page.elements
+ .filter((e) => e.visible && !e.locked)
+ .filter((e) => e.x < x + w && e.x + e.width > x && e.y < y + h && e.y + e.height > y)
+ .map((e) => e.id)
+ if (hits.length) setSelection(hits)
+ else clearSelection()
+ }
+
const handleStageMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (editingMode !== 'editing') return
if (tool === 'draw') {
@@ -246,17 +288,32 @@ export default function CanvasStage() {
const pointer = stage?.getPointerPosition()
if (!pointer) return
const px = (pointer.x - pan.x) / zoom
- const py = (pointer.y - pan.y) / zoom
+ const py = (pointer.y - pan.y) / zoom
drawingRef.current = true
setDraft([px, py, px, py])
return
}
const target = e.target
- if (target === e.target.getStage() || target.name() === 'page-bg') {
+ const onEmpty = target === e.target.getStage() || target.name() === 'page-bg'
+ if (!onEmpty) return
+
+ const middleButton = e.evt.button === 1
+ if (middleButton || spaceRef.current) {
clearSelection()
beginPan(e.evt.clientX, e.evt.clientY)
+ e.evt.preventDefault()
+ return
+ }
+
+ if (e.evt.button === 0) {
+ // left button on empty area → marquee selection (canva behaviour)
+ const pt = pagePoint(e.evt.clientX, e.evt.clientY)
+ if (!pt) return
+ marqueeRef.current = true
+ setMarquee({ x0: pt.x, y0: pt.y, x1: pt.x, y1: pt.y })
}
}
+
const handleStageTouchStart = (e: KonvaEventObject<TouchEvent>) => {
if (editingMode !== 'editing' || tool === 'draw') return
if (e.evt.touches.length === 2) {
@@ -279,10 +336,27 @@ export default function CanvasStage() {
}
}
- // window-level gesture listeners (pan + pinch)
+ // window-level gesture listeners (pan + pinch + marquee)
useEffect(() => {
- const onMove = (e: MouseEvent) => movePan(e.clientX, e.clientY)
- const onUp = () => endPan()
+ const onMove = (e: MouseEvent) => {
+ if (marqueeRef.current) {
+ const pt = pagePoint(e.clientX, e.clientY)
+ if (pt) setMarquee((m) => (m ? { ...m, x1: pt.x, y1: pt.y } : m))
+ return
+ }
+ movePan(e.clientX, e.clientY)
+ }
+ const onUp = () => {
+ if (marqueeRef.current) {
+ marqueeRef.current = false
+ setMarquee((m) => {
+ if (m) selectInMarquee(m)
+ return null
+ })
+ return
+ }
+ endPan()
+ }
const onTouchMove = (e: TouchEvent) => {
const pinch = pinchRef.current
if (pinch && e.touches.length === 2) {
@@ -322,7 +396,24 @@ export default function CanvasStage() {
window.removeEventListener('touchend', onTouchEnd)
window.removeEventListener('touchcancel', onTouchEnd)
}
- }, [pan, zoom])
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [pan, zoom, page])
+
+ // ── right-click context menu ───────────────────────────────
+ const handleContextMenu = (e: KonvaEventObject<PointerEvent>) => {
+ e.evt.preventDefault()
+ if (editingMode !== 'editing') return
+ const target = e.target
+ const isElement = target.name() === 'cv-element'
+ if (isElement) {
+ const id = target.id()
+ if (id && !selectedIds.includes(id)) setSelection([id])
+ setCtxMenu({ x: e.evt.clientX, y: e.evt.clientY, kind: 'element' })
+ } else {
+ clearSelection()
+ setCtxMenu({ x: e.evt.clientX, y: e.evt.clientY, kind: 'page' })
+ }
+ }
// ── wheel: ctrl/cmd = zoom, plain = pan ────────────────────
const handleWheel = (e: KonvaEventObject<WheelEvent>) => {
@@ -413,10 +504,17 @@ export default function CanvasStage() {
lineHeight: `${editingText.lineHeight}`,
letterSpacing: `${editingText.letterSpacing * zoom}px`,
color: editingText.fill,
- textAlign: editingText.align,
+ textAlign: editingText.align === 'justify' ? 'left' : editingText.align,
}
: null
+ /** canva-style circle anchors on the transformer */
+ const anchorStyleFunc = useCallback((anchor: Konva.Shape) => {
+ const a = anchor as Konva.Rect
+ a.cornerRadius(a.width() / 2)
+ a.strokeWidth(0)
+ }, [])
+
return (
<div
ref={containerRef}
@@ -430,6 +528,7 @@ export default function CanvasStage() {
height={containerSize.h}
onMouseDown={handleStageMouseDown}
onTouchStart={handleStageTouchStart}
+ onContextMenu={handleContextMenu}
onWheel={handleWheel}
>
<Layer ref={layerRef}>
@@ -450,16 +549,47 @@ export default function CanvasStage() {
<Transformer
ref={trRef}
keepRatio
+ rotateEnabled
+ flipEnabled={false}
boundBoxFunc={(oldBox, newBox) => (newBox.width < 8 || newBox.height < 8 ? oldBox : newBox)}
+ // canva-measured selection chrome: #7630D7 2px border + white circle handles
+ borderStroke={SELECTION_COLOR}
+ borderStrokeWidth={2 / zoom}
+ borderDash={undefined}
+ anchorStroke={SELECTION_COLOR}
+ anchorFill="#FFFFFF"
+ anchorSize={10 / zoom}
+ anchorCornerRadius={5 / zoom}
+ anchorStyleFunc={anchorStyleFunc}
+ anchorStrokeWidth={0}
+ rotateAnchorOffset={26 / zoom}
+ rotationSnaps={[0, 45, 90, 135, 180, 225, 270, 315]}
+ rotationSnapTolerance={4}
+ padding={2 / zoom}
+ useSingleNodeRotation
/>
- {/* snapping guides */}
+ {/* snapping guides — canva #9954FF 2px */}
{guides.map((g, i) =>
g.axis === 'x' ? (
- <Rect key={i} x={g.position} y={0} width={1 / zoom} height={height} fill={GUIDE_COLOR} listening={false} />
+ <Rect key={i} x={g.position} y={0} width={2 / zoom} height={height} fill={GUIDE_COLOR} listening={false} />
) : (
- <Rect key={i} x={0} y={g.position} width={width} height={1 / zoom} fill={GUIDE_COLOR} listening={false} />
+ <Rect key={i} x={0} y={g.position} width={width} height={2 / zoom} fill={GUIDE_COLOR} listening={false} />
)
)}
+ {/* marquee selection rect (canva: #7630D7 border, translucent fill) */}
+ {marquee && (
+ <Rect
+ x={Math.min(marquee.x0, marquee.x1)}
+ y={Math.min(marquee.y0, marquee.y1)}
+ width={Math.abs(marquee.x1 - marquee.x0)}
+ height={Math.abs(marquee.y1 - marquee.y0)}
+ fill="rgba(118,48,215,0.08)"
+ stroke={SELECTION_COLOR}
+ strokeWidth={1.5 / zoom}
+ dash={[4 / zoom, 3 / zoom]}
+ listening={false}
+ />
+ )}
{/* freehand draft */}
{draft && draft.length >= 4 && (
<Line
@@ -477,6 +607,14 @@ export default function CanvasStage() {
</Stage>
)}
+ {/* canva-style right-click context menu */}
+ {ctxMenu && (
+ <CanvasContextMenu
+ state={ctxMenu}
+ onClose={() => setCtxMenu(null)}
+ />
+ )}
+
{/* text editing overlay */}
{editingText && textareaStyle && (
<textarea
diff --git a/src/components/editor/canvas/context-menu.tsx b/src/components/editor/canvas/context-menu.tsx
new file mode 100644
index 0000000..268a0ba
--- /dev/null
+++ b/src/components/editor/canvas/context-menu.tsx
@@ -0,0 +1,140 @@
+'use client'
+
+import { useEffect, useRef } from 'react'
+import {
+ Copy,
+ Scissors,
+ ClipboardPaste,
+ CopyPlus,
+ Trash2,
+ BringToFront,
+ SendToBack,
+ ArrowUpToLine,
+ ArrowDownToLine,
+ Group,
+ Ungroup,
+ Lock,
+ Unlock,
+ Eye,
+ EyeOff,
+ SquareStack,
+ FilePlus2,
+ Palette,
+ MousePointerClick,
+} from 'lucide-react'
+import { useEditorStore } from '@/store/editor-store'
+import { isGroup } from '@/lib/types'
+
+export interface ContextMenuState {
+ x: number
+ y: number
+ kind: 'element' | 'page'
+}
+
+interface Item {
+ label: string
+ icon: React.ComponentType<{ size?: number | string; className?: string }>
+ kbd?: string
+ danger?: boolean
+ disabled?: boolean
+ onSelect?: () => void
+}
+
+const Sep = () => <div className="cv-menu-sep" />
+
+export function CanvasContextMenu({ state, onClose }: { state: ContextMenuState; onClose: () => void }) {
+ const ref = useRef<HTMLDivElement>(null)
+ const store = useEditorStore()
+
+ useEffect(() => {
+ const close = () => onClose()
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') onClose()
+ }
+ // close on any click outside / scroll / resize
+ window.addEventListener('mousedown', (e) => {
+ if (ref.current && !ref.current.contains(e.target as Node)) close()
+ }, { once: true, capture: true })
+ window.addEventListener('wheel', close, { once: true, capture: true })
+ window.addEventListener('keydown', onKey, { once: true })
+ return () => {
+ window.removeEventListener('mousedown', close, { capture: true })
+ window.removeEventListener('wheel', close, { capture: true })
+ window.removeEventListener('keydown', onKey)
+ }
+ }, [onClose])
+
+ const selectedIds = store.selectedIds
+ const canGroup = selectedIds.length >= 2
+ const canUngroup = store.pages[store.currentPage].elements.some(
+ (el) => selectedIds.includes(el.id) && isGroup(el)
+ )
+ const hasLocked = store.pages[store.currentPage].elements.some(
+ (el) => selectedIds.includes(el.id) && el.locked
+ )
+ const anyHidden = store.pages[store.currentPage].elements.some(
+ (el) => selectedIds.includes(el.id) && !el.visible
+ )
+
+ const elementItems: Item[] = [
+ { label: 'Copy', icon: Copy, kbd: 'Ctrl+C', onSelect: () => store.copySelection() },
+ { label: 'Cut', icon: Scissors, kbd: 'Ctrl+X', onSelect: () => { store.cutSelection() } },
+ { label: 'Duplicate', icon: CopyPlus, kbd: 'Ctrl+D', onSelect: () => store.duplicateSelection() },
+ Sep as unknown as Item,
+ { label: 'Bring to front', icon: BringToFront, onSelect: () => selectedIds.forEach((id) => store.moveLayer(id, 'front')) },
+ { label: 'Bring forward', icon: ArrowUpToLine, onSelect: () => selectedIds.forEach((id) => store.moveLayer(id, 'up')) },
+ { label: 'Send backward', icon: ArrowDownToLine, onSelect: () => selectedIds.forEach((id) => store.moveLayer(id, 'down')) },
+ { label: 'Send to back', icon: SendToBack, onSelect: () => selectedIds.forEach((id) => store.moveLayer(id, 'back')) },
+ Sep as unknown as Item,
+ { label: 'Group', icon: Group, kbd: 'Ctrl+G', disabled: !canGroup, onSelect: () => store.groupSelection() },
+ { label: 'Ungroup', icon: Ungroup, kbd: 'Ctrl+Shift+G', disabled: !canUngroup, onSelect: () => store.ungroupSelection() },
+ { label: hasLocked ? 'Unlock' : 'Lock', icon: hasLocked ? Unlock : Lock, kbd: 'Ctrl+L', onSelect: () => store.setLock(selectedIds, !hasLocked) },
+ { label: anyHidden ? 'Show' : 'Hide', icon: anyHidden ? Eye : EyeOff, onSelect: () => store.setVisible(selectedIds, anyHidden) },
+ Sep as unknown as Item,
+ { label: 'Delete', icon: Trash2, kbd: 'DEL', danger: true, onSelect: () => store.deleteSelection() },
+ ]
+
+ const pageItems: Item[] = [
+ { label: 'Paste', icon: ClipboardPaste, kbd: 'Ctrl+V', onSelect: () => store.pasteClipboard() },
+ { label: 'Select all', icon: MousePointerClick, kbd: 'Ctrl+A', onSelect: () => store.setSelection(store.pages[store.currentPage].elements.filter((e) => !e.locked).map((e) => e.id)) },
+ Sep as unknown as Item,
+ { label: 'Add page', icon: FilePlus2, onSelect: () => store.addPage() },
+ { label: 'Duplicate page', icon: SquareStack, onSelect: () => store.duplicatePage(store.currentPage) },
+ { label: 'Page background', icon: Palette, onSelect: () => store.setPanel('background') },
+ Sep as unknown as Item,
+ { label: 'Delete page', icon: Trash2, kbd: 'DEL', danger: true, onSelect: () => store.deletePage(store.currentPage) },
+ ]
+
+ const items = state.kind === 'element' ? elementItems : pageItems
+
+ // clamp the menu inside the viewport
+ const style: React.CSSProperties = {
+ left: Math.min(state.x, window.innerWidth - 250),
+ top: Math.min(state.y, window.innerHeight - 420),
+ }
+
+ return (
+ <div ref={ref} className="cv-menu" style={style} role="menu" aria-label="Context menu" onClick={(e) => e.stopPropagation()}>
+ {items.map((item, i) =>
+ 'icon' in item && item.icon ? (
+ <button
+ key={i}
+ role="menuitem"
+ className={`cv-menu-item ${item.danger ? 'cv-menu-item-danger' : ''}`}
+ disabled={item.disabled}
+ onClick={() => {
+ item.onSelect?.()
+ onClose()
+ }}
+ >
+ <item.icon size={15} className="shrink-0 opacity-70" />
+ <span className="truncate">{item.label}</span>
+ {item.kbd && <span className="cv-menu-kbd">{item.kbd}</span>}
+ </button>
+ ) : (
+ <Sep key={`sep-${i}`} />
+ )
+ )}
+ </div>
+ )
+}
diff --git a/src/components/editor/canvas/element-node.tsx b/src/components/editor/canvas/element-node.tsx
index fafe358..cd08769 100644
--- a/src/components/editor/canvas/element-node.tsx
+++ b/src/components/editor/canvas/element-node.tsx
@@ -1,10 +1,12 @@
'use client'
import Konva from 'konva'
+import { useCallback, useEffect, useRef } from 'react'
import { Ellipse, Group, Image as KonvaImage, Line, Path, Rect, Star, Text } from 'react-konva'
import type { KonvaEventObject } from 'konva/lib/Node'
import type {
AnyElement,
+ GroupElement,
ImageElement,
LineElement,
ShapeElement,
@@ -30,6 +32,8 @@ export interface ElementNodeProps {
onDragEndNode?: (id: string) => void
/** double-click / double-tap (text editing) */
onDoubleClick?: (id: string) => void
+ /** render nested (inside a group / preview) — page coords are baked by the parent */
+ nested?: boolean
}
function shadowProps(el: AnyElement) {
@@ -59,17 +63,64 @@ function textEffectProps(t: TextElement): Record<string, string | number> {
case 'hollow':
return { fill: 'transparent', stroke: t.fill, strokeWidth: Math.max(1, t.fontSize * 0.05), lineJoin: 'round' as unknown as string }
case 'neon':
- return { shadowColor: t.fill, shadowBlur: 26, shadowOffsetX: 0, shadowOffsetY: 0 }
+ return { shadowColor: t.fill, shadowBlur: 30, shadowOffsetX: 0, shadowOffsetY: 0 }
+ case 'glow':
+ return { shadowColor: withAlpha(t.fill, 0.85), shadowBlur: 12, shadowOffsetX: 0, shadowOffsetY: 0 }
+ case 'outline':
+ return { stroke: t.fill, strokeWidth: Math.max(1, t.fontSize * 0.045), lineJoin: 'round' as unknown as string }
case 'echo':
return { shadowColor: withAlpha(t.fill, 0.45), shadowBlur: 0, shadowOffsetX: Math.max(4, t.fontSize * 0.12), shadowOffsetY: Math.max(4, t.fontSize * 0.12) }
+ case 'splice':
+ return { shadowColor: withAlpha(t.fill, 0.5), shadowBlur: 0, shadowOffsetX: 0, shadowOffsetY: -Math.max(3, t.fontSize * 0.09) }
default:
return {}
}
}
-export function ElementNode({ element: el, interactive, hiding, registerNode, onDragMoveNode, onDragEndNode, onDoubleClick }: ElementNodeProps) {
+/** image with Konva filters (brightness / contrast / saturation) */
+function ImageNode({ el, common }: { el: ImageElement; common: Record<string, unknown> }) {
+ const image = useLoadedImage(el.src)
+ const nodeRef = useRef<Konva.Image | null>(null)
+
+ const bright = (el.brightness ?? 0) / 100 // konva Brighten: -0.5..0.5 approx
+ const contrast = el.contrast ?? 0
+ const sat = el.saturation ?? 0
+ const needsFilters = bright !== 0 || contrast !== 0 || sat !== 0
+
+ useEffect(() => {
+ const node = nodeRef.current
+ if (!node || !image) return
+ const filters: Array<typeof Konva.Filters.Brighten> = []
+ if (bright !== 0) filters.push(Konva.Filters.Brighten)
+ if (contrast !== 0) filters.push(Konva.Filters.Contrast)
+ if (sat !== 0) filters.push(Konva.Filters.HSL)
+ node.filters(filters)
+ node.brightness(bright)
+ node.contrast(contrast)
+ node.saturation(sat / 100)
+ if (filters.length) node.cache()
+ else node.clearCache()
+ node.getLayer()?.batchDraw()
+ }, [image, bright, contrast, sat])
+
+ return (
+ <KonvaImage
+ {...common}
+ ref={(n) => { nodeRef.current = n; (common.ref as (node: Konva.Node | null) => void | undefined)?.(n) }}
+ image={image ?? undefined}
+ width={el.width}
+ height={el.height}
+ cornerRadius={el.radius}
+ scaleX={el.flipH ? -1 : 1}
+ scaleY={el.flipV ? -1 : 1}
+ offsetX={el.flipH ? el.width : 0}
+ offsetY={el.flipV ? el.height : 0}
+ />
+ )
+}
+
+export function ElementNode({ element: el, interactive, hiding, registerNode, onDragMoveNode, onDragEndNode, onDoubleClick, nested }: ElementNodeProps) {
const store = useEditorStore()
- const image = useLoadedImage(el.type === 'image' ? (el as ImageElement).src : undefined)
// ── shared interaction handlers ────────────────────────────
const handleClick = (e: KonvaEventObject<MouseEvent | TouchEvent>) => {
@@ -97,6 +148,18 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, on
const handleDragEnd = (node: Konva.Node) => {
if (!interactive) return
+ if (el.type === 'group') {
+ // bake drag delta into children so ungroup restores the moved positions
+ const g = el as GroupElement
+ const dx = node.x() - g.x
+ const dy = node.y() - g.y
+ store.updateElementsLive([el.id], {
+ x: Math.round(node.x()),
+ y: Math.round(node.y()),
+ children: g.children.map((c) => ({ ...c, x: Math.round(c.x + dx), y: Math.round(c.y + dy) })),
+ })
+ return
+ }
if (el.type === 'ellipse' || el.type === 'star') {
store.updateElementsLive([el.id], { x: node.x() - el.width / 2, y: node.y() - el.height / 2 })
} else {
@@ -112,10 +175,41 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, on
const handleTransformEnd = (node: Konva.Node) => {
if (!interactive) return
- const sx = node.scaleX()
- const sy = node.scaleY()
- node.scaleX(1)
- node.scaleY(1)
+ const sx = Math.abs(node.scaleX())
+ const sy = Math.abs(node.scaleY())
+ // restore flip sign for images (transformer resets scale)
+ if (el.type === 'image') {
+ const im = el as ImageElement
+ node.scaleX(im.flipH ? -1 : 1)
+ node.scaleY(im.flipV ? -1 : 1)
+ } else {
+ node.scaleX(1)
+ node.scaleY(1)
+ }
+
+ if (el.type === 'group') {
+ // bake scale into children (children use page coords relative to group origin)
+ const g = el as GroupElement
+ const dx = node.x() - g.x
+ const dy = node.y() - g.y
+ const children = g.children.map((c) => ({
+ ...c,
+ x: Math.round(g.x + dx + (c.x - g.x) * sx),
+ y: Math.round(g.y + dy + (c.y - g.y) * sy),
+ width: Math.max(4, c.width * sx),
+ height: Math.max(4, c.height * sy),
+ rotation: (c.rotation + node.rotation()) % 360,
+ }))
+ store.updateElementsLive([el.id], {
+ children,
+ x: Math.round(node.x()),
+ y: Math.round(node.y()),
+ width: Math.max(8, g.width * sx),
+ height: Math.max(8, g.height * sy),
+ rotation: node.rotation(),
+ })
+ return
+ }
const patch: Record<string, number> = {}
@@ -204,17 +298,56 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, on
case 'text': {
const t = el as TextElement
const effect = t.effect && t.effect !== 'none' ? textEffectProps(t) : {}
+ const rendered = t.uppercase ? t.text.toUpperCase() : t.text
+
+ if (t.effect === 'background') {
+ // canva "Background" effect: solid block behind the text
+ const bg = t.effectBackground ?? '#EFEFEF'
+ const h = Math.max(t.height, t.fontSize * t.lineHeight + 8)
+ return (
+ <Group {...common}>
+ <Rect width={t.width} height={h} fill={bg} cornerRadius={Math.min(8, t.fontSize * 0.2)} />
+ <Text
+ text={rendered}
+ fontSize={t.fontSize}
+ fontFamily={t.fontFamily}
+ fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`}
+ textDecoration={[t.underline ? 'underline' : '', t.strike ? 'line-through' : ''].filter(Boolean).join(' ')}
+ fill={t.fill}
+ align={t.align === 'justify' ? 'left' : t.align}
+ width={t.width}
+ lineHeight={t.lineHeight}
+ letterSpacing={t.letterSpacing}
+ wrap="word"
+ perfectDrawEnabled={false}
+ ref={() => undefined}
+ />
+ </Group>
+ )
+ }
+
+ if (t.effect === 'splice') {
+ // canva "Splice": sliced look — ghost copies above & below
+ return (
+ <Group {...common}>
+ <Text text={rendered} fontSize={t.fontSize} fontFamily={t.fontFamily} fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`} fill={withAlpha(t.fill, 0.35)} align={t.align === 'justify' ? 'left' : t.align} width={t.width} lineHeight={t.lineHeight} letterSpacing={t.letterSpacing} wrap="word" y={-Math.max(3, t.fontSize * 0.09)} perfectDrawEnabled={false} />
+ <Text text={rendered} fontSize={t.fontSize} fontFamily={t.fontFamily} fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`} fill={withAlpha(t.fill, 0.35)} align={t.align === 'justify' ? 'left' : t.align} width={t.width} lineHeight={t.lineHeight} letterSpacing={t.letterSpacing} wrap="word" y={Math.max(3, t.fontSize * 0.09)} perfectDrawEnabled={false} />
+ <Text text={rendered} fontSize={t.fontSize} fontFamily={t.fontFamily} fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`} fill={t.fill} align={t.align === 'justify' ? 'left' : t.align} width={t.width} lineHeight={t.lineHeight} letterSpacing={t.letterSpacing} wrap="word" perfectDrawEnabled={false} />
+ </Group>
+ )
+ }
+
return (
<Text
{...common}
{...effect}
- text={t.text}
+ text={rendered}
fontSize={t.fontSize}
fontFamily={t.fontFamily}
fontStyle={`${t.italic ? 'italic ' : ''}${t.bold ? 'bold' : 'normal'}`}
textDecoration={[t.underline ? 'underline' : '', t.strike ? 'line-through' : ''].filter(Boolean).join(' ')}
fill={t.fill}
- align={t.align}
+ align={t.align === 'justify' ? 'left' : t.align}
width={t.width}
lineHeight={t.lineHeight}
letterSpacing={t.letterSpacing}
@@ -296,7 +429,7 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, on
case 'image': {
const im = el as ImageElement
- return <KonvaImage {...common} image={image ?? undefined} width={im.width} height={im.height} cornerRadius={im.radius} />
+ return <ImageNode el={im} common={common} />
}
case 'sticker': {
@@ -304,6 +437,24 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, on
return <Text {...common} text={sk.char} fontSize={sk.fontSize} fontFamily="'Segoe UI Emoji', 'Apple Color Emoji', 'Noto Color Emoji', sans-serif" width={sk.width} height={sk.height} align="center" />
}
+ case 'group': {
+ const g = el as GroupElement
+ return (
+ <Group {...common} clip={undefined}>
+ {g.children
+ .filter((c) => c.visible)
+ .map((c) => (
+ <ElementNode
+ key={c.id}
+ element={{ ...c, x: c.x - g.x, y: c.y - g.y } as AnyElement}
+ interactive={false}
+ nested
+ />
+ ))}
+ </Group>
+ )
+ }
+
default: {
// exhaustive: every ElementType is handled above
return null
@@ -313,10 +464,11 @@ export function ElementNode({ element: el, interactive, hiding, registerNode, on
/** non-interactive renderer used inside thumbnails / previews */
export function PreviewElements({ elements }: { elements: AnyElement[] }) {
+ const reg = useCallback(() => undefined, [])
return (
<Group listening={false}>
{elements.map((el) => (
- <ElementNode key={el.id} element={el} interactive={false} />
+ <ElementNode key={el.id} element={el} interactive={false} registerNode={reg} />
))}
</Group>
)
diff --git a/src/components/editor/panels/ElementsPanel.tsx b/src/components/editor/panels/ElementsPanel.tsx
index 5a0c4d2..ddb02a9 100644
--- a/src/components/editor/panels/ElementsPanel.tsx
+++ b/src/components/editor/panels/ElementsPanel.tsx
@@ -1,7 +1,7 @@
'use client'
-import { useState } from 'react'
-import { Square, Circle, Triangle, Star, Minus, ArrowRight, MoveHorizontal } from 'lucide-react'
+import { useMemo, useState } from 'react'
+import { Square, Circle, Triangle, Star, Minus, ArrowRight, MoveHorizontal, Search, Hexagon, Pentagon, Diamond, CircleDashed } from 'lucide-react'
import { GRAPHICS, STICKER_GROUPS } from '@/lib/editor-utils'
import { addGraphic, addLine, addShape, addSticker } from '../add-element'
import { cn } from '@/lib/utils'
@@ -10,19 +10,62 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
function GraphicIcon({ path }: { path: string }) {
return (
<svg viewBox="0 0 100 100" className="h-7 w-7" fill="currentColor" aria-hidden="true">
- <path d={path} />
+ <path d={path} fillRule="evenodd" />
</svg>
)
}
+const BASIC_SHAPES = [
+ { id: 'rect', label: 'Square', icon: Square },
+ { id: 'rounded', label: 'Rounded', icon: null },
+ { id: 'ellipse', label: 'Circle', icon: Circle },
+ { id: 'triangle', label: 'Triangle', icon: Triangle },
+ { id: 'star', label: 'Star', icon: Star },
+] as const
+
+const POLY_SHAPES = [
+ { id: 'pentagon', label: 'Pentagon', icon: Pentagon },
+ { id: 'hexagon', label: 'Hexagon', icon: Hexagon },
+ { id: 'octagon', label: 'Octagon', icon: null },
+ { id: 'diamond', label: 'Diamond', icon: Diamond },
+ { id: 'semi-circle', label: 'Semicircle', icon: CircleDashed },
+] as const
+
+const GRAPHIC_GROUPS: { name: string; ids: string[] }[] = [
+ { name: 'Decorative', ids: ['heart', 'blob', 'cloud', 'moon', 'sparkle', 'wave'] },
+ { name: 'Badges & labels', ids: ['badge', 'banner', 'ribbon', 'frame', 'speech'] },
+ { name: 'Icons', ids: ['bolt', 'check-circle', 'arrow'] },
+]
+
export function ElementsPanel() {
const [tab, setTab] = useState('shapes')
+ const [query, setQuery] = useState('')
+
+ const filteredGraphics = useMemo(() => {
+ const q = query.trim().toLowerCase()
+ if (!q) return null
+ return GRAPHICS.filter((g) => g.name.toLowerCase().includes(q))
+ }, [query])
+
+ const searchPlaceholder = 'Search shapes & graphics'
return (
<Tabs value={tab} onValueChange={setTab} className="flex flex-col h-full bg-[#16181D] text-[#EDEEF2]">
- <div className="px-4 pt-4 pb-3 border-b border-white/[0.07]">
+ <div className="px-4 pt-4 pb-3 border-b border-white/[0.07] shrink-0">
<h3 className="font-bold text-sm">Elements</h3>
- <p className="text-xs text-white/50 mt-0.5">Shapes, lines, graphics, stickers.</p>
+ <div className="flex items-center gap-2 h-9 rounded-lg bg-white/[0.06] border border-white/10 px-2.5 mt-2.5">
+ <Search size={13} className="text-white/40 shrink-0" />
+ <input
+ value={query}
+ onChange={(e) => {
+ setQuery(e.target.value)
+ if (e.target.value) setTab('graphics')
+ }}
+ className="bg-transparent outline-none text-[12px] text-white w-full placeholder:text-white/35"
+ placeholder={searchPlaceholder}
+ aria-label={searchPlaceholder}
+ />
+ </div>
<TabsList className="mt-3 w-full grid grid-cols-4 h-8 bg-white/[0.05]">
<TabsTrigger value="shapes" className="text-xs data-[state=active]:bg-[#7630D7] data-[state=active]:text-white">Shapes</TabsTrigger>
<TabsTrigger value="lines" className="text-xs data-[state=active]:bg-[#7630D7] data-[state=active]:text-white">Lines</TabsTrigger>
@@ -32,27 +75,20 @@ export function ElementsPanel() {
</div>
<TabsContent value="shapes" className="flex-1 overflow-y-auto cv-scroll-dark p-4 mt-0">
+ <SectionTitle>Basic shapes</SectionTitle>
+ <div className="grid grid-cols-3 gap-2 mb-4">
+ {BASIC_SHAPES.map((s) => (
+ <ShapeTile key={s.id} label={s.label} onClick={() => addShape(s.id as 'rect')}>
+ {s.icon ? <s.icon size={26} strokeWidth={1.6} className="text-white/80" /> : <span className="h-[22px] w-[22px] rounded-md border-2 border-white/80" aria-hidden="true" />}
+ </ShapeTile>
+ ))}
+ </div>
+ <SectionTitle>Polygons</SectionTitle>
<div className="grid grid-cols-3 gap-2">
- {[
- { id: 'rect', label: 'Square', icon: Square },
- { id: 'rounded', label: 'Rounded', icon: null },
- { id: 'ellipse', label: 'Circle', icon: Circle },
- { id: 'triangle', label: 'Triangle', icon: Triangle },
- { id: 'star', label: 'Star', icon: Star },
- ].map((s) => (
- <button
- key={s.id}
- onClick={() => addShape(s.id as 'rect')}
- className="flex flex-col items-center gap-1.5 rounded-xl border border-white/10 bg-white/[0.03] p-3 hover:border-[#7630D7] hover:bg-[#7630D7]/10 transition-all"
- aria-label={`Add ${s.label}`}
- >
- {s.icon ? (
- <s.icon size={26} strokeWidth={1.6} className="text-white/80" />
- ) : (
- <span className="h-[22px] w-[22px] rounded-md border-2 border-white/80" aria-hidden="true" />
- )}
- <span className="text-[11px] text-white/55">{s.label}</span>
- </button>
+ {POLY_SHAPES.map((s) => (
+ <ShapeTile key={s.id} label={s.label} onClick={() => addGraphic(s.id)}>
+ {s.icon ? <s.icon size={26} strokeWidth={1.6} className="text-white/80" /> : <GraphicIcon path={GRAPHICS.find((g) => g.id === 'octagon')?.path ?? ''} />}
+ </ShapeTile>
))}
</div>
</TabsContent>
@@ -79,19 +115,30 @@ export function ElementsPanel() {
</TabsContent>
<TabsContent value="graphics" className="flex-1 overflow-y-auto cv-scroll-dark p-4 mt-0">
- <div className="grid grid-cols-3 gap-2">
- {GRAPHICS.map((g) => (
- <button
- key={g.id}
- onClick={() => addGraphic(g.id)}
- className="flex flex-col items-center gap-1.5 rounded-xl border border-white/10 bg-white/[0.03] p-3 text-white/80 hover:border-[#7630D7] hover:bg-[#7630D7]/10 hover:text-white transition-all"
- aria-label={`Add ${g.name}`}
- >
- <GraphicIcon path={g.path} />
- <span className="text-[11px] text-white/55">{g.name}</span>
- </button>
- ))}
- </div>
+ {filteredGraphics ? (
+ <>
+ <SectionTitle>{filteredGraphics.length ? `Results for “${query}”` : `No results for “${query}”`}</SectionTitle>
+ <div className="grid grid-cols-3 gap-2">
+ {filteredGraphics.map((g) => (
+ <GraphicTile key={g.id} g={g} />
+ ))}
+ </div>
+ </>
+ ) : (
+ GRAPHIC_GROUPS.map((group) => (
+ <div key={group.name} className="mb-4">
+ <SectionTitle>{group.name}</SectionTitle>
+ <div className="grid grid-cols-3 gap-2">
+ {group.ids
+ .map((id) => GRAPHICS.find((g) => g.id === id))
+ .filter((g): g is NonNullable<typeof g> => !!g)
+ .map((g) => (
+ <GraphicTile key={g.id} g={g} />
+ ))}
+ </div>
+ </div>
+ ))
+ )}
</TabsContent>
<TabsContent value="stickers" className="flex-1 overflow-y-auto cv-scroll-dark p-4 mt-0">
@@ -116,3 +163,36 @@ export function ElementsPanel() {
</Tabs>
)
}
+
+function SectionTitle({ children }: { children: React.ReactNode }) {
+ return <h4 className="text-[11px] font-bold text-white/45 uppercase tracking-wide mb-2.5">{children}</h4>
+}
+
+function ShapeTile({ label, children, onClick }: { label: string; children: React.ReactNode; onClick: () => void }) {
+ return (
+ <button
+ onClick={onClick}
+ className="flex flex-col items-center justify-center gap-1.5 rounded-xl border border-white/10 bg-white/[0.03] p-3 h-[84px] hover:border-[#7630D7] hover:bg-[#7630D7]/10 transition-all"
+ aria-label={`Add ${label}`}
+ >
+ <span className="h-7 flex items-center">{children}</span>
+ <span className="text-[11px] text-white/55">{label}</span>
+ </button>
+ )
+}
+
+function GraphicTile({ g }: { g: { id: string; name: string; path: string } }) {
+ return (
+ <button
+ onClick={() => addGraphic(g.id)}
+ className={cn(
+ 'flex flex-col items-center justify-center gap-1.5 rounded-xl border border-white/10 bg-white/[0.03] p-3 h-[84px] text-white/80',
+ 'hover:border-[#7630D7] hover:bg-[#7630D7]/10 hover:text-white transition-all'
+ )}
+ aria-label={`Add ${g.name}`}
+ >
+ <GraphicIcon path={g.path} />
+ <span className="text-[11px] text-white/55">{g.name}</span>
+ </button>
+ )
+}
diff --git a/src/components/editor/panels/UploadsPanel.tsx b/src/components/editor/panels/UploadsPanel.tsx
index b979d69..1a22546 100644
--- a/src/components/editor/panels/UploadsPanel.tsx
+++ b/src/components/editor/panels/UploadsPanel.tsx
@@ -1,8 +1,10 @@
'use client'
import { useRef, useState } from 'react'
-import { Upload, Trash2 } from 'lucide-react'
-import { addImageFromFile, addImageFromSrc } from '../add-element'
+import { Upload, Trash2, ImageIcon, Replace, Wallpaper } from 'lucide-react'
+import { addImageFromFile, addImageFromSrc, readImageFile, replaceSelectedImage } from '../add-element'
+import { createImageElement } from '@/lib/types'
+import { useEditorStore } from '@/store/editor-store'
import { toast } from '@/hooks/use-toast'
import { cn } from '@/lib/utils'
@@ -18,25 +20,20 @@ const uploadGallery: { items: UploadItem[] } = { items: [] }
export function UploadsPanel() {
const fileRef = useRef<HTMLInputElement>(null)
const [, force] = useState(0)
+ const selectedIds = useEditorStore((s) => s.selectedIds)
+ const pages = useEditorStore((s) => s.pages)
+ const currentPage = useEditorStore((s) => s.currentPage)
+ const hasImageSelected = pages[currentPage].elements.some(
+ (e) => selectedIds.includes(e.id) && e.type === 'image'
+ )
const handleFiles = async (files: FileList | null) => {
if (!files?.length) return
let ok = 0
for (const file of Array.from(files)) {
try {
- const src = await new Promise<string>((resolve, reject) => {
- const r = new FileReader()
- r.onload = () => resolve(String(r.result))
- r.onerror = () => reject(new Error('read failed'))
- r.readAsDataURL(file)
- })
- const dims = await new Promise<{ w: number; h: number }>((resolve) => {
- const img = new window.Image()
- img.onload = () => resolve({ w: img.naturalWidth, h: img.naturalHeight })
- img.onerror = () => resolve({ w: 500, h: 500 })
- img.src = src
- })
- uploadGallery.items.unshift({ src, w: dims.w, h: dims.h })
+ const { src, w, h } = await readImageFile(file)
+ uploadGallery.items.unshift({ src, w, h })
await addImageFromFile(file)
ok += 1
} catch {
@@ -44,14 +41,54 @@ export function UploadsPanel() {
}
}
if (ok === 0) toast({ title: 'Could not upload images', variant: 'destructive' })
+ else toast({ title: `${ok} image${ok > 1 ? 's' : ''} uploaded` })
force((n) => n + 1)
}
+ const useGalleryItem = (item: UploadItem) => {
+ if (hasImageSelected) {
+ replaceSelectedImage(item.src, item.w, item.h)
+ toast({ title: 'Image replaced' })
+ } else {
+ addImageFromSrc(item.src, item.w, item.h)
+ }
+ }
+
+ const setAsBackground = (item: UploadItem) => {
+ // full-bleed cover image via a page-sized image element locked behind everything
+ const state = useEditorStore.getState()
+ const ratio = Math.max(state.width / item.w, state.height / item.h)
+ const w = Math.round(item.w * ratio)
+ const h = Math.round(item.h * ratio)
+ state.addElement(
+ createImageElement(item.src, item.w, item.h, {
+ x: Math.round((state.width - w) / 2),
+ y: Math.round((state.height - h) / 2),
+ width: w,
+ height: h,
+ })
+ )
+ // send to back + lock — a canva background behaves non-interactive
+ const el = useEditorStore.getState().pages[useEditorStore.getState().currentPage].elements.at(-1)
+ if (el) {
+ state.moveLayer(el.id, 'back')
+ state.setLock([el.id], true)
+ }
+ toast({ title: 'Set as background' })
+ }
+
return (
<div className="flex flex-col h-full bg-[#16181D] text-[#EDEEF2]">
- <div className="px-4 pt-4 pb-3 border-b border-white/[0.07]">
+ <div className="px-4 pt-4 pb-3 border-b border-white/[0.07] shrink-0">
<h3 className="font-bold text-sm">Uploads</h3>
- <p className="text-xs text-white/50 mt-0.5">Images stay in this browser session.</p>
+ <p className="text-xs text-white/50 mt-0.5">
+ {hasImageSelected ? 'Click a file to replace the selected image.' : 'Images stay in this browser session.'}
+ </p>
+ {hasImageSelected && (
+ <div className="mt-2 inline-flex items-center gap-1.5 text-[11px] font-semibold text-[#02C0CC] bg-[#02C0CC]/10 border border-[#02C0CC]/25 rounded-full px-2.5 py-1">
+ <Replace size={11} /> Replace mode
+ </div>
+ )}
</div>
<div
className="flex-1 overflow-y-auto cv-scroll-dark p-4"
@@ -68,7 +105,7 @@ export function UploadsPanel() {
>
<Upload size={22} />
<span className="text-sm font-medium text-white/80">Click or drag images here</span>
- <span className="text-xs">PNG, JPG, SVG, GIF</span>
+ <span className="text-xs">PNG, JPG, SVG, GIF — or drop straight onto the canvas</span>
</button>
<input
ref={fileRef}
@@ -83,7 +120,7 @@ export function UploadsPanel() {
aria-label="File upload"
/>
- {uploadGallery.items.length > 0 && (
+ {uploadGallery.items.length > 0 ? (
<>
<div className="flex items-center justify-between mt-6 mb-2">
<h4 className="text-xs font-semibold text-white/50">Session uploads</h4>
@@ -99,17 +136,36 @@ export function UploadsPanel() {
</div>
<div className="grid grid-cols-3 gap-2">
{uploadGallery.items.map((item, i) => (
- <button
- key={i}
- onClick={() => addImageFromSrc(item.src, item.w, item.h)}
- className={cn('rounded-lg overflow-hidden border border-white/10 hover:border-[#7630D7] transition-all aspect-square bg-[#0F1015]')}
- aria-label="Add uploaded image to canvas"
- >
- <img src={item.src} alt="Uploaded" className="w-full h-full object-cover" />
- </button>
+ <div key={i} className="group relative">
+ <button
+ onClick={() => useGalleryItem(item)}
+ className={cn(
+ 'w-full rounded-lg overflow-hidden border transition-all aspect-square bg-[#0F1015]',
+ hasImageSelected
+ ? 'border-[#02C0CC]/60 hover:border-[#02C0CC]'
+ : 'border-white/10 hover:border-[#7630D7]'
+ )}
+ aria-label={hasImageSelected ? 'Replace selected image' : 'Add uploaded image to canvas'}
+ >
+ <img src={item.src} alt="Uploaded" className="w-full h-full object-cover" />
+ </button>
+ <button
+ onClick={() => setAsBackground(item)}
+ className="absolute bottom-1 right-1 h-7 w-7 rounded-lg bg-black/60 backdrop-blur text-white/90 hidden group-hover:flex items-center justify-center hover:bg-black/80"
+ title="Set image as background"
+ aria-label="Set image as background"
+ >
+ <Wallpaper size={13} />
+ </button>
+ </div>
))}
</div>
</>
+ ) : (
+ <div className="mt-6 flex flex-col items-center py-6 text-white/35">
+ <ImageIcon size={28} strokeWidth={1.4} />
+ <p className="text-xs mt-2.5 text-center leading-relaxed">No uploads yet.<br />Your images will appear here.</p>
+ </div>
)}
</div>
</div>
diff --git a/src/components/editor/toolbar/ColorMenu.tsx b/src/components/editor/toolbar/ColorMenu.tsx
new file mode 100644
index 0000000..018c55f
--- /dev/null
+++ b/src/components/editor/toolbar/ColorMenu.tsx
@@ -0,0 +1,187 @@
+'use client'
+
+import { useEffect, useRef, useState } from 'react'
+import { X, Pipette, Plus, ChevronRight, Search } from 'lucide-react'
+import { SOLID_SWATCHES, GRADIENT_PRESETS } from '@/lib/editor-utils'
+import { useEditorStore } from '@/store/editor-store'
+import { cn } from '@/lib/utils'
+
+interface ColorMenuProps {
+ /** current colour value */
+ value: string
+ onChange: (color: string, committed: boolean) => void
+ /** gradient swatches apply from→to (page background context only) */
+ onGradient?: (from: string, to: string, angle: number) => void
+ /** menu title (canva: "Text colour" / "Background colour" / "Fill") */
+ title?: string
+ children?: React.ReactNode
+}
+
+/** canva-style colour menu: quick row, brand kit, solid grid, gradient rows. */
+export function ColorMenu({ value, onChange, onGradient, title = 'Colour', children }: ColorMenuProps) {
+ const [open, setOpen] = useState(false)
+ const [pos, setPos] = useState<{ x: number; y: number } | null>(null)
+ const [hex, setHex] = useState(value)
+ const triggerRef = useRef<HTMLButtonElement>(null)
+ const brand = useEditorStore((s) => s.brand)
+
+ useEffect(() => { setHex(value) }, [value])
+
+ const openMenu = () => {
+ const r = triggerRef.current?.getBoundingClientRect()
+ if (r) {
+ const W = 250
+ const x = Math.min(r.left, window.innerWidth - W - 12)
+ const y = r.bottom + 6 > window.innerHeight - 380 ? Math.max(8, r.top - 386) : r.bottom + 6
+ setPos({ x, y })
+ }
+ setOpen(true)
+ }
+
+ const apply = (c: string) => {
+ onChange(c, true)
+ }
+
+ const tryHex = () => {
+ const m = hex.trim().match(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i)
+ if (m) {
+ const h = m[1].length === 3 ? '#' + m[1].split('').map((c) => c + c).join('') : '#' + m[1]
+ apply(h)
+ }
+ }
+
+ const eyedropper = async () => {
+ const EyeDropper = (window as unknown as { EyeDropper?: new () => { open: () => Promise<{ sRGBHex: string }> } }).EyeDropper
+ if (!EyeDropper) return
+ try {
+ const res = await new EyeDropper().open()
+ apply(res.sRGBHex)
+ } catch { /* cancelled */ }
+ }
+
+ return (
+ <>
+ <button ref={triggerRef} onClick={openMenu} className="cv-tbtn" aria-label={title} title={title}>
+ {children ?? (
+ <span
+ className="block h-[18px] w-[18px] rounded-full border-2 border-white/90 shadow-[0_0_0_1px_rgba(0,0,0,0.35)]"
+ style={{ background: value === 'transparent' ? 'repeating-conic-gradient(#e3e3e8 0% 25%, #ffffff 0% 50%) 50% / 8px 8px' : value }}
+ />
+ )}
+ </button>
+
+ {open && pos && (
+ <>
+ <div className="fixed inset-0 z-[70]" onClick={() => setOpen(false)} onContextMenu={(e) => { e.preventDefault(); setOpen(false) }} />
+ <div className="cv-menu !min-w-[250px] !max-w-[250px] !p-0" style={{ left: pos.x, top: pos.y }}>
+ {/* header */}
+ <div className="flex items-center justify-between px-3 h-10 border-b border-white/[0.07]">
+ <span className="text-[13px] font-bold text-white">{title}</span>
+ <button className="text-white/60 hover:text-white" onClick={() => setOpen(false)} aria-label="Close colour menu">
+ <X size={15} />
+ </button>
+ </div>
+
+ {/* hex input */}
+ <div className="px-3 pt-2.5 pb-1">
+ <div className="flex items-center gap-2 h-8 rounded-lg bg-white/[0.06] border border-white/10 px-2.5">
+ <Search size={12} className="text-white/40 shrink-0" />
+ <input
+ value={hex}
+ onChange={(e) => setHex(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') tryHex() }}
+ onBlur={tryHex}
+ className="bg-transparent outline-none text-[12px] text-white w-full placeholder:text-white/35"
+ placeholder="Try “blue” or “#00c4cc”"
+ maxLength={9}
+ />
+ </div>
+ </div>
+
+ {/* quick row: spectrum / eyedropper / current */}
+ <div className="flex items-center gap-3 px-3 py-2.5">
+ <label className="relative cursor-pointer" title="Spectrum">
+ <span
+ className="block h-9 w-9 rounded-full relative"
+ style={{ background: 'conic-gradient(from 0deg, #ff004c, #ff7a00, #ffe600, #4dff00, #00ffc8, #00c2ff, #4d00ff, #ff00d4, #ff004c)' }}
+ >
+ <span className="absolute inset-0 flex items-center justify-center">
+ <span className="h-5 w-5 rounded-full bg-[#1a1b22] flex items-center justify-center">
+ <Plus size={12} className="text-white" />
+ </span>
+ </span>
+ </span>
+ <input
+ type="color"
+ value={/^#[0-9a-f]{6}$/i.test(value) ? value : '#ffffff'}
+ onChange={(e) => onChange(e.target.value, false)}
+ onBlur={(e) => onChange(e.target.value, true)}
+ className="absolute inset-0 opacity-0 cursor-pointer"
+ aria-label="Open spectrum picker"
+ />
+ </label>
+ <button className="h-9 w-9 rounded-full bg-white/[0.08] border border-white/10 flex items-center justify-center text-white/80 hover:bg-white/[0.14]" onClick={eyedropper} title="Eyedropper" aria-label="Eyedropper">
+ <Pipette size={14} />
+ </button>
+ <button
+ className="h-9 w-9 rounded-full border-2 border-white/80"
+ style={{ background: value === 'transparent' ? 'repeating-conic-gradient(#e3e3e8 0% 25%, #ffffff 0% 50%) 50% / 8px 8px' : value }}
+ title="Current colour"
+ aria-label="Current colour"
+ onClick={() => apply(value)}
+ />
+ </div>
+
+ {/* brand kit */}
+ <Section label="Brand Kit" icon="palette">
+ <div className="flex flex-wrap gap-2 px-3 pb-2.5">
+ {brand.colors.map((c) => (
+ <button key={c} className="cv-swatch h-7 w-7" style={{ background: c }} data-selected={value === c} onClick={() => apply(c)} aria-label={`Brand colour ${c}`} />
+ ))}
+ </div>
+ </Section>
+
+ {/* default solid colours */}
+ <Section label="Default solid colours" icon="droplet">
+ <div className="grid grid-cols-7 gap-2 px-3 pb-2.5">
+ {SOLID_SWATCHES.map((c) => (
+ <button key={c} className="cv-swatch h-7 w-7" style={{ background: c }} data-selected={value === c} onClick={() => apply(c)} aria-label={c} />
+ ))}
+ </div>
+ </Section>
+
+ {/* gradients (background context) */}
+ {onGradient && (
+ <Section label="Default gradient colours" icon="gradient">
+ <div className="grid grid-cols-7 gap-2 px-3 pb-2.5">
+ {GRADIENT_PRESETS.map((g, i) => (
+ <button
+ key={i}
+ className="cv-swatch h-7 w-7"
+ style={{ background: `linear-gradient(${g.angle}deg, ${g.from}, ${g.to})` }}
+ onClick={() => onGradient(g.from, g.to, g.angle)}
+ aria-label={`Gradient ${g.from} to ${g.to}`}
+ />
+ ))}
+ </div>
+ </Section>
+ )}
+ </div>
+ </>
+ )}
+ </>
+ )
+}
+
+function Section({ label, icon, children }: { label: string; icon: string; children: React.ReactNode }) {
+ const [expanded, setExpanded] = useState(true)
+ return (
+ <div className="border-t border-white/[0.07]">
+ <button className="w-full flex items-center gap-2 px-3 py-2 text-[12px] font-semibold text-white/85 hover:text-white" onClick={() => setExpanded(!expanded)}>
+ <ChevronRight size={12} className={cn('transition-transform', expanded && 'rotate-90')} />
+ {label}
+ </button>
+ {expanded && children}
+ </div>
+ )
+}
diff --git a/src/components/editor/toolbar/FontDropdown.tsx b/src/components/editor/toolbar/FontDropdown.tsx
new file mode 100644
index 0000000..e308eaa
--- /dev/null
+++ b/src/components/editor/toolbar/FontDropdown.tsx
@@ -0,0 +1,127 @@
+'use client'
+
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { Search, ChevronDown, SlidersHorizontal, Star } from 'lucide-react'
+import { FONTS } from '@/lib/editor-utils'
+import { cn } from '@/lib/utils'
+
+interface FontDropdownProps {
+ value: string
+ onChange: (family: string) => void
+}
+
+/** canva-style font dropdown: search + category pills + live previews */
+export function FontDropdown({ value, onChange }: FontDropdownProps) {
+ const [open, setOpen] = useState(false)
+ const [pos, setPos] = useState<{ x: number; y: number } | null>(null)
+ const [query, setQuery] = useState('')
+ const ref = useRef<HTMLDivElement>(null)
+ const [cat, setCat] = useState<string>('All')
+
+ const cats = ['All', 'sans', 'serif', 'display', 'handwriting']
+
+ const list = useMemo(
+ () =>
+ FONTS.filter(
+ (f) =>
+ (cat === 'All' || f.category === cat) &&
+ f.label.toLowerCase().includes(query.toLowerCase())
+ ),
+ [query, cat]
+ )
+
+ const toggle = () => {
+ if (!open) {
+ const r = ref.current?.getBoundingClientRect()
+ if (r) {
+ const W = 262
+ const x = Math.min(r.left, window.innerWidth - W - 12)
+ const y = r.bottom + 6 > window.innerHeight - 340 ? Math.max(8, r.top - 346) : r.bottom + 6
+ setPos({ x, y })
+ }
+ }
+ setOpen(!open)
+ }
+
+ useEffect(() => {
+ if (!open) return
+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false) }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [open])
+
+ return (
+ <div ref={ref} className="relative shrink-0">
+ <button
+ onClick={toggle}
+ className="cv-tbtn gap-1.5 !min-w-[112px] !max-w-[132px] !px-2.5"
+ aria-label="Toggle font selector"
+ title={`Font: ${value}`}
+ >
+ <span className="truncate text-[13px]" style={{ fontFamily: value }}>{value}</span>
+ <ChevronDown size={12} className="opacity-60 shrink-0" />
+ </button>
+
+ {open && pos && (
+ <>
+ <div className="fixed inset-0 z-[60]" onClick={() => setOpen(false)} onContextMenu={(e) => { e.preventDefault(); setOpen(false) }} />
+ <div className="cv-menu !min-w-[262px] !max-w-[262px] !p-0" style={{ left: pos.x, top: pos.y }}>
+ {/* search */}
+ <div className="p-2.5 pb-2 border-b border-white/[0.07]">
+ <div className="flex items-center gap-2 h-9 rounded-lg bg-white/[0.06] border border-white/10 px-2.5">
+ <Search size={13} className="text-white/40 shrink-0" />
+ <input
+ autoFocus
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ className="bg-transparent outline-none text-[12px] text-white w-full placeholder:text-white/35"
+ placeholder="Try “Pacifico” or “Anton”"
+ aria-label="Search fonts"
+ />
+ <SlidersHorizontal size={13} className="text-white/40 shrink-0" />
+ </div>
+ {/* category pills */}
+ <div className="flex gap-1.5 mt-2 flex-wrap">
+ {cats.map((c) => (
+ <button
+ key={c}
+ onClick={() => setCat(c)}
+ className={cn(
+ 'h-6 px-2.5 rounded-full text-[11px] font-medium capitalize border transition-colors',
+ cat === c ? 'bg-white/[0.16] text-white border-white/25' : 'bg-transparent text-white/60 border-white/12 hover:text-white'
+ )}
+ >
+ {c}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {/* font rows */}
+ <div className="max-h-[280px] overflow-y-auto cv-scroll py-1">
+ {list.map((f) => (
+ <button
+ key={f.family}
+ onClick={() => { onChange(f.family); setOpen(false) }}
+ className={cn(
+ 'w-full flex items-center gap-2.5 px-3 h-[38px] text-left hover:bg-white/[0.07]',
+ value === f.family && 'bg-white/[0.09]'
+ )}
+ role="option"
+ aria-selected={value === f.family}
+ >
+ <Star size={12} className={cn('shrink-0', value === f.family ? 'text-[#FFD166]' : 'text-white/20')} />
+ <span className="text-[12px] text-white/85 truncate w-[86px] shrink-0" style={{ fontFamily: 'Inter' }}>{f.label}</span>
+ <span className="text-[17px] text-white truncate flex-1" style={{ fontFamily: f.family }}>AaBbCc 123</span>
+ </button>
+ ))}
+ {!list.length && (
+ <div className="px-3 py-6 text-center text-[12px] text-white/40">No fonts match “{query}”</div>
+ )}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/editor/toolbar/popover-kit.tsx b/src/components/editor/toolbar/popover-kit.tsx
new file mode 100644
index 0000000..a00e492
--- /dev/null
+++ b/src/components/editor/toolbar/popover-kit.tsx
@@ -0,0 +1,137 @@
+'use client'
+
+import { useRef, useState, ReactNode } from 'react'
+import { cn } from '@/lib/utils'
+
+/** shared anchored popover for the context toolbar (canva .cv-pop style) */
+export function ToolbarPopover({
+ children,
+ trigger,
+ title,
+ width = 232,
+}: {
+ children: ReactNode
+ trigger: (open: boolean) => ReactNode
+ title?: string
+ width?: number
+}) {
+ const [open, setOpen] = useState(false)
+ const [pos, setPos] = useState<{ x: number; y: number } | null>(null)
+ const ref = useRef<HTMLDivElement>(null)
+
+ const toggle = () => {
+ if (!open) {
+ const r = ref.current?.getBoundingClientRect()
+ if (r) {
+ const x = Math.min(r.left, window.innerWidth - width - 12)
+ const y = r.bottom + 6 > window.innerHeight - 300 ? Math.max(8, r.top - 306) : r.bottom + 6
+ setPos({ x, y })
+ }
+ }
+ setOpen(!open)
+ }
+
+ return (
+ <div ref={ref} className="relative shrink-0">
+ <span onClick={toggle}>{trigger(open)}</span>
+ {open && pos && (
+ <>
+ <div className="fixed inset-0 z-[60]" onClick={() => setOpen(false)} onContextMenu={(e) => { e.preventDefault(); setOpen(false) }} />
+ <div className="cv-pop" style={{ left: pos.x, top: pos.y, minWidth: width }}>
+ {title && <div className="text-[12px] font-bold text-white/90 mb-2.5">{title}</div>}
+ {children}
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
+
+/** labelled slider row (canva spacing/transparency style) */
+export function SliderRow({
+ label,
+ value,
+ min,
+ max,
+ step,
+ defaultValue,
+ onChange,
+ onCommit,
+ format,
+}: {
+ label: string
+ value: number
+ min: number
+ max: number
+ step: number
+ defaultValue?: number
+ onChange: (v: number) => void
+ onCommit?: (v: number) => void
+ format?: (v: number) => string
+}) {
+ return (
+ <div className="mb-3.5 last:mb-0">
+ <div className="flex items-center justify-between mb-1.5">
+ <span className="text-[12px] text-white/80 font-medium">{label}</span>
+ <input
+ type="number"
+ value={Number(value.toFixed(2))}
+ min={min}
+ max={max}
+ step={step}
+ onChange={(e) => {
+ const v = Number(e.target.value)
+ if (!Number.isNaN(v)) onChange(v)
+ }}
+ onBlur={() => onCommit?.(value)}
+ className="h-7 w-16 rounded-lg bg-white/[0.07] border border-white/10 px-2 text-[12px] text-white outline-none focus:border-[#7630D7] [color-scheme:dark]"
+ aria-label={label}
+ />
+ </div>
+ <input
+ type="range"
+ className="cv-slider w-full"
+ style={{ background: `linear-gradient(to right, #7630D7 ${((value - min) / (max - min)) * 100}%, rgba(255,255,255,0.14) ${((value - min) / (max - min)) * 100}%)` }}
+ min={min}
+ max={max}
+ step={step}
+ value={value}
+ onChange={(e) => onChange(Number(e.target.value))}
+ onPointerUp={() => onCommit?.(value)}
+ aria-label={`${label} slider`}
+ />
+ {format && <div className="text-[10px] text-white/40 mt-1">{format(value)}</div>}
+ </div>
+ )
+}
+
+/** small square icon tile used in the position popover (canva 2×2 grid) */
+export function IconTile({
+ icon,
+ label,
+ onClick,
+ disabled,
+ active,
+}: {
+ icon: ReactNode
+ label: string
+ onClick?: () => void
+ disabled?: boolean
+ active?: boolean
+}) {
+ return (
+ <button
+ onClick={onClick}
+ disabled={disabled}
+ className={cn(
+ 'flex flex-col items-center justify-center gap-1 rounded-lg py-2 text-[10px] font-medium text-white/80 transition-colors',
+ 'hover:bg-white/[0.09] disabled:opacity-35 disabled:pointer-events-none',
+ active && 'bg-white/[0.13] text-white'
+ )}
+ aria-label={label}
+ >
+ {icon}
+ <span>{label}</span>
+ </button>
+ )
+}
diff --git a/src/lib/editor-utils.ts b/src/lib/editor-utils.ts
index c3612d4..f0712d8 100644
--- a/src/lib/editor-utils.ts
+++ b/src/lib/editor-utils.ts
@@ -168,6 +168,56 @@ export const GRAPHICS: GraphicDef[] = [
name: 'Banner',
path: 'M2 10 H98 V74 L82 62 L66 74 L50 62 L34 74 L18 62 L2 74 Z',
},
+ {
+ id: 'pentagon',
+ name: 'Pentagon',
+ path: 'M50 2 L96 36 L78 94 H22 L4 36 Z',
+ },
+ {
+ id: 'hexagon',
+ name: 'Hexagon',
+ path: 'M25 4 H75 L96 50 L75 96 H25 L4 50 Z',
+ },
+ {
+ id: 'octagon',
+ name: 'Octagon',
+ path: 'M30 2 H70 L96 30 V70 L70 98 H30 L4 70 V30 Z',
+ },
+ {
+ id: 'cloud',
+ name: 'Cloud',
+ path: 'M24 76 C10 76 2 66 2 54 C2 42 12 33 24 34 C28 18 42 8 58 8 C76 8 90 20 92 38 C96 44 98 50 96 58 C94 70 84 76 74 76 Z',
+ },
+ {
+ id: 'moon',
+ name: 'Moon',
+ path: 'M62 2 C30 8 6 34 6 62 C6 86 26 98 40 98 C20 88 12 64 22 42 C32 22 52 8 78 8 C74 4 68 2 62 2 Z',
+ },
+ {
+ id: 'bolt',
+ name: 'Bolt',
+ path: 'M56 2 L18 56 H44 L38 98 L82 40 H54 Z',
+ },
+ {
+ id: 'check-circle',
+ name: 'Check circle',
+ path: 'M50 2 C76 2 98 24 98 50 C98 76 76 98 50 98 C24 98 2 76 2 50 C2 24 24 2 50 2 Z M44 72 L76 40 L68 32 L44 56 L32 44 L24 52 Z',
+ },
+ {
+ id: 'diamond',
+ name: 'Diamond',
+ path: 'M50 2 L98 50 L50 98 L2 50 Z',
+ },
+ {
+ id: 'semi-circle',
+ name: 'Semicircle',
+ path: 'M2 50 A48 48 0 0 1 98 50 Z',
+ },
+ {
+ id: 'frame',
+ name: 'Frame',
+ path: 'M2 2 H98 V98 H2 Z M14 14 V86 H86 V14 Z',
+ },
]
// ── Stickers (emoji) ─────────────────────────────────────────
diff --git a/src/lib/types.ts b/src/lib/types.ts
index e4dc449..8e2d385 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -13,17 +13,22 @@ export type ElementType =
| 'stroke'
| 'image'
| 'sticker'
+ | 'group'
-export type TextAlign = 'left' | 'center' | 'right'
+export type TextAlign = 'left' | 'center' | 'right' | 'justify'
-/** Canva-style text effects */
-export type TextEffect = 'none' | 'shadow' | 'lift' | 'hollow' | 'neon' | 'echo'
+/** Canva-style text effects (v0.3: aligned to canva 2026 naming) */
+export type TextEffect = 'none' | 'shadow' | 'lift' | 'hollow' | 'neon' | 'echo' | 'glow' | 'outline' | 'background' | 'splice'
export const TEXT_EFFECTS: { id: TextEffect; label: string }[] = [
{ id: 'none', label: 'None' },
- { id: 'shadow', label: 'Shadow' },
+ { id: 'shadow', label: 'Drop' },
{ id: 'lift', label: 'Lift' },
+ { id: 'glow', label: 'Glow' },
{ id: 'hollow', label: 'Hollow' },
+ { id: 'outline', label: 'Outline' },
+ { id: 'background', label: 'Background' },
+ { id: 'splice', label: 'Splice' },
{ id: 'neon', label: 'Neon' },
{ id: 'echo', label: 'Echo' },
]
@@ -59,10 +64,13 @@ export interface TextElement extends BaseElement {
italic: boolean
underline: boolean
strike: boolean
+ uppercase: boolean
fill: string
align: TextAlign
lineHeight: number
letterSpacing: number
+ /** text background block colour (canva "Background" effect) */
+ effectBackground?: string
/** canva-style effect preset */
effect?: TextEffect
}
@@ -92,6 +100,12 @@ export interface ImageElement extends BaseElement {
radius: number // corner clip
naturalWidth: number
naturalHeight: number
+ flipH?: boolean
+ flipV?: boolean
+ /** basic adjustments (0 = neutral, applied via Konva filters) */
+ brightness?: number // -100..100
+ contrast?: number // -100..100
+ saturation?: number // -100..100
}
export interface StickerElement extends BaseElement {
@@ -100,6 +114,14 @@ export interface StickerElement extends BaseElement {
fontSize: number
}
+/** A group nests child elements at their original page coordinates.
+ * Selecting/moving/transforming the group transforms children with it. */
+export interface GroupElement extends BaseElement {
+ type: 'group'
+ /** full child elements (positions relative to the page, same as before grouping) */
+ children: AnyElement[]
+}
+
/** Freehand stroke — points are [x0,y0,x1,y1,…] relative to (x, y). */
export interface StrokeElement extends BaseElement {
type: 'stroke'
@@ -128,6 +150,7 @@ export type AnyElement =
| StrokeElement
| ImageElement
| StickerElement
+ | GroupElement
export type Background =
| { type: 'solid'; color: string }
@@ -223,6 +246,7 @@ export function createTextElement(init: BaseInit & Partial<TextElement> = {}): T
italic: false,
underline: false,
strike: false,
+ uppercase: false,
fill: '#1F2226',
align: 'center',
lineHeight: 1.25,
@@ -273,10 +297,30 @@ export function createImageElement(
radius: 12,
naturalWidth,
naturalHeight,
+ flipH: false,
+ flipV: false,
+ brightness: 0,
+ contrast: 0,
+ saturation: 0,
...init,
}
}
+/** wrap child elements into a group; children keep page coords */
+export function createGroupElement(children: AnyElement[]): GroupElement {
+ const xs = children.map((c) => c.x)
+ const ys = children.map((c) => c.y)
+ const x1 = Math.min(...xs)
+ const y1 = Math.min(...ys)
+ const x2 = Math.max(...children.map((c) => c.x + c.width))
+ const y2 = Math.max(...children.map((c) => c.y + c.height))
+ return {
+ ...baseElement('group', { x: x1, y: y1, width: x2 - x1, height: y2 - y1 }),
+ type: 'group',
+ children: children.map((c) => ({ ...c })),
+ }
+}
+
export function createStickerElement(char: string, init: BaseInit & Partial<StickerElement> = {}): StickerElement {
return {
...baseElement('sticker', { width: 160, height: 160, ...init }),
@@ -336,3 +380,6 @@ export function isImage(el: AnyElement): el is ImageElement {
export function isSticker(el: AnyElement): el is StickerElement {
return el.type === 'sticker'
}
+export function isGroup(el: AnyElement): el is GroupElement {
+ return el.type === 'group'
+}
diff --git a/src/store/editor-store.ts b/src/store/editor-store.ts
index 0362986..6415246 100644
--- a/src/store/editor-store.ts
+++ b/src/store/editor-store.ts
@@ -6,6 +6,7 @@ import {
type AnyElement,
type Background,
type BrandKit,
+ createGroupElement,
DEFAULT_BRAND,
type DesignRecord,
type PageData,
@@ -81,11 +82,16 @@ interface EditorState {
deleteSelection: () => void
duplicateSelection: () => void
copySelection: () => void
+ cutSelection: () => void
pasteClipboard: () => void
moveLayer: (id: string, dir: 'up' | 'down' | 'front' | 'back') => void
reorderLayer: (dragId: string, targetIndex: number) => void
setLock: (ids: string[], locked: boolean) => void
setVisible: (ids: string[], visible: boolean) => void
+ groupSelection: () => void
+ ungroupSelection: () => void
+ alignElements: (ids: string[], mode: 'left' | 'cx' | 'right' | 'top' | 'cy' | 'bottom') => void
+ flipSelection: (axis: 'h' | 'v') => void
// page ops
addPage: () => void
@@ -100,6 +106,10 @@ interface EditorState {
zoomIn: () => void
zoomOut: () => void
resetZoom: () => void
+ fitToScreen: () => void
+ /** workspace viewport size (set by CanvasStage for fit-to-screen) */
+ viewport: { width: number; height: number }
+ setViewport: (v: { width: number; height: number }) => void
// canva-2026 chrome
setEditingMode: (m: 'editing' | 'viewing') => void
@@ -266,6 +276,13 @@ export const useEditorStore = create<EditorState>((set, get) => ({
clipboard = clone(pages[currentPage].elements.filter((e) => selectedIds.includes(e.id)))
},
+ cutSelection: () => {
+ const { selectedIds, pages, currentPage } = get()
+ if (!selectedIds.length) return
+ clipboard = clone(pages[currentPage].elements.filter((e) => selectedIds.includes(e.id)))
+ get().deleteSelection()
+ },
+
pasteClipboard: () => {
if (!clipboard.length) return
get().pushHistory()
@@ -308,6 +325,68 @@ export const useEditorStore = create<EditorState>((set, get) => ({
setLock: (ids, locked) => get().updateElements(ids, { locked }),
setVisible: (ids, visible) => get().updateElements(ids, { visible }),
+ groupSelection: () => {
+ const { selectedIds, pages, currentPage } = get()
+ const page = pages[currentPage]
+ const children = page.elements.filter((e) => selectedIds.includes(e.id) && !e.locked)
+ if (children.length < 2) return
+ get().pushHistory()
+ const group = createGroupElement(children)
+ const next = clone(pages)
+ next[currentPage].elements = [...next[currentPage].elements.filter((e) => !selectedIds.includes(e.id)), group]
+ set({ pages: next, selectedIds: [group.id] })
+ },
+
+ ungroupSelection: () => {
+ const { selectedIds, pages, currentPage } = get()
+ const page = pages[currentPage]
+ const groups = page.elements.filter((e) => selectedIds.includes(e.id) && e.type === 'group')
+ if (!groups.length) return
+ get().pushHistory()
+ const next = clone(pages)
+ let released: string[] = []
+ for (const g of groups) {
+ if (g.type !== 'group') continue
+ next[currentPage].elements = next[currentPage].elements.filter((e) => e.id !== g.id)
+ next[currentPage].elements.push(...g.children.map((c) => ({ ...clone(c) })))
+ released = [...released, ...g.children.map((c) => c.id)]
+ }
+ set({ pages: next, selectedIds: released })
+ },
+
+ alignElements: (ids, mode) => {
+ if (!ids.length) return
+ get().pushHistory()
+ const { pages, currentPage, width, height } = get()
+ const next = clone(pages)
+ next[currentPage].elements = next[currentPage].elements.map((el) => {
+ if (!ids.includes(el.id)) return el
+ switch (mode) {
+ case 'left': return { ...el, x: 0 }
+ case 'cx': return { ...el, x: Math.round((width - el.width) / 2) }
+ case 'right': return { ...el, x: width - el.width }
+ case 'top': return { ...el, y: 0 }
+ case 'cy': return { ...el, y: Math.round((height - el.height) / 2) }
+ case 'bottom': return { ...el, y: height - el.height }
+ }
+ })
+ set({ pages: next })
+ },
+
+ flipSelection: (axis) => {
+ const { selectedIds, pages, currentPage } = get()
+ if (!selectedIds.length) return
+ get().pushHistory()
+ const next = clone(pages)
+ next[currentPage].elements = next[currentPage].elements.map((el) => {
+ if (!selectedIds.includes(el.id)) return el
+ if (el.type === 'image') return { ...el, flipH: axis === 'h' ? !el.flipH : el.flipH, flipV: axis === 'v' ? !el.flipV : el.flipV }
+ // shapes/text: mirror via negative scale is not in the model; rotate 180 for symmetric flip feel
+ return { ...el, rotation: (el.rotation + (axis === 'h' ? 0 : 180)) % 360 }
+ })
+ set({ pages: next })
+ },
+
addPage: () => {
get().pushHistory()
const { pages } = get()
@@ -359,6 +438,14 @@ export const useEditorStore = create<EditorState>((set, get) => ({
zoomIn: () => set({ zoom: Math.min(ZOOM_MAX, get().zoom * 1.2) }),
zoomOut: () => set({ zoom: Math.max(ZOOM_MIN, get().zoom / 1.2) }),
resetZoom: () => set({ zoom: 1 }),
+ fitToScreen: () => {
+ const { width, height, viewport } = get()
+ if (!viewport.width || !viewport.height) { set({ zoom: 1 }); return }
+ const z = Math.min((viewport.width - 96) / width, (viewport.height - 96) / height)
+ set({ zoom: Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z)) })
+ },
+ viewport: { width: 0, height: 0 },
+ setViewport: (v) => set({ viewport: v }),
setEditingMode: (m) => set({ editingMode: m }),
setPreviewOpen: (open) => set({ previewOpen: open }),