-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathTaskItem.tsx
More file actions
1096 lines (1002 loc) · 36.7 KB
/
Copy pathTaskItem.tsx
File metadata and controls
1096 lines (1002 loc) · 36.7 KB
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useState, useCallback, useMemo, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { GripVertical, ChevronRight, X, Loader2, FileText, Link, AlertCircle, Play, CircleDot } from 'lucide-react';
import { useAppStore, type TaskRunStatus } from '@/stores/appStore';
import { maaService } from '@/services/maaService';
import { useResolvedContent } from '@/services/contentResolver';
import { generateTaskPipelineOverride } from '@/utils';
import { OptionEditor, SwitchGrid, switchHasNestedOptions } from './OptionEditor';
import { ContextMenu, useContextMenu } from './ContextMenu';
import { Tooltip } from './ui/Tooltip';
import { ConfirmDialog } from './ConfirmDialog';
import { buildListItemMenuItems, InlineNameEditor } from './listItemShared';
import {
TriStateCheckbox,
getTaskCheckboxState,
} from './ui/TriStateCheckbox';
import { taskStartService } from '@/services/taskStartService';
import type { MenuItem } from './ContextMenu';
import type { SelectedTask } from '@/types/interface';
import { isMxuSpecialTask, getMxuSpecialTask, findMxuOptionByKey } from '@/types/specialTasks';
import { getInterfaceLangKey } from '@/i18n';
import clsx from 'clsx';
import { loggers } from '@/utils/logger';
/** 选项预览标签组件 */
function OptionPreviewTag({
label,
value,
type,
}: {
label: string;
value: string;
type: 'select' | 'checkbox' | 'switch' | 'input';
}) {
// 截断过长的显示值
const truncateText = (text: string, max: number) =>
text.length > max ? text.slice(0, max) + '…' : text;
return (
<span
className={clsx(
'inline-flex items-center gap-1 px-1.5 py-0.5 text-xs rounded',
'text-text-tertiary',
'max-w-[140px]',
)}
title={`${label}: ${value}`}
>
{type === 'switch' ? (
// Switch 类型:显示选项名 + 状态圆点
<>
<span className="truncate">{truncateText(label, 6)}</span>
<span
className={clsx(
'w-1.5 h-1.5 rounded-full flex-shrink-0',
value === 'ON' ? 'bg-success/70' : 'bg-text-muted/50',
)}
/>
</>
) : (
// Select/Input 类型:显示选项名: 值
<>
<span className="truncate flex-shrink-0">{truncateText(label, 4)}</span>
<span className="flex-shrink-0">:</span>
<span className="truncate">{truncateText(value, 6)}</span>
</>
)}
</span>
);
}
interface TaskItemProps {
instanceId: string;
task: SelectedTask;
}
/** 描述内容组件:显示从文件/URL/直接文本解析的内容 */
function DescriptionContent({
html,
loading,
type,
loaded,
error,
}: {
html: string;
loading: boolean;
type: 'url' | 'file' | 'text';
loaded: boolean;
error?: string;
}) {
const { t } = useTranslation();
if (loading) {
return (
<div className="flex items-center gap-1.5 text-xs text-text-muted">
<Loader2 className="w-3 h-3 animate-spin" />
<span>{t('taskItem.loadingDescription')}</span>
</div>
);
}
return (
<div className="space-y-1">
{/* 来源提示 */}
{loaded && type !== 'text' && (
<div className="flex items-center gap-1 text-[10px] text-text-muted">
{type === 'file' ? <FileText className="w-3 h-3" /> : <Link className="w-3 h-3" />}
<span>{t(type === 'file' ? 'taskItem.loadedFromFile' : 'taskItem.loadedFromUrl')}</span>
</div>
)}
{/* 加载错误提示 */}
{error && type !== 'text' && (
<div className="flex items-center gap-1 text-[10px] text-warning">
<AlertCircle className="w-3 h-3" />
<span>
{t('taskItem.loadDescriptionFailed')}: {error}
</span>
</div>
)}
{/* 内容 */}
{html && (
<div
className="text-xs text-text-secondary [&_p]:my-0.5 [&_a]:text-accent [&_a]:hover:underline"
dangerouslySetInnerHTML={{ __html: html }}
/>
)}
</div>
);
}
/** 选项分组项类型 */
type OptionGroup =
| { type: 'single'; optionKey: string }
| { type: 'switchGrid'; optionKeys: string[] };
/** 检查选项是否与当前控制器不兼容 */
function isOptionControllerIncompatible(
optionDef: import('@/types/interface').OptionDefinition | null | undefined,
currentControllerName: string | undefined,
): boolean {
if (!optionDef?.controller || optionDef.controller.length === 0) return false;
if (!currentControllerName) return false;
return !optionDef.controller.includes(currentControllerName);
}
/** v2.3.0: 检查选项是否与当前资源不兼容 */
function isOptionResourceIncompatible(
optionDef: import('@/types/interface').OptionDefinition | null | undefined,
currentResourceName: string | undefined,
): boolean {
if (!optionDef?.resource || optionDef.resource.length === 0) return false;
if (!currentResourceName) return false;
return !optionDef.resource.includes(currentResourceName);
}
/** 选项列表渲染器:自动将连续的无子选项 switch 分组为网格 */
function OptionListRenderer({
instanceId,
taskId,
optionKeys,
optionValues,
disabled,
currentControllerName,
currentResourceName,
}: {
instanceId: string;
taskId: string;
optionKeys: string[];
optionValues: Record<string, import('@/types/interface').OptionValue>;
disabled: boolean;
currentControllerName: string | undefined;
currentResourceName: string | undefined;
}) {
const { projectInterface, resolveI18nText, language } = useAppStore();
const { t } = useTranslation();
const langKey = getInterfaceLangKey(language);
// 获取选项定义(支持 MXU 特殊任务)
const getOptionDef = (optionKey: string) => {
const isMxuOption = optionKey.startsWith('__MXU_');
return isMxuOption ? findMxuOptionByKey(optionKey) : projectInterface?.option?.[optionKey];
};
// 将选项分组:连续 5 个以上无子选项的 switch 合并为网格
const groups = useMemo(() => {
const result: OptionGroup[] = [];
let currentSwitchGroup: string[] = [];
const flushSwitchGroup = () => {
if (currentSwitchGroup.length > 4) {
// 超过 4 个,使用网格
result.push({ type: 'switchGrid', optionKeys: [...currentSwitchGroup] });
} else {
// 4 个及以下,单独渲染
for (const key of currentSwitchGroup) {
result.push({ type: 'single', optionKey: key });
}
}
currentSwitchGroup = [];
};
for (const optionKey of optionKeys) {
const optionDef = getOptionDef(optionKey);
// 判断是否为无子选项的 switch
const isSimpleSwitch = optionDef?.type === 'switch' && !switchHasNestedOptions(optionDef);
if (isSimpleSwitch) {
currentSwitchGroup.push(optionKey);
} else {
// 非 switch 或有子选项,先刷新当前 switch 组
flushSwitchGroup();
result.push({ type: 'single', optionKey });
}
}
// 处理末尾的 switch 组
flushSwitchGroup();
return result;
}, [optionKeys, projectInterface?.option]);
// 构建 SwitchGrid 的数据
const buildSwitchGridItems = (keys: string[]) => {
return keys.map((optionKey) => {
const optionDef = getOptionDef(optionKey);
const value = optionValues[optionKey];
const isChecked = value?.type === 'switch' ? value.value : false;
const isMxuOption = optionKey.startsWith('__MXU_');
// 对于 MXU 内置选项,使用 t() 翻译;否则使用 resolveI18nText
const label = isMxuOption
? t(optionDef?.label || optionKey)
: resolveI18nText(optionDef?.label, langKey) || optionKey;
const description = isMxuOption
? optionDef?.description
? t(optionDef.description)
: undefined
: resolveI18nText(optionDef?.description, langKey);
const controllerIncompatible = isOptionControllerIncompatible(
optionDef,
currentControllerName,
);
const resourceIncompatible = isOptionResourceIncompatible(optionDef, currentResourceName);
return {
optionKey,
label,
description,
isChecked,
controllerIncompatible: controllerIncompatible || resourceIncompatible,
};
});
};
return (
<div className="space-y-4">
{groups.map((group, index) => {
if (group.type === 'switchGrid') {
return (
<SwitchGrid
key={`grid-${index}`}
instanceId={instanceId}
taskId={taskId}
items={buildSwitchGridItems(group.optionKeys)}
disabled={disabled}
/>
);
}
const optionDef = getOptionDef(group.optionKey);
const optionControllerIncompatible = isOptionControllerIncompatible(
optionDef,
currentControllerName,
);
const optionResourceIncompatible = isOptionResourceIncompatible(
optionDef,
currentResourceName,
);
const optionIncompatible = optionControllerIncompatible || optionResourceIncompatible;
const parentIncompatibilityReason = optionControllerIncompatible
? 'controller'
: optionResourceIncompatible
? 'resource'
: undefined;
return (
<OptionEditor
key={group.optionKey}
instanceId={instanceId}
taskId={taskId}
optionKey={group.optionKey}
value={optionValues[group.optionKey]}
disabled={disabled || optionIncompatible}
controllerIncompatible={optionIncompatible}
parentIncompatibilityReason={parentIncompatibilityReason}
/>
);
})}
</div>
);
}
export function TaskItem({ instanceId, task }: TaskItemProps) {
const { t } = useTranslation();
const [isEditing, setIsEditing] = useState(false);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [editName, setEditName] = useState('');
const {
projectInterface,
toggleTaskEnabled,
setTaskRunOnce,
toggleTaskExpanded,
removeTaskFromInstance,
confirmBeforeDelete,
renameTask,
duplicateTask,
moveTaskUp,
moveTaskDown,
moveTaskToTop,
moveTaskToBottom,
resolveI18nText,
language,
getActiveInstance,
showOptionPreview,
instanceTaskRunStatus,
instances,
findMaaTaskIdBySelectedTaskId,
basePath,
interfaceTranslations,
animatingTaskIds,
removeAnimatingTaskId,
} = useAppStore();
// 获取任务运行状态
const taskRunStatus: TaskRunStatus = instanceTaskRunStatus[instanceId]?.[task.id] || 'idle';
// 获取实例运行状态
const instance = instances.find((i) => i.id === instanceId);
const isInstanceRunning = instance?.isRunning || false;
// 获取任务定义 - 支持 MXU 内置特殊任务
const isMxuTask = isMxuSpecialTask(task.taskName);
const mxuSpecialTask = isMxuTask ? getMxuSpecialTask(task.taskName) : null;
const taskDef = isMxuTask
? mxuSpecialTask?.taskDef
: projectInterface?.task.find((t) => t.name === task.taskName);
// 检查任务是否与当前控制器/资源兼容
// 未选择时,使用第一个控制器/资源作为默认值判断兼容性
const currentControllerName = instance?.controllerName || projectInterface?.controller[0]?.name;
const currentResourceName = instance?.resourceName || projectInterface?.resource[0]?.name;
const langKey = getInterfaceLangKey(language);
const isControllerIncompatible = useMemo(() => {
if (!taskDef?.controller || taskDef.controller.length === 0) return false;
if (!currentControllerName) return false;
return !taskDef.controller.includes(currentControllerName);
}, [taskDef?.controller, currentControllerName]);
const isResourceIncompatible = useMemo(() => {
if (!taskDef?.resource || taskDef.resource.length === 0) return false;
if (!currentResourceName) return false;
return !taskDef.resource.includes(currentResourceName);
}, [taskDef?.resource, currentResourceName]);
const isIncompatible = isControllerIncompatible || isResourceIncompatible;
// 生成不兼容提示信息
const incompatibleReason = useMemo(() => {
if (!isIncompatible) return '';
const reasons: string[] = [];
if (isControllerIncompatible) {
reasons.push(t('taskItem.incompatibleController'));
}
if (isResourceIncompatible) {
reasons.push(t('taskItem.incompatibleResource'));
}
return reasons.join(', ');
}, [isIncompatible, isControllerIncompatible, isResourceIncompatible, t]);
// 生成支持的控制器提示(用于 Tooltip hover 显示)
const supportedControllerHint = useMemo(() => {
if (!isControllerIncompatible || !taskDef?.controller || taskDef.controller.length === 0)
return '';
const labels = taskDef.controller.map((name) => {
const ctrl = projectInterface?.controller.find((c) => c.name === name);
return ctrl ? resolveI18nText(ctrl.label, langKey) || ctrl.name : name;
});
return t('taskItem.supportedControllers', { controllers: labels.join(', ') });
}, [
isControllerIncompatible,
taskDef?.controller,
projectInterface?.controller,
resolveI18nText,
langKey,
t,
]);
// 紧凑模式:实例运行时,未参与运行的任务显示为紧凑样式
const isCompact = isInstanceRunning && !task.enabled && !task.runOnce && taskRunStatus === 'idle';
// 判断是否可以编辑选项:实例未运行时始终可以编辑,运行中只有 pending 或 idle 状态的任务可以编辑
const canEditOptions =
!isInstanceRunning || taskRunStatus === 'idle' || taskRunStatus === 'pending';
// 判断是否可以调整顺序/删除(实例运行时禁用)
const canReorder = !isInstanceRunning;
const canDelete = !isInstanceRunning;
// 用于追踪选项值变化的 ref(避免首次渲染时触发)
const prevOptionValuesRef = useRef<string | null>(null);
// 入场动画状态
const isAnimating = animatingTaskIds.includes(task.id);
const animationElementRef = useRef<HTMLDivElement | null>(null);
// 当选项值变化且任务状态为 pending 时,调用 overridePipeline 更新任务配置
useEffect(() => {
const currentOptionValues = JSON.stringify(task.optionValues);
// 首次渲染时只记录当前值,不触发 override
if (prevOptionValuesRef.current === null) {
prevOptionValuesRef.current = currentOptionValues;
return;
}
// 如果选项值没有变化,不处理
if (prevOptionValuesRef.current === currentOptionValues) {
return;
}
// 更新 ref
prevOptionValuesRef.current = currentOptionValues;
// 只有 pending 状态的任务才需要调用 overridePipeline
if (taskRunStatus !== 'pending') {
return;
}
// 获取对应的 maaTaskId
const maaTaskId = findMaaTaskIdBySelectedTaskId(instanceId, task.id);
if (maaTaskId === null) {
return;
}
// 生成新的 pipeline override 并调用后端
const pipelineOverride = generateTaskPipelineOverride(
task,
projectInterface,
currentControllerName,
currentResourceName,
);
maaService.overridePipeline(instanceId, maaTaskId, pipelineOverride).catch((err) => {
loggers.task.error('Failed to override pipeline:', err);
});
}, [
task.optionValues,
taskRunStatus,
instanceId,
task.id,
projectInterface,
currentControllerName,
currentResourceName,
]);
const { state: menuState, show: showMenu, hide: hideMenu } = useContextMenu();
// 获取翻译表
const translations = interfaceTranslations[langKey];
// 使用新的 Hook 解析任务描述(支持文件/URL/直接文本)
const resolvedDescription = useResolvedContent(
taskDef?.description ? resolveI18nText(taskDef.description, langKey) : undefined,
basePath,
translations,
);
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: task.id,
disabled: !canReorder,
});
// 禁止 X 方向位移,仅允许垂直拖动;同时忽略 dnd-kit 的缩放分量,
// 避免拖拽中的半透明项在高度变化时把文本一起纵向拉伸。
const constrainedTransform = transform
? {
...transform,
x: 0,
scaleX: 1,
scaleY: 1,
}
: null;
const style = {
transform: CSS.Transform.toString(constrainedTransform),
transition,
};
// 合并 sortable ref 和动画 ref
const setRefs = useCallback(
(node: HTMLDivElement | null) => {
setNodeRef(node);
animationElementRef.current = node;
},
[setNodeRef],
);
// 动画结束后移除动画状态
useEffect(() => {
if (!isAnimating || !animationElementRef.current) return;
const element = animationElementRef.current;
const handleAnimationEnd = () => {
removeAnimatingTaskId(task.id);
};
element.addEventListener('animationend', handleAnimationEnd);
return () => element.removeEventListener('animationend', handleAnimationEnd);
}, [isAnimating, task.id, removeAnimatingTaskId]);
// 对于 MXU 内置任务,使用 t() 翻译,否则使用 resolveI18nText
const originalLabel = taskDef
? isMxuTask
? t(taskDef.label || taskDef.name)
: resolveI18nText(taskDef.label, langKey) || taskDef.name
: '';
const displayName = task.customName || originalLabel;
const hasOptions = !!taskDef?.option && taskDef.option.length > 0;
// 判断是否有描述内容(包括正在加载的情况)
const hasDescription = !!resolvedDescription.html || resolvedDescription.loading;
// 有选项或有描述时都可以展开
const canExpand = hasOptions || hasDescription;
// 生成选项预览信息(最多显示3个)
const optionPreviews = useMemo(() => {
if (!hasOptions) return [];
if (!projectInterface?.option && !isMxuTask) return [];
const previews: {
key: string;
label: string;
value: string;
type: 'select' | 'checkbox' | 'switch' | 'input';
}[] = [];
const maxPreviews = 3;
for (const optionKey of taskDef.option || []) {
if (previews.length >= maxPreviews) break;
// 优先从 projectInterface 查找,MXU 特殊任务从注册表查找
const isMxuOption = optionKey.startsWith('__MXU_');
const optionDef = isMxuOption
? findMxuOptionByKey(optionKey)
: projectInterface?.option?.[optionKey];
if (!optionDef) continue;
// MXU 特殊任务的 label 是 i18n key,需要用 t() 翻译
const optionLabel = isMxuOption
? t(optionDef.label || optionKey)
: resolveI18nText(optionDef.label, langKey) || optionKey;
const optionValue = task.optionValues[optionKey];
if (optionDef.type === 'switch') {
const isOn = optionValue?.type === 'switch' ? optionValue.value : false;
previews.push({
key: optionKey,
label: optionLabel,
value: isOn ? 'ON' : 'OFF',
type: 'switch',
});
} else if (optionDef.type === 'input') {
const inputValues = optionValue?.type === 'input' ? optionValue.values : {};
// 获取第一个有值的输入项
const firstInput = optionDef.inputs[0];
if (firstInput) {
const inputValue = inputValues[firstInput.name] || firstInput.default || '';
if (inputValue) {
previews.push({
key: optionKey,
label: optionLabel,
value: inputValue,
type: 'input',
});
}
}
} else if (optionDef.type === 'checkbox') {
const caseNames =
optionValue?.type === 'checkbox' ? optionValue.caseNames : optionDef.default_case || [];
previews.push({
key: optionKey,
label: optionLabel,
value: `${caseNames.length}/${optionDef.cases.length}`,
type: 'checkbox',
});
} else {
// select 类型(默认)
const caseName =
optionValue?.type === 'select'
? optionValue.caseName
: optionDef.default_case || optionDef.cases?.[0]?.name || '';
const selectedCase = optionDef.cases?.find((c) => c.name === caseName);
// MXU 特殊任务的 case label 也需要用 t() 翻译
const caseLabel = selectedCase
? isMxuOption
? t(selectedCase.label || selectedCase.name)
: resolveI18nText(selectedCase.label, langKey) || selectedCase.name
: caseName;
previews.push({
key: optionKey,
label: optionLabel,
value: caseLabel,
type: 'select',
});
}
}
return previews;
}, [
hasOptions,
projectInterface?.option,
taskDef?.option,
task.optionValues,
langKey,
resolveI18nText,
isMxuTask,
t,
]);
const checkboxState = getTaskCheckboxState(task.enabled, Boolean(task.runOnce));
const handleCheckboxClick = () => {
if (isInstanceRunning || isIncompatible) return;
toggleTaskEnabled(instanceId, task.id);
};
const handleCheckboxContextMenu = useCallback(
(e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
if (isInstanceRunning || isIncompatible) return;
const menuItems: MenuItem[] = [
{
id: 'run-once',
label: t('contextMenu.runOnceTask'),
icon: CircleDot,
checked: Boolean(task.runOnce),
onClick: () => setTaskRunOnce(instanceId, task.id, !task.runOnce),
},
{
id: 'clear-run-once',
label: t('contextMenu.clearRunOnceTask'),
disabled: !task.runOnce,
onClick: () => setTaskRunOnce(instanceId, task.id, false),
},
];
showMenu(e, menuItems);
},
[t, task.runOnce, instanceId, task.id, isInstanceRunning, isIncompatible, setTaskRunOnce, showMenu],
);
const handleRunFromHere = useCallback(async () => {
if (!instance || isInstanceRunning || isIncompatible) return;
await taskStartService.start(instance, { startFromTaskId: task.id });
}, [instance, isInstanceRunning, isIncompatible, task.id]);
const handleRunSingle = useCallback(async () => {
if (!instance || isInstanceRunning || isIncompatible) return;
await taskStartService.start(instance, { singleTaskId: task.id });
}, [instance, isInstanceRunning, isIncompatible, task.id]);
const handleNameClick = (e: React.MouseEvent) => {
e.stopPropagation();
if (isInstanceRunning || isIncompatible) return;
toggleTaskEnabled(instanceId, task.id);
};
const handleSaveEdit = () => {
renameTask(instanceId, task.id, editName.trim());
setIsEditing(false);
};
const handleCancelEdit = () => {
setIsEditing(false);
setEditName('');
};
// 右键菜单处理
const handleContextMenu = useCallback(
(e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
const instance = getActiveInstance();
if (!instance) return;
const tasks = instance.selectedTasks;
const taskIndex = tasks.findIndex((t) => t.id === task.id);
const menuItems: MenuItem[] = [
{
id: 'run-from-here',
label: t('contextMenu.runFromHere'),
icon: Play,
disabled: isInstanceRunning || isIncompatible,
onClick: () => void handleRunFromHere(),
},
{
id: 'run-single',
label: t('contextMenu.runSingleTask'),
icon: Play,
disabled: isInstanceRunning || isIncompatible,
onClick: () => void handleRunSingle(),
},
{ id: 'divider-run', label: '', divider: true },
...buildListItemMenuItems({
labels: {
duplicate: t('contextMenu.duplicateTask'),
rename: t('contextMenu.renameTask'),
enable: t('contextMenu.enableTask'),
disable: t('contextMenu.disableTask'),
expand: t('contextMenu.expandOptions'),
collapse: t('contextMenu.collapseOptions'),
moveUp: t('contextMenu.moveUp'),
moveDown: t('contextMenu.moveDown'),
moveToTop: t('contextMenu.moveToTop'),
moveToBottom: t('contextMenu.moveToBottom'),
delete: t('contextMenu.deleteTask'),
},
isEnabled: task.enabled,
isExpanded: !!task.expanded,
canExpand,
isFirst: taskIndex === 0,
isLast: taskIndex === tasks.length - 1,
isLocked: isInstanceRunning,
onDuplicate: () => duplicateTask(instanceId, task.id),
onRename: () => {
setEditName(task.customName || '');
setIsEditing(true);
},
onToggle: () => toggleTaskEnabled(instanceId, task.id),
onExpand: () => toggleTaskExpanded(instanceId, task.id),
onMoveUp: () => moveTaskUp(instanceId, task.id),
onMoveDown: () => moveTaskDown(instanceId, task.id),
onMoveToTop: () => moveTaskToTop(instanceId, task.id),
onMoveToBottom: () => moveTaskToBottom(instanceId, task.id),
onDelete: () => {
if (!confirmBeforeDelete) {
removeTaskFromInstance(instanceId, task.id);
return;
}
setShowDeleteConfirm(true);
},
}),
];
showMenu(e, menuItems);
},
[
t,
task,
instanceId,
canExpand,
getActiveInstance,
duplicateTask,
toggleTaskEnabled,
toggleTaskExpanded,
moveTaskUp,
moveTaskDown,
moveTaskToTop,
moveTaskToBottom,
removeTaskFromInstance,
confirmBeforeDelete,
showMenu,
isInstanceRunning,
isIncompatible,
handleRunFromHere,
handleRunSingle,
],
);
if (!taskDef) return null;
// 状态指示器颜色
const getStatusIndicatorClass = (): string => {
switch (taskRunStatus) {
case 'pending':
return 'bg-text-muted';
case 'running':
return 'bg-accent task-running-indicator';
case 'succeeded':
return 'bg-success';
case 'failed':
return 'bg-error';
default:
return 'bg-transparent';
}
};
// 紧凑模式:只显示最简化的任务项
if (isCompact) {
return (
<div
ref={setRefs}
style={style}
onContextMenu={handleContextMenu}
className={clsx(
'group bg-bg-secondary/50 rounded-lg border border-border/50 overflow-hidden',
'transition-all duration-200',
isDragging && 'shadow-lg opacity-50',
isAnimating && 'animate-task-slide-in',
)}
>
<div className="flex items-center gap-2 px-3 py-1.5">
{/* 复选框 - 紧凑模式下禁用 */}
<label className="flex items-center cursor-not-allowed opacity-40">
<input
type="checkbox"
checked={false}
disabled
className="w-3.5 h-3.5 rounded border-border-strong accent-accent cursor-not-allowed"
/>
</label>
{/* 任务名称 - 紧凑显示 */}
<span className="text-xs text-text-muted/70 truncate">{displayName}</span>
</div>
{/* 右键菜单 */}
{menuState.isOpen && (
<ContextMenu items={menuState.items} position={menuState.position} onClose={hideMenu} />
)}
</div>
);
}
return (
<div
ref={setRefs}
style={style}
onContextMenu={handleContextMenu}
className={clsx(
'group bg-bg-secondary rounded-lg border border-border transition-shadow relative',
isDragging && 'shadow-lg opacity-50',
taskRunStatus === 'running' && 'task-item-running',
isAnimating && 'animate-task-slide-in',
)}
>
{/* 任务状态指示器(左侧竖条) */}
{taskRunStatus !== 'idle' && (
<div
className={clsx(
'absolute left-0 top-0 bottom-0 w-1.5 rounded-l-lg transition-colors',
getStatusIndicatorClass(),
)}
title={t(`taskItem.status.${taskRunStatus}`)}
/>
)}
{/* 任务头部 */}
<div className="flex items-center gap-2 p-3">
{/* 拖拽手柄 */}
<div
{...attributes}
{...(canReorder ? listeners : {})}
className={clsx(
'p-1 rounded',
canReorder
? 'cursor-grab active:cursor-grabbing hover:bg-bg-hover'
: 'cursor-not-allowed opacity-30',
)}
>
<GripVertical className="w-4 h-4 text-text-muted" />
</div>
{/* 启用复选框 - 运行时或不兼容时禁用 */}
<div
className={clsx(
'flex items-center relative',
isInstanceRunning || isIncompatible ? 'opacity-50' : '',
)}
title={
isIncompatible
? incompatibleReason
: checkboxState === 'once'
? t('taskItem.runOnceHint')
: undefined
}
>
<TriStateCheckbox
state={checkboxState}
disabled={isInstanceRunning || isIncompatible}
onClick={handleCheckboxClick}
onContextMenu={handleCheckboxContextMenu}
/>
{/* 不兼容警告图标 */}
{isIncompatible && (
<AlertCircle className="w-3.5 h-3.5 text-warning absolute -top-1 -right-1 pointer-events-none" />
)}
</div>
{/* 任务名称 + 展开区域容器 */}
<div className="flex-1 flex items-center min-w-0">
{isEditing ? (
<InlineNameEditor
value={editName}
onChange={setEditName}
onSave={handleSaveEdit}
onCancel={handleCancelEdit}
placeholder={originalLabel}
/>
) : (
<>
{/* 任务名称:单击切换选中 */}
<div
className={clsx(
'flex items-center gap-1 min-w-0 overflow-hidden',
isInstanceRunning || isIncompatible ? 'cursor-not-allowed' : 'cursor-pointer',
)}
onClick={handleNameClick}
title={t('taskItem.clickToToggle')}
>
<span
className={clsx(
'min-w-0 text-sm font-medium truncate',
task.enabled
? 'text-text-primary'
: task.runOnce
? 'text-accent'
: 'text-text-muted',
)}
>
{displayName}
</span>
{task.customName && (
<span className="min-w-0 truncate text-xs text-text-muted">
({originalLabel})
</span>
)}
</div>
{/* 不带选项的任务:直接显示不兼容警告 */}
{!canExpand && isIncompatible && (
<div className="flex-1 flex items-center gap-1.5 mx-2 overflow-hidden">
<Tooltip content={supportedControllerHint || undefined}>
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 text-xs text-warning">
<AlertCircle className="w-3 h-3" />
{incompatibleReason}
</span>
</Tooltip>
</div>
)}
{/* 展开/折叠点击区域(包含选项预览) */}
{canExpand && (
<div
onClick={() => toggleTaskExpanded(instanceId, task.id)}
className="flex-1 min-w-0 flex items-center self-stretch min-h-[28px] cursor-pointer"
title={task.expanded ? t('taskItem.collapse') : t('taskItem.expand')}
>
{/* 选项预览标签 - 未展开时显示:不兼容时显示警告,否则显示选项预览 */}
{!task.expanded && (
<div className="flex-1 flex items-center gap-1.5 mx-2 overflow-hidden">
{isIncompatible ? (
<Tooltip content={supportedControllerHint || undefined}>
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 text-xs text-warning">
<AlertCircle className="w-3 h-3" />
{incompatibleReason}
</span>
</Tooltip>
) : (
showOptionPreview &&
optionPreviews.length > 0 &&
optionPreviews.map((preview) => (
<OptionPreviewTag
key={preview.key}
label={preview.label}
value={preview.value}
type={preview.type}
/>
))
)}
</div>
)}
{/* 展开/折叠箭头 */}
<div className="flex shrink-0 items-center justify-end pl-2 ml-auto">
<ChevronRight
className={clsx(
'w-4 h-4 text-text-secondary transition-transform duration-150 ease-out',
task.expanded && 'rotate-90',
)}
/>
</div>
</div>
)}
</>
)}