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.

16.7 KB
Raw Blame
import type { CanvasManager } from 'features/controlLayers/konva/CanvasManager';
import { CanvasModuleBase } from 'features/controlLayers/konva/CanvasModuleBase';
import type { CanvasToolModule } from 'features/controlLayers/konva/CanvasTool/CanvasToolModule';
import { canvasToBlob, getPrefixedId } from 'features/controlLayers/konva/util';
import { type CanvasTextSettingsState, selectCanvasTextSlice } from 'features/controlLayers/store/canvasTextSlice';
import type { Coordinate, RgbaColor } from 'features/controlLayers/store/types';
import { buildCommittedTextImageState, getCommittedTextImageDimensions } from 'features/controlLayers/text/textCommit';
import {
  getFontStackById,
  subscribeToCustomTextFontStacks,
  TEXT_RASTER_PADDING,
} from 'features/controlLayers/text/textConstants';
import {
  buildFontDescriptor,
  calculateLayerPosition,
  hasVisibleGlyphs,
  measureTextContent,
  renderTextToCanvas,
  type TextMeasureConfig,
} from 'features/controlLayers/text/textRenderer';
import { type TextSessionStatus, transitionTextSessionStatus } from 'features/controlLayers/text/textSessionMachine';
import { awaitUserFontReady } from 'features/controlLayers/text/textUserFonts';
import { toast } from 'features/toast/toast';
import { selectActiveTab } from 'features/ui/store/uiSelectors';
import { t } from 'i18next';
import Konva from 'konva';
import type { KonvaEventObject } from 'konva/lib/Node';
import { atom } from 'nanostores';
import type { Logger } from 'roarr';
import { uploadImage } from 'services/api/endpoints/images';

type CanvasTextSessionState = {
  id: string;
  anchor: Coordinate;
  position: Coordinate | null;
  size: { width: number; height: number } | null;
  rotation: number;
  status: CanvasTextSessionStatus;
  createdAt: number;
  text: string;
};

type CanvasTextToolModuleConfig = {
  CURSOR_MIN_WIDTH_PX: number;
};

type CanvasTextSessionStatus = Exclude<TextSessionStatus, 'idle'>;

const coerceSessionStatus = (status: TextSessionStatus): CanvasTextSessionStatus => {
  if (status === 'idle') {
    return 'pending';
  }
  return status;
};

const DEFAULT_CONFIG: CanvasTextToolModuleConfig = {
  CURSOR_MIN_WIDTH_PX: 1.5,
};

export class CanvasTextToolModule extends CanvasModuleBase {
  readonly type = 'text_tool';
  readonly id: string;
  readonly path: string[];
  readonly parent: CanvasToolModule;
  readonly manager: CanvasManager;
  readonly log: Logger;

  config: CanvasTextToolModuleConfig = DEFAULT_CONFIG;

  konva: {
    group: Konva.Group;
    cursor: Konva.Rect;
    label: Konva.Text;
  };

  $session = atom<CanvasTextSessionState | null>(null);
  private subscriptions = new Set<() => void>();
  private cursorHeight = 0;
  private cursorMetricsKey: string | null = null;

  constructor(parent: CanvasToolModule) {
    super();
    this.id = getPrefixedId(this.type);
    this.parent = parent;
    this.manager = parent.manager;
    this.path = this.manager.buildPath(this);
    this.log = this.manager.buildLogger(this);

    this.konva = {
      group: new Konva.Group({ name: `${this.type}:group`, listening: false }),
      cursor: new Konva.Rect({
        name: `${this.type}:cursor`,
        width: 1,
        height: 10,
        listening: false,
        perfectDrawEnabled: false,
      }),
      label: new Konva.Text({
        name: `${this.type}:label`,
        text: 'T',
        listening: false,
        perfectDrawEnabled: false,
      }),
    };

    this.konva.group.add(this.konva.cursor);
    this.konva.group.add(this.konva.label);
    this.konva.label.visible(true);

    this.subscriptions.add(
      this.manager.stateApi.createStoreSubscription(selectCanvasTextSlice, () => {
        this.render();
      })
    );
    this.subscriptions.add(
      this.manager.stateApi.createStoreSubscription(selectActiveTab, (activeTab) => {
        if (activeTab !== 'canvas') {
          this.clearSession();
        }
      })
    );
    this.subscriptions.add(
      this.parent.$cursorPos.listen(() => {
        this.render();
      })
    );
    this.subscriptions.add(
      subscribeToCustomTextFontStacks(() => {
        this.cursorMetricsKey = null;
        this.render();
      })
    );
  }

