Skip to content

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

20.1 KB
Raw Blame
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { X } from 'lucide-react';
import {
  renderSaturatedLines,
  renderStreamLines,
  SaturatedLinesOptions,
  StreamLinesOptions,
} from '../utils/mangaEffectsEngine';
import { isImeComposing, useI18n } from '../i18n';

interface MangaEffectsModalProps {
  isOpen: boolean;
  onClose: () => void;
  canvasWidth: number;
  canvasHeight: number;
  onApply: (type: 'saturated' | 'stream', options: SaturatedLinesOptions | StreamLinesOptions) => void;
}

export const MangaEffectsModal: React.FC<MangaEffectsModalProps> = ({
  isOpen,
  onClose,
  canvasWidth,
  canvasHeight,
  onApply,
}) => {
  const { t } = useI18n();
  const [activeTab, setActiveTab] = useState<'saturated' | 'stream'>('saturated');

  const safeCanvasWidth = Math.max(1, canvasWidth);
  const safeCanvasHeight = Math.max(1, canvasHeight);
  const previewMaxW = 300;
  const previewMaxH = 360;
  const previewFitScale = Math.min(previewMaxW / safeCanvasWidth, previewMaxH / safeCanvasHeight);
  const previewWidth = Math.max(40, Math.round(safeCanvasWidth * previewFitScale));
  const previewHeight = Math.max(40, Math.round(safeCanvasHeight * previewFitScale));

  const prevDimsRef = useRef<{ w: number; h: number }>({
    w: safeCanvasWidth,
    h: safeCanvasHeight,
  });

  // Saturated Lines State
  const [satOptions, setSatOptions] = useState<SaturatedLinesOptions>({
    centerX: Math.round(safeCanvasWidth * 0.5),
    centerY: Math.round(safeCanvasHeight * 0.5),
    innerRadius: Math.round(Math.min(safeCanvasWidth, safeCanvasHeight) * 0.2),
    density: 120,
    spacingJitter: 0.5,
    lengthJitter: 0.35,
    lineWidth: 4,
    taper: 'in',
    color: '#000000',
  });

  // Stream Lines State
  const [streamOptions, setStreamOptions] = useState<StreamLinesOptions>({
    angle: 0,
    density: 80,
    lineLength: Math.round(Math.min(safeCanvasWidth, safeCanvasHeight) * 0.5),
    lengthNoise: 0.4,
    thickness: 3,
    thicknessNoise: 0.5,
    gapNoise: 0.3,
    color: '#000000',
  });

  // Re-sync default center/radius/length whenever the modal opens on a document with different dimensions
  useEffect(() => {
    if (!isOpen) return;
    if (
      prevDimsRef.current.w !== safeCanvasWidth ||
      prevDimsRef.current.h !== safeCanvasHeight
    ) {
      prevDimsRef.current = { w: safeCanvasWidth, h: safeCanvasHeight };
      setSatOptions((prev) => ({
        ...prev,
        centerX: Math.round(safeCanvasWidth * 0.5),
        centerY: Math.round(safeCanvasHeight * 0.5),
        innerRadius: Math.round(Math.min(safeCanvasWidth, safeCanvasHeight) * 0.2),
      }));
      setStreamOptions((prev) => ({
        ...prev,
        lineLength: Math.round(Math.min(safeCanvasWidth, safeCanvasHeight) * 0.5),
      }));
    }
  }, [isOpen, safeCanvasWidth, safeCanvasHeight]);

  const previewCanvasRef = useRef<HTMLCanvasElement>(null);

  // Re-draw preview canvas whenever parameters change
  const updatePreview = useCallback(() => {
    const canvas = previewCanvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    ctx.clearRect(0, 0, canvas.width, canvas.height);
    // Draw white background
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // Scaling ratio to fit canvas inside preview box
    const scaleX = canvas.width / safeCanvasWidth;
    const scaleY = canvas.height / safeCanvasHeight;
    const strokeScale = Math.max(0.001, Math.min(scaleX, scaleY));

    ctx.save();
    ctx.scale(scaleX, scaleY);

    if (activeTab === 'saturated') {
      renderSaturatedLines(ctx, safeCanvasWidth, safeCanvasHeight, satOptions);

      // Draw faint indicator circle for center cutout
      ctx.strokeStyle = '#38bdf8';
      ctx.lineWidth = 1.5 / strokeScale;
      ctx.setLineDash([4 / strokeScale, 4 / strokeScale]);
      ctx.beginPath();
      ctx.arc(satOptions.centerX, satOptions.centerY, satOptions.innerRadius, 0, Math.PI * 2);
      ctx.stroke();

      // Crosshair at center
      ctx.beginPath();
      ctx.arc(satOptions.centerX, satOptions.centerY, 3 / strokeScale, 0, Math.PI * 2);
      ctx.fillStyle = '#38bdf8';
      ctx.fill();
    } else {
      renderStreamLines(ctx, safeCanvasWidth, safeCanvasHeight, streamOptions);
    }

    ctx.restore();
  }, [activeTab, safeCanvasWidth, safeCanvasHeight, satOptions, streamOptions]);

  useEffect(() => {
    if (isOpen) {
      updatePreview();
    }
  }, [isOpen, updatePreview, previewWidth, previewHeight]);

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

  if (!isOpen) return null;

  // Handle clicking on preview canvas to set focal point for saturated lines
  const handlePreviewClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (activeTab !== 'saturated') return;
    const canvas = previewCanvasRef.current;
    if (!canvas) return;
    const rect = canvas.getBoundingClientRect();
    if (rect.width <= 0 || rect.height <= 0) return;
    const clickX = Math.max(0, Math.min(rect.width, e.clientX - rect.left));
    const clickY = Math.max(0, Math.min(rect.height, e.clientY - rect.top));

    setSatOptions((prev) => ({
      ...prev,
      centerX: Math.round((clickX / rect.width) * safeCanvasWidth),
      centerY: Math.round((clickY / rect.height) * safeCanvasHeight),
    }));
  };

  const handleApplyClick = () => {
    if (activeTab === 'saturated') {
      onApply('saturated', satOptions);
    } else {
      onApply('stream', streamOptions);
    }
    onClose();
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="manga-effects-modal-title"
      className="fixed inset-0 z-50 flex items-center justify-center bg-ui-overlay p-4 select-none"
      onClick={onClose}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        className="w-[680px] 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="manga-effects-modal-title" className="text-xs font-medium text-ui-primary">
            {t('Manga Effect Lines')}
          </h2>
          <button
            type="button"
            onClick={onClose}
            aria-label={t('Close')}
            title={t('Cancel (Esc)')}
            className="w-6 h-6 flex items-center justify-center rounded-ui-sm 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>

        {/* Tab Switcher */}
        <div className="flex border-b border-ui-subtle bg-ui-header px-4">
          <button
            type="button"
            onClick={() => setActiveTab('saturated')}
            className={`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors cursor-pointer ${
              activeTab === 'saturated'
                ? 'border-ui-accent text-ui-primary'
                : 'border-transparent text-ui-muted hover:text-ui-primary'
            }`}
          >
            {t('Saturated Lines (Focus / Burst)')}
          </button>
          <button
            type="button"
            onClick={() => setActiveTab('stream')}
            className={`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors cursor-pointer ${
              activeTab === 'stream'
                ? 'border-ui-accent text-ui-primary'
                : 'border-transparent text-ui-muted hover:text-ui-primary'
            }`}
          >
            {t('Stream Lines (Parallel Speed)')}
          </button>
        </div>

        {/* Body: Left Preview, Right Controls */}
        <div className="p-4 flex space-x-4 max-h-[480px]">
          {/* Interactive Preview Canvas */}
          <div className="flex flex-col items-center">
            <div className="relative border border-ui-default rounded-ui-sm overflow-hidden bg-white">
              <canvas
                ref={previewCanvasRef}
                width={previewWidth}
                height={previewHeight}
                onClick={handlePreviewClick}
                className="cursor-crosshair block"
                title={activeTab === 'saturated' ? t('Click on preview to move focus center') : undefined}
              />
            </div>
            {activeTab === 'saturated' && (
              <span className="text-[10px] text-ui-muted mt-1.5">
                {t('Click preview to reposition focus point')}
              </span>
            )}
          </div>

          {/* Right Parameters Panel */}
          <div className="flex-1 space-y-3 overflow-y-auto pr-1 text-xs">
            {activeTab === 'saturated' ? (
              <>
                <div>
                  <div className="flex justify-between text-[11px] mb-1">
                    <span className="text-ui-muted">{t('Center Cutout Radius')}</span>
                    <span className="font-ui-mono tabular-nums text-ui-primary">{satOptions.innerRadius}px</span>
                  </div>
                  <input
                    type="range"
                    min={10}
                    max={Math.round(Math.min(canvasWidth, canvasHeight) * 0.45)}
                    value={satOptions.innerRadius}
                    onChange={(e) =>
                      setSatOptions((p) => ({ ...p, innerRadius: Number(e.target.value) }))
                    }
                    className="w-full"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] mb-1">
                    <span className="text-ui-muted">{t('Line Density')}</span>
                    <span className="font-ui-mono tabular-nums text-ui-primary">{t('{count} lines', { count: satOptions.density })}</span>
                  </div>
                  <input
                    type="range"
                    min={20}
                    max={400}
                    value={satOptions.density}
                    onChange={(e) =>
                      setSatOptions((p) => ({ ...p, density: Number(e.target.value) }))
                    }
                    className="w-full"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] mb-1">
                    <span className="text-ui-muted">{t('Stroke Width')}</span>
                    <span className="font-ui-mono tabular-nums text-ui-primary">{satOptions.lineWidth}px</span>
                  </div>
                  <input
                    type="range"
                    min={1}
                    max={12}
                    value={satOptions.lineWidth}
                    onChange={(e) =>
                      setSatOptions((p) => ({ ...p, lineWidth: Number(e.target.value) }))
                    }
                    className="w-full"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] mb-1">
                    <span className="text-ui-muted">{t('Spacing & Depth Jitter')}</span>
                    <span className="font-ui-mono tabular-nums text-ui-primary">{Math.round(satOptions.spacingJitter * 100)}%</span>
                  </div>
                  <input
                    type="range"
                    min={0}
                    max={100}
                    value={Math.round(satOptions.spacingJitter * 100)}
                    onChange={(e) =>
                      setSatOptions((p) => ({
                        ...p,
                        spacingJitter: Number(e.target.value) / 100,
                        lengthJitter: Number(e.target.value) / 100,
                      }))
                    }
                    className="w-full"
                  />
                </div>

                <div className="flex items-center space-x-2 pt-1">
                  <span className="text-[11px] text-ui-muted">{t('Taper Direction')}</span>
                  <button
                    type="button"
                    onClick={() => setSatOptions((p) => ({ ...p, taper: 'in' }))}
                    className={`px-2 py-0.5 rounded-ui-xs text-[11px] border transition-colors cursor-pointer ${
                      satOptions.taper === 'in'
                        ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border font-medium'
                        : 'bg-ui-input border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                    }`}
                  >
                    {t('Point to Center')}
                  </button>
                  <button
                    type="button"
                    onClick={() => setSatOptions((p) => ({ ...p, taper: 'none' }))}
                    className={`px-2 py-0.5 rounded-ui-xs text-[11px] border transition-colors cursor-pointer ${
                      satOptions.taper === 'none'
                        ? 'bg-ui-accent-subtle text-ui-accent border-ui-accent-border font-medium'
                        : 'bg-ui-input border-ui-subtle text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover'
                    }`}
                  >
                    {t('Uniform')}
                  </button>
                </div>
              </>
            ) : (
              <>
                <div>
                  <div className="flex justify-between text-[11px] mb-1">
                    <span className="text-ui-muted">{t('Angle')}</span>
                    <span className="font-ui-mono tabular-nums text-ui-primary">{streamOptions.angle}°</span>
                  </div>
                  <div className="flex items-center space-x-2">
                    <input
                      type="range"
                      min={0}
                      max={360}
                      value={streamOptions.angle}
                      onChange={(e) =>
                        setStreamOptions((p) => ({ ...p, angle: Number(e.target.value) }))
                      }
                      className="flex-1"
                    />
                    <div className="flex space-x-1">
                      {[0, 90, 45].map((deg) => (
                        <button
                          key={deg}
                          type="button"
                          onClick={() => setStreamOptions((p) => ({ ...p, angle: deg }))}
                          className="px-1.5 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle font-ui-mono tabular-nums text-[10px] text-ui-primary cursor-pointer transition-colors"
                        >
                          {deg}°
                        </button>
                      ))}
                    </div>
                  </div>
                </div>

                <div>
                  <div className="flex justify-between text-[11px] mb-1">
                    <span className="text-ui-muted">{t('Density')}</span>
                    <span className="font-ui-mono tabular-nums text-ui-primary">{t('{count} lines', { count: streamOptions.density })}</span>
                  </div>
                  <input
                    type="range"
                    min={15}
                    max={300}
                    value={streamOptions.density}
                    onChange={(e) =>
                      setStreamOptions((p) => ({ ...p, density: Number(e.target.value) }))
                    }
                    className="w-full"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] mb-1">
                    <span className="text-ui-muted">{t('Streak Length')}</span>
                    <span className="font-ui-mono tabular-nums text-ui-primary">{streamOptions.lineLength}px</span>
                  </div>
                  <input
                    type="range"
                    min={50}
                    max={1200}
                    value={streamOptions.lineLength}
                    onChange={(e) =>
                      setStreamOptions((p) => ({ ...p, lineLength: Number(e.target.value) }))
                    }
                    className="w-full"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] mb-1">
                    <span className="text-ui-muted">{t('Thickness')}</span>
                    <span className="font-ui-mono tabular-nums text-ui-primary">{streamOptions.thickness}px</span>
                  </div>
                  <input
                    type="range"
                    min={1}
                    max={10}
                    value={streamOptions.thickness}
                    onChange={(e) =>
                      setStreamOptions((p) => ({ ...p, thickness: Number(e.target.value) }))
                    }
                    className="w-full"
                  />
                </div>

                <div>
                  <div className="flex justify-between text-[11px] mb-1">
                    <span className="text-ui-muted">{t('Thickness & Length Noise')}</span>
                    <span className="font-ui-mono tabular-nums text-ui-primary">
                      {Math.round(streamOptions.thicknessNoise * 100)}%
                    </span>
                  </div>
                  <input
                    type="range"
                    min={0}
                    max={100}
                    value={Math.round(streamOptions.thicknessNoise * 100)}
                    onChange={(e) =>
                      setStreamOptions((p) => ({
                        ...p,
                        thicknessNoise: Number(e.target.value) / 100,
                        lengthNoise: Number(e.target.value) / 100,
                      }))
                    }
                    className="w-full"
                  />
                </div>
              </>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="px-4 py-2.5 bg-ui-header border-t border-ui-subtle flex items-center justify-between">
          <button
            type="button"
            onClick={() => {
              if (activeTab === 'saturated') {
                setSatOptions({
                  centerX: Math.round(canvasWidth * 0.5),
                  centerY: Math.round(canvasHeight * 0.5),
                  innerRadius: Math.round(Math.min(canvasWidth, canvasHeight) * 0.2),
                  density: 120,
                  spacingJitter: 0.5,
                  lengthJitter: 0.35,
                  lineWidth: 4,
                  taper: 'in',
                  color: '#000000',
                });
              } else {
                setStreamOptions({
                  angle: 0,
                  density: 80,
                  lineLength: Math.round(Math.min(canvasWidth, canvasHeight) * 0.5),
                  lengthNoise: 0.4,
                  thickness: 3,
                  thicknessNoise: 0.5,
                  gapNoise: 0.3,
                  color: '#000000',
                });
              }
            }}
            className="text-xs text-ui-muted hover:text-ui-primary transition-colors cursor-pointer"
          >
            {t('Reset Defaults')}
          </button>

          <div className="flex items-center gap-2">
            <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 font-medium rounded-ui-sm text-xs transition-colors cursor-pointer"
            >
              {t('Cancel')}
            </button>
            <button
              type="button"
              onClick={handleApplyClick}
              className="px-4 py-1.5 bg-ui-accent text-ui-accent-contrast hover:opacity-90 rounded-ui-sm text-xs font-medium transition-opacity cursor-pointer"
            >
              {t('Apply Effect')}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};