Skip to content

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

10.0 KB
Raw Blame
import React, { useEffect, useState } from 'react';
import { X, Loader2 } from 'lucide-react';
import { uiStoreActions } from '../stores';
import {
  exportNativeWebtoonChapterZip,
  saveWebtoonZipWithDialog,
} from '../utils/webtoonExporter';
import { isImeComposing, useI18n } from '../i18n';

interface WebtoonExportModalProps {
  isOpen: boolean;
  onClose: () => void;
  documentId?: string | null;
  canvasWidth: number;
  canvasHeight: number;
  documentTitle?: string;
}

export const WebtoonExportModal: React.FC<WebtoonExportModalProps> = ({
  isOpen,
  onClose,
  documentId = null,
  canvasWidth,
  canvasHeight,
  documentTitle = 'webtoon_chapter',
}) => {
  const { t } = useI18n();
  const [sliceHeight, setSliceHeight] = useState(1280);
  const [format, setFormat] = useState<'jpg' | 'png'>('jpg');
  const [quality, setQuality] = useState(92);
  const [isExporting, setIsExporting] = useState(false);
  const [progress, setProgress] = useState<{ current: number; total: number; percent: number } | null>(null);

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

  if (!isOpen) return null;

  const totalSlices = Math.max(1, Math.ceil(canvasHeight / sliceHeight));

  const handleStartExport = async () => {
    try {
      setIsExporting(true);
      setProgress({ current: 0, total: totalSlices, percent: 0 });

      const sliceOpts = {
        sliceWidth: canvasWidth,
        sliceHeight,
        format,
        quality: quality / 100,
        filePrefix: `${documentTitle.replace(/\s+/g, '_')}_slice_`,
        onProgress: (p: { current: number; total: number; percent: number }) => setProgress(p),
      };
      const zipBytes = await exportNativeWebtoonChapterZip(
        documentId,
        canvasWidth,
        canvasHeight,
        sliceOpts
      );

      const zipName = `${documentTitle.replace(/\s+/g, '_')}_slices.zip`;
      const saveRes = await saveWebtoonZipWithDialog(zipBytes, zipName);
      setIsExporting(false);
      setProgress(null);
      if (saveRes.canceled) {
        return;
      }
      onClose();
    } catch (err) {
      console.error('Webtoon export error:', err);
      setIsExporting(false);
      setProgress(null);
      void uiStoreActions.alertDialog({
        title: t('Webtoon Export Failed'),
        message: t('Failed to export webtoon slices.'),
        detail: err instanceof Error ? err.message : undefined,
      });
    }
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="webtoon-export-modal-title"
      className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-4 select-none"
      onClick={() => {
        if (!isExporting) onClose();
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="w-[460px] max-w-[95vw] bg-ui-panel border border-ui-default rounded-ui-lg shadow-ui-popover overflow-hidden flex flex-col text-ui-primary font-ui-sans"
      >
        {/* Header */}
        <div className="h-10 px-4 bg-ui-header border-b border-ui-subtle flex items-center justify-between">
          <h2 id="webtoon-export-modal-title" className="text-xs font-medium text-ui-primary">
            {t('Webtoon Chapter Slicer')}
          </h2>
          {!isExporting && (
            <button
              type="button"
              onClick={onClose}
              aria-label={t('Close')}
              title={t('Cancel (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>

        {/* Content */}
        <div className="p-4 space-y-4 text-xs">
          <div className="bg-ui-header p-3 rounded-ui-md border border-ui-subtle space-y-1">
            <div className="flex justify-between">
              <span className="text-ui-muted">{t('Canvas Dimensions')}</span>
              <span className="font-ui-mono tabular-nums text-ui-primary">{canvasWidth} × {canvasHeight} px</span>
            </div>
            <div className="flex justify-between">
              <span className="text-ui-muted">{t('Total Slices')}</span>
              <span className="font-ui-mono tabular-nums text-ui-accent font-medium">
                {t('{count} tiles', { count: totalSlices })}
              </span>
            </div>
            <div className="flex justify-between">
              <span className="text-ui-muted">{t('Tile Dimensions')}</span>
              <span className="font-ui-mono tabular-nums text-ui-primary">{canvasWidth} × {sliceHeight} px</span>
            </div>
          </div>

          <div className="space-y-1.5">
            <div className="flex justify-between">
              <label className="text-[11px] text-ui-muted">{t('Slice Tile Height')}</label>
              <span className="font-ui-mono tabular-nums text-ui-primary">{sliceHeight}px</span>
            </div>
            <div className="flex gap-1.5">
              {[800, 1024, 1280, 1920].map((h) => (
                <button
                  key={h}
                  type="button"
                  onClick={() => setSliceHeight(h)}
                  className={`flex-1 py-1 rounded-ui-sm font-ui-mono tabular-nums text-xs border cursor-pointer transition-colors ${
                    sliceHeight === h
                      ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border font-medium'
                      : 'bg-ui-header border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                  }`}
                >
                  {h}px
                </button>
              ))}
            </div>
          </div>

          <div className="space-y-1.5">
            <label className="text-[11px] text-ui-muted">{t('Output Format')}</label>
            <div className="grid grid-cols-2 gap-1.5">
              <button
                type="button"
                onClick={() => setFormat('jpg')}
                className={`py-1.5 rounded-ui-sm text-xs border cursor-pointer transition-colors ${
                  format === 'jpg'
                    ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border font-medium'
                    : 'bg-ui-header border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                {t('JPEG (Standard)')}
              </button>
              <button
                type="button"
                onClick={() => setFormat('png')}
                className={`py-1.5 rounded-ui-sm text-xs border cursor-pointer transition-colors ${
                  format === 'png'
                    ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border font-medium'
                    : 'bg-ui-header border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                {t('PNG (Lossless)')}
              </button>
            </div>
          </div>

          {format === 'jpg' && (
            <div className="space-y-1.5">
              <div className="flex justify-between text-[11px]">
                <span className="text-ui-muted">{t('JPEG Quality')}</span>
                <span className="font-ui-mono tabular-nums text-ui-primary">{quality}%</span>
              </div>
              <input
                type="range"
                min={50}
                max={100}
                value={quality}
                onChange={(e) => setQuality(Number(e.target.value))}
                className="w-full"
              />
            </div>
          )}

          {isExporting && progress && (
            <div className="space-y-2 pt-2 border-t border-ui-subtle">
              <div className="flex justify-between text-[11px]">
                <span className="text-ui-primary flex items-center gap-1.5 tabular-nums">
                  <Loader2 className="w-3.5 h-3.5 animate-spin text-ui-accent" />
                  <span>
                    {t('Slicing tile {current} of {total}...', {
                      current: progress.current,
                      total: progress.total,
                    })}
                  </span>
                </span>
                <span className="font-ui-mono tabular-nums text-ui-primary">{progress.percent}%</span>
              </div>
              <div className="w-full bg-ui-input h-1.5 rounded-full overflow-hidden border border-ui-subtle">
                <div
                  className="bg-ui-accent h-full transition-all duration-150"
                  style={{ width: `${progress.percent}%` }}
                />
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-4 py-2.5 bg-ui-header border-t border-ui-subtle flex items-center justify-end gap-2">
          {!isExporting && (
            <button
              type="button"
              onClick={onClose}
              className="px-3.5 py-1.5 bg-ui-control hover:bg-ui-control-hover border border-ui-default text-ui-primary rounded-ui-sm text-xs font-medium transition-colors cursor-pointer"
            >
              {t('Cancel')}
            </button>
          )}
          <button
            type="button"
            onClick={handleStartExport}
            disabled={isExporting}
            className="px-3.5 py-1.5 rounded-ui-sm text-xs font-medium bg-ui-accent text-ui-accent-contrast hover:opacity-90 transition-opacity cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed tabular-nums"
          >
            {isExporting
              ? t('Packaging ZIP...')
              : t('Export {count} Tiles (.ZIP)', { count: totalSlices })}
          </button>
        </div>
      </div>
    </div>
  );
};