  destroy = () => {
    this.subscriptions.forEach((unsubscribe) => unsubscribe());
    this.subscriptions.clear();
    this.konva.group.destroy();
  };

  syncCursorStyle = () => {
    const session = this.$session.get();
    if (session?.status === 'editing') {
      this.manager.stage.setCursor('default');
      return;
    }
    this.manager.stage.setCursor('none');
  };

  render = () => {
    const textSettings = this.manager.stateApi.runSelector(selectCanvasTextSlice);
    const cursorPos = this.parent.$cursorPos.get();
    const session = this.$session.get();

    if (this.parent.$tool.get() !== 'text' || !cursorPos || (session && session.status === 'editing')) {
      this.setVisibility(false);
      return;
    }

    this.setVisibility(true);
    this.setCursorDimensions(textSettings);
    this.setCursorPosition(cursorPos.relative, textSettings);
  };

  private setCursorDimensions = (settings: CanvasTextSettingsState) => {
    const onePixel = this.manager.stage.unscale(this.config.CURSOR_MIN_WIDTH_PX);
    const cursorWidth = Math.max(onePixel * 2, onePixel);
    const metricsKey = `${settings.fontId}|${settings.fontSize}|${settings.bold}|${settings.italic}|${settings.lineHeight}`;
    if (this.cursorMetricsKey !== metricsKey) {
      const measureConfig: TextMeasureConfig = {
        text: 'Mg',
        fontSize: settings.fontSize,
        fontFamily: getFontStackById(settings.fontId),
        fontWeight: settings.bold ? 700 : 400,
        fontStyle: settings.italic ? 'italic' : 'normal',
        lineHeight: settings.lineHeight,
      };
      const metrics = measureTextContent(measureConfig);
      this.cursorHeight = Math.max(metrics.lineHeightPx, settings.fontSize) + TEXT_RASTER_PADDING * 2;
      this.cursorMetricsKey = metricsKey;
    }
    const height = this.cursorHeight || settings.fontSize + TEXT_RASTER_PADDING * 2;
    this.konva.cursor.setAttrs({
      width: cursorWidth,
      height,
    });
    this.konva.label.setAttrs({
      fontFamily: getFontStackById('uiSerif'),
      fontSize: Math.max(12, height * 0.35),
      fontStyle: settings.bold ? '700' : '400',
      fill: 'rgba(0, 0, 0, 1)',
      stroke: 'rgba(255, 255, 255, 1)',
      strokeWidth: Math.max(1, onePixel),
    });
    this.konva.cursor.fill('rgba(0, 0, 0, 1)');
    this.konva.cursor.stroke('rgba(255, 255, 255, 1)');
    this.konva.cursor.strokeWidth(onePixel);
  };

  private setCursorPosition = (cursor: Coordinate, _settings: CanvasTextSettingsState) => {
    const top = cursor.y - TEXT_RASTER_PADDING;
    this.konva.cursor.setAttrs({
      x: cursor.x,
      y: top,
    });
    const labelFontSize = this.konva.label.fontSize();
    this.konva.label.setAttrs({
      x: cursor.x + this.konva.cursor.width() * 1.5,
      y: top + this.konva.cursor.height() - labelFontSize * 0.6,
    });
  };

  private setVisibility = (visible: boolean) => {
    this.konva.group.visible(visible);
    this.konva.label.visible(visible);
  };

  onStagePointerMove = (e: KonvaEventObject<PointerEvent>) => {
    if (e.target !== this.parent.konva.stage) {
      return;
    }
    const cursorPos = this.parent.$cursorPos.get();
    if (!cursorPos) {
      return;
    }
  };

  onStagePointerEnter = (e: KonvaEventObject<PointerEvent>) => {
    if (e.target !== this.parent.konva.stage) {
      return;
    }
    const cursorPos = this.parent.$cursorPos.get();
    if (!cursorPos) {
      return;
    }
  };

  onStagePointerDown = (e: KonvaEventObject<PointerEvent>) => {
    // Only allow left-click/primary pointer to begin typing sessions.
    if (e.target !== this.parent.konva.stage || e.evt.button !== 0) {
      return;
    }
    const cursorPos = this.parent.$cursorPos.get();
    if (!cursorPos) {
      return;
    }
    if (this.$session.get()) {
      return;
    }
    this.beginSession(cursorPos.relative);
  };

