Skip to content

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

17.2 KB
Raw Blame
import React, { useEffect, useState } from 'react';
import {
  AlertTriangle,
  ArrowDownToLine,
  ArrowRight,
  CheckCircle2,
  Loader2,
  RefreshCw,
  Save,
  X,
} from 'lucide-react';
import { isTauriEnvironment } from '../hooks/useMultiplayer';
import { updaterService } from '../services/updaterService';
import { useDocumentStore } from '../stores/useDocumentStore';
import { useUpdaterStore } from '../stores/useUpdaterStore';
import {
  hasStructuredChangelogMarkdown,
  parseChangelogSections,
} from '../utils/changelog';
import { ChangelogBox } from './ChangelogBox';
import { isImeComposing, useI18n } from '../i18n';

export interface UpdateModalProps {
  hasActiveCollabSession: boolean;
  onSaveFirst?: () => void;
}

function formatMegabytes(bytes: number): string {
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

export const UpdateModal: React.FC<UpdateModalProps> = ({
  hasActiveCollabSession,
  onSaveFirst,
}) => {
  const { t, formatDate } = useI18n();
  const isModalOpen = useUpdaterStore((s) => s.isModalOpen);
  const status = useUpdaterStore((s) => s.status);
  const currentVersion = useUpdaterStore((s) => s.currentVersion);
  const availableVersion = useUpdaterStore((s) => s.availableVersion);
  const releaseDate = useUpdaterStore((s) => s.releaseDate);
  const releaseNotes = useUpdaterStore((s) => s.releaseNotes);
  const downloadedBytes = useUpdaterStore((s) => s.downloadedBytes);
  const totalBytes = useUpdaterStore((s) => s.totalBytes);
  const progressPercent = useUpdaterStore((s) => s.progressPercent);
  const errorMessage = useUpdaterStore((s) => s.errorMessage);

  const hasUnsavedChanges = useDocumentStore((s) => s.documents.some((d) => d.isDirty));
  const [confirmingGuard, setConfirmingGuard] = useState(false);

  useEffect(() => {
    if (!isModalOpen || status !== 'available') {
      setConfirmingGuard(false);
    }
  }, [isModalOpen, status]);

  if (!isTauriEnvironment() || !isModalOpen) {
    return null;
  }

  const isBusy = status === 'downloading' || status === 'ready';
  const hasSafetyRisk = hasUnsavedChanges || hasActiveCollabSession;
  const formattedDate = releaseDate
    ? formatDate(releaseDate, { year: 'numeric', month: 'short', day: 'numeric' })
    : null;

  const handleClose = () => {
    if (isBusy) return;
    setConfirmingGuard(false);
    updaterService.closeUpdateModal();
  };

  const handleInstallClick = () => {
    const dirtyNow = useDocumentStore.getState().documents.some((d) => d.isDirty);
    if ((dirtyNow || hasActiveCollabSession) && !confirmingGuard) {
      setConfirmingGuard(true);
      return;
    }
    setConfirmingGuard(false);
    void updaterService.downloadAndInstallUpdate();
  };

  const handleSaveFirst = () => {
    setConfirmingGuard(false);
    updaterService.closeUpdateModal();
    onSaveFirst?.();
  };

  const handleLater = () => {
    if (isBusy) return;
    setConfirmingGuard(false);
    updaterService.dismissBanner();
    updaterService.closeUpdateModal();
  };

  const handleSkipVersion = () => {
    if (isBusy) return;
    setConfirmingGuard(false);
    updaterService.skipAvailableVersion();
  };

  const safetyWarningMessage =
    hasUnsavedChanges && hasActiveCollabSession
      ? t(
          'You have unsaved changes and an active multiplayer session — save your work before installing, because Ink Studio will restart.'
        )
      : hasUnsavedChanges
        ? t(
            'You have unsaved changes — save your work before installing, because Ink Studio will restart.'
          )
        : t(
            'You have an active multiplayer session — save your work before installing, because Ink Studio will restart.'
          );

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="update-modal-title"
      className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-4 select-none"
      onClick={handleClose}
      onKeyDown={(e) => {
        if (isImeComposing(e)) return;
        if (e.key === 'Escape' && !isBusy) {
          handleClose();
        }
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="bg-ui-panel rounded-ui-lg shadow-ui-popover w-full max-w-lg flex flex-col overflow-hidden text-xs text-ui-primary border border-ui-default"
      >
        {/* Header */}
        <div className="h-10 px-4 flex items-center justify-between bg-ui-header border-b border-ui-subtle shrink-0">
          <div className="flex items-center gap-2">
            <ArrowDownToLine className="w-3.5 h-3.5 text-ui-accent" />
            <span id="update-modal-title" className="text-xs font-medium text-ui-primary">
              {t('Software Update')}
            </span>
          </div>
          {!isBusy && (
            <button
              type="button"
              onClick={handleClose}
              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"
              title={t('Close (Esc)')}
              aria-label={t('Close update modal')}
            >
              <X className="w-3.5 h-3.5" />
            </button>
          )}
        </div>

        {/* Body */}
        <div className="p-5 space-y-4">
          {status === 'checking' && (
            <div className="py-8 flex flex-col items-center justify-center gap-3 text-center">
              <Loader2 className="w-6 h-6 text-ui-accent animate-spin" />
              <div className="space-y-1">
                <div className="text-xs font-medium text-ui-primary">
                  {t('Checking for updates...')}
                </div>
                <div className="text-[11px] text-ui-muted font-ui-mono tabular-nums">
                  {t('Current version: v{version}', { version: currentVersion })}
                </div>
              </div>
            </div>
          )}

          {status === 'up-to-date' && (
            <div className="py-6 flex flex-col items-center justify-center gap-3 text-center">
              <div className="w-10 h-10 rounded-full bg-ui-header border border-ui-subtle flex items-center justify-center text-ui-success">
                <CheckCircle2 className="w-5 h-5" />
              </div>
              <div className="space-y-1">
                <div className="text-xs font-medium text-ui-primary">
                  {t('Ink Studio is up to date')}
                </div>
                <div className="text-[11px] text-ui-muted font-ui-mono tabular-nums">
                  {t('v{version} is the latest available version.', { version: currentVersion })}
                </div>
              </div>
            </div>
          )}

          {status === 'error' && (
            <div className="space-y-3">
              <div className="p-3.5 rounded-ui-md bg-ui-danger/10 border border-ui-danger/35 flex items-start gap-2.5">
                <AlertTriangle className="w-4 h-4 text-ui-danger shrink-0 mt-0.5" />
                <div className="space-y-1 min-w-0">
                  <div className="text-xs font-medium text-ui-primary">
                    {t('Update check failed')}
                  </div>
                  <div className="text-[11px] text-ui-muted break-words">
                    {errorMessage || t('Unable to reach the update server.')}
                  </div>
                </div>
              </div>
            </div>
          )}

          {status === 'idle' && (
            <div className="py-6 flex flex-col items-center justify-center gap-2 text-center">
              <div className="text-xs font-medium text-ui-primary">
                {t('Check for Ink Studio updates')}
              </div>
              <div className="text-[11px] text-ui-muted font-ui-mono tabular-nums">
                {t('Installed version: v{version}', { version: currentVersion })}
              </div>
            </div>
          )}

          {(status === 'available' || status === 'downloading' || status === 'ready') && (
            <>
              {/* Version comparison card */}
              <div className="p-3.5 rounded-ui-md bg-ui-header border border-ui-subtle flex items-center justify-between gap-3">
                <div className="space-y-0.5">
                  <div className="text-[10px] uppercase tracking-wider text-ui-muted">
                    {t('Version Update')}
                  </div>
                  <div className="flex items-center gap-2 font-ui-mono tabular-nums text-xs">
                    <span className="text-ui-muted">v{currentVersion}</span>
                    <ArrowRight className="w-3.5 h-3.5 text-ui-accent" />
                    <span className="text-ui-primary font-semibold">
                      v{availableVersion}
                    </span>
                  </div>
                </div>
                {formattedDate && (
                  <span className="text-[10px] text-ui-muted font-ui-mono tabular-nums shrink-0">
                    {formattedDate}
                  </span>
                )}
              </div>

              {/* Scrollable release notes (structured Markdown or plain-text fallback) */}
              <div className="space-y-1.5">
                <div className="text-[11px] font-medium text-ui-primary">{t('Release Notes')}</div>
                {(() => {
                  const rawNotes = releaseNotes?.trim() || '';
                  if (rawNotes && hasStructuredChangelogMarkdown(rawNotes)) {
                    const sections = parseChangelogSections(rawNotes);
                    if (sections.length > 0) {
                      return (
                        <ChangelogBox
                          entry={{
                            version: availableVersion || '',
                            sections,
                            rawBody: rawNotes,
                          }}
                          maxHeightClass="max-h-48"
                        />
                      );
                    }
                  }
                  return (
                    <div className="bg-ui-header rounded-ui-md p-3 max-h-44 overflow-y-auto border border-ui-subtle select-text">
                      <pre className="whitespace-pre-wrap break-words font-ui-sans text-[11px] leading-relaxed text-ui-secondary">
                        {rawNotes || t('Bug fixes and performance improvements.')}
                      </pre>
                    </div>
                  );
                })()}
              </div>

              {/* Download progress bar */}
              {(status === 'downloading' || status === 'ready') && (
                <div className="space-y-1.5 bg-ui-header rounded-ui-md p-3 border border-ui-subtle">
                  <div className="flex items-center justify-between text-[11px]">
                    <span className="text-ui-primary font-medium flex items-center gap-1.5">
                      <Loader2 className="w-3.5 h-3.5 text-ui-accent animate-spin" />
                      {status === 'ready'
                        ? t('Installing update & restarting...')
                        : t('Downloading update...')}
                    </span>
                    <span className="font-ui-mono tabular-nums text-ui-muted">
                      {totalBytes
                        ? `${formatMegabytes(downloadedBytes)} / ${formatMegabytes(totalBytes)} (${progressPercent}%)`
                        : downloadedBytes > 0
                        ? formatMegabytes(downloadedBytes)
                        : `${progressPercent}%`}
                    </span>
                  </div>
                  <div className="w-full h-1.5 rounded-full bg-ui-control overflow-hidden">
                    <div
                      className="h-full bg-ui-accent transition-all duration-150"
                      style={{ width: `${Math.max(2, Math.min(100, progressPercent))}%` }}
                    />
                  </div>
                </div>
              )}

              {/* Safety warning for unsaved changes or active multiplayer session */}
              {status === 'available' && hasSafetyRisk && (
                <div
                  className={`p-3 rounded-ui-md border flex items-start gap-2.5 ${
                    confirmingGuard
                      ? 'bg-ui-warning/15 border-ui-warning/50'
                      : 'bg-ui-header border-ui-warning/35'
                  }`}
                >
                  <AlertTriangle className="w-4 h-4 text-ui-warning shrink-0 mt-0.5" />
                  <div className="space-y-1 text-[11px]">
                    <div className="font-medium text-ui-warning">
                      {confirmingGuard
                        ? t('Confirm Restart Before Installing')
                        : t('Active Work Detected')}
                    </div>
                    <p className="text-ui-secondary leading-relaxed">
                      {safetyWarningMessage}
                    </p>
                  </div>
                </div>
              )}
            </>
          )}
        </div>

        {/* Footer actions */}
        <div className="px-4 py-2.5 bg-ui-header flex items-center justify-between gap-2 border-t border-ui-subtle">
          {status === 'available' ? (
            confirmingGuard ? (
              <>
                <button
                  type="button"
                  onClick={() => setConfirmingGuard(false)}
                  className="px-2.5 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-secondary hover:text-ui-primary transition-colors cursor-pointer"
                >
                  {t('Back')}
                </button>
                <div className="flex items-center gap-2">
                  {hasUnsavedChanges && onSaveFirst && (
                    <button
                      type="button"
                      onClick={handleSaveFirst}
                      className="flex items-center gap-1.5 px-3 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary font-medium transition-colors cursor-pointer"
                    >
                      <Save className="w-3.5 h-3.5" />
                      <span>{t('Save First')}</span>
                    </button>
                  )}
                  <button
                    type="button"
                    onClick={handleInstallClick}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-ui-sm bg-ui-warning/20 hover:bg-ui-warning/30 border border-ui-warning/50 text-ui-warning font-semibold transition-colors cursor-pointer"
                  >
                    <ArrowDownToLine className="w-3.5 h-3.5" />
                    <span>{t('Install & Restart Anyway')}</span>
                  </button>
                </div>
              </>
            ) : (
              <>
                <button
                  type="button"
                  onClick={handleSkipVersion}
                  className="px-2.5 py-1.5 rounded-ui-sm text-[11px] text-ui-muted hover:text-ui-primary hover:bg-ui-control-hover transition-colors cursor-pointer"
                >
                  {t('Skip This Version')}
                </button>
                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={handleLater}
                    className="px-3 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary transition-colors cursor-pointer"
                  >
                    {t('Later')}
                  </button>
                  <button
                    type="button"
                    onClick={handleInstallClick}
                    className="flex items-center gap-1.5 px-3.5 py-1.5 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 font-medium transition-opacity cursor-pointer"
                  >
                    <ArrowDownToLine className="w-3.5 h-3.5" />
                    <span>{t('Download & Install')}</span>
                  </button>
                </div>
              </>
            )
          ) : status === 'downloading' || status === 'ready' ? (
            <div className="w-full text-right text-[11px] text-ui-muted">
              {t('Please keep Ink Studio open until the update completes.')}
            </div>
          ) : (
            <>
              <div />
              <div className="flex items-center gap-2">
                {(status === 'error' || status === 'up-to-date' || status === 'idle') && (
                  <button
                    type="button"
                    onClick={() => void updaterService.checkForUpdates({ silent: false })}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary transition-colors cursor-pointer"
                  >
                    <RefreshCw className="w-3 h-3" />
                    <span>{status === 'error' ? t('Retry') : t('Check Again')}</span>
                  </button>
                )}
                <button
                  type="button"
                  onClick={handleClose}
                  className="px-3.5 py-1.5 rounded-ui-sm bg-ui-accent text-ui-accent-contrast hover:opacity-90 font-medium transition-opacity cursor-pointer"
                >
                  {t('Close')}
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );
};