Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

14.1 KB
Raw Blame
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
  DEFAULT_TEXT_SETTINGS,
  loadInitialTextSettings,
  TEXT_SETTINGS_STORAGE_KEY,
} from '../textSettings';
import { toolStoreActions, useToolStore } from '../../stores/useToolStore';
import { TextEditorOverlay } from '../../components/TextEditorOverlay';
import { TextSettings } from '../../types/editor';

interface MiniNode {
  nodeType: number;
  nodeName: string;
  parentNode: MiniElement | null;
  ownerDocument: MiniDocument;
}

class MiniTextNode implements MiniNode {
  public nodeType = 3;
  public nodeName = '#text';
  public nodeValue: string;
  public parentNode: MiniElement | null = null;
  public ownerDocument: MiniDocument;

  constructor(text: string, ownerDocument: MiniDocument) {
    this.nodeValue = text;
    this.ownerDocument = ownerDocument;
  }
}

class MiniCommentNode implements MiniNode {
  public nodeType = 8;
  public nodeName = '#comment';
  public nodeValue: string;
  public parentNode: MiniElement | null = null;
  public ownerDocument: MiniDocument;

  constructor(text: string, ownerDocument: MiniDocument) {
    this.nodeValue = text;
    this.ownerDocument = ownerDocument;
  }
}

class MiniElement extends EventTarget implements MiniNode {
  public nodeType = 1;
  public nodeName: string;
  public tagName: string;
  public namespaceURI = 'http://www.w3.org/1999/xhtml';
  public ownerDocument: MiniDocument;
  public parentNode: MiniElement | null = null;
  public childNodes: MiniNode[] = [];
  public style: Record<string, string> = {};
  public disabled = false;
  public className = '';
  public isContentEditable = false;
  public value = '';
  public type = '';
  public checked = false;
  public selected = false;
  public defaultSelected = false;
  public multiple = false;
  public width = 0;
  public height = 0;
  private attrs = new Map<string, string>();

  get options(): MiniElement[] {
    return this.childNodes.filter(
      (n): n is MiniElement => n instanceof MiniElement && n.tagName === 'OPTION'
    );
  }

  constructor(tag: string, ownerDocument: MiniDocument) {
    super();
    this.nodeName = tag.toUpperCase();
    this.tagName = tag.toUpperCase();
    if (this.tagName === 'TEXTAREA') this.type = 'textarea';
    this.ownerDocument = ownerDocument;
  }

  get firstChild(): MiniNode | null {
    return this.childNodes[0] ?? null;
  }

  get textContent(): string {
    return this.childNodes
      .map((n) => (n instanceof MiniTextNode ? n.nodeValue : n instanceof MiniElement ? n.textContent : ''))
      .join('');
  }

  set textContent(val: string) {
    this.childNodes = val ? [new MiniTextNode(val, this.ownerDocument)] : [];
  }

  getContext(): null {
    return null;
  }

  setSelectionRange(): void {}

  appendChild<T extends MiniNode>(child: T): T {
    if (child.parentNode) child.parentNode.removeChild(child);
    child.parentNode = this;
    this.childNodes.push(child);
    return child;
  }

  insertBefore<T extends MiniNode>(child: T, ref: MiniNode | null): T {
    if (!ref) return this.appendChild(child);
    if (child.parentNode) child.parentNode.removeChild(child);
    const idx = this.childNodes.indexOf(ref);
    child.parentNode = this;
    if (idx === -1) this.childNodes.push(child);
    else this.childNodes.splice(idx, 0, child);
    return child;
  }

  removeChild<T extends MiniNode>(child: T): T {
    const idx = this.childNodes.indexOf(child);
    if (idx !== -1) {
      this.childNodes.splice(idx, 1);
      child.parentNode = null;
    }
    return child;
  }

  setAttribute(name: string, value: string): void {
    this.attrs.set(name, String(value));
    if (name === 'class') this.className = String(value);
    if (name === 'disabled') this.disabled = true;
    if (name === 'value') this.value = String(value);
  }

  getAttribute(name: string): string | null {
    return this.attrs.get(name) ?? null;
  }

  removeAttribute(name: string): void {
    this.attrs.delete(name);
    if (name === 'disabled') this.disabled = false;
  }

  hasAttribute(name: string): boolean {
    return this.attrs.has(name);
  }

  focus(): void {
    this.ownerDocument.activeElement = this;
    this.dispatchEvent(new Event('focusin', { bubbles: true }));
  }

  attachEvent(): void {}

  detachEvent(): void {}

  blur(): void {
    if (this.ownerDocument.activeElement === this) {
      this.ownerDocument.activeElement = null;
    }
  }

  override dispatchEvent(event: Event): boolean {
    const path: EventTarget[] = [];
    let cur: MiniElement | null = this;
    while (cur) {
      path.push(cur);
      cur = cur.parentNode;
    }
    path.push(this.ownerDocument);
    if (this.ownerDocument.defaultView) {
      path.push(this.ownerDocument.defaultView);
    }

    Object.defineProperty(event, 'target', { value: this, configurable: true });
    for (const node of path) {
      Object.defineProperty(event, 'currentTarget', { value: node, configurable: true });
      EventTarget.prototype.dispatchEvent.call(node, event);
      if (event.cancelBubble) break;
    }
    return !event.defaultPrevented;
  }
}

