Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

5.4 KB
Raw Blame
/* oxlint-disable react-perf/jsx-no-new-function-as-prop -- the container ref callback is intentionally re-created when `engine` changes, so a project switch detaches the old engine and attaches the new one. */
import type { CanvasKeyOwner } from '@workbench/canvas-engine/api';
import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
import type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react';

import { Box } from '@chakra-ui/react';
import { isResizeDragActive, subscribeResizeDrag } from '@platform/ui/ResizeHandle';
import { useWorkbenchFocusTarget } from '@workbench/focusRegions';
import { getHotkeyTargetWidget, resolveHotkeyTarget } from '@workbench/hotkeys/targetWidget';
import { getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';
import { CANVAS_SURFACE_ATTR, shouldFocusCanvasSurface } from '@workbench/widgets/canvas/surfaceFocus';
import { TextEditPortal } from '@workbench/widgets/canvas/TextEditPortal';
import { useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { useRef } from 'react';

export type CanvasSurfaceEngine = Pick<
  CanvasEngineHandle,
  'document' | 'interaction' | 'layers' | 'projectId' | 'surface' | 'viewport'
>;

/** Focuses the container in capture before engine handlers, keeping focus already inside (text editing). */
const focusCanvasSurface = (event: ReactPointerEvent<HTMLDivElement>) => {
  if (shouldFocusCanvasSurface(event.currentTarget, event.target, document.activeElement)) {
    event.currentTarget.focus({ preventScroll: true });
  }
};

/** Engine-keyed ref callback: binds the canvases and ResizeObserver; the engine owns input without React renders. */
export const CanvasSurface = ({ engine, instanceId }: { engine: CanvasSurfaceEngine; instanceId: string }) => {
  const screenRef = useRef<HTMLCanvasElement>(null);
  const overlayRef = useRef<HTMLCanvasElement>(null);
  const getFocusTarget = useWorkbenchFocusTarget();
  const queries = useWorkbenchQueries();

  // The engine's own keys ask the judge the hotkey runtime asks, with the same inputs, only on keydown: this canvas
  // owns the key, the Layers widget acting on its layers is a companion, and any other widget keeps it.
  const resolveKeyOwner = (event: KeyboardEvent): CanvasKeyOwner => {
    const project = queries.getSnapshot().activeProject;
    if (project.id !== engine.projectId) {
      return 'elsewhere';
    }
    const target = resolveHotkeyTarget({
      focusTarget: getFocusTarget(),
      project: getWidgetPlacementProject(project),
      targetWidget: getHotkeyTargetWidget(event.target),
    });
    return target.activeInstanceId === instanceId
      ? 'surface'
      : target.activeWidgetTypeId === 'layers'
        ? 'companion'
        : 'elsewhere';
  };

  const bindContainer = (container: HTMLDivElement) => {
    const screen = screenRef.current;
    const overlay = overlayRef.current;
    if (!screen || !overlay) {
      return;
    }

    engine.surface.attach(screen, overlay, container, { resolveKeyOwner });

    // A handle drag defers the resize and full recomposition to its release; pixel CSS sizes make the interim canvas
    // crop or reveal rather than stretch.
    let isSizeStale = false;
    let syncedSize = '';
    const syncSize = (canDefer: boolean) => {
      if (canDefer && isResizeDragActive()) {
        isSizeStale = true;
        return;
      }
      isSizeStale = false;
      const width = container.clientWidth;
      const height = container.clientHeight;
      const dpr = globalThis.devicePixelRatio || 1;
      // Resizing reallocates and recomposes everything, so an unchanged size is skipped.
      if (canDefer && syncedSize === `${width}x${height}@${dpr}`) {
        return;
      }
      syncedSize = `${width}x${height}@${dpr}`;
      for (const canvas of [screen, overlay]) {
        canvas.style.width = `${width}px`;
        canvas.style.height = `${height}px`;
      }
      engine.surface.resize(width, height, dpr);
    };

    // The first sync never waits: the fit below needs a sized viewport.
    syncSize(false);
    // Fit the document into view the first time this canvas is shown, once the viewport is sized. The shell keeps
    // widgets mounted across layout switches, so this callback re-runs on every re-show and an unconditional fit would
    // reset the user's zoom and pan each time they came back.
    engine.viewport.fitToViewOnFirstShow();

    const observer = new ResizeObserver(() => syncSize(true));
    observer.observe(container);
    const unsubscribeResizeDrag = subscribeResizeDrag(() => {
      if (isSizeStale) {
        syncSize(true);
      }
    });

    return () => {
      unsubscribeResizeDrag();
      observer.disconnect();
      engine.surface.detach();
    };
  };

  return (
    <Box
      ref={bindContainer}
      {...{ [CANVAS_SURFACE_ATTR]: '' }}
      h="full"
      outline="none"
      overflow="hidden"
      position="relative"
      tabIndex={-1}
      w="full"
      onPointerDownCapture={focusCanvasSurface}
    >
      <canvas ref={screenRef} style={CANVAS_STYLE} />
      <canvas ref={overlayRef} style={OVERLAY_STYLE} />
      {/* Position text editing inside the canvas container so documentToScreen offsets share the canvas origin. */}
      <TextEditPortal engine={engine} />
    </Box>
  );
};

const CANVAS_STYLE: CSSProperties = {
  left: 0,
  position: 'absolute',
  top: 0,
  touchAction: 'none',
};

const OVERLAY_STYLE: CSSProperties = { ...CANVAS_STYLE, zIndex: 1 };