  beginSession = (anchor: Coordinate) => {
    const current = this.$session.get();
    if (current && current.status === 'editing') {
      return;
    }
    const id = getPrefixedId('text_session');
    const status = coerceSessionStatus(transitionTextSessionStatus('idle', 'BEGIN'));
    this.$session.set({
      id,
      anchor,
      position: null,
      size: null,
      rotation: 0,
      status,
      createdAt: Date.now(),
      text: '',
    });
  };

  markSessionEditing = (id: string) => {
    const current = this.$session.get();
    if (!current || current.id !== id) {
      return;
    }
    const nextStatus = coerceSessionStatus(transitionTextSessionStatus(current.status, 'EDIT'));
    this.$session.set({
      ...current,
      status: nextStatus,
    });
  };

  clearSession = () => {
    this.$session.set(null);
  };

  updateSessionText = (sessionId: string, text: string) => {
    const current = this.$session.get();
    if (!current || current.id !== sessionId) {
      return;
    }
    this.$session.set({ ...current, text });
  };

  updateSessionPosition = (sessionId: string, position: Coordinate) => {
    const current = this.$session.get();
    if (!current || current.id !== sessionId) {
      return;
    }
    this.$session.set({ ...current, position });
  };

  updateSessionSize = (sessionId: string, size: { width: number; height: number }) => {
    const current = this.$session.get();
    if (!current || current.id !== sessionId) {
      return;
    }
    this.$session.set({ ...current, size });
  };

  updateSessionRotation = (sessionId: string, rotation: number) => {
    const current = this.$session.get();
    if (!current || current.id !== sessionId) {
      return;
    }
    this.$session.set({ ...current, rotation });
  };

  updateSessionAnchor = (sessionId: string, anchor: Coordinate) => {
    const current = this.$session.get();
    if (!current || current.id !== sessionId) {
      return;
    }
    this.$session.set({ ...current, anchor });
  };

  onToolChanged = () => {
    const session = this.$session.get();
    if (!session || session.status === 'committed') {
      return;
    }
    if (this.parent.$tool.get() !== 'text') {
      this.parent.setBaseTool('text');
    }
  };

  requestCommit = (sessionId: string) => {
    const session = this.$session.get();
    if (!session || session.id !== sessionId) {
      return;
    }
    const rawText = session.text.replace(/\r/g, '');
    if (!hasVisibleGlyphs(rawText)) {
      this.clearSession();
      return;
    }

    const textSettings = this.manager.stateApi.runSelector(selectCanvasTextSlice);
    const canvasSettings = this.manager.stateApi.getSettings();
    const color = canvasSettings.activeColor === 'fgColor' ? canvasSettings.fgColor : canvasSettings.bgColor;

    this.$session.set({
      ...session,
      status: coerceSessionStatus(transitionTextSessionStatus(session.status, 'COMMIT')),
    });

    void this.commitSession(session, rawText, textSettings, color);
  };

