iink-ts - v5.0.0
    Preparing search index...

    Class InteractiveInkCanvas

    Hierarchy (View Summary)

    Implements

    Index
    • Apply or replace CSS custom properties on the canvas root element. Clears all existing --ms-ink-* properties first, then sets the provided vars. Does not reinitialize — current model and session are preserved. Pass undefined to reset to stylesheet defaults.

      Parameters

      • vars: Record<string, string> | undefined

      Returns void

    • get connectionState(): TCanvasConnectionState

      Derived, UI-oriented canvas state — see TCanvasConnectionState. Listen to event.addConnectionStateChangedListener for change notifications.

      Returns TCanvasConnectionState

    • get cursorClasses(): string[]

      CSS classes toggled by setCursorStyle to reflect the current tool on the mounting root element. Default 2-state (draw/erase) set; override alongside getCursorClass for variants with additional tools.

      Returns string[]

    • get initializationPromise(): Promise<void>

      Promise that resolves when the WebSocket session is fully initialized. Await this before calling any recognition methods.

      Returns Promise<void>

    • get isOffline(): boolean

      True while the connection is down after a first one succeeded, changes queued or not. Listen to event.addConnectionStatusChangedListener for change notifications.

      Returns boolean

    • get model(): IIModel

      Current symbol model containing all ink, text, math, and shape symbols.

      Returns IIModel

    • get penStyle(): TStyle

      Current pen style applied to new strokes. Setting this merges the provided partial style with the current style.

      Returns TStyle

    • set penStyle(
          penStyle: {
              color?: string;
              fill?: string;
              opacity?: number;
              pen?: TPenNib;
              penAngle?: number;
              penSmoothing?: number;
              penSpeed?: number;
              width?: number;
              [key: string]: string | number | undefined;
          },
      ): void

      Parameters

      • penStyle: {
            color?: string;
            fill?: string;
            opacity?: number;
            pen?: TPenNib;
            penAngle?: number;
            penSmoothing?: number;
            penSpeed?: number;
            width?: number;
            [key: string]: string | number | undefined;
        }

      Returns void

    • get readOnly(): boolean

      Whether real pointer input (write/erase/select/move) is currently blocked - see readOnly setter.

      Returns boolean

    • set readOnly(value: boolean): void

      Block or restore real pointer input across every tool at once (write/erase/select/move all attach through layers.rendering), and reflect it with a "not-allowed" cursor. Used e.g. by canvas.playback so a replayed stroke can't race the user's own input.

      Parameters

      • value: boolean

      Returns void

    • set renderingConfiguration(
          renderingConfiguration: TIIRendererConfiguration,
      ): void

      Apply a partial rendering configuration at runtime. Triggers a resize and guide-row recompute.

      Parameters

      Returns void

    • get tool(): CanvasTool

      Active editing tool. Setting this switches cursor style, attaches/detaches the corresponding manager, clears selection, and emits a toolChanged event.

      Returns CanvasTool

    • set tool(i: CanvasTool): void

      Parameters

      Returns void

    • Add multiple symbols to the model and renderer

      Parameters

      • symList: TSymbol[]

        Array of symbols to add

      • addToHistory: boolean = true

        Whether to add to history (default: true)

      Returns Promise<TSymbol[]>

      Promise resolving to array of added symbols

    • Change the order of a symbol in the rendering stack

      Parameters

      • symbol: TSymbol

        Symbol to reorder

      • position: "first" | "last" | "forward" | "backward"

        New position (first, last, forward, backward)

      Returns void

    • Change the order of multiple symbols in the rendering stack

      Parameters

      • symbols: TSymbol[]

        Symbols to reorder

      • position: "first" | "last" | "forward" | "backward"

        New position (first, last, forward, backward)

      Returns void

    • Clear all content from the canvas

      Returns Promise<void>

      Promise that resolves when cleared

    • Force label fully inactive regardless of how many startOperation calls are pending. For level-triggered signals with a single external "done" event (e.g. the client's idle event) rather than one end call per start call.

      Parameters

      Returns void

    • Clears the rootElement.iink back-reference set in the constructor, guarded so it only clears the reference if it's still pointing at this instance — a newer canvas mounted on the same element (e.g. Canvas.load() replacing an instance) must not have its own reference clobbered by this (older) instance's destroy() running after the fact. Every destroy() implementation must call this, or the mounting DOM element keeps a strong reference to the entire destroyed canvas graph.

      Returns void

    • Convert specific symbols, or all symbols if none specified

      Parameters

      • Optionalsymbols: TSymbol[]

        Symbols to convert (defaults to all symbols)

      Returns Promise<void>

      Promise that resolves when conversion is complete

    • Copy selected symbols (or all symbols if nothing selected) to the internal clipboard

      Returns void

    • Create a symbol from partial data

      Parameters

      Returns Promise<TSymbol>

      Promise resolving to created symbol

    • Create multiple symbols from partial data

      Parameters

      Returns Promise<TSymbol[]>

      Promise resolving to array of created symbols

    • Cut selected symbols: copy them to clipboard, then remove from model

      Returns Promise<void>

    • Destroy the canvas and clean up resources

      Returns Promise<void>

      Promise that resolves when destruction is complete

    • Export the content and hand the resulting file to the browser.

      Parameters

      • format: TDownloadFormat

        Format to download; pdf opens the print flow instead of saving a file

      • Optionaloptions: TPDFDownloadOptions

        Which symbols to export, plus the file name. The PDF settings (format/orientation/mode/scale) are ignored by every other format.

      Returns Promise<void>

      await canvas.download("svg")
      await canvas.download("text", { scope: "selection", filename: "notes" })
      await canvas.download("pdf", { orientation: "landscape" })
    • Duplicate specific symbols, or all symbols if none specified

      Parameters

      • Optionalsymbols: TSymbol[]

        Symbols to duplicate (defaults to all symbols)

      Returns Promise<TSymbol[]>

      Promise resolving with duplicated symbols

    • Export content to specified MIME types

      Parameters

      • OptionalmimeTypes: string[]

        Array of MIME types to export

      Returns Promise<TExport>

      Promise resolving with exports

    • Export the content in the given format.

      pdf is not available here — printing produces no in-memory value, use InteractiveInkCanvas.download instead.

      Type Parameters

      Parameters

      • format: F

        Format to export to; the resolved type follows from it

      • Optionaloptions: TExportOptions

        Which symbols to export (scope, or an explicit symbols list)

      Returns Promise<TExportResultMap[F]>

      Promise resolving with the exported content

      const symbols = await canvas.exportAs("json")
      const markdown = await canvas.exportAs("markdown")
      const svg = await canvas.exportAs("svg", { scope: "selection" })
    • Extract all math symbols recursively

      Parameters

      • symbols: TSymbol[] | undefined

        Symbols to extract maths from

      Returns TMath[]

      Array of extracted math symbols

    • Extract all strokes from symbols recursively

      Parameters

      • symbols: TSymbol[] | undefined

        Symbols to extract strokes from

      Returns TStroke[]

      Array of extracted strokes

    • The single class from cursorClasses that should be active for the current tool.

      Returns string

    • Get bounding box for a list of symbols

      Parameters

      • symbols: TSymbol[]

        Symbols to calculate bounds for

      • margin: number = SELECTION_PADDING

        TMargin to add around bounds (default: SELECTION_PADDING)

      Returns TBox

      Bounding box containing all symbols

    • Type Parameters

      Parameters

      • type: string

      Returns SymbolUtil<T> | undefined

    • Get the current viewport zoom level.

      Returns number

      Current zoom factor (1.0 = 100 %)

    • Parameters

      • event: WheelEvent

      Returns void

    • Import strokes from point events

      Parameters

      • partialStrokes: {
            creationTime?: number;
            decoratorKind?: DecoratorKind;
            endAnchor?: {
                entryPoint?: { x?: number; y?: number };
                normalizedX?: number;
                normalizedY?: number;
                symbolId?: string;
            };
            id?: string;
            isSolverOutput?: boolean;
            jiixBlockId?: string;
            jiixBlockType?: "Text"
            | "Math"
            | "Node"
            | "Edge"
            | "Decorator";
            modificationDate?: number;
            pointers?: (
                { dt?: number; p?: number; x?: number; y?: number }
                | undefined
            )[];
            pointerType?: string;
            startAnchor?: {
                entryPoint?: { x?: number; y?: number };
                normalizedX?: number;
                normalizedY?: number;
                symbolId?: string;
            };
            style?: {
                color?: string;
                fill?: string;
                opacity?: number;
                pen?: TPenNib;
                penAngle?: number;
                penSmoothing?: number;
                penSpeed?: number;
                width?: number;
                [key: string]: string
                | number
                | undefined;
            };
            transform?: {
                tx?: number;
                ty?: number;
                xx?: number;
                xy?: number;
                yx?: number;
                yy?: number;
            };
            type?: Stroke;
        }[]

        Array of partial stroke data

        • OptionalcreationTime?: number
        • OptionaldecoratorKind?: DecoratorKind
        • OptionalendAnchor?: {
              entryPoint?: { x?: number; y?: number };
              normalizedX?: number;
              normalizedY?: number;
              symbolId?: string;
          }
          • OptionalentryPoint?: { x?: number; y?: number }

            Intersection of the edge with the shape border, in world coordinates.

          • OptionalnormalizedX?: number
          • OptionalnormalizedY?: number
          • OptionalsymbolId?: string
        • Optionalid?: string
        • OptionalisSolverOutput?: boolean
        • OptionaljiixBlockId?: string
        • OptionaljiixBlockType?: "Text" | "Math" | "Node" | "Edge" | "Decorator"
        • OptionalmodificationDate?: number
        • Optionalpointers?: ({ dt?: number; p?: number; x?: number; y?: number } | undefined)[]
        • OptionalpointerType?: string
        • OptionalstartAnchor?: {
              entryPoint?: { x?: number; y?: number };
              normalizedX?: number;
              normalizedY?: number;
              symbolId?: string;
          }
          • OptionalentryPoint?: { x?: number; y?: number }

            Intersection of the edge with the shape border, in world coordinates.

          • OptionalnormalizedX?: number
          • OptionalnormalizedY?: number
          • OptionalsymbolId?: string
        • Optionalstyle?: {
              color?: string;
              fill?: string;
              opacity?: number;
              pen?: TPenNib;
              penAngle?: number;
              penSmoothing?: number;
              penSpeed?: number;
              width?: number;
              [key: string]: string | number | undefined;
          }
        • Optionaltransform?: { tx?: number; ty?: number; xx?: number; xy?: number; yx?: number; yy?: number }

          Where this symbol sits, relative to the coordinates it stores.

          A transform writes here and nowhere else: the raw coordinates are what the symbol was created with and never move again. That is what lets the renderer apply a change by rewriting one attribute instead of rebuilding the element, and what keeps undo exact — re-applying an inverse matrix restores the value bit for bit, where re-transforming coordinates accumulated rounding.

          • Optionaltx?: number

            translation x

          • Optionalty?: number

            translation y

          • Optionalxx?: number

            scaling x

          • Optionalxy?: number

            shearing y

          • Optionalyx?: number

            shearing x

          • Optionalyy?: number

            scaling y

        • Optionaltype?: Stroke

      Returns Promise<IIModel>

      Promise resolving to updated model

    • Initialize the canvas: render layers, attach input handlers, connect to the WebSocket client, and load the initial session. Called automatically by Canvas.load() — do not call manually.

      Returns Promise<void>

      If the client connection or session setup fails

    • Only relevant for WebSocket-backed canvas; other variants never call this.

      Parameters

      Returns void

    • Display an error in the canvas overlay and emit an error event.

      Parameters

      • error: unknown

        Error to display and emit

      Returns void

    • Parameters

      • idle: boolean

      Returns void

      The client's idle event only fires in response to an explicit client.waitForIdle() call (a request/response pair, not a push notification) — it does NOT fire automatically after every addStrokes()/transform/etc. So it cannot be used to end a "Recognizing" operation reliably. This only preserves the public event.emitIdle passthrough for consumers who call waitForIdle() themselves.

    • Called once the canvas has connected to its backend for the first time.

      Returns void

    • Returns Promise<void>

    • With ignoreGestureStrokes the backend never emits a contentChanged for a gesture stroke, so the debounced synchronize scheduled by onContentChanged has nothing left to reschedule it - force one here instead of relying on that mechanism.

      Returns Promise<void>

    • Shift the viewport by the given pixel delta without changing zoom.

      Parameters

      • dx: number

        Horizontal offset in pixels (positive = pan right)

      • dy: number

        Vertical offset in pixels (positive = pan down)

      Returns void

    • Paste clipboard symbols at an offset and select them

      Returns Promise<void>

    • Redo the previously undone action

      Returns Promise<IIModel>

      Promise resolving to updated model

    • Type Parameters

      Parameters

      Returns void

    • Remove a symbol from the model

      Parameters

      • id: string

        ID of symbol to remove

      • addToHistory: boolean = true

        Whether to add to history (default: true)

      Returns Promise<void>

      Promise that resolves when symbol is removed

    • Remove multiple symbols from the model

      Parameters

      • ids: string[]

        Array of symbol IDs to remove

      • addToHistory: boolean = true

        Whether to add to history (default: true)

      Returns Promise<TSymbol[]>

      Promise that resolves when symbols are removed

    • Replace old symbols with new symbols

      Parameters

      • oldSymbols: TSymbol[]

        Array of old symbols to be replaced

      • newSymbols: TSymbol[]

        Array of new symbols to replace with

      • addToHistory: boolean = true

        Whether to add this operation to history (default: true)

      Returns Promise<void>

    • Resize the canvas

      Parameters

      • dimensions: { height?: number; width?: number } = {}

        New height and/or width

      Returns Promise<void>

      Promise that resolves when resize is complete

    • Resolves the target height/width for resize(): an explicit value wins, otherwise falls back to the mounting root element's computed size, clamped to minDimensions.

      Parameters

      • Optionalheight: number
      • Optionalwidth: number

      Returns { height: number; width: number }

    • Select symbols by their IDs

      Parameters

      • ids: string[]

        Array of symbol IDs to select

      Returns void

    • Select all symbols

      Returns void

    • On top of the base badge tracking, cancels the pending debounced synchronize() as soon as a new gesture starts - so a stroke/transform beginning right as the debounce timer would otherwise fire never races it (it'll be rescheduled once that gesture's own content change comes in).

      Parameters

      Returns void

    • Synchronize strokes with JIIX export

      Returns Promise<void>

    • Common teardown shared by every variant's destroy(): stops the resize observer, removes all event listeners, and destroys the DOM layers and the renderer. Each variant calls this in addition to its own teardown (input-handler detach, client/menu/model/history cleanup, etc.) and must still call clearRootElementReference itself afterwards.

      Returns void

    • Run fn, marking label as an active operation for the duration (shown on the canvas state badge tooltip). Safe against overlapping/concurrent calls with the same or different labels, and against fn throwing (the operation is always ended).

      Type Parameters

      • T

      Parameters

      Returns Promise<T>

    • Undo the last action

      Returns Promise<IIModel>

      Promise resolving to updated model

    • Unselect all currently selected symbols

      Returns void

    • Update layer UI with debouncing

      Parameters

      • timeout: number = 500

        Debounce timeout in milliseconds (default: 500ms)

      Returns void

    • Change the recognition configuration (language, math solver…) without destroying the canvas. Opens a new backend session with it and re-sends every user stroke; the canvas is read-only meanwhile. Calls are serialized, and those waiting for a running one are applied together.

      Parameters

      • partial: {
            alwaysConnected?: boolean;
            export?: {
                image?: {
                    guides?: boolean;
                    viewport?: { height?: number; width?: number; x?: number; y?: number };
                };
                "image-resolution"?: number;
                jiix?: {
                    "bounding-box"?: boolean;
                    "full-stroke-ids"?: boolean;
                    ids?: boolean;
                    strokes?: boolean;
                    style?: boolean;
                    text?: { chars?: boolean; lines?: boolean; words?: boolean };
                };
                mathml?: { flavor?: { name?: string } };
            };
            gesture?: { enable?: boolean; ignoreGestureStrokes?: boolean };
            lang?: string;
            math?: {
                "angle-unit"?: TAngleUnit;
                "decimal-separator"?: string;
                enable?: boolean;
                "fractional-part-digits"?: number;
                options?: TSolverOptions;
                "rounding-mode"?: TRoundingMode;
                solver?: {
                    "angle-unit"?: TAngleUnit;
                    "auto-variable-management"?: {
                        enable?: boolean;
                        "scoping-policy"?: TScopingPolicy;
                    };
                    "decimal-separator"?: string;
                    enable?: boolean;
                    "fractional-part-digits"?: number;
                    options?: TSolverOptions;
                    "rounding-mode"?: TRoundingMode;
                };
            };
            "raw-content"?: {
                classification?: { types?: (TRecognitionType | undefined)[] };
                gestures?: (TRecognitionGesture | undefined)[];
                recognition?: { types?: (TRecognitionType | undefined)[] };
                "session-time"?: number;
                text?: {
                    addLKText?: boolean;
                    customLexicon?: (string | undefined)[];
                    customResources?: (string | undefined)[];
                };
            };
        }

        Keys to change; an array replaces the current one, undefined clears a key

      Returns Promise<void>

      If the new session fails to open; the previous configuration is then restored

      await canvas.updateRecognitionConfiguration({ lang: "fr_FR" })
      await canvas.updateRecognitionConfiguration({ math: { solver: { "angle-unit": "deg" } } })
    • Update one symbol: updateSymbols([id], patch, addToHistory).

      Parameters

      Returns Promise<TSymbol | undefined>

      The updated record, or undefined when no symbol has this id

    • Update symbols by id, each with the same patch.

      • an object patch: style is merged into each symbol's style, font is applied to the texts (any other symbol ignores it);
      • a function patch: called with a draft of each symbol, to change it at will.

      Texts and maths are re-measured, and a text that gets wider or narrower slides the texts after it on its row. The backend hears only of strokes that appeared or disappeared: style is not recognized. Only the symbols named are touched, whatever the size of the document.

      Parameters

      • ids: string[]
      • patch: TSymbolUpdate
      • addToHistory: boolean = true

        Whether to add to history (default: true). Texts slid along are part of the same entry.

      Returns Promise<TSymbol[]>

      The updated records; an id with no symbol is skipped

      await canvas.updateSymbols(ids, { style: { color: "#ff0000" } })
      await canvas.updateSymbols(ids, { font: { size: 18, weight: "bold" } })
      await canvas.updateSymbols([text.id], (draft) => { if (isText(draft)) draft.decorators = [] })
    • Wait for the client to become idle

      Returns Promise<void>

      Promise that resolves when idle

    • Set the viewport zoom level, optionally anchored to a point.

      Parameters

      • zoom: number

        Target zoom factor (e.g. 1.5 = 150 %)

      • OptionalcenterX: number

        X coordinate to zoom around (pixels, default: viewport center)

      • OptionalcenterY: number

        Y coordinate to zoom around (pixels, default: viewport center)

      Returns void

    • Zoom and pan the view to fit the given symbols (or all symbols) within the viewport. Resets to zoom 1 if there are no symbols.

      Parameters

      • Optionalsymbols: TSymbol[]

        Symbols to fit (default: all model symbols)

      Returns void

    WebSocket client handling real-time communication with the MyScript backend.

    Manages smart connectors and anchor-based endpoint updates.

    Converts ink strokes to recognized text, math, or shape symbols.

    dom: typeof DOMFactory = DOMFactory

    Static utility class for creating DOM elements.

    eraser: EraseManager

    Handles erasing strokes and symbols via pointer interaction.

    Event bus for subscribing to canvas lifecycle and content events.

    EXPORT_RETRY_DEBOUNCE_MS: 300
    exportManager: IIExportManager

    Produces every export format and drives the file downloads.

    Detects and processes touch/pointer gestures (scratch-out, join, insert, etc.).

    Manages undo/redo history stack for all symbol changes.

    info?: TApiInfos

    Server API information (version, etc.) loaded on first connection.

    Queries and maps JIIX data to local symbols for math/text label resolution.

    Handles keyboard shortcuts and hotkey-based tool switching.

    layers: CanvasLayer

    DOM layer manager handling rendering, UI, and modal elements.

    Where the menus, the connection state and the minimap sit

    logger: Logger = ...

    Logger instance for this canvas.

    Manages math recognition: variables, computation, and evaluation rendering.

    Manages the floating UI menu (tool selector, style panel, action buttons).

    Handles canvas panning when the Move tool is active.

    Manages all visual overlays: math/text block indicators, debug visualizations.

    PASTE_OFFSET: 20
    pdfExport: PDFExportManager

    Builds print-only DOM/CSS layers and drives PDF export via native browser print.

    Replays a recorded set of strokes with play/pause/speed control.

    renderer: SVGRenderer

    SVG renderer responsible for drawing symbols onto the canvas layer.

    Handles symbol selection, selection group rendering, and hit-testing.

    Manages snapping behavior for symbols during move/resize operations.

    synchronizer: IISynchronizerManager

    Synchronizes the local model with the JIIX export from the backend client.

    Orchestrates translate, resize, and rotation transforms on selected symbols.

    Manages text and math symbol layout: bounds computation and reflow after edits.

    Handles ink input: captures pointer events and creates strokes.

    ZOOM_FIT_MARGIN: 40