Skip to content
Design
Hook

Hooks

What next-ai-draw-io runs automatically, and when. A hook is a command Claude Code fires at a fixed moment, without you asking for it.

From plugin
next-ai-draw-io
37k7 hooks1 MCP

Where it lives

  • hooks/use-diagram-tool-handlers.tsGitHub
    Read the script
    import type { ChatAddToolOutputFunction } from "ai"
    import type { RefObject } from "react"
    import type {
        ValidationState,
        ValidationStatus,
    } from "@/components/chat/ValidationCard"
    import type { LoadMode } from "@/contexts/diagram-context"
    import type { ChatUIMessage } from "@/lib/chat-message"
    import { type AiCanvasState, diagramFingerprint } from "@/lib/diagram-context"
    import { pageModelXml, pageSelectorFor, placeOnPage } from "@/lib/diagram-pages"
    import type { ValidationResult } from "@/lib/diagram-validator"
    import { formatValidationFeedback } from "@/lib/diagram-validator"
    import { isMxCellXmlComplete } from "@/lib/utils"
    import { foldCells } from "@/packages/mcp-server/src/compact-cells.ts"
    import { notesText } from "@/packages/mcp-server/src/diagram-operations.ts"
    import {
        type EditOperation,
        editDiagram,
    } from "@/packages/mcp-server/src/edit-diagram.ts"
    import { restoreImageData } from "@/packages/mcp-server/src/embedded-images.ts"
    import { prepareNewDiagram } from "@/packages/mcp-server/src/new-diagram.ts"
    import { hasCells } from "@/packages/mcp-server/src/pages.ts"
    
    // The page a drawing is wrapped in; on the canvas it replaces the page the
    // model works on, so the canvas page keeps its own id and name
    const NEW_PAGE = { pageId: "page-1", pageName: "Page-1" }
    
    // The type the model named for a drawing whose output was cut off, for the
    // append_diagram call that completes it
    let truncatedType: string | undefined
    
    /** What the layout of the diagram's type did, for the tool result */
    const laidText = (laid: string[]) =>
        laid.length > 0
            ? ` ${laid.join(" ")} The cells on the canvas now have these positions and paths.`
            : ""
    
    interface ToolCall {
        toolCallId: string
        toolName: string
        input: unknown
    }
    
    // useChat's addToolOutput, typed with the chat's tools
    type AddToolOutputFn = ChatAddToolOutputFunction<ChatUIMessage>
    
    const MAX_VALIDATION_RETRIES = 3
    
    // Type for the validation function passed from useValidateDiagram hook
    type ValidateDiagramFn = (
        imageData: string,
        sessionId?: string,
    ) => Promise<ValidationResult>
    
    interface UseDiagramToolHandlersParams {
        partialXmlRef: RefObject<string>
        // Diagram before a cut off display_diagram whose half drawn preview
        // stays while append_diagram finishes it; null when none is pending
        continuationOriginalRef: RefObject<string | null>
        editDiagramOriginalXmlRef: RefObject<Map<string, string>>
        // Tool calls the streaming preview must leave alone (shared with it)
        processedToolCallsRef: RefObject<Set<string>>
        // Failed VLM validations in the current user turn (reset on each user message)
        validationRetryCountRef: RefObject<number>
        chartXMLRef: RefObject<string>
        // The page the model reads and writes in this turn (the one the user
        // viewed when it began); null, or absent, means the first page
        turnPageIdRef?: RefObject<string | null>
        // The canvas after each change the model made, by tool call: the next
        // message sends the canvas only when it differs (lib/diagram-context.ts)
        aiCanvasStatesRef?: RefObject<Map<string, AiCanvasState>>
        onDisplayChart: (
            xml: string,
            skipValidation?: boolean,
            mode?: LoadMode,
            meta?: { toolCallId?: string; pageId?: string | null },
        ) => string | null
        onFetchChart: () => Promise<string>
        captureValidationPng?: (pageId?: string | null) => Promise<string | null>
        validateDiagram?: ValidateDiagramFn
        enableVlmValidation?: boolean
        sessionId?: string
        // Called when a screenshot check begins; the function it returns
        // tells whether the user pressed Stop in this turn, also after the next
        // message was sent. A check that has not started then is skipped (one
        // already running is cancelled by the caller).
        watchStop?: () => () => boolean
        onValidationStateChange?: (
            toolCallId: string,
            state: ValidationState,
        ) => void
    }
    
    /**
     * Hook that creates the onToolCall handler for diagram-related tools.
     * Handles display_diagram, edit_diagram, and append_diagram tools.
     *
     * Note: addToolOutput is passed at call time (not hook init) because
     * it comes from useChat which creates a circular dependency.
     */
    export function useDiagramToolHandlers({
        partialXmlRef,
        continuationOriginalRef,
        editDiagramOriginalXmlRef,
        processedToolCallsRef,
        validationRetryCountRef,
        chartXMLRef,
        turnPageIdRef,
        aiCanvasStatesRef,
        onDisplayChart,
        onFetchChart,
        captureValidationPng,
        validateDiagram,
        enableVlmValidation = true,
        sessionId,
        watchStop,
        onValidationStateChange,
    }: UseDiagramToolHandlersParams) {
        // Helper to update validation state
        const updateValidationState = (
            toolCallId: string,
            status: ValidationStatus,
            options?: {
                attempt?: number
                maxAttempts?: number
                result?: ValidationResult
                error?: string
                imageData?: string
            },
        ) => {
            if (onValidationStateChange) {
                onValidationStateChange(toolCallId, {
                    status,
                    ...options,
                })
            }
        }
        const handleToolCall = async (
            { toolCall }: { toolCall: ToolCall },
            addToolOutput: AddToolOutputFn,
        ) => {
            processedToolCallsRef.current.add(toolCall.toolCallId)
            // Only display_diagram, edit_diagram and a completing append_diagram
            // put their result on the canvas. Other tools (get_shape_library,
            // which the server runs, still arrives here) leave the stored
            // originals for the preview code to undo.
            if (toolCall.toolName === "display_diagram") {
                await handleDisplayDiagram(toolCall, addToolOutput, takeOriginals())
            } else if (toolCall.toolName === "edit_diagram") {
                await handleEditDiagram(toolCall, addToolOutput, takeOriginals())
            } else if (toolCall.toolName === "
  • hooks/use-dictionary.tsGitHub
    Read the script
    "use client"
    
    import React, { createContext, useContext } from "react"
    import type { Dictionary } from "@/lib/i18n/dictionaries"
    
    const DictionaryContext = createContext<Dictionary | null>(null)
    
    export function DictionaryProvider({
        children,
        dictionary,
    }: React.PropsWithChildren<{ dictionary: Dictionary }>) {
        return React.createElement(
            DictionaryContext.Provider,
            { value: dictionary },
            children,
        )
    }
    
    export function useDictionary() {
        const dict = useContext(DictionaryContext)
        if (!dict) {
            throw new Error(
                "useDictionary must be used within a DictionaryProvider",
            )
        }
        return dict
    }
    
  • hooks/use-model-config.tsGitHub
    Read the script
    "use client"
    
    import { useCallback, useEffect, useState } from "react"
    import { getApiEndpoint } from "@/lib/base-path"
    import { PROVIDERS } from "@/lib/providers"
    import type { FlattenedServerModel } from "@/lib/server-model-config"
    import { STORAGE_KEYS } from "@/lib/storage"
    import { supportsThinkingToggle } from "@/lib/thinking-capabilities"
    import {
        createEmptyConfig,
        createModelConfig,
        createProviderConfig,
        type FlattenedModel,
        findModelById,
        flattenModels,
        type ModelConfig,
        type MultiModelConfig,
        type ProviderConfig,
        type ProviderName,
    } from "@/lib/types/model-config"
    import { noteAction } from "@/lib/user-actions"
    
    // A provider of a known type that holds a list of models
    const isKnownProvider = (p: { provider: string; models?: unknown }) =>
        Object.hasOwn(PROVIDERS, p.provider) && Array.isArray(p.models)
    
    /**
     * The stored config without providers this version does not know or
     * cannot read (saved by another version, or edited by hand): they would
     * break every list of models, and the page with them on every load. They
     * stay in storage (saveConfig keeps them). Throws on bad JSON.
     */
    function parseStoredConfig(stored: string): MultiModelConfig {
        const config = JSON.parse(stored) as MultiModelConfig
        const known = config.providers.filter(isKnownProvider)
        if (known.length < config.providers.length) {
            console.warn(
                "Skipped saved providers this version does not know:",
                config.providers
                    .filter((p) => !isKnownProvider(p))
                    .map((p) => p.provider),
            )
        }
        return { ...config, providers: known }
    }
    
    /**
     * Load config from localStorage
     */
    function loadConfig(): MultiModelConfig {
        const stored = localStorage.getItem(STORAGE_KEYS.modelConfigs)
        if (stored) {
            try {
                return parseStoredConfig(stored)
            } catch {
                console.error("Failed to parse model config")
            }
        }
    
        return createEmptyConfig()
    }
    
    /**
     * Save config to localStorage
     */
    function saveConfig(config: MultiModelConfig): void {
        // Providers this version does not know are not in config: keep them,
        // with their keys, for the version that saved them
        let unknown: MultiModelConfig["providers"] = []
        try {
            const stored = localStorage.getItem(STORAGE_KEYS.modelConfigs)
            if (stored) {
                unknown = (JSON.parse(stored) as MultiModelConfig).providers.filter(
                    (p) => !isKnownProvider(p),
                )
            }
        } catch {
            // Unreadable: nothing to keep
        }
        localStorage.setItem(
            STORAGE_KEYS.modelConfigs,
            JSON.stringify({
                ...config,
                providers: [...config.providers, ...unknown],
            }),
        )
    }
    
    /**
     * Server model to fall back to: the one marked default, else the first one
     */
    function defaultServerModelId(
        serverModels: FlattenedServerModel[],
    ): string | undefined {
        return (serverModels.find((m) => m.isDefault) ?? serverModels[0])?.id
    }
    
    export interface UseModelConfigReturn {
        // State
        config: MultiModelConfig
        isLoaded: boolean
    
        // Getters
        models: FlattenedModel[]
        selectedModelId: string | undefined
    
        // Actions
        setSelectedModelId: (modelId: string | undefined) => void
        /** Load the server's models again: a selected one that is gone gives
         * way to the default */
        reloadServerModels: () => void
        addProvider: (provider: ProviderName) => ProviderConfig
        updateProvider: (
            providerId: string,
            updates: Partial<ProviderConfig>,
        ) => void
        deleteProvider: (providerId: string) => void
        addModel: (providerId: string, modelId: string) => ModelConfig
        updateModel: (
            providerId: string,
            modelConfigId: string,
            updates: Partial<ModelConfig>,
        ) => void
        deleteModel: (providerId: string, modelConfigId: string) => void
    }
    
    export function useModelConfig(): UseModelConfigReturn {
        const [config, setConfig] = useState<MultiModelConfig>(createEmptyConfig)
        const [isLoaded, setIsLoaded] = useState(false)
        const [serverModels, setServerModels] = useState<FlattenedServerModel[]>([])
        const [serverLoaded, setServerLoaded] = useState(false)
    
        // Load client config on mount
        useEffect(() => {
            const loaded = loadConfig()
            setConfig(loaded)
            setIsLoaded(true)
        }, [])
    
        // Pick up config changes saved by other tabs, so this tab neither shows a
        // stale model nor overwrites their changes on its next save
        useEffect(() => {
            const handleStorage = (e: StorageEvent) => {
                if (e.key === STORAGE_KEYS.modelConfigs) setConfig(loadConfig())
            }
            window.addEventListener("storage", handleStorage)
            return () => window.removeEventListener("storage", handleStorage)
        }, [])
    
        // Load server models on mount (if any), and again when the desktop app
        // restarted its server for another preset
        useEffect(() => {
            loadServerModels()
            return window.electronAPI?.onServerRestarted?.(loadServerModels)
        }, [])
    
        function loadServerModels() {
            fetch(getApiEndpoint("/api/server-models"))
                .then((res) => {
                    if (!res.ok) {
                        console.error(
                            "Failed to load server models:",
                            res.status,
                            res.statusText,
                        )
                        throw new Error(`Request failed with status ${res.status}`)
                    }
                    return res.json()
                })
                .then((data) => {
                    const raw: FlattenedServerModel[] = data?.models || []
                    setServerModels(raw)
                    setServerLoaded(true)
    
                    // Auto-select the default server model if no model is selected,
                    // or if the saved server model is gone (renamed or removed)
                    setConfig((prev) => {
                  
  • hooks/use-panel-width.tsGitHub
    Read the script
    import { useEffect, useState } from "react"
    import { PANEL_MIN_WIDTH, useSettingsStore } from "@/stores/settings-store"
    
    // Room the canvas keeps next to the chat panel in a small window
    const MIN_CANVAS_WIDTH = 400
    
    /** The chat panel's width, narrower when the window has no room for it */
    export function usePanelWidth(): number {
        const width = useSettingsStore((s) => s.panelWidth)
        // Set after mounting, so the server render and the first one agree
        const [windowWidth, setWindowWidth] = useState(Number.POSITIVE_INFINITY)
        useEffect(() => {
            const update = () => setWindowWidth(window.innerWidth)
            update()
            window.addEventListener("resize", update)
            return () => window.removeEventListener("resize", update)
        }, [])
        return Math.max(
            PANEL_MIN_WIDTH,
            Math.min(width, windowWidth - MIN_CANVAS_WIDTH),
        )
    }
    
  • hooks/use-path-locale.tsGitHub
    Read the script
    "use client"
    
    import { usePathname } from "next/navigation"
    import { i18n, type Locale } from "@/lib/i18n/config"
    
    /** The locale at the start of the address, for links to the site pages */
    export function usePathLocale(): Locale {
        const first = usePathname().split("/")[1] ?? ""
        return (i18n.locales as readonly string[]).includes(first)
            ? (first as Locale)
            : i18n.defaultLocale
    }
    
  • hooks/use-session-manager.tsGitHub
    Read the script
    "use client"
    
    import { useCallback, useEffect, useRef, useState } from "react"
    import { toast } from "sonner"
    import { useDictionary } from "@/hooks/use-dictionary"
    import { toastUnexpectedError } from "@/lib/client-error-report"
    import type { Dictionary } from "@/lib/i18n/dictionaries"
    import { formatMessage } from "@/lib/i18n/utils"
    import {
        type ChatSession,
        createEmptySession,
        deleteSession as deleteSessionFromDB,
        enforceSessionLimit,
        extractTitle,
        getAllSessionMetadata,
        getSession,
        isIndexedDBAvailable,
        lastSaveError,
        MAX_SESSIONS,
        readSessionCount,
        renameSession as renameSessionInDB,
        type SessionMetadata,
        type StoredMessage,
        saveSession,
    } from "@/lib/session-storage"
    import { STORAGE_KEYS } from "@/lib/storage"
    import type { DiagramVersion } from "@/stores/versions-store"
    
    export interface SessionData {
        messages: StoredMessage[]
        xmlSnapshots: [number, string][]
        diagramXml: string
        thumbnailDataUrl?: string
        versions?: DiagramVersion[]
        /** Title for a session created by this save (default: first message) */
        title?: string
    }
    
    // Taken right before a save's data is read: the chat on screen then, and
    // the order of the reads
    export interface SaveTicket {
        generation: number
        seq: number
    }
    
    export interface UseSessionManagerReturn {
        // State
        sessions: SessionMetadata[]
        currentSessionId: string | null
        currentSession: ChatSession | null
        isLoading: boolean
        isAvailable: boolean
    
        // Actions
        switchSession: (id: string) => Promise<SessionData | null>
        deleteSession: (id: string) => Promise<{ wasCurrentSession: boolean }>
        // ticket: getSaveTicket() before the data was read (by default, now).
        // The save is dropped if another chat is on screen when its turn comes,
        // or if a copy of this chat read later was saved already.
        // Resolves to false when the save failed (the user was told)
        saveCurrentSession: (
            data: SessionData,
            ticket?: SaveTicket,
        ) => Promise<boolean>
        refreshSessions: () => Promise<void>
        clearCurrentSession: () => void
        getChatGeneration: () => number
        /** The chat on screen now, also right after a save created it */
        getCurrentSessionId: () => string | null
        getSaveTicket: () => SaveTicket
        renameSession: (id: string, title: string) => Promise<void>
        /**
         * Run before the URL (browser back or forward) puts another chat on
         * screen: the chat on screen is saved first, which the app's own ways
         * of leaving it do themselves
         */
        setBeforeUrlSwitch: (handler: (() => Promise<void>) | null) => void
        /**
         * Runs fn while the chat with this id is about to be put on screen: a
         * save meanwhile that creates a session (over the chat limit) does not
         * delete it as the oldest one
         */
        whileOpening: <T>(id: string, fn: () => Promise<T>) => Promise<T>
    }
    
    // Reading the session list loads every stored session in full, and window
    // focus also fires each time the user clicks back from the draw.io iframe
    const FOCUS_REFRESH_INTERVAL_MS = 30_000
    
    // The order of the stored list: the chat saved last comes first
    const newestFirst = (a: SessionMetadata, b: SessionMetadata) =>
        b.updatedAt - a.updatedAt
    
    function notifySaveFailed(dict: Dictionary) {
        // Same id, so repeated failures update one toast instead of stacking.
        // The storage error goes into the record.
        toastUnexpectedError(
            dict.errors.sessionSaveFailed,
            dict.report.button,
            lastSaveError(),
            {
                id: "session-save-failed",
            },
        )
    }
    
    interface UseSessionManagerOptions {
        /** Session ID from URL param - if provided, load this session; if null, start blank */
        initialSessionId?: string | null
    }
    
    export function useSessionManager(
        options: UseSessionManagerOptions = {},
    ): UseSessionManagerReturn {
        const { initialSessionId } = options
        const dict = useDictionary()
        const [sessions, setSessions] = useState<SessionMetadata[]>([])
        const [currentSessionId, setCurrentSessionId] = useState<string | null>(
            null,
        )
        const [currentSession, setCurrentSession] = useState<ChatSession | null>(
            null,
        )
        const [isLoading, setIsLoading] = useState(true)
        const [isAvailable, setIsAvailable] = useState(false)
    
        const isInitializedRef = useRef(false)
        // Sequence guard for URL changes - prevents out-of-order async resolution
        const urlChangeSequenceRef = useRef(0)
        // The chat on screen, read by saves that run after a render or a wait
        const currentSessionRef = useRef<ChatSession | null>(null)
        // Goes up each time another chat is put on screen (creating the
        // session of the chat on screen does not count)
        const chatGenerationRef = useRef(0)
        // Saves run one at a time, so two saves of a new chat create it once
        const saveQueueRef = useRef<Promise<unknown>>(Promise.resolve())
        // The last ticket number, and that of the newest data saved
        const saveSeqRef = useRef(0)
        const savedSeqRef = useRef(0)
    
        const beforeUrlSwitchRef = useRef<(() => Promise<void>) | null>(null)
        // The chat about to be put on screen, while the one on screen is saved
        const openingSessionRef = useRef<{ id: string } | null>(null)
        const whileOpening = useCallback(
            async <T>(id: string, fn: () => Promise<T>): Promise<T> => {
                // Its own: another one opened meanwhile sets another
                const opening = { id }
                openingSessionRef.current = opening
                try {
                    return await fn()
                } finally {
                    if (openingSessionRef.current === opening) {
                        openingSessionRef.current = null
                    }
                }
            },
            [],
        )
        const setBeforeUrlSwitch = useCallback(
            (handler: (() => Promise<void>) | null) => {
                beforeUrlSwitchRef.current = handler
            },
            [],
     
  • hooks/use-validate-diagram.tsGitHub

All 7 scripts are listed above. The source is inlined for 6 of them, starting with whatever hooks.json actually runs. See all of them in the repo.

Read the script before you install anything that runs on your machine. This is the one part of a plugin that acts without being asked.

@dayuanjiang
Ships withnext-ai-draw-io

Draw and edit draw.io diagrams by chatting with an AI. Describe a diagram in a sentence and the AI draws it on a real draw.io canvas. Edit it by hand like any draw.io file, or select a few shapes and tell the AI what to change.

Stars on GitHub

Momentum

stars in total
37.1k
Star history of DayuanJiang/next-ai-draw-io on GitHub, a chart by star-history.com

More plugins that ship hooks.

ux-ui-agent-skills

ux-ui-agent-skills

Gives a coding assistant design skills for building interfaces: audit a UI against accessibility rules, generate a brand design system of tokens, apply a visual style, and build data-heavy dashboards with real charts.

26 skills+43.2k
@plugin87@plugin87
Install Plugin
naksha

naksha

Assembles a virtual design team inside Claude Code to produce UI, UX, visual, social media, email, and data design output. A design manager picks the right specialist roles for each task.

1 skill+3356
@adityaraj0421@adityaraj0421
Install Plugin
designpowers

designpowers

An agent design team you control. 10 agents that run an inclusive design process while you direct. The system notices how you design and reflects it back. Designpowers is an open, model-agnostic design workflow that gives you a team of 10 design agents.

36 skills+2263
@owl-listener@owl-listener
Install Plugin
bridge-ds

bridge-ds

Bridge connects Claude Code to the Figma Plugin API over WebSocket, so you can design, extract your design system, and fix or ship Figma components from the terminal.

5 skills+2156
@noemuch@noemuch
Install Plugin

Questions about the hooks in next-ai-draw-io.

Which coding agents can use the hooks in next-ai-draw-io?
The hooks in next-ai-draw-io install in Claude Code and Cursor: each runs Claude Code hooks from .claude/settings.json, so copy the hooks there.