Skip to content

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

4.2 KB
Raw Blame
import { isTauriEnvironment } from './tauriEnv';

export const MIN_INTERFACE_SCALE = 60;
export const MAX_INTERFACE_SCALE = 200;
export const DEFAULT_INTERFACE_SCALE = 100;
export const INTERFACE_SCALE_STEP = 5;
export const INTERFACE_SCALE_PRESETS = [60, 80, 100, 125, 150, 200] as const;

let activeNativeWebviewZoom = 1;
let lastAppliedNativeScale: number | null = null;

/**
 * Clamps and normalizes an interface scale percentage into the supported [60, 200] range.
 */
export function clampInterfaceScale(value: unknown): number {
  if (typeof value !== 'number' || !Number.isFinite(value)) {
    return DEFAULT_INTERFACE_SCALE;
  }
  return Math.max(MIN_INTERFACE_SCALE, Math.min(MAX_INTERFACE_SCALE, Math.round(value)));
}

/**
 * Returns the active Tauri native WebView zoom factor (1.0 when running in web mode or at 100%).
 * Used by native tablet input to convert OS window client coordinates into zoomed CSS pixels.
 */
export function getActiveNativeWebviewZoom(): number {
  return activeNativeWebviewZoom;
}

/**
 * Returns the active root CSS `zoom` factor in web mode (1.0 when at 100% or when Tauri native
 * WebView zoom is active). Used to keep the WebGL2/2D viewport compositor and pointer-to-canvas
 * transforms aligned with CSS-zoomed artboard overlays (including the 3D viewport stage).
 */
export function getActiveCssZoom(): number {
  if (typeof document === 'undefined' || !document.documentElement) return 1;
  const raw = document.documentElement.style?.zoom;
  if (!raw) return 1;
  const parsed = parseFloat(String(raw));
  return Number.isFinite(parsed) && parsed > 0.25 && parsed < 4 ? parsed : 1;
}

/**
 * Resets internal interface scale tracking state (primarily for unit tests).
 */
export function resetInterfaceScaleState(): void {
  activeNativeWebviewZoom = 1;
  lastAppliedNativeScale = null;
}

export const INTERFACE_SCALE_APPLIED_EVENT = 'ink-interface-scale-applied';

function notifyInterfaceScaleApplied(scale: number, factor: number): void {
  if (typeof window === 'undefined' || typeof CustomEvent !== 'function') return;
  try {
    window.dispatchEvent(
      new CustomEvent(INTERFACE_SCALE_APPLIED_EVENT, { detail: { scale, factor } })
    );
  } catch {
    // Ignore synthetic window dispatch failures in tests
  }
}

/**
 * Applies the user's interface scale (60%–200%) across the application.
 * - On Tauri desktop, uses the native WebView zoom API (`getCurrentWebview().setZoom`) so all
 *   DOM coordinates, floating panels, modals, HiDPI canvas backing buffers, and pointer events
 *   remain 100% geometrically aligned.
 * - On Web browsers, falls back to root CSS `zoom`.
 */
export async function applyInterfaceScale(percent: number): Promise<number> {
  const clamped = clampInterfaceScale(percent);
  const factor = clamped / 100;

  if (typeof document !== 'undefined' && document.documentElement) {
    const root = document.documentElement;
    if (typeof root.setAttribute === 'function') {
      root.setAttribute('data-ui-scale', String(clamped));
    }
    if (root.style) {
      if (typeof root.style.setProperty === 'function') {
        root.style.setProperty('--ui-scale', String(factor));
      }

      if (!isTauriEnvironment()) {
        activeNativeWebviewZoom = 1;
        lastAppliedNativeScale = null;
        root.style.zoom = clamped === DEFAULT_INTERFACE_SCALE ? '' : String(factor);
        notifyInterfaceScaleApplied(clamped, factor);
        return clamped;
      }

      // Clear any web CSS zoom when native WebView zoom is active
      root.style.zoom = '';
    } else if (!isTauriEnvironment()) {
      activeNativeWebviewZoom = 1;
      lastAppliedNativeScale = null;
      notifyInterfaceScaleApplied(clamped, factor);
      return clamped;
    }
  }

  if (isTauriEnvironment()) {
    activeNativeWebviewZoom = factor;
    if (lastAppliedNativeScale !== clamped) {
      lastAppliedNativeScale = clamped;
      try {
        const { getCurrentWebview } = await import('@tauri-apps/api/webview');
        await getCurrentWebview().setZoom(factor);
      } catch (err) {
        console.warn('Failed to apply native WebView interface scale:', err);
      }
      notifyInterfaceScaleApplied(clamped, factor);
    }
  } else {
    activeNativeWebviewZoom = 1;
  }

  return clamped;
}