Skip to content

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

15.4 KB
Raw Blame
import React, { useEffect, useState } from 'react';
import {
  RotateCcw,
  Trash2,
  AlertTriangle,
  FileText,
  Layers,
  Loader2,
  X,
} from 'lucide-react';
import { CrashedSessionInfo } from '../services/recoveryService';
import { isImeComposing, useI18n } from '../i18n';

interface CrashRecoveryModalProps {
  isOpen: boolean;
  sessions: CrashedSessionInfo[];
  onRestore: (session: CrashedSessionInfo) => Promise<void>;
  onDiscard: (session: CrashedSessionInfo) => Promise<void>;
  onDiscardAll: (sessions: CrashedSessionInfo[]) => Promise<void>;
  onClose?: () => void;
}

interface ParsedSessionManifest {
  documentName?: string;
  width?: number;
  height?: number;
  dpi?: number;
  colorMode?: string;
  layers?: unknown[];
}

function parseSessionManifest(manifestJson?: string | null): ParsedSessionManifest | null {
  if (!manifestJson) return null;
  try {
    return JSON.parse(manifestJson) as ParsedSessionManifest;
  } catch {
    return null;
  }
}

export const CrashRecoveryModal: React.FC<CrashRecoveryModalProps> = ({
  isOpen,
  sessions,
  onRestore,
  onDiscard,
  onDiscardAll,
  onClose,
}) => {
  const { t, td, formatDateTime } = useI18n();
  const [selectedIndex, setSelectedIndex] = useState<number>(0);
  const [isRestoring, setIsRestoring] = useState<boolean>(false);
  const [isDiscarding, setIsDiscarding] = useState<boolean>(false);
  const [isDiscardingAll, setIsDiscardingAll] = useState<boolean>(false);

  const isBusy = isRestoring || isDiscarding || isDiscardingAll;

  useEffect(() => {
    if (sessions.length > 0 && selectedIndex >= sessions.length) {
      setSelectedIndex(sessions.length - 1);
    }
  }, [sessions.length, selectedIndex]);

  useEffect(() => {
    if (!isOpen || !onClose) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (isImeComposing(e)) return;
      if (e.key === 'Escape' && !isBusy) {
        e.preventDefault();
        e.stopPropagation();
        onClose();
      }
    };
    window.addEventListener('keydown', handleKeyDown, true);
    return () => window.removeEventListener('keydown', handleKeyDown, true);
  }, [isOpen, isBusy, onClose]);

  if (!isOpen || sessions.length === 0) return null;

  const safeIndex = Math.min(selectedIndex, sessions.length - 1);
  const currentSession = sessions[safeIndex] || sessions[0];
  const manifestData = parseSessionManifest(currentSession.manifest_json);

  const documentName = manifestData?.documentName || t('Untitled Document');
  const width = manifestData?.width || 3000;
  const height = manifestData?.height || 3000;
  const dpi = manifestData?.dpi || 600;
  const colorMode = manifestData?.colorMode || 'color';
  const layerCount = manifestData?.layers?.length || 1;

  const crashDate = currentSession.timestamp
    ? formatDateTime(currentSession.timestamp, {
        dateStyle: 'medium',
        timeStyle: 'medium',
      })
    : t('Unknown');

  const handleRestoreClick = async () => {
    if (isBusy) return;
    setIsRestoring(true);
    try {
      await onRestore(currentSession);
    } finally {
      setIsRestoring(false);
    }
  };

  const handleDiscardClick = async () => {
    if (isBusy) return;
    setIsDiscarding(true);
    try {
      await onDiscard(currentSession);
    } finally {
      setIsDiscarding(false);
    }
  };

  const handleDiscardAllClick = async () => {
    if (isBusy) return;
    setIsDiscardingAll(true);
    try {
      await onDiscardAll(sessions);
    } finally {
      setIsDiscardingAll(false);
    }
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="crash-recovery-title"
      className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-4 select-none"
    >
      <div className="bg-ui-panel rounded-ui-lg shadow-ui-popover border border-ui-default w-full max-w-[660px] flex flex-col overflow-hidden text-xs text-ui-primary">
        {/* Header Bar */}
        <div className="h-10 px-4 flex items-center justify-between gap-3 bg-ui-header border-b border-ui-subtle shrink-0">
          <div className="flex items-center gap-2 min-w-0">
            <AlertTriangle className="w-3.5 h-3.5 text-ui-warning shrink-0" />
            <h2
              id="crash-recovery-title"
              className="text-xs font-medium text-ui-primary truncate"
            >
              {t('Restore Unsaved Session')}
            </h2>
            <span className="inline-flex items-center gap-1.5 font-ui-mono text-[10px] px-1.5 py-0.5 rounded-ui-xs bg-ui-panel border border-ui-subtle text-ui-secondary shrink-0">
              <span className="w-1.5 h-1.5 rounded-full bg-ui-accent" />
              {t('WAL Protected')}
            </span>
          </div>

          <div className="flex items-center gap-2 shrink-0">
            {sessions.length > 1 && (
              <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted bg-ui-control px-1.5 py-0.5 rounded-ui-xs">
                {safeIndex + 1} / {sessions.length}
              </span>
            )}
            {onClose && !isBusy && (
              <button
                type="button"
                onClick={onClose}
                aria-label={t('Close recovery dialog')}
                title={t('Close (Esc)')}
                className="w-6 h-6 rounded-ui-sm flex items-center justify-center text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
              >
                <X className="w-3.5 h-3.5" />
              </button>
            )}
          </div>
        </div>

        {/* Multiple Sessions Selector */}
        {sessions.length > 1 && (
          <div className="px-4 py-2 bg-ui-header border-b border-ui-subtle flex items-center gap-3 overflow-x-auto no-scrollbar shrink-0">
            <span className="text-[10px] text-ui-muted font-medium uppercase tracking-wider shrink-0">
              {t('Sessions')}
            </span>
            <div className="inline-flex items-center gap-0.5 bg-ui-input p-0.5 rounded-ui-sm border border-ui-subtle">
              {sessions.map((s, idx) => {
                const isActive = idx === safeIndex;
                const sessionManifest = parseSessionManifest(s.manifest_json);
                const sessionTitle =
                  sessionManifest?.documentName || t('Session {n}', { n: idx + 1 });
                return (
                  <button
                    key={s.session_id}
                    type="button"
                    disabled={isBusy}
                    title={sessionTitle}
                    onClick={() => setSelectedIndex(idx)}
                    className={`px-2.5 py-1 rounded-ui-xs text-[11px] tabular-nums transition-colors cursor-pointer shrink-0 inline-flex items-center gap-1.5 disabled:opacity-50 ${
                      isActive
                        ? 'bg-ui-control-active text-ui-primary font-medium'
                        : 'text-ui-muted hover:text-ui-primary'
                    }`}
                  >
                    {isActive && (
                      <span className="w-1.5 h-1.5 rounded-full bg-ui-accent shrink-0" />
                    )}
                    <span>{t('Session {n}', { n: idx + 1 })}</span>
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {/* Modal Main Content */}
        <div className="p-5 space-y-4 bg-ui-panel">
          <p className="text-[11px] text-ui-muted leading-relaxed">
            {t('Ink Studio detected an unexpected shutdown. Your progress can be restored from the recovery journal below.')}
          </p>

          {/* Document Preview & Metadata Grid */}
          <div className="grid grid-cols-1 md:grid-cols-12 gap-4 items-stretch">
            {/* Visual Thumbnail Preview (5 cols) */}
            <div className="md:col-span-5 flex flex-col">
              <div
                className="w-full aspect-square bg-ui-void border border-ui-subtle rounded-ui-md overflow-hidden relative flex items-center justify-center"
                style={
                  currentSession.thumbnail_data_url
                    ? {
                        backgroundImage:
                          'conic-gradient(var(--ui-bg-panel) 90deg, var(--ui-bg-void) 90deg 180deg, var(--ui-bg-panel) 180deg 270deg, var(--ui-bg-void) 270deg)',
                        backgroundSize: '12px 12px',
                      }
                    : undefined
                }
              >
                {currentSession.thumbnail_data_url ? (
                  <img
                    src={currentSession.thumbnail_data_url}
                    alt={t('Document preview')}
                    className="w-full h-full object-contain p-1.5"
                  />
                ) : (
                  <div className="flex flex-col items-center justify-center p-4 text-center">
                    <Layers className="w-8 h-8 mb-2 text-ui-disabled" />
                    <span className="text-[11px] font-medium text-ui-secondary">
                      {t('No Snapshot Preview')}
                    </span>
                    <span className="text-[10px] text-ui-muted mt-0.5">
                      {t('WAL journal entries intact')}
                    </span>
                  </div>
                )}
                <div className="absolute bottom-2 left-2 bg-ui-floating border border-ui-default px-1.5 py-0.5 rounded-ui-xs text-[10px] font-ui-mono tabular-nums text-ui-primary">
                  {width} × {height}
                </div>
              </div>
            </div>

            {/* Metadata Fields (7 cols) */}
            <div className="md:col-span-7 flex flex-col justify-between gap-3 min-w-0">
              <div className="min-w-0">
                <div className="flex items-center gap-2 min-w-0">
                  <FileText className="w-3.5 h-3.5 text-ui-accent shrink-0" />
                  <h3
                    className="text-sm font-semibold text-ui-primary truncate"
                    title={documentName}
                  >
                    {documentName}
                  </h3>
                </div>
                <p
                  className="text-[10px] text-ui-muted font-ui-mono mt-0.5 truncate select-text"
                  title={currentSession.session_id}
                >
                  ID: {currentSession.session_id}
                </p>
              </div>

              <div className="grid grid-cols-2 gap-1.5">
                <div className="bg-ui-header border border-ui-subtle rounded-ui-sm px-2.5 py-2">
                  <span className="text-[10px] text-ui-muted block">{t('Canvas Size')}</span>
                  <span className="text-xs font-medium font-ui-mono tabular-nums text-ui-primary">
                    {width} × {height}
                  </span>
                </div>

                <div className="bg-ui-header border border-ui-subtle rounded-ui-sm px-2.5 py-2">
                  <span className="text-[10px] text-ui-muted block">{t('Resolution')}</span>
                  <span className="text-xs font-medium font-ui-mono tabular-nums text-ui-primary">{dpi} DPI</span>
                </div>

                <div className="bg-ui-header border border-ui-subtle rounded-ui-sm px-2.5 py-2">
                  <span className="text-[10px] text-ui-muted block">{t('Layer Tree')}</span>
                  <span className="text-xs font-medium tabular-nums text-ui-primary">
                    {layerCount === 1
                      ? t('{n} Layer', { n: layerCount })
                      : t('{n} Layers', { n: layerCount })}
                  </span>
                </div>

                <div className="bg-ui-header border border-ui-subtle rounded-ui-sm px-2.5 py-2">
                  <span className="text-[10px] text-ui-muted block">{t('Color Mode')}</span>
                  <span className="text-xs font-medium text-ui-primary capitalize">
                    {td(colorMode, 'colorMode')}
                  </span>
                </div>
              </div>

              {/* Timestamp & Process Info */}
              <div className="bg-ui-header rounded-ui-sm border border-ui-subtle divide-y divide-ui-subtle text-[11px]">
                <div className="px-2.5 py-1.5 flex items-center justify-between gap-2">
                  <span className="text-ui-muted">{t('Terminated At')}</span>
                  <span className="text-ui-primary font-ui-mono tabular-nums">{crashDate}</span>
                </div>
                <div className="px-2.5 py-1.5 flex items-center justify-between gap-2">
                  <span className="text-ui-muted">{t('Previous PID')}</span>
                  <span className="text-ui-secondary font-ui-mono tabular-nums">{currentSession.pid}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Modal Action Footer */}
        <div className="px-4 py-2.5 bg-ui-header border-t border-ui-subtle flex items-center justify-between gap-2 flex-wrap shrink-0">
          <div className="flex items-center gap-2 flex-wrap">
            <button
              type="button"
              disabled={isBusy}
              onClick={handleDiscardClick}
              className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-ui-sm text-xs font-medium bg-ui-control hover:bg-ui-danger/15 border border-ui-default hover:border-ui-danger/40 text-ui-danger transition-colors disabled:opacity-50 cursor-pointer"
            >
              {isDiscarding ? (
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
              ) : (
                <Trash2 className="w-3.5 h-3.5" />
              )}
              <span>{isDiscarding ? t('Discarding...') : t('Discard & Start Fresh')}</span>
            </button>

            <button
              type="button"
              disabled={isBusy}
              onClick={handleDiscardAllClick}
              data-testid="discard-all-sessions-btn"
              title={
                sessions.length > 1
                  ? t('Permanently discard all {count} unsaved sessions', { count: sessions.length })
                  : t('Permanently discard all unsaved sessions')
              }
              className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-ui-sm text-xs font-medium bg-ui-danger/15 hover:bg-ui-danger/25 border border-ui-danger/40 hover:border-ui-danger/60 text-ui-danger transition-colors disabled:opacity-50 cursor-pointer"
            >
              {isDiscardingAll ? (
                <Loader2 className="w-3.5 h-3.5 animate-spin" />
              ) : (
                <Trash2 className="w-3.5 h-3.5" />
              )}
              <span>
                {isDiscardingAll
                  ? t('Discarding All...')
                  : sessions.length > 1
                    ? t('Discard All Sessions ({count})', { count: sessions.length })
                    : t('Discard All Sessions')}
              </span>
            </button>
          </div>

          <button
            type="button"
            autoFocus
            disabled={isBusy}
            onClick={handleRestoreClick}
            className="inline-flex items-center gap-1.5 px-4 py-1.5 rounded-ui-sm text-xs font-medium bg-ui-accent text-ui-accent-contrast hover:opacity-90 disabled:opacity-50 transition-opacity cursor-pointer shrink-0"
          >
            {isRestoring ? (
              <Loader2 className="w-3.5 h-3.5 animate-spin" />
            ) : (
              <RotateCcw className="w-3.5 h-3.5" />
            )}
            <span>{isRestoring ? t('Restoring Canvas...') : t('Restore Session')}</span>
          </button>
        </div>
      </div>
    </div>
  );
};