Examples
App elements
Assets and media
Fundamentals
Intents
Design interaction
Drag and drop
Design elements
Localization
Content replacement
Design audit
Audit design elements for positioning issues and automatically fix elements that are too close to page edges.
Running this example
To run this example locally:
-
If you haven't already, create a new app in the Developer Portal(opens in a new tab or window). For more information, refer to our Quickstart guide.
-
In your app's configuration on the Developer Portal(opens in a new tab or window), ensure the "Development URL" is set to
http://localhost:8080
. -
Clone the starter kit:
git clone https://github.com/canva-sdks/canva-apps-sdk-starter-kit.gitcd canva-apps-sdk-starter-kitSHELL -
Install dependencies:
npm installSHELL -
Run the example:
npm run start design_auditSHELL -
Click the Preview URL link shown in the terminal to open the example in the Canva editor.
Example app source code
// For usage information, see the README.md file.import { Alert, Button, Rows, Text } from "@canva/app-ui-kit";import { openDesign, type DesignEditing } from "@canva/design";import { useState } from "react";import * as styles from "styles/components.css";type FixResult = {totalElementsFixed: number; // Total number of elements that were repositionedtotalPagesModified: number; // Total number of pages that had at least one element modified};type AppState = {isLoading: boolean; // Whether we're currently processing the designlastFixResult?: FixResult; // Results from the last fix operation, undefined if never runerrorMessage?: string; // Error message from the last operation, undefined if no error};const SAFE_DISTANCE = 100; // Minimum safe distance from page edges in pixelsconst initialState: AppState = {isLoading: false,};export const App = () => {const [state, setState] = useState<AppState>(initialState);// Helper function to check if an element is too close to page edges and fix its positionconst checkAndFixElement = (element: DesignEditing.AbsoluteElement, // The element to check and potentially fixpageDimensions: { width: number; height: number } | undefined, // The page's dimensions): boolean => {// Skip unsupported element types that can't be positionedif (element.type === "unsupported") {return false;}// Skip pages with unbounded dimensions (like whiteboards)// Pages with unbounded dimensions don't have a dimensions propertyif (!pageDimensions) {return false;}// Calculate how far the element is from each edge of the pageconst distanceFromRight =pageDimensions.width - (element.left + element.width);const distanceFromBottom =pageDimensions.height - (element.top + element.height);let wasFixed = false;// Fix the position by moving element to minimum safe distance from edges// Note: We can directly modify element properties - changes will be applied when session.sync() is called// Fix top/bottom positioningif (element.top < SAFE_DISTANCE) {element.top = SAFE_DISTANCE;wasFixed = true;} else if (distanceFromBottom < SAFE_DISTANCE) {element.top = pageDimensions.height - element.height - SAFE_DISTANCE;wasFixed = true;}// Fix left/right positioningif (element.left < SAFE_DISTANCE) {element.left = SAFE_DISTANCE;wasFixed = true;} else if (distanceFromRight < SAFE_DISTANCE) {element.left = pageDimensions.width - element.width - SAFE_DISTANCE;wasFixed = true;}// Return whether the element needed fixingreturn wasFixed;};// Main function demonstrating multi-page design editing with openDesign API// This showcases the key patterns for working with all pages in a design:// 1. Opening design with "all_pages" context// 2. Iterating through page refs// 3. Opening individual pages for editing// 4. Making element modifications// 5. Syncing all changes atomicallyconst fixPositioningIssues = async () => {// Update UI to show we're processing and clear any previous errorsetState((prev) => ({...prev,isLoading: true,errorMessage: undefined,}));try {// Track our results across all pageslet totalElementsFixed = 0;let totalPagesModified = 0;// Open the design with multi-page access// The "all_pages" context gives us access to all pages in the design// The "all_pages" context is currently in preview and may changeawait openDesign({ type: "all_pages" }, async (session) => {// Get refs for all pages in the design// session.pageRefs is a List containing basic info about each pagefor (const pageRef of session.pageRefs.toArray()) {// Filter out pages we can't or shouldn't edit// Only process "absolute" pages (pages with fixed or unbounded dimensions)// Skip locked pages as they can't be modifiedif (pageRef.type !== "absolute" || pageRef.locked) {continue;}// Open each individual page for editing// session.helpers.openPage gives us access to the page's full contentawait session.helpers.openPage(pageRef, async (pageResult) => {let elementsFixedOnPage = 0;// Process all elements on the page// pageResult.page.elements is a List containing all elements on this pagepageResult.page.elements.forEach((element) => {// Skip locked elements as they can't be modifiedif (element.locked) {return;}// Check and fix the element's positionif (checkAndFixElement(element, pageResult.page.dimensions)) {elementsFixedOnPage++;}});// Track totalstotalElementsFixed += elementsFixedOnPage;if (elementsFixedOnPage > 0) {totalPagesModified++;}});}// Apply all changes to the live design// Changes are only applied when session.sync() is called// All modifications across all pages are applied atomicallyawait session.sync();});// Update UI with resultssetState((prev) => ({...prev,isLoading: false,lastFixResult: { totalElementsFixed, totalPagesModified },}));} catch (error) {// Handle errors gracefullyconst errorMessage =error instanceof Error ? error.message : "An unexpected error occurred";setState((prev) => ({...prev,isLoading: false,errorMessage,}));}};return (<div className={styles.scrollContainer}><Rows spacing="2u"><Text>This app automatically fixes elements that are positioned too close tothe edges of pages.</Text><Buttonvariant="primary"onClick={fixPositioningIssues}disabled={state.isLoading}>Fix element positioning</Button>{state.lastFixResult && (<Alert tone="positive">Fixed {state.lastFixResult.totalElementsFixed} element(s) across{" "}{state.lastFixResult.totalPagesModified} pages.</Alert>)}{state.errorMessage && (<Alert tone="critical">{state.errorMessage}</Alert>)}</Rows></div>);};
TYPESCRIPT
// For usage information, see the README.md file.import { AppUiProvider } from "@canva/app-ui-kit";import { createRoot } from "react-dom/client";import { App } from "./app";import "@canva/app-ui-kit/styles.css";const root = createRoot(document.getElementById("root") as Element);function render() {root.render(<AppUiProvider><App /></AppUiProvider>,);}render();// Hot Module Replacement for development (automatically reloads the app when changes are made)if (module.hot) {module.hot.accept("./app", render);}
TYPESCRIPT
# Design auditDemonstrates how to audit design elements for positioning issues and automatically fix elements that are positioned too close to page edges. Shows how to use the Design Editing API to iterate over every element on all pages of the design.For API reference docs and instructions on running this example, see: https://www.canva.dev/docs/apps/examples/design-audit/.Related examples: See design_interaction/design_editing for other complex design editing workflows using the Design Editing API.NOTE: This example differs from what is expected for public apps to pass a Canva review:- Uses the preview Design Editing API "all_pages" design context. Production apps must not use preview APIs- Element positioning logic is simplified for demonstration. Production apps should implement comprehensive positioning validation with support for different design types and element constraints- Error handling is simplified for demonstration. Production apps must implement comprehensive error handling with clear user feedback and graceful failure modes- Internationalization is not implemented. Production apps must support multiple languages using the `@canva/app-i18n-kit` package to pass Canva review requirements
MARKDOWN
API reference
Need help?
- Join our Community Forum(opens in a new tab or window)
- Report issues with this example on GitHub(opens in a new tab or window)