Skip to content

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

4.8 KB
Raw Blame
/**
 * Canonical filename and extension hygiene utilities for Ink Studio saves, resaves, and exports.
 *
 * Guarantees that repeated Save / Save As / Export / Reopen cycles never accumulate chained
 * extensions like `Artwork.ink.ink.ink.png.ink`, while preserving Unicode names and intentional
 * dots inside titles (e.g. `Chapter 1.2`, `Page v2.0`).
 */

export const KNOWN_DOCUMENT_EXTENSIONS = new Set([
  '.ink',
  '.sora',
  '.psd',
  '.psb',
  '.clip',
  '.csp',
  '.lip',
  '.png',
  '.jpg',
  '.jpeg',
  '.webp',
  '.bmp',
  '.gif',
  '.svg',
]);

function extractBaseName(raw: string): string {
  const normalized = raw.replace(/\\/g, '/');
  const slash = normalized.lastIndexOf('/');
  return slash >= 0 ? normalized.slice(slash + 1) : normalized;
}

function stripIllegalFileChars(raw: string): string {
  let out = '';
  for (let i = 0; i < raw.length; i++) {
    const ch = raw[i];
    const code = raw.charCodeAt(i);
    if (code < 0x20 || code === 0x7f) continue;
    if (
      ch === '<' ||
      ch === '>' ||
      ch === ':' ||
      ch === '"' ||
      ch === '/' ||
      ch === '\\' ||
      ch === '|' ||
      ch === '?' ||
      ch === '*'
    ) {
      continue;
    }
    out += ch;
  }
  return out;
}

/**
 * Normalizes an extension string to lowercase with a single leading dot (e.g. `'INK'` -> `'.ink'`).
 */
export function normalizeExtension(ext: string, fallback: string = '.ink'): string {
  const cleaned = (ext || '')
    .trim()
    .toLowerCase()
    .replace(/^\.+/, '')
    .replace(/[^a-z0-9_-]/g, '');
  if (!cleaned) return fallback;
  return `.${cleaned}`;
}

/**
 * Strips any directory prefix, trailing unsaved `*` markers, and ALL chained trailing known
 * document/image extensions (e.g. `"Hero.ink.ink.png.ink*"` -> `"Hero"`), while preserving
 * non-extension dots like `"Chapter 1.2"`.
 */
export function stripDocumentExtensions(rawName: string | null | undefined): string {
  if (!rawName || typeof rawName !== 'string') return '';
  let current = extractBaseName(rawName).trim().replace(/\*+$/g, '').trim();

  while (current.length > 0) {
    const lastDot = current.lastIndexOf('.');
    if (lastDot <= 0) break;
    const tail = current.slice(lastDot).toLowerCase();
    if (KNOWN_DOCUMENT_EXTENSIONS.has(tail)) {
      const next = current.slice(0, lastDot).replace(/[.\s]+$/g, '');
      if (!next) break;
      current = next;
    } else {
      break;
    }
  }

  return current;
}

/**
 * Produces a filesystem-safe document stem with all chained known extensions stripped.
 * Preserves Unicode characters, spaces, hyphens, underscores, and dots in version numbers.
 */
export function sanitizeDocumentStem(
  rawName: string | null | undefined,
  fallback: string = 'Untitled'
): string {
  const stripped = stripDocumentExtensions(rawName);
  const safe = stripIllegalFileChars(stripped)
    .replace(/\s+/g, ' ')
    .trim()
    .replace(/^\.+|\.+$/g, '')
    .trim();
  return safe || fallback;
}

/**
 * Builds a clean `stem.ext` filename guaranteed to have exactly one clean extension.
 */
export function buildCleanFileName(
  rawName: string | null | undefined,
  extension: string,
  fallback: string = 'Untitled'
): string {
  const stem = sanitizeDocumentStem(rawName, fallback);
  const ext = normalizeExtension(extension);
  return `${stem}${ext}`;
}

/**
 * Extracts the final known extension and clean stem from an opened or saved filename.
 * Collapses accidental chained extensions (e.g. `Hero.ink.png` -> stem `Hero`, ext `.png`, fileName `Hero.png`).
 */
export function normalizeSavedFileName(
  rawFileName: string,
  fallbackExt: string = '.ink'
): { fileName: string; stem: string; extension: string } {
  const base = extractBaseName(rawFileName).trim().replace(/\*+$/g, '').trim();
  const lastDot = base.lastIndexOf('.');
  let ext = '';
  if (lastDot > 0) {
    const candidate = base.slice(lastDot).toLowerCase();
    if (KNOWN_DOCUMENT_EXTENSIONS.has(candidate)) {
      ext = candidate;
    }
  }
  const resolvedExt = ext || (fallbackExt ? normalizeExtension(fallbackExt) : '');
  const stem = sanitizeDocumentStem(base, 'Untitled');
  return {
    fileName: resolvedExt ? `${stem}${resolvedExt}` : stem,
    stem,
    extension: resolvedExt,
  };
}

/**
 * Returns the parent directory of a native filesystem path, or `undefined` if none.
 */
export function getParentDirectory(filePath: string | null | undefined): string | undefined {
  if (!filePath || typeof filePath !== 'string') return undefined;
  const trimmed = filePath.trim();
  if (!trimmed) return undefined;
  const lastBack = trimmed.lastIndexOf('\\');
  const lastFwd = trimmed.lastIndexOf('/');
  const idx = Math.max(lastBack, lastFwd);
  if (idx <= 0) return undefined;
  // Preserve Windows drive root `C:\`
  if (idx === 2 && /^[a-zA-Z]:/.test(trimmed)) {
    return trimmed.slice(0, 3);
  }
  return trimmed.slice(0, idx);
}