Skip to content

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

4.0 KB
Raw Blame
import { StirlingFileStub, FileId } from "@editor/types/fileContext";
import { fileStorage } from "@editor/services/fileStorage";
import {
  DiskUnavailableReason,
  desktopFileLinkingSupported,
  getDiskFileState,
} from "@editor/services/desktopFileLink";
import {
  detachedFields,
  diskAvailabilityFields,
} from "@editor/services/diskFileSync";
import type {
  DetachedOpenFile,
  PruneOptions,
} from "@editor-core/services/pruneMissingRecentFiles";

export type { DetachedOpenFile, PruneOptions };

/** Reconciles the file list against disk so a file deleted outside the app never shows as available;
 *  the open path re-checks for the delete-after-draw race. No-op off desktop. */

/** True for real local IndexedDB records; ephemeral `server-`/`shared-` stubs have no disk link. */
export function hasLocalRecord(stub: StirlingFileStub): boolean {
  return !stub.id.startsWith("server-") && !stub.id.startsWith("shared-");
}

/** Unedited v1 holds the same bytes as disk, so losing it loses nothing unique.
 *  Non-leaf is excluded: it is the version-history root "revert to original" needs. */
export function isPristineLocalPassthrough(stub: StirlingFileStub): boolean {
  return (
    !stub.isDirty &&
    stub.isLeaf !== false &&
    (stub.versionNumber ?? 1) === 1 &&
    (stub.toolHistory?.length ?? 0) === 0
  );
}

/** Local-only stubs with a dead `localFilePath`: pristine passthroughs are deleted, the rest are
 *  detached (old path kept for the UI). Server-backed skipped - the server may hold the only copy. */
export async function pruneMissingRecentFiles(
  stubs: StirlingFileStub[],
  options: PruneOptions = {},
): Promise<StirlingFileStub[]> {
  if (!desktopFileLinkingSupported) return stubs;

  const linked = stubs.filter(
    (stub) =>
      stub.localFilePath && !stub.remoteStorageId && hasLocalRecord(stub),
  );
  if (linked.length === 0) return stubs;

  const states = await Promise.all(
    linked.map((stub) => getDiskFileState(stub.localFilePath!)),
  );

  const marks = new Map<FileId, DiskUnavailableReason | undefined>(
    linked.map((stub, i) => [
      stub.id,
      diskAvailabilityFields(states[i]).diskUnavailableReason,
    ]),
  );

  const openIds = options.openFileIds;
  const toDelete: FileId[] = [];
  const toDetach: StirlingFileStub[] = [];
  const detachedOpen: DetachedOpenFile[] = [];
  linked.forEach((stub, i) => {
    if (states[i].availability !== "gone") return;
    if (openIds?.has(stub.id)) {
      toDetach.push(stub);
      detachedOpen.push({
        id: stub.id,
        name: stub.name,
        path: stub.localFilePath!,
      });
    } else if (isPristineLocalPassthrough(stub)) {
      toDelete.push(stub.id);
    } else {
      toDetach.push(stub);
    }
  });

  if (detachedOpen.length > 0) {
    options.onOpenFilesDetached?.(detachedOpen);
  }

  const remarked = linked.some(
    (stub) => marks.get(stub.id) !== stub.diskUnavailableReason,
  );
  if (toDelete.length === 0 && toDetach.length === 0 && !remarked) return stubs;

  if (toDelete.length > 0) {
    try {
      await fileStorage.deleteMultipleStirlingFiles(toDelete);
    } catch (error) {
      console.error("[pruneMissingRecentFiles] delete failed:", error);
    }
  }
  if (toDetach.length > 0) {
    await Promise.all(
      toDetach.map((stub) =>
        fileStorage
          .updateFileMetadata(stub.id, detachedFields(stub.localFilePath))
          .catch((error) =>
            console.error("[pruneMissingRecentFiles] detach failed:", error),
          ),
      ),
    );
  }

  const deleteSet = new Set<FileId>(toDelete);
  const detachSet = new Map<FileId, string | undefined>(
    toDetach.map((stub) => [stub.id, stub.localFilePath]),
  );
  return stubs
    .filter((stub) => !deleteSet.has(stub.id))
    .map((stub) => {
      if (detachSet.has(stub.id)) {
        return { ...stub, ...detachedFields(detachSet.get(stub.id)) };
      }
      if (!marks.has(stub.id)) return stub;
      const mark = marks.get(stub.id);
      if (mark === stub.diskUnavailableReason) return stub;
      return { ...stub, diskUnavailableReason: mark };
    });
}