Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
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
/**
 * This panel is used with FF_1170 + FF_3873 in new interface,
 * but it's also used in old interface with FF_3873, but without FF_1170.
 * Only this component should get interface updates, other versions should be removed.
 */
 
import { observer } from "mobx-react";
import type React from "react";
import { useCallback, useState } from "react";
 
import { Button, ButtonGroup, type ButtonProps } from "@humansignal/ui";
import { IconBan, IconChevronDown } from "@humansignal/icons";
import { Dropdown } from "@humansignal/ui";
import type { CustomButtonType } from "../../stores/CustomButton";
import { cn } from "../../utils/bem";
import { FF_REVIEWER_FLOW, isFF } from "../../utils/feature-flags";
import { isDefined, toArray } from "../../utils/utilities";
import {
  AcceptButton,
  ButtonTooltip,
  controlsInjector,
  RejectButtonDefinition,
  SkipButton,
  UnskipButton,
} from "./buttons";
 
import "./Controls.scss";
 
// these buttons can be reused inside custom buttons or can be replaces with custom buttons
type SupportedInternalButtons = "accept" | "reject";
// special places for custom buttons — before, after or instead of internal buttons
type SpecialPlaces = "_before" | "_after" | "_replace";
// @todo should be Instance<typeof AppStore>["customButtons"] but it doesn't fit to itself
type CustomButtonsField = Map<
  SpecialPlaces | SupportedInternalButtons,
  CustomButtonType | SupportedInternalButtons | Array<CustomButtonType | SupportedInternalButtons>
>;
type ControlButtonProps = {
  button: CustomButtonType;
  disabled: boolean;
  variant?: ButtonProps["variant"];
  look?: ButtonProps["look"];
  onClick: (e: React.MouseEvent) => void;
};
 
export const EMPTY_SUBMIT_TOOLTIP = "此项目不允许空标注";
 
/**
 * Custom action button component, rendering buttons from store.customButtons
 */
const ControlButton = observer(({ button, disabled, onClick, variant, look }: ControlButtonProps) => {
  return (
    <Button
      {...button.props}
      variant={button.variant ?? variant}
      look={button.look ?? look}
      tooltip={button.tooltip}
      className="w-[150px]"
      aria-label={button.ariaLabel}
      disabled={button.disabled || disabled}
      onClick={onClick}
    >
      {button.title}
    </Button>
  );
});
 
