Skip to content

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

14.7 KB
Raw Blame
import React, { useState } from 'react';
import {
  Play,
  Circle,
  Square,
  Plus,
  Trash2,
  ChevronDown,
  ChevronRight,
  Download,
  Upload,
  FolderPlus,
} from 'lucide-react';
import {
  AutoAction,
  exportAutoActionSetsJson,
  importAutoActionSetsJson,
} from '../utils/autoActionEngine';
import { autoActionStoreActions, useAutoActionStore } from '../stores';
import { saveFileWithDialog } from '../utils/fileSaveDialog';
import { isImeComposing, useI18n } from '../i18n';

export interface AutoActionPanelProps {
  hasOpenDocument: boolean;
  onPlayAction: (action: AutoAction) => void;
  showToast?: (msg: string) => void;
}

export const AutoActionPanel: React.FC<AutoActionPanelProps> = React.memo(
  ({ hasOpenDocument, onPlayAction, showToast }) => {
    const { t, td } = useI18n();
    const sets = useAutoActionStore((s) => s.sets);
    const activeSetId = useAutoActionStore((s) => s.activeSetId);
    const selectedActionId = useAutoActionStore((s) => s.selectedActionId);
    const isRecording = useAutoActionStore((s) => s.isRecording);
    const recordingActionId = useAutoActionStore((s) => s.recordingActionId);
    const isPlaying = useAutoActionStore((s) => s.isPlaying);

    const [expandedIds, setExpandedIds] = useState<Record<string, boolean>>({});
    const [newActionName, setNewActionName] = useState('');

    const activeSet = sets.find((s) => s.id === activeSetId) ?? sets[0];
    const selectedAction =
      activeSet?.actions.find((a) => a.id === selectedActionId) ?? activeSet?.actions[0] ?? null;

    const toggleExpand = (id: string) => {
      setExpandedIds((prev) => ({ ...prev, [id]: !prev[id] }));
    };

    const handleCreateAction = () => {
      const created = autoActionStoreActions.createAction(newActionName || undefined);
      setNewActionName('');
      setExpandedIds((prev) => ({ ...prev, [created.id]: true }));
    };

    const handleCreateSet = () => {
      const name = t('Action Set {n}', { n: sets.length + 1 });
      autoActionStoreActions.createSet(name);
      showToast?.(t('Created set "{name}"', { name }));
    };

    const handleToggleRecord = () => {
      if (isRecording) {
        autoActionStoreActions.stopRecording();
        showToast?.(t('Auto Action recording stopped'));
      } else {
        const id = autoActionStoreActions.startRecording(selectedAction?.id);
        setExpandedIds((prev) => ({ ...prev, [id]: true }));
        showToast?.(t('Recording Auto Action steps...'));
      }
    };

    const handleExportJson = async () => {
      try {
        const json = exportAutoActionSetsJson(sets);
        const res = await saveFileWithDialog({
          data: json,
          suggestedName: 'inkstudio-auto-actions.json',
          mimeType: 'application/json',
          description: t('Ink Studio Auto Actions'),
          extensions: ['.json'],
          category: 'auto-action',
          title: t('Save Auto Actions As'),
        });
        if (res.canceled) return;
        showToast?.(t('Exported {fileName}', { fileName: res.fileName }));
      } catch {
        showToast?.(t('Failed to export Auto Action sets'));
      }
    };

    const handleImportJson = () => {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.json';
      input.onchange = async () => {
        const file = input.files?.[0];
        if (!file) return;
        try {
          const text = await file.text();
          const imported = importAutoActionSetsJson(text);
          autoActionStoreActions.replaceSets(imported);
          showToast?.(t('Imported {count} Auto Action set(s)', { count: imported.length }));
        } catch (err) {
          showToast?.(
            err instanceof Error ? td(err.message) : t('Failed to import Auto Actions')
          );
        }
      };
      input.click();
    };

    return (
      <div className="flex flex-col h-full w-full bg-ui-panel text-ui-primary select-none overflow-hidden">
        {/* Set Selector & Toolbar */}
        <div className="p-2 border-b border-ui-subtle space-y-1.5 shrink-0">
          <div className="flex items-center gap-1">
            <select
              value={activeSet?.id ?? ''}
              onChange={(e) => autoActionStoreActions.selectSet(e.target.value)}
              className="flex-1 bg-ui-input text-[11px] text-ui-primary px-1.5 py-1 rounded-ui-sm border border-ui-default min-w-0"
            >
              {sets.map((s) => (
                <option key={s.id} value={s.id}>
                  {td(s.name)}
                </option>
              ))}
            </select>
            <button
              type="button"
              onClick={handleCreateSet}
              title={t('New Action Set')}
              className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-icon-muted hover:text-ui-primary cursor-pointer transition-colors"
            >
              <FolderPlus className="w-3.5 h-3.5" />
            </button>
            <button
              type="button"
              onClick={handleImportJson}
              title={t('Import Action Sets (.json)')}
              className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-icon-muted hover:text-ui-primary cursor-pointer transition-colors"
            >
              <Upload className="w-3.5 h-3.5" />
            </button>
            <button
              type="button"
              onClick={handleExportJson}
              title={t('Export Action Sets (.json)')}
              className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-icon-muted hover:text-ui-primary cursor-pointer transition-colors"
            >
              <Download className="w-3.5 h-3.5" />
            </button>
          </div>

          <div className="flex items-center gap-1">
            <input
              type="text"
              value={newActionName}
              onChange={(e) => setNewActionName(e.target.value)}
              onKeyDown={(e) => {
                if (isImeComposing(e)) return;
                if (e.key === 'Enter') handleCreateAction();
              }}
              placeholder={t('New action name...')}
              className="flex-1 bg-ui-input text-[11px] text-ui-primary placeholder:text-ui-muted px-2 py-1 rounded-ui-sm border border-ui-default min-w-0 focus:outline-none focus:border-ui-focus"
            />
            <button
              type="button"
              onClick={handleCreateAction}
              title={t('Create Auto Action')}
              className="p-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-primary cursor-pointer transition-colors"
            >
              <Plus className="w-3.5 h-3.5" />
            </button>
          </div>
        </div>

        {/* Recording Status Banner */}
        {isRecording && (
          <div className="px-2.5 py-1 bg-ui-danger/15 border-b border-ui-danger/30 flex items-center justify-between text-[10px] text-ui-danger shrink-0">
            <div className="flex items-center gap-1.5">
              <span className="w-2 h-2 rounded-full bg-ui-danger animate-pulse" />
              <span>{t('Recording commands...')}</span>
            </div>
            <button
              type="button"
              onClick={() => autoActionStoreActions.stopRecording()}
              className="px-1.5 py-0.5 rounded-ui-xs bg-ui-danger/20 hover:bg-ui-danger/35 text-ui-danger font-medium cursor-pointer transition-colors"
            >
              {t('Stop')}
            </button>
          </div>
        )}

        {/* Action List */}
        <div className="flex-1 overflow-y-auto p-1.5 space-y-1">
          {!activeSet || activeSet.actions.length === 0 ? (
            <div className="text-[11px] text-ui-muted text-center py-6">
              {t('No actions in this set. Click + to create one.')}
            </div>
          ) : (
            activeSet.actions.map((action) => {
              const isSelected = action.id === selectedAction?.id;
              const isExpanded = Boolean(expandedIds[action.id]);
              const isRecThis = isRecording && recordingActionId === action.id;

              return (
                <div
                  key={action.id}
                  className={`rounded-ui-sm border transition-colors ${
                    isSelected
                      ? 'bg-ui-control-active border-ui-default'
                      : 'bg-ui-input border-ui-subtle hover:border-ui-default'
                  }`}
                >
                  <div
                    onClick={() => autoActionStoreActions.selectAction(action.id)}
                    className="flex items-center gap-1 px-1.5 py-1.5 cursor-pointer"
                  >
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        toggleExpand(action.id);
                      }}
                      className="text-ui-icon-muted hover:text-ui-primary cursor-pointer"
                    >
                      {isExpanded ? (
                        <ChevronDown className="w-3 h-3" />
                      ) : (
                        <ChevronRight className="w-3 h-3" />
                      )}
                    </button>

                    <span className="flex-1 text-[11px] font-medium truncate">
                      {td(action.name)}
                    </span>

                    <span className="text-[9px] font-ui-mono tabular-nums text-ui-muted mr-1">
                      {action.steps.length}
                    </span>

                    {isRecThis && (
                      <span className="w-2 h-2 rounded-full bg-ui-danger animate-pulse mr-0.5" />
                    )}

                    <button
                      type="button"
                      disabled={!hasOpenDocument || isPlaying || action.steps.length === 0}
                      onClick={(e) => {
                        e.stopPropagation();
                        onPlayAction(action);
                      }}
                      title={t('Play Auto Action')}
                      className="p-1 rounded-ui-xs bg-ui-control hover:bg-ui-accent hover:text-ui-accent-contrast text-ui-primary disabled:opacity-35 cursor-pointer transition-colors"
                    >
                      <Play className="w-3 h-3" />
                    </button>

                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        autoActionStoreActions.deleteAction(action.id);
                      }}
                      title={t('Delete Action')}
                      className="p-1 rounded-ui-xs hover:bg-ui-danger/15 text-ui-muted hover:text-ui-danger cursor-pointer transition-colors"
                    >
                      <Trash2 className="w-3 h-3" />
                    </button>
                  </div>

                  {isExpanded && (
                    <div className="px-2 pb-1.5 pt-1 space-y-1 border-t border-ui-subtle">
                      {action.steps.length === 0 ? (
                        <div className="text-[10px] text-ui-muted italic py-1">
                          {t('Empty. Press Record and perform layer/filter commands.')}
                        </div>
                      ) : (
                        action.steps.map((step) => (
                          <div
                            key={step.id}
                            className="flex items-center gap-1.5 text-[10px] text-ui-secondary bg-ui-panel border border-ui-subtle rounded-ui-xs px-1.5 py-1"
                          >
                            <input
                              type="checkbox"
                              checked={step.enabled !== false}
                              onChange={() =>
                                autoActionStoreActions.toggleStepEnabled(action.id, step.id)
                              }
                              className="cursor-pointer"
                            />
                            <span
                              className={`flex-1 truncate ${
                                step.enabled === false ? 'line-through opacity-50' : ''
                              }`}
                            >
                              {td(step.label)}
                            </span>
                            <button
                              type="button"
                              onClick={() =>
                                autoActionStoreActions.deleteStep(action.id, step.id)
                              }
                              className="text-ui-muted hover:text-ui-danger cursor-pointer"
                              title={t('Remove step')}
                            >
                              <Trash2 className="w-2.5 h-2.5" />
                            </button>
                          </div>
                        ))
                      )}
                    </div>
                  )}
                </div>
              );
            })
          )}
        </div>

        {/* Bottom Transport Bar */}
        <div className="p-2 border-t border-ui-subtle flex items-center justify-between gap-1.5 shrink-0 bg-ui-header">
          <button
            type="button"
            disabled={!hasOpenDocument || isPlaying}
            onClick={handleToggleRecord}
            className={`flex-1 py-1.5 px-2 rounded-ui-sm text-[11px] font-medium flex items-center justify-center gap-1.5 cursor-pointer transition-colors disabled:opacity-40 border ${
              isRecording
                ? 'bg-ui-danger/20 hover:bg-ui-danger/30 border-ui-danger/50 text-ui-danger'
                : 'bg-ui-control hover:bg-ui-control-hover border-ui-subtle text-ui-primary'
            }`}
          >
            {isRecording ? (
              <>
                <Square className="w-3 h-3 fill-current" />
                <span>{t('Stop')}</span>
              </>
            ) : (
              <>
                <Circle className="w-3 h-3 text-ui-danger fill-ui-danger" />
                <span>{t('Record')}</span>
              </>
            )}
          </button>

          <button
            type="button"
            disabled={!hasOpenDocument || isPlaying || !selectedAction || selectedAction.steps.length === 0}
            onClick={() => selectedAction && onPlayAction(selectedAction)}
            className="flex-1 py-1.5 px-2 rounded-ui-sm text-[11px] font-medium bg-ui-accent text-ui-accent-contrast hover:opacity-90 flex items-center justify-center gap-1.5 cursor-pointer transition-opacity disabled:opacity-40"
          >
            <Play className="w-3 h-3 fill-current" />
            <span>{t('Play')}</span>
          </button>
        </div>
      </div>
    );
  }
);

AutoActionPanel.displayName = 'AutoActionPanel';