class MiniDocument extends EventTarget {
  public nodeType = 9;
  public nodeName = '#document';
  public oninput = null;
  public defaultView: EventTarget | null = null;
  public documentElement: MiniElement;
  public body: MiniElement;
  public activeElement: MiniElement | null = null;

  constructor() {
    super();
    this.documentElement = new MiniElement('html', this);
    this.body = new MiniElement('body', this);
    this.documentElement.appendChild(this.body);
  }

  createElement(tag: string): MiniElement {
    return new MiniElement(tag, this);
  }

  createElementNS(_ns: string, tag: string): MiniElement {
    return new MiniElement(tag, this);
  }

  createTextNode(text: string): MiniTextNode {
    return new MiniTextNode(text, this);
  }

  createComment(text: string): MiniCommentNode {
    return new MiniCommentNode(text, this);
  }
}

function findElements(root: MiniElement, pred: (el: MiniElement) => boolean): MiniElement[] {
  const result: MiniElement[] = [];
  const walk = (el: MiniElement) => {
    if (pred(el)) result.push(el);
    for (const child of el.childNodes) {
      if (child instanceof MiniElement) walk(child);
    }
  };
  walk(root);
  return result;
}

function findByTestId(root: MiniElement, testId: string): MiniElement | undefined {
  return findElements(root, (el) => el.getAttribute('data-testid') === testId)[0];
}

function createMemoryStorage(): Storage {
  const map = new Map<string, string>();
  return {
    get length() {
      return map.size;
    },
    clear() {
      map.clear();
    },
    getItem(key: string) {
      return map.get(key) ?? null;
    },
    key(index: number) {
      return Array.from(map.keys())[index] ?? null;
    },
    removeItem(key: string) {
      map.delete(key);
    },
    setItem(key: string, value: string) {
      map.set(key, String(value));
    },
  };
}

