Skip to content

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

9.3 KB
Raw Blame
import { TextSettings } from '../types/editor';
import { safeLocalStorageGetItem, safeLocalStorageSetItem } from './safeStorage';

export const TEXT_SETTINGS_STORAGE_KEY = 'ink_studio_text_settings';

export interface TextFontOption {
  value: string;
  label: string;
  category: 'Sans' | 'Serif' | 'Manga' | 'Display' | 'Mono' | 'System';
}

export const TEXT_FONT_PRESETS: ReadonlyArray<TextFontOption> = [
  {
    value: "Inter, 'Segoe UI', system-ui, -apple-system, sans-serif",
    label: 'Sans Clean',
    category: 'Sans',
  },
  {
    value: "'Segoe UI', Roboto, Helvetica, Arial, sans-serif",
    label: 'Segoe UI / System',
    category: 'Sans',
  },
  {
    value: "Arial, 'Helvetica Neue', Helvetica, sans-serif",
    label: 'Arial / Helvetica',
    category: 'Sans',
  },
  {
    value: 'Verdana, Geneva, sans-serif',
    label: 'Verdana',
    category: 'Sans',
  },
  {
    value: "'Trebuchet MS', 'Gill Sans', sans-serif",
    label: 'Trebuchet MS',
    category: 'Sans',
  },
  {
    value: "Georgia, 'Times New Roman', serif",
    label: 'Georgia Serif',
    category: 'Serif',
  },
  {
    value: "'Times New Roman', Times, serif",
    label: 'Times New Roman',
    category: 'Serif',
  },
  {
    value: "'Palatino Linotype', 'Book Antiqua', Palatino, serif",
    label: 'Palatino',
    category: 'Serif',
  },
  {
    value: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",
    label: 'Manga / Comic',
    category: 'Manga',
  },
  {
    value: "'Anime Ace', 'Comic Sans MS', sans-serif",
    label: 'Anime Ace',
    category: 'Manga',
  },
  {
    value: "Impact, 'Arial Black', sans-serif",
    label: 'Impact (SFX)',
    category: 'Display',
  },
  {
    value: "'JetBrains Mono', Consolas, 'Courier New', monospace",
    label: 'Monospace',
    category: 'Mono',
  },
  {
    value: "'Hiragino Sans', 'Hiragino Kaku Gothic ProN', 'Yu Gothic', 'Meiryo', 'Noto Sans JP', sans-serif",
    label: 'Japanese Gothic (游ゴシック)',
    category: 'Sans',
  },
  {
    value: "'Hiragino Mincho ProN', 'Yu Mincho', 'BIZ UDPMincho', 'Noto Serif JP', serif",
    label: 'Japanese Mincho (游明朝)',
    category: 'Serif',
  },
  {
    value: "'BIZ UDPGothic', 'Meiryo', 'Hiragino Kaku Gothic ProN', 'Noto Sans JP', sans-serif",
    label: 'Japanese UI Sans (BIZ UDゴシック)',
    category: 'Sans',
  },
  {
    value: "'Yu Mincho', 'Hiragino Mincho ProN', 'Yu Gothic', 'Meiryo', serif",
    label: 'Japanese Manga (明朝・縦書き)',
    category: 'Manga',
  },
];

export const TEXT_QUICK_COLORS: ReadonlyArray<{ hex: string; label: string }> = [
  { hex: '#ffffff', label: 'White' },
  { hex: '#000000', label: 'Black' },
  { hex: '#f4f4f5', label: 'Soft White' },
  { hex: '#ef4444', label: 'Red' },
  { hex: '#f59e0b', label: 'Amber' },
  { hex: '#38bdf8', label: 'Sky' },
];

export const TEXT_FONT_SIZE_PRESETS: ReadonlyArray<number> = [
  14, 18, 24, 32, 36, 48, 64, 84, 120,
];

/**
 * Standard Ink Studio Text Tool defaults:
 * plain white text without outlines and clean proportional sans typography.
 */
export const DEFAULT_TEXT_SETTINGS: TextSettings = {
  text: '',
  fontFamily: "Inter, 'Segoe UI', system-ui, -apple-system, sans-serif",
  fontSize: 36,
  lineSpacing: 1.25,
  letterSpacing: 0,
  bold: false,
  italic: false,
  underline: false,
  align: 'left',
  outline: false,
  outlineColor: '#000000',
  outlineWidth: 3,
  color: '#ffffff',
  writingMode: 'horizontal-tb',
  opacity: 1,
  maxWidth: null,
};

function clampFinite(value: unknown, min: number, max: number, fallback: number): number {
  const n = typeof value === 'number' ? value : Number(value);
  if (!Number.isFinite(n)) return fallback;
  return Math.max(min, Math.min(max, n));
}

function normalizeColor(value: unknown, fallback: string): string {
  if (typeof value === 'string') {
    const trimmed = value.trim();
    if (/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(trimmed)) {
      return trimmed.toLowerCase();
    }
  }
  return fallback;
}

/**
 * Extracts only the reusable typography/style fields from a TextSettings patch
 * (omitting transient draft `text` and per-instance `maxWidth`).
 */
