Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

6.6 KB
Raw Blame
import {
  TOOL_FORMATS,
  TOOL_FORMAT_EXTENSIONS,
  type ToolFormat,
} from "@editor/types/toolIO";
import type { StirlingFileStub } from "@editor/types/fileContext";

/**
 * Consolidated file size formatting utility
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}

export function readFileAsDataUrl(file: Blob): Promise<string> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      if (typeof reader.result === "string") resolve(reader.result);
      else reject(new Error("File could not be read as a data URL"));
    };
    reader.onerror = () => reject(reader.error);
    reader.readAsDataURL(file);
  });
}

/**
 * Get file date as string
 */
export function getFileDate(file: File | { lastModified: number }): string {
  if (file.lastModified) {
    return new Date(file.lastModified).toLocaleString();
  }
  return "Unknown";
}

/**
 * Get file size as string (legacy method for backward compatibility)
 */
export function getFileSize(file: File | { size: number }): string {
  if (!file.size) return "Unknown";
  return formatFileSize(file.size);
}

/**
 * Detects and normalizes file extension from filename
 * @param filename - The filename to extract extension from
 * @returns Normalized file extension in lowercase, empty string if no extension
 */
export function detectFileExtension(filename: string): string {
  if (!filename || typeof filename !== "string") return "";

  const parts = filename.split(".");
  // If there's no extension (no dots or only one part), return empty string
  if (parts.length <= 1) return "";

  // Get the last part (extension) in lowercase
  let extension = parts[parts.length - 1].toLowerCase();

  // Normalize common extension variants
  if (extension === "jpeg") extension = "jpg";

  return extension;
}

/**
 * Removes the file extension from a filename
 * @param filename - The filename to process
 * @param options - Options for processing
 * @param options.preserveCase - If true, preserves original case. If false (default), converts to lowercase
 * @returns Filename without extension
 * @example
 * getFilenameWithoutExtension('document.pdf') // 'document'
 * getFilenameWithoutExtension('my.file.name.txt') // 'my.file.name'
 * getFilenameWithoutExtension('REPORT.PDF', { preserveCase: true }) // 'REPORT'
 */
export function getFilenameWithoutExtension(
  filename: string,
  options: { preserveCase?: boolean } = {},
): string {
  if (!filename || typeof filename !== "string") return "";

  const { preserveCase = false } = options;
  const withoutExtension = filename.replace(/\.[^.]+$/, "");

  return preserveCase ? withoutExtension : withoutExtension.toLowerCase();
}

/**
 * Splits a filename into its base and extension, keeping the dot on the
 * extension so `base + extension` round-trips. A name with no extension (or a
 * leading-dot name like ".env") gets an empty extension.
 * @example splitFileName('report.pdf') // ['report', '.pdf']
 */
export function splitFileName(name: string): [string, string] {
  const dot = name.lastIndexOf(".");
  return dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ""];
}

/** Characters Windows/macOS reject in a filename, which is also what a download saves as. */
export const ILLEGAL_FILE_NAME_CHARS = /[\\/:*?"<>|]/;

/**
 * Checks if a file is a PDF based on extension and MIME type
 * @param file - File or file-like object with name and type properties
 * @returns true if the file appears to be a PDF
 */
export function isPdfFile(
  file: { name?: string; type?: string } | File | Blob | null | undefined,
): boolean {
  if (!file) return false;

  const name = "name" in file ? file.name : undefined;
  const type = file.type;

  // Check MIME type first (most reliable)
  if (type === "application/pdf") return true;

  // Check file extension as fallback
  if (name) {
    const ext = detectFileExtension(name);
    if (ext === "pdf") return true;
  }

  return false;
}

/**
 * Uses FileContext's detected password protection when present; no file bytes are read.
 * Multiple categories can match (for example DOCX is both WORD and EBOOK); unknown files match none.
 */
export function getFileFormats(
  file: Pick<StirlingFileStub, "name" | "type" | "processedFile">,
): ToolFormat[] {
  if (file.processedFile?.isEncrypted) return ["PDF_ENCRYPTED"];
  if (isPdfFile(file)) return ["PDF"];
  const extension = detectFileExtension(file.name);
  return TOOL_FORMATS.filter((format) => {
    const extensions: readonly string[] = TOOL_FORMAT_EXTENSIONS[format];
    return extensions.includes(extension);
  });
}

export type NonPdfFileType =
  | "image"
  | "csv"
  | "json"
  | "text"
  | "markdown"
  | "html"
  | "unknown";

export const IMAGE_EXTENSIONS = new Set([
  "png",
  "jpg",
  "jpeg",
  "gif",
  "bmp",
  "svg",
  "tiff",
  "tif",
  "webp",
]);
const CSV_EXTENSIONS = new Set(["csv", "tsv"]);
const JSON_EXTENSIONS = new Set(["json"]);
const TEXT_EXTENSIONS = new Set(["txt"]);
const MARKDOWN_EXTENSIONS = new Set(["md", "markdown"]);
const HTML_EXTENSIONS = new Set(["html", "htm"]);

/** All file extensions that the built-in viewer can render. */
export const VIEWER_SUPPORTED_EXTENSIONS: string[] = [
  "pdf",
  ...IMAGE_EXTENSIONS,
  ...CSV_EXTENSIONS,
  ...JSON_EXTENSIONS,
  ...TEXT_EXTENSIONS,
  ...MARKDOWN_EXTENSIONS,
  ...HTML_EXTENSIONS,
];

/**
 * Detects the non-PDF file type category for viewer routing.
 * Returns 'unknown' for PDFs or unrecognized formats.
 */
export function detectNonPdfFileType(
  file: { name?: string; type?: string } | File | null | undefined,
): NonPdfFileType {
  if (!file) return "unknown";

  const name = "name" in file ? file.name : undefined;
  const mimeType = file.type ?? "";

  // Check MIME type first
  if (mimeType.startsWith("image/")) return "image";
  if (mimeType === "text/csv") return "csv";
  if (mimeType === "text/tab-separated-values") return "csv";
  if (mimeType === "application/json") return "json";
  if (mimeType === "text/html") return "html";
  if (mimeType === "text/markdown") return "markdown";

  // Fall back to extension
  if (name) {
    const ext = detectFileExtension(name);
    if (IMAGE_EXTENSIONS.has(ext)) return "image";
    if (CSV_EXTENSIONS.has(ext)) return "csv";
    if (JSON_EXTENSIONS.has(ext)) return "json";
    if (MARKDOWN_EXTENSIONS.has(ext)) return "markdown";
    if (TEXT_EXTENSIONS.has(ext)) return "text";
    if (HTML_EXTENSIONS.has(ext)) return "html";
  }

  return "unknown";
}