  private commitSession = async (
    session: CanvasTextSessionState,
    rawText: string,
    textSettings: CanvasTextSettingsState,
    color: RgbaColor
  ) => {
    const fontReadiness = await awaitUserFontReady(textSettings.fontId);
    if (fontReadiness !== 'ready') {
      const currentSession = this.$session.get();
      if (currentSession?.id === session.id) {
        this.$session.set({ ...currentSession, status: 'editing' });
      }
      const isTimeout = fontReadiness === 'timeout';
      toast({
        id: isTimeout
          ? `custom-font-still-loading:${textSettings.fontId}`
          : `custom-font-load-failed:${textSettings.fontId}`,
        status: 'error',
        title: t(isTimeout ? 'toast.customFontStillLoading' : 'toast.customFontLoadFailed'),
        description: t(isTimeout ? 'toast.customFontStillLoadingDesc' : 'toast.customFontUnavailableDesc'),
        withCount: false,
      });
      return;
    }

    if (typeof document !== 'undefined' && document.fonts?.load) {
      const fontSpec = buildFontDescriptor({
        fontFamily: getFontStackById(textSettings.fontId),
        fontWeight: textSettings.bold ? 700 : 400,
        fontStyle: textSettings.italic ? 'italic' : 'normal',
        fontSize: textSettings.fontSize,
      });
      try {
        await document.fonts.load(fontSpec);
        await document.fonts.ready;
      } catch {
        // Ignore font load failures and proceed with available metrics.
      }
    }

    const renderResult = renderTextToCanvas({
      text: rawText,
      fontSize: textSettings.fontSize,
      fontFamily: getFontStackById(textSettings.fontId),
      fontWeight: textSettings.bold ? 700 : 400,
      fontStyle: textSettings.italic ? 'italic' : 'normal',
      underline: textSettings.underline,
      strikethrough: textSettings.strikethrough,
      lineHeight: textSettings.lineHeight,
      color,
      alignment: textSettings.alignment,
      padding: TEXT_RASTER_PADDING,
      devicePixelRatio: window.devicePixelRatio ?? 1,
    });

    const rotation = session.rotation ?? 0;
    const dprScale = renderResult.canvas.width / renderResult.totalWidth;
    let renderCanvas = renderResult.canvas;
    let totalWidth = renderResult.totalWidth;
    let totalHeight = renderResult.totalHeight;
    if (session.size) {
      const targetWidth = Math.max(1, Math.ceil(session.size.width));
      const targetHeight = Math.max(1, Math.ceil(session.size.height));
      if (targetWidth !== totalWidth || targetHeight !== totalHeight) {
        const adjustedCanvas = document.createElement('canvas');
        adjustedCanvas.width = Math.max(1, Math.ceil(targetWidth * dprScale));
        adjustedCanvas.height = Math.max(1, Math.ceil(targetHeight * dprScale));
        const ctx = adjustedCanvas.getContext('2d');
        if (!ctx) {
          throw new Error('Unable to acquire 2D context for adjusted canvas');
        }
        ctx.drawImage(renderCanvas, 0, 0);
        renderCanvas = adjustedCanvas;
        totalWidth = targetWidth;
        totalHeight = targetHeight;
      }
    }

    if (rotation !== 0) {
      const rotated = rotateCanvas(renderCanvas, rotation, dprScale);
      renderCanvas = rotated.canvas;
      totalWidth = rotated.width;
      totalHeight = rotated.height;
    }

    const blob = await canvasToBlob(renderCanvas);
    const imageDTO = await uploadImage({
      file: new File([blob], 'canvas-text.png', { type: 'image/png' }),
      image_category: 'other',
      is_intermediate: true,
      silent: true,
    });
    const { width: committedWidth, height: committedHeight } = getCommittedTextImageDimensions(totalWidth, totalHeight);
    const imageState = buildCommittedTextImageState(imageDTO, totalWidth, totalHeight);

    const extraLeftPadding = Math.ceil(textSettings.fontSize * 0.12);
    const fallbackPosition = calculateLayerPosition(
      session.anchor,
      textSettings.alignment,
      renderResult.contentWidth,
      TEXT_RASTER_PADDING,
      extraLeftPadding
    );
    const basePosition = session.position ? { x: session.position.x, y: session.position.y } : fallbackPosition;
    const baseSize = session.size ?? { width: renderResult.totalWidth, height: renderResult.totalHeight };
    const position =
      rotation === 0
        ? basePosition
        : {
            x: basePosition.x + baseSize.width / 2 - committedWidth / 2,
            y: basePosition.y + baseSize.height / 2 - committedHeight / 2,
          };

    const selectedAdapter = this.manager.stateApi.getSelectedEntityAdapter();
    const addAfter =
      selectedAdapter && selectedAdapter.state.type === 'raster_layer' ? selectedAdapter.state.id : undefined;

    this.manager.stateApi.addRasterLayer({
      overrides: {
        objects: [imageState],
        position,
        name: this.buildLayerName(rawText),
      },
      isSelected: true,
      addAfter,
    });

    this.clearSession();
  };

  private buildLayerName = (text: string) => {
    const flattened = text.replace(/\s+/g, ' ').trim();
    if (!flattened) {
      return 'Text';
    }
    return flattened.length > 32 ? `${flattened.slice(0, 29)}…` : flattened;
  };
}

const rotateCanvas = (source: HTMLCanvasElement, radians: number, dprScale: number) => {
  const width = source.width;
  const height = source.height;
  const cos = Math.abs(Math.cos(radians));
  const sin = Math.abs(Math.sin(radians));
  const newWidthPx = Math.ceil(width * cos + height * sin);
  const newHeightPx = Math.ceil(width * sin + height * cos);
  const canvas = document.createElement('canvas');
  canvas.width = Math.max(1, newWidthPx);
  canvas.height = Math.max(1, newHeightPx);
  const ctx = canvas.getContext('2d');
  if (!ctx) {
    throw new Error('Unable to acquire 2D context for rotation');
  }
  ctx.translate(newWidthPx / 2, newHeightPx / 2);
  ctx.rotate(radians);
  ctx.drawImage(source, -width / 2, -height / 2);
  return {
    canvas,
    width: newWidthPx / dprScale,
    height: newHeightPx / dprScale,
  };
};