export function extractPersistableTextStyle(
  settings: Partial<TextSettings>
): Partial<TextSettings> {
  const out: Partial<TextSettings> = {};
  if (typeof settings.fontFamily === 'string' && settings.fontFamily.trim()) {
    out.fontFamily = settings.fontFamily.trim();
  }
  if (settings.fontSize !== undefined) {
    out.fontSize = Math.round(clampFinite(settings.fontSize, 6, 400, DEFAULT_TEXT_SETTINGS.fontSize));
  }
  if (settings.lineSpacing !== undefined) {
    out.lineSpacing = Number(
      clampFinite(settings.lineSpacing, 0.7, 3.0, DEFAULT_TEXT_SETTINGS.lineSpacing ?? 1.25).toFixed(2)
    );
  }
  if (settings.letterSpacing !== undefined) {
    out.letterSpacing = Number(
      clampFinite(settings.letterSpacing, -10, 60, DEFAULT_TEXT_SETTINGS.letterSpacing ?? 0).toFixed(1)
    );
  }
  if (typeof settings.bold === 'boolean') out.bold = settings.bold;
  if (typeof settings.italic === 'boolean') out.italic = settings.italic;
  if (typeof settings.underline === 'boolean') out.underline = settings.underline;
  if (settings.align === 'left' || settings.align === 'center' || settings.align === 'right') {
    out.align = settings.align;
  }
  if (typeof settings.outline === 'boolean') out.outline = settings.outline;
  if (settings.outlineColor !== undefined) {
    out.outlineColor = normalizeColor(settings.outlineColor, DEFAULT_TEXT_SETTINGS.outlineColor);
  }
  if (settings.outlineWidth !== undefined) {
    out.outlineWidth = Math.round(
      clampFinite(settings.outlineWidth, 1, 24, DEFAULT_TEXT_SETTINGS.outlineWidth)
    );
  }
  if (settings.color !== undefined) {
    out.color = normalizeColor(settings.color, DEFAULT_TEXT_SETTINGS.color);
  }
  if (settings.writingMode === 'horizontal-tb' || settings.writingMode === 'vertical-rl') {
    out.writingMode = settings.writingMode;
  }
  if (settings.opacity !== undefined) {
    out.opacity = Number(clampFinite(settings.opacity, 0.05, 1, 1).toFixed(2));
  }
  return out;
}

export function normalizeTextSettings(raw?: Partial<TextSettings> | null): TextSettings {
  const safeStyle = raw ? extractPersistableTextStyle(raw) : {};
  const maxWidth =
    raw && typeof raw.maxWidth === 'number' && Number.isFinite(raw.maxWidth) && raw.maxWidth >= 24
      ? Math.round(raw.maxWidth)
      : null;
  return {
    ...DEFAULT_TEXT_SETTINGS,
    ...safeStyle,
    text: typeof raw?.text === 'string' ? raw.text : '',
    maxWidth,
  };
}

export function loadInitialTextSettings(): TextSettings {
  try {
    const saved = safeLocalStorageGetItem(TEXT_SETTINGS_STORAGE_KEY);
    if (saved) {
      const parsed = JSON.parse(saved) as Partial<TextSettings>;
      return normalizeTextSettings({ ...parsed, text: '', maxWidth: null });
    }
  } catch {
    // Ignore storage / parse errors and use defaults
  }
  return { ...DEFAULT_TEXT_SETTINGS };
}

export function saveTextSettings(settings: TextSettings): void {
  const persistable = extractPersistableTextStyle(settings);
  safeLocalStorageSetItem(
    TEXT_SETTINGS_STORAGE_KEY,
    JSON.stringify(persistable),
    'text settings'
  );
}

/**
 * Returns font options ensuring the currently selected fontFamily (e.g. from an opened
 * .ink file or local system font) is always present in the dropdown.
 */
export function getTextFontOptions(
  currentFontFamily?: string,
  extraSystemFonts?: ReadonlyArray<string>
): TextFontOption[] {
  const options: TextFontOption[] = [...TEXT_FONT_PRESETS];
  const seenValues = new Set(options.map((o) => o.value));
  const seenLabels = new Set(options.map((o) => o.label.toLowerCase()));

  if (extraSystemFonts && extraSystemFonts.length > 0) {
    for (const family of extraSystemFonts) {
      const clean = family.trim();
      if (!clean) continue;
      const value = clean.includes(',') ? clean : `'${clean.replace(/'/g, '')}', sans-serif`;
      if (seenValues.has(value) || seenLabels.has(clean.toLowerCase())) continue;
      seenValues.add(value);
      seenLabels.add(clean.toLowerCase());
      options.push({ value, label: clean, category: 'System' });
    }
  }

  if (currentFontFamily && currentFontFamily.trim() && !seenValues.has(currentFontFamily)) {
    const primaryName =
      currentFontFamily
        .split(',')[0]
        ?.trim()
        .replace(/^['"]|['"]$/g, '') || currentFontFamily;
    options.unshift({
      value: currentFontFamily,
      label: primaryName,
      category: 'System',
    });
  }

  return options;
}

let cachedSystemFonts: string[] | null = null;

/**
 * Best-effort discovery of installed system fonts using the Local Font Access API
 * when supported by the host WebView/browser.
 */
export async function queryInstalledSystemFonts(): Promise<string[]> {
  if (cachedSystemFonts) return cachedSystemFonts;
  if (typeof window === 'undefined') return [];
  const queryLocalFonts = (
    window as unknown as {
      queryLocalFonts?: () => Promise<Array<{ family?: string }>>;
    }
  ).queryLocalFonts;
  if (typeof queryLocalFonts !== 'function') return [];
  try {
    const fonts = await queryLocalFonts();
    const families = new Set<string>();
    for (const font of fonts) {
      if (font?.family && typeof font.family === 'string') {
        families.add(font.family.trim());
      }
    }
    cachedSystemFonts = Array.from(families).sort((a, b) => a.localeCompare(b));
    return cachedSystemFonts;
  } catch {
    return [];
  }
}