export const Controls = controlsInjector<{ annotation: MSTAnnotation }>(
  observer(({ store, history, annotation }) => {
    const isReview = store.hasInterface("review") || annotation.canBeReviewed;
    const isNotQuickView = store.hasInterface("topbar:prevnext");
    const historySelected = isDefined(store.annotationStore.selectedHistory);
    const { userGenerate, sentUserGenerate, versions, results, editable: annotationEditable } = annotation;
    const dropdownTrigger = cn("dropdown").elem("trigger").toClassName();
    const customButtons: CustomButtonsField = store.customButtons;
    const buttons: React.ReactNode[] = [];
 
    const [isInProgress, setIsInProgress] = useState(false);
    const disabled = !annotationEditable || store.isSubmitting || historySelected || isInProgress;
    const submitDisabled = store.hasInterface("annotations:deny-empty") && results.length === 0;
 
    /** Check all things related to comments and then call the action if all is good */
    const handleActionWithComments = useCallback(
      async (e: React.MouseEvent, callback: () => any, errorMessage: string) => {
        const { addedCommentThisSession, currentComment, commentFormSubmit } = store.commentStore;
        const comment = currentComment[annotation.id];
        // accept both old and new comment formats
        const commentText = (comment?.text ?? comment)?.trim();
 
        if (isInProgress) return;
        setIsInProgress(true);
 
        const selected = store.annotationStore?.selected;
 
        if (addedCommentThisSession) {
          selected?.submissionInProgress();
          callback();
        } else if (commentText) {
          e.preventDefault();
          selected?.submissionInProgress();
          await commentFormSubmit();
          callback();
        } else {
          store.commentStore.setTooltipMessage(errorMessage);
        }
        setIsInProgress(false);
      },
      [
        store.rejectAnnotation,
        store.skipTask,
        store.commentStore.currentComment,
        store.commentStore.commentFormSubmit,
        store.commentStore.addedCommentThisSession,
        isInProgress,
      ],
    );
 
    if (annotation.isNonEditableDraft) return <></>;
 
    const buttonsBefore = customButtons.get("_before");
    const buttonsReplacement = customButtons.get("_replace");
    const firstToRender = buttonsReplacement ?? buttonsBefore;
 
    // either we render _before buttons and then the rest, or we render only _replace buttons
    if (firstToRender) {
      const allButtons = toArray(firstToRender);
      for (const customButton of allButtons) {
        // @todo make a list of all internal buttons and use them here to mix custom buttons with internal ones
        // string buttons is a way to render internal buttons
        if (typeof customButton === "string") {
          if (customButton === "accept") {
            // just an example of internal button usage
            // @todo move buttons to separate components
            buttons.push(<AcceptButton key={customButton} disabled={disabled} history={history} store={store} />);
          }
        } else {
          buttons.push(
            <ControlButton
              key={customButton.name}
              disabled={disabled}
              button={customButton}
              onClick={() => store.handleCustomButton?.(customButton)}
            />,
          );
        }
      }
    }
 
    if (buttonsReplacement) {
      return <div className={cn("controls").toClassName()}>{buttons}</div>;
    }
 
    if (isReview) {
      const customRejectButtons = toArray(customButtons.get("reject"));
      const hasCustomReject = customRejectButtons.length > 0;
      const originalRejectButton = RejectButtonDefinition;
 
      // @todo implement reuse of internal buttons later (they are set as strings)
      const rejectButtons: CustomButtonType[] = hasCustomReject
        ? customRejectButtons.filter((button) => typeof button !== "string")
        : [originalRejectButton];
 
      rejectButtons.forEach((button) => {
        const action = hasCustomReject ? () => store.handleCustomButton?.(button) : () => store.rejectAnnotation({});
 
        const onReject = async (e: React.MouseEvent) => {
          const selected = store.annotationStore?.selected;
 
          if (store.hasInterface("comments:reject")) {
            handleActionWithComments(e, action, "请在拒绝前输入评论");
          } else {
            selected?.submissionInProgress();
            await store.commentStore.commentFormSubmit();
            action();
          }
        };
 
        buttons.push(<ControlButton key={button.name} button={button} disabled={disabled} onClick={onReject} />);
      });
      buttons.push(<AcceptButton key="review-accept" disabled={disabled} history={history} store={store} />);
    } else if (annotation.skipped) {
      buttons.push(
        <div className={cn("controls").elem("skipped-info").toClassName()} key="skipped">
          <IconBan /> 已跳过
        </div>,
      );
      buttons.push(<UnskipButton key="unskip" disabled={disabled} store={store} />);
    } else {
      if (store.hasInterface("skip")) {
        const onSkipWithComment = (e: React.MouseEvent, action: () => any) => {
          handleActionWithComments(e, action, "请在跳过前输入评论");
        };
 
        buttons.push(<SkipButton key="skip" disabled={disabled} store={store} onSkipWithComment={onSkipWithComment} />);
      }
 
      const isDisabled = disabled || submitDisabled;
 
      const useExitOption = !isDisabled && isNotQuickView;
 
      const SubmitOption = ({
        isUpdate,
        onClickMethod,
      }: {
        isUpdate: boolean;
        onClickMethod: () => any;
      }) => {
        return (
          <div className="p-tighter rounded">
            <Button
              name="submit-option"
              look="string"
              size="small"
              className="w-[150px]"
              onClick={async (event) => {
                event.preventDefault();
 
                const selected = store.annotationStore?.selected;
 
                selected?.submissionInProgress();
 
                if ("URLSearchParams" in window) {
                  const searchParams = new URLSearchParams(window.location.search);
 
                  searchParams.set("exitStream", "true");
                  const newRelativePathQuery = `${window.location.pathname}?${searchParams.toString()}`;
 
                  window.history.pushState(null, "", newRelativePathQuery);
                }
 
                await store.commentStore.commentFormSubmit();
                onClickMethod();
              }}
            >
              {`${isUpdate ? "更新" : "提交"} 并退出`}
            </Button>
          </div>
        );
      };
 
      if (userGenerate || (store.explore && !userGenerate && store.hasInterface("submit"))) {
        const title = submitDisabled ? EMPTY_SUBMIT_TOOLTIP : "保存结果: [ Ctrl+Enter ]";
 
        buttons.push(
          <ButtonTooltip key="submit" title={title}>
            <div className={cn("controls").elem("tooltip-wrapper").toClassName()}>
              <ButtonGroup>
                <Button
                  aria-label="Submit current annotation"
                  name="submit"
                  className="w-[150px]"
                  disabled={isDisabled}
                  onClick={async (event) => {
                    if ((event.target as HTMLButtonElement).classList.contains(dropdownTrigger)) return;
                    const selected = store.annotationStore?.selected;
 
                    selected?.submissionInProgress();
                    await store.commentStore.commentFormSubmit();
                    store.submitAnnotation();
                  }}
                >
                  Submit
                  提交
                </Button>
                {useExitOption ? (
                  <Dropdown.Trigger
                    alignment="top-right"
                    content={
                      <div className="p-tight bg-neutral-surface">
                        <SubmitOption onClickMethod={store.submitAnnotation} isUpdate={false} />
                      </div>
                    }
                  >
                    <Button disabled={isDisabled} aria-label="Submit annotation">
                      <IconChevronDown />
                    </Button>
                  </Dropdown.Trigger>
                ) : null}
              </ButtonGroup>
            </div>
          </ButtonTooltip>,
        );
      } else if ((userGenerate && sentUserGenerate) || (!userGenerate && store.hasInterface("update"))) {
        const isUpdate = Boolean(isFF(FF_REVIEWER_FLOW) || sentUserGenerate || versions.result);
        // no changes were made over previously submitted version — no drafts, no pending changes
        const noChanges = isFF(FF_REVIEWER_FLOW) && !history.canUndo && !annotation.draftId;
        const isUpdateDisabled = isDisabled || noChanges;
        const button = (
          <ButtonTooltip key="update" title={noChanges ? "未做更改" : "更新此任务: [ Ctrl+Enter ]"}>
            <ButtonGroup>
              <Button
                aria-label="submit"
                name="submit"
                className="w-[150px]"
                disabled={isUpdateDisabled}
                onClick={async (event) => {
                  if ((event.target as HTMLButtonElement).classList.contains(dropdownTrigger)) return;
                  const selected = store.annotationStore?.selected;
 
                  selected?.submissionInProgress();
                  await store.commentStore.commentFormSubmit();
                  store.updateAnnotation();
                }}
              >
                {isUpdate ? "更新" : "提交"}
              </Button>
              {useExitOption ? (
                <Dropdown.Trigger
                  alignment="top-right"
                  content={<SubmitOption onClickMethod={store.updateAnnotation} isUpdate={isUpdate} />}
                >
                  <Button disabled={isUpdateDisabled} aria-label="Update annotation">
                    <IconChevronDown />
                  </Button>
                </Dropdown.Trigger>
              ) : null}
            </ButtonGroup>
          </ButtonTooltip>
        );
 
        buttons.push(button);
      }
    }
 
    return <div className={cn("controls").toClassName()}>{buttons}</div>;
  }),
);