### Install @shadcn/designer Package Source: https://ds.shadcn.com/docs/guides/installation.md Install the designer package using npm, replacing YOUR_LICENSE_KEY with your actual license key. ```bash npm install https://ds.shadcn.com/registry\?license\=YOUR_LICENSE_KEY ``` -------------------------------- ### Default Designer Setup Source: https://ds.shadcn.com/docs/concepts/designer.md Renders the default editor experience using Designer, DesignerContent, DesignerCanvas, and DesignerFrame. This is the basic setup mirrored in the initial example. ```tsx import * as React from "react" import { Designer, DesignerCanvas, DesignerContent, DesignerFrame, } from "@shadcn/designer" export function CustomDesigner() { return ( ) } ``` -------------------------------- ### Basic Setup with Unit Configuration Source: https://ds.shadcn.com/docs/unit-system Configure the Designer component with preferred units, frame size, and DPI settings for print. ```javascript import { Designer } from "@shadcn/designer" function PrintDesigner() { return ( {/* Designer content */} ) } ``` -------------------------------- ### Install Tailwind CSS Dependencies Source: https://ds.shadcn.com/docs/guides/installation.md Add Tailwind CSS and its Vite plugin as project dependencies. ```bash npm install tailwindcss @tailwindcss/vite ``` -------------------------------- ### Unit Conversion Examples with DPI Source: https://ds.shadcn.com/docs/concepts/unit-system.md Illustrates how physical units like inches and millimeters are converted to pixels based on the Dots Per Inch (DPI) setting. Examples are provided for both screen (96 DPI) and print (300 DPI). ```tsx // At 96 DPI (screen) const screenDpi = 96 toPixels(1, "in", screenDpi) // 96px toPixels(25.4, "mm", screenDpi) // 96px (25.4mm = 1 inch) // At 300 DPI (print) const printDpi = 300 toPixels(1, "in", printDpi) // 300px toPixels(25.4, "mm", printDpi) // 300px ``` -------------------------------- ### Static Frame Example Source: https://ds.shadcn.com/docs/examples/save.md Use DesignerStaticFrame for a read-only preview of design layers. Ensure you import the component from '@shadcn/designer'. ```tsx import { DesignerStaticFrame } from "@shadcn/designer" export function SaveExampleViewStaticFrame({ layers }: { layers: Layer[] }) { return } ``` -------------------------------- ### Conversion Examples with DPI Source: https://ds.shadcn.com/docs/unit-system Shows how to use the `toPixels` function to convert physical units to pixels at different DPI settings (screen and print). ```typescript // At 96 DPI (screen) const screenDpi = 96 toPixels(1, "in", screenDpi) // 96px toPixels(25.4, "mm", screenDpi) // 96px (25.4mm = 1 inch) // At 300 DPI (print) const printDpi = 300 toPixels(1, "in", printDpi) // 300px toPixels(25.4, "mm", printDpi) // 300px ``` -------------------------------- ### Designer Component Setup Source: https://ds.shadcn.com/docs/concepts/unit-system.md Configure the Designer component with frame size, unit system, and DPI settings for print or digital design. ```APIDOC ## Designer Component Setup ### Description Configure the Designer component with your preferred units and DPI settings. This setup is crucial for defining the canvas size and how measurements are handled, especially when designing for print. ### Props - **frameSize** (object) - Required - Defines the dimensions of the design frame. - **width** (number) - Required - The width of the frame. - **height** (number) - Required - The height of the frame. - **unit** (string) - Optional - The unit of measurement for width and height. Defaults to 'px'. Supported units: 'px', 'mm', 'in', 'cm', 'pt'. - **unitSystem** (string) - Required - The unit system to use for displaying values within the designer. Supported units: 'px', 'mm', 'in', 'cm', 'pt'. - **dpi** (number) - Optional - The Dots Per Inch setting, important for print-related conversions. Defaults to 96. - **defaultLayers** (array) - Optional - Initial layers to be rendered in the designer. ### Request Example ```tsx import { Designer } from "@shadcn/designer" function PrintDesigner() { return ( {/* Designer content */} ) } ``` ``` -------------------------------- ### Uncontrolled Designer Example Source: https://ds.shadcn.com/docs/reference/designer.md Use defaultLayers for uncontrolled mode when the Designer should manage its own state. This is suitable for demos and static examples. ```tsx import { Designer } from "@shadcn/designer" function UncontrolledDesigner() { return ( { console.log("Designer mounted") }} > {/* Designer content */} ) } ``` -------------------------------- ### Basic Designer Setup with Components Source: https://ds.shadcn.com/docs/guides/installation.md Set up a basic designer with a canvas and frame using core components. The default frame size is 1024x1024. ```tsx import { Designer, DesignerContent, DesignerCanvas, DesignerFrame, } from "@shadcn/designer"; export default function App() { return ( ); } ``` -------------------------------- ### Layer Storage Example Source: https://ds.shadcn.com/docs/unit-system Illustrates how layer values are stored with their original units, preserving precision across different unit systems. ```typescript const layer: Layer = { id: "1", name: "Business Card", type: "frame", value: "", cssVars: { // Dimensions in millimeters "--width": "85mm", "--height": "55mm", "--translate-x": "10mm", "--translate-y": "10mm", // Border in points "--border-width": "1pt", // Font size in points "--content-font-size": "12pt", // Mixed units are supported "--padding-top": "5mm", "--margin-left": "0.25in", } } ``` -------------------------------- ### Basic Setup for Print Designer Source: https://ds.shadcn.com/docs/concepts/unit-system.md Configure the Designer component with frame size in millimeters, set the unit system to 'mm', and specify a high DPI for print. ```tsx import { Designer } from "@shadcn/designer" function PrintDesigner() { return ( {/* Designer content */} ) } ``` -------------------------------- ### useKeybindings Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current keybinding configuration. This hook provides access to the defined keyboard shortcuts and their associated keys. ```APIDOC ## useKeybindings ### Description Gets the current keybinding configuration. ### Usage ```tsx import { useKeybindings } from "@shadcn/designer" function ShortcutList() { const keybindings = useKeybindings() return (
{Object.entries(keybindings).map(([key, binding]) => (
{binding.name}: {binding.key}
))}
) } ``` ``` -------------------------------- ### Standalone App Integration Source: https://ds.shadcn.com/docs/guides/installation.md Import the Designer component and its stylesheet for a standalone application setup. ```tsx import { Designer } from "@shadcn/designer"; import "@shadcn/designer/styles.css"; export default function App() { return ; } ``` -------------------------------- ### useUnitSystem Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current unit system being used for display. Possible values include 'px', 'mm', 'in', 'cm', and 'pt'. ```APIDOC ## useUnitSystem ### Description Gets the current unit system being used for display. ### Usage ```tsx import { useUnitSystem } from "@shadcn/designer" function UnitDisplay() { const unitSystem = useUnitSystem() // "px" | "mm" | "in" | "cm" | "pt" return Current unit: {unitSystem} } ``` ``` -------------------------------- ### Custom Designer with Panels and Content Source: https://ds.shadcn.com/docs/examples/panels Shows a complete example of a custom Designer component including imported elements and content within the panels. ```tsx import { Designer, DesignerCanvas, DesignerContent, DesignerFrame, DesignerPanel, } from "@shadcn/designer" export function CustomDesigner() { return (
Left Panel
Right Panel
) } ``` -------------------------------- ### Compose Editor UI with Shell Components Source: https://ds.shadcn.com/docs/concepts/designer.md Assemble a complete editor interface by integrating panels, toolbars, and headers around the designer canvas. This example demonstrates a basic shell structure. ```tsx import * as React from "react" import { Designer, DesignerCanvas, DesignerContent, DesignerFrame, DesignerHeader, DesignerPanel, DesignerToolbar, DesignerToolbarGroup, DesignerToolbarButton, } from "@shadcn/designer" import { Button } from "@shadcn/ui/button" export function DesignerWithShell() { return (
Brand Poster
Add Duplicate

Layer

Select a layer to edit properties.

) } ``` -------------------------------- ### ActionToolbarZoom Example Source: https://ds.shadcn.com/docs/reference/toolbar.md Implement ActionToolbarZoom for zoom controls within the designer toolbar. This snippet requires DesignerToolbar and DesignerToolbarGroup for proper rendering. ```tsx import { ActionToolbarZoom, DesignerToolbar, DesignerToolbarGroup } from "@shadcn/designer" function CustomDesignerToolbar() { return ( ) } ``` -------------------------------- ### Input Scrubber with useScrubber Hook Source: https://ds.shadcn.com/docs/changelog.md Example of using the useScrubber hook to create an input scrubber for faster adjustments. It handles pointer locking, acceleration, and modifier shortcuts. ```tsx import * as React from "react" import { useScrubber } from "@shadcn/designer" function DimensionScrubber() { const { scrubProps, value } = useScrubber({ value: 120, onChange: (next) => console.log("Width", next), }) return ( ) } ``` -------------------------------- ### ActionToolbarAddLayer Example Source: https://ds.shadcn.com/docs/reference/toolbar.md Use ActionToolbarAddLayer to provide controls for adding new layers within the designer toolbar. Ensure DesignerToolbar and DesignerToolbarGroup are imported. ```tsx import { ActionToolbarAddLayer, DesignerToolbar, DesignerToolbarGroup } from "@shadcn/designer" function CustomDesignerToolbar() { return ( ) } ``` -------------------------------- ### useDesignerTool Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the currently active designer tool. Returns a string representing the tool, e.g., 'move' or 'hand'. ```APIDOC ## useDesignerTool ### Description Gets the currently active designer tool. Returns a string representing the tool. ### Method Signature `useDesignerTool(): 'move' | 'hand'` ### Return Value A string indicating the current tool ('move' or 'hand'). ### Usage Example ```tsx import { useDesignerTool } from "@shadcn/designer" function ToolIndicator() { const tool = useDesignerTool() return (
Active tool: {tool === "move" ? "Move Tool" : "Hand Tool"}
) } ``` ``` -------------------------------- ### Example Usage of InferLayerTypes Source: https://ds.shadcn.com/docs/reference/types.md Demonstrates how `InferLayerTypes` infers the structure of layer types, including their values and optional meta properties, from a provided array of layer definitions. ```typescript const layerTypes = [ createLayerType({ type: "text", name: "Text", defaultValues: { name: "Text", value: "Hello" }, render: () => null }), createLayerType({ type: "card", name: "Card", defaultValues: { name: "Card", value: "", meta: { author: "" } }, render: () => null }), ] // InferLayerTypes = { // text: { value: string }; // card: { value: string; meta: { author: string } } // } ``` -------------------------------- ### Basic Designer with Frame Source: https://ds.shadcn.com/docs/examples/basic.md Renders a basic editor with a single frame layer inside a canvas. This is the simplest setup for the Designer component. ```tsx import { Designer, DesignerCanvas, DesignerContent, DesignerFrame, } from "@shadcn/designer" function CustomDesigner() { return ( ) } ``` -------------------------------- ### Update package.json to latest minor version Source: https://ds.shadcn.com/docs/guides/update.md Update your `package.json` to reference the latest minor version of `@shadcn/designer` by changing the `version` parameter in the registry URL. Run `pnpm install` afterwards. ```json { "name": "my-designer", "dependencies": { "@shadcn/designer": "https://ds.shadcn.com/registry?version=PACKAGE_VERSION&license=YOUR_LICENSE_KEY" } } ``` -------------------------------- ### Image Generator Component Setup Source: https://ds.shadcn.com/docs/examples/image-generator.md Sets up the Designer component to allow only image layer types and configures a default single image layer with specified dimensions. ```tsx function ExampleImageGenerator() { return (
layer.type === "image" )} defaultLayers={[ { id: "image-1", type: "image", name: "Generated Image", isLocked: true, value: "", cssVars: { "--width": "1024px", "--height": "1024px", }, }, ]}>
) } ``` -------------------------------- ### Update package.json to version 2.0.0 Source: https://ds.shadcn.com/docs/guides/update.md Modify your `package.json` to point to the registry URL for version 2.0.0. After updating, run `pnpm install` to fetch the new version. ```json { "name": "my-designer", "dependencies": { "@shadcn/designer": "https://ds.shadcn.com/registry?version=2.0.0&license=YOUR_LICENSE_KEY" } } ``` -------------------------------- ### Import and Use useLayers Hook Source: https://ds.shadcn.com/docs/examples/export-layers Import the `useLayers` hook from the Shadcn Designer library and call it to get the current layers object. ```tsx import { useLayers } from "@shadcn/designer" const layers = useLayers() ``` -------------------------------- ### Controlled Designer Example Source: https://ds.shadcn.com/docs/reference/designer.md Use layers and onLayersChange for controlled mode when external state management is required. The onLayersChange callback is triggered by user actions. ```tsx import { Designer } from "@shadcn/designer" import { useState } from "react" function ControlledDesigner() { const [layers, setLayers] = useState([ { id: "text-1", type: "text", name: "Hello", value: "Hello World", cssVars: { "--width": "200px", "--height": "100px", } } ]) const handleLayersChange = (newLayers) => { setLayers(newLayers) // Optionally save to external storage saveToDatabase(newLayers) } return ( {/* Designer content */} ) } ``` -------------------------------- ### Programmatically Switch Designer Tools Source: https://ds.shadcn.com/docs/examples/designer-tool.md Use the `useSetDesignerTool` hook to change the active designer tool. This example demonstrates switching between 'move' and 'hand' modes using buttons. ```tsx import { useDesignerTool, useSetDesignerTool } from "@shadcn/designer" import { Button } from "@/components/ui/button" function CustomToolSwitcher() { const tool = useDesignerTool() const setTool = useSetDesignerTool() return (
) } ``` -------------------------------- ### Create CSS Variable Action with Custom Serialization Source: https://ds.shadcn.com/docs/reference/hooks.md Creates a CSS variable action with custom serialization and deserialization functions. This example defines how to serialize a number to 'px' and deserialize it back. ```typescript const fontSize = createLayerCssVarAction("--font-size", "16px", { serialize: (value: number) => `${value}px`, deserialize: (value: string | undefined) => { return value ? parseInt(value) : 16 } }) ``` -------------------------------- ### Get Debug Mode State Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current debug mode state. This hook is used to conditionally render debug information or enable/disable debugging features. ```tsx import { useDebug } from "@shadcn/designer" function DebugPanel() { const debug = useDebug() if (!debug) return null return
Debug information...
} ``` -------------------------------- ### Get Unit System Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current unit system being used for display (e.g., px, mm, in). This hook is essential for consistent measurement representation across the application. ```tsx import { useUnitSystem } from "@shadcn/designer" function UnitDisplay() { const unitSystem = useUnitSystem() // "px" | "mm" | "in" | "cm" | "pt" return Current unit: {unitSystem} } ``` -------------------------------- ### Get All Layers Source: https://ds.shadcn.com/docs/reference/hooks.md Retrieves all layers present in the design canvas. Use this to get a complete list of layers for display or processing. For adding or removing layers, refer to `useAddLayers` and `useDeleteLayers`. ```tsx import { useLayers } from "@shadcn/designer" function LayerCount() { const layers = useLayers() return Total layers: {layers.length} } ``` -------------------------------- ### Adding Default Layers Source: https://ds.shadcn.com/docs/examples/basic.md Shows how to initialize the Designer with predefined layers using the `defaultLayers` prop. This is useful for loading existing content or setting up initial states. ```tsx function CustomDesigner() { return ( ) } ``` -------------------------------- ### Get DPI Setting Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current DPI (dots per inch) setting used for unit conversions. The default DPI is typically 96, but this can be adjusted for different display or print contexts. ```tsx import { useDPI } from "@shadcn/designer" function DPIIndicator() { const dpi = useDPI() // Default: 96 return DPI: {dpi} } ``` -------------------------------- ### Create a New Vite Project Source: https://ds.shadcn.com/docs/guides/installation.md Use this command to scaffold a new Vite project with React and TypeScript. ```bash npx create-vite@latest my-designer --template react-ts ``` -------------------------------- ### useTargets Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current interaction targets on the canvas. Returns an array of targets. ```APIDOC ## useTargets ### Description Gets the current interaction targets on the canvas. ### Method Signature `useTargets(): Target[]` ### Return Value An array of `Target` objects representing the currently selected or active targets on the canvas. ### Usage Example ```tsx import { useTargets } from "@shadcn/designer" function TargetInfo() { const targets = useTargets() return
Active targets: {targets.length}
} ``` ``` -------------------------------- ### Add License Key to package.json Source: https://ds.shadcn.com/docs/guides/image-browser.md Add your license key to the package.json file to enable the shadcn/designer registry. ```json "@shadcn/designer": "https://ds.shadcn.com/registry?license=YOUR_LICENSE_KEY&version=0.4.2", ``` -------------------------------- ### useFrameSize Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current frame/canvas size. Returns an object with width and height properties. ```APIDOC ## useFrameSize ### Description Gets the current frame/canvas size. ### Method Signature `useFrameSize(): { width: number; height: number }` ### Return Value An object containing the `width` and `height` of the canvas. ### Usage Example ```tsx import { useFrameSize } from "@shadcn/designer" function FrameInfo() { const frameSize = useFrameSize() return (
Canvas: {frameSize.width} × {frameSize.height}
) } ``` ``` -------------------------------- ### Adding Unit Support to Existing Designer Project Source: https://ds.shadcn.com/docs/concepts/unit-system.md Guidance on integrating unit support into an existing project. Shows how to add the ActionUnitSelector to the DesignerHeader and configure the Designer component with initial unit system and DPI. ```tsx // Before (pixels only) {/* content */} // After (with unit support) {/* Add unit switcher */} {/* content */} ``` -------------------------------- ### useZoom Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current zoom level of the canvas. Returns a number representing the zoom level. ```APIDOC ## useZoom ### Description Gets the current zoom level of the canvas. ### Method Signature `useZoom(): number` ### Return Value A number representing the current zoom level (e.g., 1.0 for 100%). ### Usage Example ```tsx import { useZoom } from "@shadcn/designer" function ZoomIndicator() { const zoom = useZoom() return {Math.round(zoom * 100)}% } ``` ``` -------------------------------- ### Import Full Stylesheet for Standalone Apps Source: https://ds.shadcn.com/docs/concepts/theming.md Import the complete stylesheet for standalone applications to enable theming via `--ds-*` variables. ```tsx import "@shadcn/designer/styles.css"; ``` -------------------------------- ### Capture Image with Microlink mql Source: https://ds.shadcn.com/docs/guides/convert-image.md Capture the rendered static frame as an image using the Microlink mql package. This requires the full URL to your page and specific screenshot options. Note that this will not work on the dev server. ```ts import mql from "@microlink/mql" const imageUrl = "FULL_URL_TO_YOUR_PAGE" const { data } = await mql(imageUrl, { screenshot: { element: "#post-image", type: "jpeg", fullPage: false, }, }) ``` -------------------------------- ### useLayers Source: https://ds.shadcn.com/docs/reference/hooks.md Gets all layers in the design. This hook returns an array containing all layer objects present in the design canvas. ```APIDOC ## useLayers ### Description Gets all layers in the design. ### Usage ```tsx import { useLayers } from "@shadcn/designer" function LayerCount() { const layers = useLayers() return Total layers: {layers.length} } ``` **Note:** To add or remove layers, see [`useAddLayers`](#useaddlayers) and [`useDeleteLayers`](#usedeletelayers). ``` -------------------------------- ### Configuring Frame Size with Units Source: https://ds.shadcn.com/docs/concepts/unit-system.md Demonstrates setting the frame size using different units like millimeters, inches, and the default pixels. ```tsx // A4 paper in millimeters frameSize={{ width: 210, height: 297, unit: "mm" }} // US Letter in inches frameSize={{ width: 8.5, height: 11, unit: "in" }} // Screen size in pixels (default) frameSize={{ width: 1920, height: 1080 }} // unit defaults to "px" ``` -------------------------------- ### useSelectedLayerIds Source: https://ds.shadcn.com/docs/reference/hooks.md Gets an array of IDs for currently selected layers. This hook is useful for operations that require layer identifiers. ```APIDOC ## useSelectedLayerIds ### Description Gets an array of IDs for currently selected layers. ### Usage ```tsx import { useSelectedLayerIds } from "@shadcn/designer" function SelectedLayerCount() { const selectedLayerIds = useSelectedLayerIds() return Selected: {selectedLayerIds.length} } ``` ``` -------------------------------- ### useSelectedLayers Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the currently selected layers on the canvas. This hook returns an array of layer objects that are currently selected. ```APIDOC ## useSelectedLayers ### Description Gets the currently selected layers on the canvas. ### Usage ```tsx import { useSelectedLayers } from "@shadcn/designer" function LayerInfo() { const selectedLayers = useSelectedLayers() return (
{selectedLayers.length > 0 ? (

Selected: {selectedLayers[0].name}

) : (

No layers selected

)}
) } ``` ``` -------------------------------- ### ActionToolbarHistory Example Source: https://ds.shadcn.com/docs/reference/toolbar.md Integrate ActionToolbarHistory to include undo and redo functionality in your designer toolbar. This component requires DesignerToolbar and DesignerToolbarGroup. ```tsx import { ActionToolbarHistory, DesignerToolbar, DesignerToolbarGroup } from "@shadcn/designer" function CustomDesignerToolbar() { return ( ) } ``` -------------------------------- ### Basic Panel Layout Source: https://ds.shadcn.com/docs/examples/panels Demonstrates the basic structure for placing DesignerPanel components around the DesignerCanvas. ```tsx Left Panel Right Panel ``` -------------------------------- ### Add Keyboard Shortcut to Layer Source: https://ds.shadcn.com/docs/concepts/layers.md Define a keybinding for a layer type to enable quick creation via keyboard shortcut. The shortcut is automatically registered and displayed in the help dialog. ```tsx export const shapeLayer = createLayerType({ type: "shape", name: "Shape", keybinding: { key: "s", label: "S", labelMac: "S", description: "Add Shape", group: "New Layer", }, // ... }); ``` -------------------------------- ### useDPI Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current DPI (dots per inch) setting used for unit conversions. The default value is 96. ```APIDOC ## useDPI ### Description Gets the current DPI (dots per inch) setting used for unit conversions. ### Usage ```tsx import { useDPI } from "@shadcn/designer" function DPIIndicator() { const dpi = useDPI() // Default: 96 return DPI: {dpi} } ``` ``` -------------------------------- ### useLayersWithStyles Source: https://ds.shadcn.com/docs/reference/hooks.md Gets all layers with computed styles applied. This hook returns an array of layer objects, each augmented with their calculated styles. ```APIDOC ## useLayersWithStyles ### Description Gets all layers with computed styles applied. ### Usage ```tsx import { useLayersWithStyles } from "@shadcn/designer" function StyledLayerList() { const layersWithStyles = useLayersWithStyles() return (
{layersWithStyles.map(layer => (
{layer.name}
))}
) } ``` ``` -------------------------------- ### useUnitSystem Hook Source: https://ds.shadcn.com/docs/examples/unit-system.md Retrieve the current unit system setting from the Designer context. ```javascript const unitSystem = useUnitSystem() // "px" | "mm" | "cm" | "in" | "pt" ``` -------------------------------- ### Configuring Default Unit System and DPI Source: https://ds.shadcn.com/docs/examples/unit-system.md Set the initial unit system and DPI when initializing the Designer component. This is useful for print-focused editors. ```tsx import { Designer, DesignerCanvas, DesignerFrame } from "@shadcn/designer" function PrintDesigner() { return ( ) } ``` -------------------------------- ### Get Current Unit System with useUnitSystem Hook Source: https://ds.shadcn.com/docs/unit-system Retrieve the current unit system being used for display in the Designer component. ```javascript import { useUnitSystem } from "@shadcn/designer" function MyComponent() { const unitSystem = useUnitSystem() // "px" | "mm" | "in" | "cm" | "pt" return
Current unit: {unitSystem}
} ``` -------------------------------- ### Get Current Designer Tool Source: https://ds.shadcn.com/docs/changelog.md Use `useDesignerTool` to retrieve the currently active tool on the canvas, such as the 'move' or 'hand' tool. ```tsx import { useDesignerTool } from "@shadcn/designer" function ToolIndicator() { const tool = useDesignerTool() return (
Active: {tool === "move" ? "Move Tool" : "Hand Tool"}
) } ``` -------------------------------- ### Basic DesignerToolbar Usage Source: https://ds.shadcn.com/docs/reference/designer.md Demonstrates how to use DesignerToolbar to group buttons and separators. Import necessary components from '@shadcn/designer' and '@tabler/icons-react'. ```tsx import { DesignerToolbar, DesignerToolbarGroup, DesignerToolbarButton, DesignerToolbarSeparator } from "@shadcn/designer" import { IconArrowBackUp } from "@tabler/icons-react" function CustomDesigner() { return ( {}}> ) } ``` -------------------------------- ### Display All Keybindings with useKeybindings Source: https://ds.shadcn.com/docs/concepts/keybindings.md The `useKeybindings` hook retrieves a merged map of all keybindings (built-in, custom, and added). This is useful for creating a help dialog to list shortcuts. ```tsx import { type Keybinding, useKeybindings } from "@shadcn/designer"; import { useIsMac } from "@shadcn/designer/hooks"; import { useMemo } from "react"; export function KeyboardShortcuts() { const keybindings = useKeybindings(); const isMac = useIsMac(); const groups = useMemo(() => { return Object.values(keybindings).reduce( (acc, keybinding) => { acc[keybinding.group] = [...(acc[keybinding.group] ?? []), keybinding]; return acc; }, {} as Record // Explicitly type the accumulator ); }, [keybindings]); return (
{Object.entries(groups).map(([group, items]) => (

{group}

    {items.map((keybinding) => (
  • {keybinding.description} {isMac ? keybinding.labelMac : keybinding.label}
  • ))}
))}
); } ``` -------------------------------- ### Custom Designer with Toolbar Source: https://ds.shadcn.com/docs/examples/toolbar.md This snippet demonstrates how to set up a custom designer with a toolbar containing predefined actions like 'Add Layer' and a custom button. It includes necessary imports from '@shadcn/designer' and '@tabler/icons-react'. ```tsx import { ActionToolbarAddLayer, Designer, DesignerCanvas, DesignerContent, DesignerFrame, DesignerToolbar, DesignerToolbarButton, DesignerToolbarGroup, DesignerToolbarSeparator, } from "@shadcn/designer" import { IconPlus } from "@tabler/icons-react" import { toast } from "sonner" function CustomDesigner() { return ( toast("Custom Button Clicked")} > Button ) } ``` -------------------------------- ### useDebug Source: https://ds.shadcn.com/docs/reference/hooks.md Gets the current debug mode state. This hook returns a boolean indicating whether the debug mode is currently active. ```APIDOC ## useDebug ### Description Gets the current debug mode state. ### Usage ```tsx import { useDebug } from "@shadcn/designer" function DebugPanel() { const debug = useDebug() if (!debug) return null return
Debug information...
} ``` ``` -------------------------------- ### DPI Presets for Different Contexts Source: https://ds.shadcn.com/docs/unit-system Provides predefined DPI values for common use cases like screen, print, and retina displays. ```javascript Copyconst DPI_PRESETS = { screen: 96, print: 300, retina: 192, } ``` -------------------------------- ### Get Keybinding Configuration Source: https://ds.shadcn.com/docs/reference/hooks.md Retrieves the current keybinding configuration. This hook is useful for displaying or interacting with the application's shortcut settings. ```tsx import { useKeybindings } from "@shadcn/designer" function ShortcutList() { const keybindings = useKeybindings() return (
{Object.entries(keybindings).map(([key, binding]) => (
{binding.name}: {binding.key}
))}
) } ``` -------------------------------- ### Get Layers with Styles Source: https://ds.shadcn.com/docs/reference/hooks.md Retrieves all layers along with their computed styles applied. This is useful for rendering layers with their final visual appearance. ```tsx import { useLayersWithStyles } from "@shadcn/designer" function StyledLayerList() { const layersWithStyles = useLayersWithStyles() return (
{layersWithStyles.map(layer => (
{layer.name}
))}
) } ``` -------------------------------- ### Get Selected Layers Source: https://ds.shadcn.com/docs/reference/hooks.md Retrieves the currently selected layers on the canvas. Useful for displaying information about the selected layer(s) or performing actions on them. ```tsx import { useSelectedLayers } from "@shadcn/designer" function LayerInfo() { const selectedLayers = useSelectedLayers() return (
{selectedLayers.length > 0 ? (

Selected: {selectedLayers[0].name}

) : (

No layers selected

)}
) } ``` -------------------------------- ### Import Tailwind CSS in Global Styles Source: https://ds.shadcn.com/docs/guides/installation.md Replace the content of your src/index.css file with the Tailwind CSS import. ```css @import "tailwindcss"; ``` -------------------------------- ### Get Zoom Level Source: https://ds.shadcn.com/docs/reference/hooks.md The `useZoom` hook retrieves the current zoom level of the canvas. It returns a number representing the zoom factor. ```tsx import { useZoom } from "@shadcn/designer" function ZoomIndicator() { const zoom = useZoom() return {Math.round(zoom * 100)}% } ``` -------------------------------- ### Use Custom Keybinding with useShortcut Source: https://ds.shadcn.com/docs/concepts/keybindings.md After registering custom keybindings, they become available for use with the `useShortcut` hook, providing autocompletion and type checking. ```tsx useShortcut("TOGGLE_PANEL_LEFT", () => { setLeftPanelOpen((open) => !open); }); ``` -------------------------------- ### Get Frame Size Source: https://ds.shadcn.com/docs/reference/hooks.md The `useFrameSize` hook returns the current dimensions of the canvas or frame. It provides an object with `width` and `height` properties. ```tsx import { useFrameSize } from "@shadcn/designer" function FrameInfo() { const frameSize = useFrameSize() return (
Canvas: {frameSize.width} × {frameSize.height}
) } ``` -------------------------------- ### Build API Route for Memes Source: https://ds.shadcn.com/docs/guides/image-browser.md Create an API route to fetch memes from the Imgflip API, implementing faux pagination and search functionality. ```tsx import { NextRequest, NextResponse } from "next/server" import { imagesResponseSchema } from "@shadcn/designer/schema" const DEFAULT_QUERY = "Pikachu" export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url) const query = searchParams.get("query") || DEFAULT_QUERY const page = Number(searchParams.get("page")) || 1 const per_page = Number(searchParams.get("per_page")) || 9 const url = `https://api.imgflip.com/get_memes` const response = await fetch(url) const data = await response.json() // Imgflip does not have pagination. // We'll implement a faux pagination and search. const startIndex = (page - 1) * per_page const endIndex = startIndex + per_page const memes = data.data.memes.filter((meme: { name: string }) => meme.name.toLowerCase().includes(query.toLowerCase()) ) const thisPage = memes.slice(startIndex, endIndex) return NextResponse.json( imagesResponseSchema.parse({ results: thisPage.map((meme: { id: string; url: string }) => ({ id: meme.id, url: meme.url, thumbnailUrl: meme.url, })), total: memes.length, total_pages: Math.ceil(memes.length / per_page), }) ) } ``` -------------------------------- ### Get Current DPI with useDPI Hook Source: https://ds.shadcn.com/docs/unit-system Retrieve the current Dots Per Inch (DPI) setting used for unit conversions. ```javascript import { useDPI } from "@shadcn/designer" function DPIDisplay() { const dpi = useDPI() // Default: 96 return
Current DPI: {dpi}
} ``` -------------------------------- ### Getting Current Frame Size Source: https://ds.shadcn.com/docs/examples/frame-size.md Use the `useFrameSize` hook to access the current width and height of the design frame within your component. ```tsx import { useFrameSize } from "@shadcn/designer" function CustomDesigner() { const { width, height } = useFrameSize() return
Frame Size: {width}x{height}
} ``` -------------------------------- ### Implementing Custom Zoom Controls with Hooks Source: https://ds.shadcn.com/docs/examples/zoom.md Utilize the useZoom and useSetZoom hooks to create custom zoom controls. This allows for fine-grained control over zoom levels, such as incremental adjustments and resetting to a base level. ```tsx function CustomZoomControls() { const zoom = useZoom() const setZoom = useSetZoom() return (
) } ``` -------------------------------- ### Initialize Page State with Jotai Source: https://ds.shadcn.com/docs/examples/pages.md Initializes Jotai atoms for managing editor pages and the selected page ID, with persistent storage. ```typescript const INITIAL_PAGES = [ { id: "1", name: "Page 1", layers: [], }, ] const pagesAtom = atomWithStorage("pages", INITIAL_PAGES) const selectedPageIdAtom = atomWithStorage("selectedPageId", INITIAL_PAGES[0].id) ``` -------------------------------- ### Extending Layer Types Source: https://ds.shadcn.com/docs/examples/basic.md Demonstrates how to extend the default layer types by adding a custom 'video' layer type. This allows for more specialized content within the designer. ```tsx import { DEFAULT_LAYER_TYPES, type LayerType } from "@shadcn/designer" // Extends the default layer types with a custom video layer type. const CUSTOM_LAYER_TYPES = [ ...DEFAULT_LAYER_TYPES, { id: "video", name: "Video", // ... other props }, ] satisfies LayerType[] function CustomDesigner() { return ( ) } ``` -------------------------------- ### Inferring Layer Types Source: https://ds.shadcn.com/docs/concepts/type-safety.md Use `InferLayerTypes` to generate the registry map required by the designer from your `layerTypes` array. This is typically used once in your application setup. ```typescript type AppLayerTypes = InferLayerTypes; ``` -------------------------------- ### Dynamic Unit Switching Component Source: https://ds.shadcn.com/docs/unit-system A client-side React component demonstrating dynamic switching of the unit system and DPI for the Designer component. ```typescript "use client" import { useState } from "react" import { Designer } from "@shadcn/designer" import type { Unit } from "@shadcn/designer/utils" function DesignerWithUnitToggle() { const [unitSystem, setUnitSystem] = useState("px") const [dpi, setDPI] = useState(96) return (
{/* Designer content */}
) } ``` -------------------------------- ### useGetLayers Source: https://ds.shadcn.com/docs/reference/hooks.md Gets specific layers by their IDs. This hook returns a function that accepts an array of layer IDs and returns the corresponding layer objects. ```APIDOC ## useGetLayers ### Description Gets specific layers by their IDs. ### Usage ```tsx import { useGetLayers } from "@shadcn/designer" function LayerDetails({ layerIds }) { const getLayers = useGetLayers() const layers = getLayers(layerIds) return (
{layers.map(layer => (
{layer.name}
))}
) } ``` ```