describe('Text Tool Defaults, Persistence & WYSIWYG Editor', () => {
  const prevLocalStorage = (globalThis as Record<string, unknown>).localStorage;
  const prevWindow = (globalThis as Record<string, unknown>).window;
  const prevDocument = (globalThis as Record<string, unknown>).document;
  const prevHTMLElement = (globalThis as Record<string, unknown>).HTMLElement;
  const prevHTMLIFrameElement = (globalThis as Record<string, unknown>).HTMLIFrameElement;
  const prevElement = (globalThis as Record<string, unknown>).Element;
  const prevNode = (globalThis as Record<string, unknown>).Node;
  const prevActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;

  let doc: MiniDocument;
  let container: MiniElement;
  let root: Root;

  beforeEach(() => {
    const storage = createMemoryStorage();
    (globalThis as Record<string, unknown>).localStorage = storage;
    (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
    const MockHTMLIFrameElement = class HTMLIFrameElement {};
    doc = new MiniDocument();
    const win = Object.assign(new EventTarget(), {
      document: doc,
      localStorage: storage,
      devicePixelRatio: 1,
      getSelection: () => ({
        anchorNode: null,
        anchorOffset: 0,
        focusNode: null,
        focusOffset: 0,
      }),
      HTMLElement: MiniElement,
      HTMLIFrameElement: MockHTMLIFrameElement,
      Element: MiniElement,
      Node: MiniElement,
    });
    doc.defaultView = win;
    container = doc.createElement('div');
    doc.body.appendChild(container);

    (globalThis as Record<string, unknown>).window = win;
    (globalThis as Record<string, unknown>).document = doc;
    (globalThis as Record<string, unknown>).HTMLElement = MiniElement;
    (globalThis as Record<string, unknown>).HTMLIFrameElement = MockHTMLIFrameElement;
    (globalThis as Record<string, unknown>).Element = MiniElement;
    (globalThis as Record<string, unknown>).Node = MiniElement;

    toolStoreActions.resetTextSettings();
    root = createRoot(container as unknown as Element);
  });

  afterEach(() => {
    act(() => {
      root.unmount();
    });
    (globalThis as Record<string, unknown>).localStorage = prevLocalStorage;
    (globalThis as Record<string, unknown>).window = prevWindow;
    (globalThis as Record<string, unknown>).document = prevDocument;
    (globalThis as Record<string, unknown>).HTMLElement = prevHTMLElement;
    (globalThis as Record<string, unknown>).HTMLIFrameElement = prevHTMLIFrameElement;
    (globalThis as Record<string, unknown>).Element = prevElement;
    (globalThis as Record<string, unknown>).Node = prevNode;
    (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = prevActEnv;
  });

  it('defaults to plain white text without outlines and natural left alignment', () => {
    expect(DEFAULT_TEXT_SETTINGS.color).toBe('#ffffff');
    expect(DEFAULT_TEXT_SETTINGS.outline).toBe(false);
    expect(DEFAULT_TEXT_SETTINGS.align).toBe('left');
    expect(DEFAULT_TEXT_SETTINGS.letterSpacing).toBe(0);
    expect(DEFAULT_TEXT_SETTINGS.opacity).toBe(1);
  });

  it('persists latest text settings to localStorage and restores them cleanly (excluding draft text)', () => {
    toolStoreActions.updateTextSettings({
      text: 'Transient draft',
      fontFamily: "Georgia, 'Times New Roman', serif",
      fontSize: 54,
      lineSpacing: 1.4,
      letterSpacing: 2.5,
      bold: true,
      italic: true,
      underline: true,
      align: 'center',
      color: '#38bdf8',
      outline: true,
      outlineColor: '#111111',
      outlineWidth: 5,
      opacity: 0.85,
    });

    const raw = localStorage.getItem(TEXT_SETTINGS_STORAGE_KEY);
    expect(raw).toBeTruthy();
    const parsed = JSON.parse(raw!);
    expect(parsed.text).toBeUndefined();
    expect(parsed.maxWidth).toBeUndefined();

    const reloaded = loadInitialTextSettings();
    expect(reloaded.text).toBe('');
    expect(reloaded.fontFamily).toBe("Georgia, 'Times New Roman', serif");
    expect(reloaded.fontSize).toBe(54);
    expect(reloaded.lineSpacing).toBe(1.4);
    expect(reloaded.letterSpacing).toBe(2.5);
    expect(reloaded.bold).toBe(true);
    expect(reloaded.italic).toBe(true);
    expect(reloaded.underline).toBe(true);
    expect(reloaded.align).toBe('center');
    expect(reloaded.color).toBe('#38bdf8');
    expect(reloaded.outline).toBe(true);
    expect(reloaded.outlineWidth).toBe(5);
    expect(reloaded.opacity).toBe(0.85);

    toolStoreActions.resetTextSettings();
    expect(useToolStore.getState().textSettings.color).toBe('#ffffff');
    expect(useToolStore.getState().textSettings.outline).toBe(false);
    expect(loadInitialTextSettings().color).toBe('#ffffff');
    expect(loadInitialTextSettings().outline).toBe(false);
  });

  it('supports WYSIWYG on-canvas keyboard shortcuts (Ctrl+B, Ctrl+U, Alt+Arrow nudge, Ctrl+Enter) and delete button', () => {
    let currentSettings: TextSettings = { ...DEFAULT_TEXT_SETTINGS, text: 'Hello' };
    const onUpdateSettings = vi.fn((updater: (prev: TextSettings) => TextSettings) => {
      currentSettings = updater(currentSettings);
    });
    const onMove = vi.fn();
    const onConfirm = vi.fn();
    const onCancel = vi.fn();
    const onDelete = vi.fn();

    act(() => {
      root.render(
        <TextEditorOverlay
          x={200}
          y={150}
          settings={currentSettings}
          editingLayerId="text-layer-1"
          primaryColor="#ff0000"
          zoom={1}
          onUpdateSettings={onUpdateSettings}
          onMove={onMove}
          onConfirm={onConfirm}
          onCancel={onCancel}
          onDelete={onDelete}
        />
      );
    });

    const textarea = findByTestId(container, 'text-editor-textarea');
    expect(textarea).toBeDefined();

    const dispatchKeyDown = (
      el: MiniElement,
      init: { key: string; ctrlKey?: boolean; metaKey?: boolean; altKey?: boolean; shiftKey?: boolean }
    ) => {
      const evt = Object.assign(new Event('keydown', { bubbles: true, cancelable: true }), {
        key: init.key,
        ctrlKey: Boolean(init.ctrlKey),
        metaKey: Boolean(init.metaKey),
        altKey: Boolean(init.altKey),
        shiftKey: Boolean(init.shiftKey),
      });
      el.dispatchEvent(evt);
    };

    // Ctrl+B toggles bold
    act(() => {
      dispatchKeyDown(textarea!, { key: 'b', ctrlKey: true });
    });
    expect(currentSettings.bold).toBe(true);

    // Ctrl+U toggles underline
    act(() => {
      dispatchKeyDown(textarea!, { key: 'u', ctrlKey: true });
    });
    expect(currentSettings.underline).toBe(true);

    // Alt+Shift+ArrowRight nudges +10px horizontally
    act(() => {
      dispatchKeyDown(textarea!, { key: 'ArrowRight', altKey: true, shiftKey: true });
    });
    expect(onMove).toHaveBeenCalledWith(210, 150);

    // Ctrl+Enter confirms
    act(() => {
      dispatchKeyDown(textarea!, { key: 'Enter', ctrlKey: true });
    });
    expect(onConfirm).toHaveBeenCalledTimes(1);

    // Delete button works for existing text layer
    const deleteBtn = findByTestId(container, 'text-delete-btn');
    expect(deleteBtn).toBeDefined();
    act(() => {
      deleteBtn!.dispatchEvent(new Event('click', { bubbles: true, cancelable: true }));
    });
    expect(onDelete).toHaveBeenCalledTimes(1);
  });
});