All files / src/components/board BoardStageEditorModal.tsx

77.77% Statements 140/180
82.92% Branches 34/41
66.66% Functions 12/18
77.77% Lines 140/180

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 2531x       1x 1x   45x 45x 45x   2x 2x 2x   2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x   1x 15x 15x 15x 15x 15x 15x 15x                 15x 15x 1x   15x   15x 1x 15x   15x 1x 9x 9x 1x 1x 15x   15x 12x 36x   12x   15x                         15x                                 15x             15x 1x 1x 1x       1x 1x 1x     1x   15x 15x 15x 15x 15x 15x         15x 15x 15x 1x 1x   15x 15x 45x 45x 15x 30x 15x 15x   45x 45x 45x 45x     45x 45x 45x 45x 45x 45x         45x 45x 45x 45x 45x 45x 45x 45x 45x     45x 30x 30x   45x 45x 45x 45x 45x 45x 45x 45x   45x 45x 45x 45x           45x 45x 45x 45x 45x 45x 45x   45x 45x 45x 45x             45x 45x 45x 45x 45x 45x 45x         45x         45x     15x   15x 15x     15x 15x             15x  
import { useEffect, useState, type FormEvent } from "react";
import type { BoardStage, CommandView, ModelProfileView } from "../../types";
import { type EditableBoardStage, toEditableBoardStages } from "./stageConfig";
 
const BACKLOG_STAGE_ID = "backlog";
const DONE_STAGE_ID = "done";
 
function isFixedStage(stageId: string): boolean {
  return stageId === BACKLOG_STAGE_ID || stageId === DONE_STAGE_ID;
}
 
function buildInitialItems(
  stages: BoardStage[],
  startWithNewStage: boolean,
): EditableBoardStage[] {
  const items = toEditableBoardStages(stages);
  if (!startWithNewStage) {
    return items;
  }
  const nextStage: EditableBoardStage = {
    id: "",
    name: "",
    profile_id: "",
    command_id: "",
    auto_start: false,
  };
  const doneIndex = items.findIndex((item) => item.id === DONE_STAGE_ID);
  if (doneIndex === -1) {
    return [...items, nextStage];
  }
  const nextItems = [...items];
  nextItems.splice(doneIndex, 0, nextStage);
  return nextItems;
}
 
export function BoardStageEditorModal({
  stages,
  profiles,
  commands,
  startWithNewStage = false,
  isSaving,
  onSave,
  onClose,
}: {
  stages: BoardStage[];
  profiles: ModelProfileView[];
  commands: CommandView[];
  startWithNewStage?: boolean;
  isSaving: boolean;
  onSave: (stages: EditableBoardStage[]) => Promise<void>;
  onClose: () => void;
}) {
  const [items, setItems] = useState<EditableBoardStage[]>(() =>
    buildInitialItems(stages, startWithNewStage),
  );
  const [error, setError] = useState<string | null>(null);
 
  useEffect(() => {
    setItems(buildInitialItems(stages, startWithNewStage));
  }, [stages, startWithNewStage]);
 
  useEffect(() => {
    const handleKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
    };
    document.addEventListener("keydown", handleKey);
    return () => document.removeEventListener("keydown", handleKey);
  }, [onClose]);
 
  const updateItem = (index: number, updates: Partial<EditableBoardStage>) => {
    setItems((current) => current.map((item, itemIndex) => (
      itemIndex === index ? { ...item, ...updates } : item
    )));
  };
 
  const moveItem = (index: number, direction: -1 | 1) => {
    setItems((current) => {
      if (isFixedStage(current[index]?.id ?? "")) return current;
      const targetIndex = index + direction;
      if (targetIndex < 0 || targetIndex >= current.length) return current;
      if (isFixedStage(current[targetIndex]?.id ?? "")) return current;
      const next = [...current];
      const [item] = next.splice(index, 1);
      next.splice(targetIndex, 0, item);
      return next;
    });
  };
 
  const addStage = () => {
    setItems((current) => {
      const nextStage: EditableBoardStage = {
        id: "",
        name: "",
        profile_id: "",
        command_id: "",
        auto_start: false,
      };
      const doneIndex = current.findIndex((item) => item.id === DONE_STAGE_ID);
      if (doneIndex === -1) return [...current, nextStage];
      const next = [...current];
      next.splice(doneIndex, 0, nextStage);
      return next;
    });
  };
 
  const removeStage = (index: number) => {
    setItems((current) => {
      if (isFixedStage(current[index]?.id ?? "")) return current;
      return current.filter((_, itemIndex) => itemIndex !== index);
    });
  };
 
  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setError(null);
    if (items.length === 0) {
      setError("Board must contain at least one stage.");
      return;
    }
    try {
      await onSave(items);
    } catch (err) {
      setError((err as Error).message);
    }
  };
 
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-card modal-card--board-editor" onClick={(event) => event.stopPropagation()}>
        <div className="modal-card__header">
          <h2 className="modal-card__title">Board Stages</h2>
          <button type="button" className="modal-card__close" onClick={onClose} disabled={isSaving}>
            &times;
          </button>
        </div>
 
        <form
          className="task-form"
          onSubmit={(event) => {
            void handleSubmit(event);
          }}
        >
          <div className="board-stage-editor">
            {items.map((item, index) => {
              const fixedStage = isFixedStage(item.id);
              const fixedStageLabel = item.id === BACKLOG_STAGE_ID
                ? "Backlog stays first and never runs directly."
                : item.id === DONE_STAGE_ID
                  ? "Done stays last and is archive-only."
                  : null;
 
              return (
                <div key={`${item.id || "new"}-${index}`} className="board-stage-editor__row">
                <div className="board-stage-editor__ordering">
                  <button type="button" className="btn btn--ghost btn--sm" onClick={() => moveItem(index, -1)} disabled={index === 0 || isSaving || fixedStage}>
                    ↑
                  </button>
                  <button
                    type="button"
                    className="btn btn--ghost btn--sm"
                    onClick={() => moveItem(index, 1)}
                    disabled={index === items.length - 1 || isSaving || fixedStage}
                  >
                    ↓
                  </button>
                </div>
 
                <div className="board-stage-editor__fields">
                  <div className="task-form__field">
                    <label className="task-form__label">Name</label>
                    <input
                      className="task-form__input"
                      value={item.name}
                      onChange={(event) => updateItem(index, { name: event.target.value })}
                      required
                      disabled={fixedStage}
                    />
                  </div>
                  {fixedStageLabel ? (
                    <p className="task-form__hint">{fixedStageLabel}</p>
                  ) : null}
 
                  <div className="task-form__row">
                    <div className="task-form__field">
                      <label className="task-form__label">Default Profile</label>
                      <select
                        className="task-form__select"
                        value={item.profile_id}
                        onChange={(event) => updateItem(index, { profile_id: event.target.value })}
                        disabled={fixedStage}
                      >
                        <option value="">No default profile</option>
                        {profiles.map((profile) => (
                          <option key={profile.id} value={profile.id}>
                            {profile.name}
                          </option>
                        ))}
                      </select>
                    </div>
 
                    <div className="task-form__field">
                      <label className="task-form__label">Default Command</label>
                      <select
                        className="task-form__select"
                        value={item.command_id}
                        onChange={(event) => updateItem(index, { command_id: event.target.value })}
                        disabled={fixedStage}
                      >
                        <option value="">No default command</option>
                        {commands.map((command) => (
                          <option key={command.id} value={command.id}>
                            {command.name} ({command.slash_alias})
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>
 
                  <label className="board-stage-editor__toggle">
                    <input
                      type="checkbox"
                      checked={item.auto_start}
                      onChange={(event) => updateItem(index, { auto_start: event.target.checked })}
                      disabled={fixedStage}
                    />
                    Auto-start when a task enters this stage
                  </label>
                </div>
 
                <button type="button" className="btn btn--ghost-danger btn--sm" onClick={() => removeStage(index)} disabled={isSaving || items.length === 1 || fixedStage}>
                  Remove
                </button>
                </div>
              );
            })}
          </div>
 
          {error ? <div className="settings-error-banner">{error}</div> : null}
 
          <div className="board-stage-editor__actions">
            <button type="button" className="btn btn--ghost" onClick={addStage} disabled={isSaving}>
              + Add Stage
            </button>
            <button type="submit" className="task-form__submit" disabled={isSaving}>
              {isSaving ? "Saving..." : "Save Board"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}