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
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
import { render, screen } from "@testing-library/react";
import type { MSTAnnotation, MSTStore } from "../../../stores/types";
import TaskSummary from "../TaskSummary";
 
// Polyfill for Object.groupBy which may not be available in test environment
if (!Object.groupBy) {
  Object.groupBy = <T, K extends PropertyKey>(
    items: Iterable<T>,
    keySelector: (item: T, index: number) => K,
  ): Partial<Record<K, T[]>> => {
    const result: Partial<Record<K, T[]>> = {};
    let index = 0;
    for (const item of items) {
      const key = keySelector(item, index++);
      if (!result[key]) {
        result[key] = [];
      }
      (result[key] as T[]).push(item);
    }
    return result;
  };
}
 
// Mock global APP_SETTINGS for user context
Object.defineProperty(window, "APP_SETTINGS", {
  value: {
    user: {
      id: 1,
      displayName: "Test User",
    },
  },
  writable: true,
});
 
describe("TaskSummary", () => {
  interface MockUser {
    id: number;
    displayName: string;
    firstName: string;
    lastName: string;
    username: string;
    email: string;
    initials: string;
    avatar: string | null;
    active: boolean;
  }
 
  interface MockControlTag {
    isControlTag: boolean;
    type: string;
    toname: string;
    perregion?: boolean;
    children?: Array<{ value: string; background: string }>;
  }
 
  interface MockObjectTag {
    isObjectTag: boolean;
    type: string;
    value: string;
    _value?: string;
    parsedValue?: string;
    _url?: string;
    dataObj?: Record<string, unknown>;
  }
 
  const createMockUser = (overrides: Partial<MockUser> = {}): MockUser => ({
    id: 1,
    displayName: "John Doe",
    firstName: "John",
    lastName: "Doe",
    username: "johndoe",
    email: "john@example.com",
    initials: "JD",
    avatar: null,
    active: true,
    ...overrides,
  });
 
  const createMockAnnotation = (overrides: Partial<MSTAnnotation> = {}): MSTAnnotation =>
    ({
      id: "1",
      pk: "1",
      type: "annotation",
      user: createMockUser(),
      createdBy: "John Doe",
      versions: {
        result: [{ from_name: "label", to_name: "text", type: "choices", value: { choices: ["positive"] } }],
      },
      results: [],
      ...overrides,
    }) as MSTAnnotation;
 
  const createMockControlTag = (name: string, type = "choices"): [string, MockControlTag] => [
    name,
    {
      isControlTag: true,
      type,
      toname: "text",
      perregion: false,
      children: [
        { value: "positive", background: "#ff0000" },
        { value: "negative", background: "#00ff00" },
      ],
    },
  ];
 
  const createMockObjectTag = (name: string, type = "text"): [string, MockObjectTag] => [
    name,
    {
      isObjectTag: true,
      type,
      value: `$${name}`, // Need $ prefix for object tags
      _value: "Sample text content",
    },
  ];
 
  interface MockStoreOverrides {
    task?: {
      dataObj?: Record<string, unknown>;
      agreement?: number;
    };
    project?: {
      review_settings?: {
        show_agreement_to_reviewers?: boolean;
      };
    } | null;
    store?: Record<string, unknown>;
    names?: Array<[string, MockControlTag | MockObjectTag]>;
  }
 
  const createMockStore = (overrides: MockStoreOverrides = {}): MSTStore["annotationStore"] => {
    const defaultNames = [createMockControlTag("label"), createMockObjectTag("text")];
    const allNames = [...defaultNames, ...(overrides.names || [])];
 
    const mockStore = {
      store: {
        task: {
          dataObj: { text: "Sample text", id: 1 },
          agreement: 85.5,
          ...overrides.task,
        },
        project: {
          review_settings: {
            show_agreement_to_reviewers: true,
          },
          ...overrides.project,
        },
        hasInterface: (interfaceName: string) => false,
        ...overrides.store,
      },
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      names: new Map(allNames as Array<[string, any]>),
      selectAnnotation: jest.fn(),
      selectPrediction: jest.fn(),
    };
 
    return mockStore as unknown as MSTStore["annotationStore"];
  };
 
  beforeEach(() => {
    jest.clearAllMocks();
  });
 
  it("renders the main headings", () => {
    const annotations = [createMockAnnotation()];
    const store = createMockStore();
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    expect(screen.getByText("Task Summary")).toBeInTheDocument();
    expect(screen.getByText("Task Data")).toBeInTheDocument();
  });
 
  it("displays agreement when enabled in project settings", () => {
    const annotations = [createMockAnnotation()];
    const store = createMockStore({
      project: {
        review_settings: {
          show_agreement_to_reviewers: true,
        },
      },
    });
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    expect(screen.getByText("Agreement")).toBeInTheDocument();
    expect(screen.getByText("85.5%")).toBeInTheDocument();
  });
 
  it("shows agreement when backend provides it (regardless of frontend settings)", () => {
    const annotations = [createMockAnnotation()];
    const store = createMockStore({
      project: {
        review_settings: {
          show_agreement_to_reviewers: false,
        },
      },
    });
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    // Backend controls agreement visibility, so if we have a number, show it
    expect(screen.getByText("Agreement")).toBeInTheDocument();
    expect(screen.getByText("85.5%")).toBeInTheDocument();
  });
 
  it("shows agreement even when project is null", () => {
    const annotations = [createMockAnnotation()];
    const store = createMockStore({
      project: null,
    });
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    // Backend controls agreement visibility, so if we have a number, show it
    expect(screen.getByText("Agreement")).toBeInTheDocument();
    expect(screen.getByText("85.5%")).toBeInTheDocument();
  });
 
  it("counts submitted annotations correctly (excludes drafts)", () => {
    const annotations = [
      createMockAnnotation({ pk: "1", type: "annotation" }),
      createMockAnnotation({ pk: "2", type: "annotation" }),
      createMockAnnotation({ pk: undefined, type: "annotation" }), // draft - should be excluded
      createMockAnnotation({ pk: "", type: "annotation" }), // draft - should be excluded
    ];
    const store = createMockStore();
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    expect(screen.getByText("Annotations")).toBeInTheDocument();
    expect(screen.getByText("2")).toBeInTheDocument(); // Only submitted annotations
  });
 
  it("counts predictions correctly", () => {
    const annotations = [
      createMockAnnotation({ pk: "1", type: "annotation" }),
      createMockAnnotation({ pk: "2", type: "prediction" }),
      createMockAnnotation({ pk: "3", type: "prediction" }),
      createMockAnnotation({ pk: undefined, type: "prediction" }), // draft - should be excluded
    ];
    const store = createMockStore();
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    expect(screen.getByText("Predictions")).toBeInTheDocument();
    expect(screen.getByText("2")).toBeInTheDocument(); // Only submitted predictions
  });
 
  it("renders labeling summary table with control tags", () => {
    const annotations = [
      createMockAnnotation({
        versions: {
          result: [
            { from_name: "sentiment", to_name: "text", type: "choices", value: { choices: ["positive"] } },
            { from_name: "category", to_name: "text", type: "choices", value: { choices: ["news"] } },
          ],
        },
      }),
    ];
    const store = createMockStore({
      names: new Map([
        createMockControlTag("sentiment", "choices"),
        createMockControlTag("category", "choices"),
        createMockObjectTag("text"),
      ]),
    });
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    expect(screen.getByText("Annotator")).toBeInTheDocument();
    expect(screen.getByText("sentiment")).toBeInTheDocument();
    expect(screen.getByText("category")).toBeInTheDocument();
  });
 
  it("renders data summary table with object tags", () => {
    const annotations = [createMockAnnotation()];
    const store = createMockStore({
      store: {
        task: {
          dataObj: { text: "Sample text", image: "image.jpg" },
        },
      },
      names: new Map([
        createMockControlTag("label"),
        createMockObjectTag("text", "text"),
        createMockObjectTag("image", "image"),
      ]),
    });
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    // Object tags should appear in the data summary (as header and badge)
    expect(screen.getAllByText("text")).toHaveLength(2); // header + badge
    expect(screen.getAllByText("image")).toHaveLength(2); // header + badge
  });
 
  it("handles empty annotations array", () => {
    const annotations: MSTAnnotation[] = [];
    const store = createMockStore();
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    // Should show 0 for both annotations and predictions
    expect(screen.getByText("Annotations")).toBeInTheDocument();
    expect(screen.getByText("Predictions")).toBeInTheDocument();
    expect(screen.getAllByText("0")).toHaveLength(2);
  });
 
  it("handles missing task agreement gracefully", () => {
    const annotations = [createMockAnnotation()];
    const store = createMockStore({
      store: {
        task: {
          agreement: undefined,
        },
        project: {
          review_settings: {
            show_agreement_to_reviewers: true,
          },
        },
      },
    });
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    // Should not display agreement when it's undefined
    expect(screen.queryByText("Agreement")).not.toBeInTheDocument();
  });
 
  it("processes control tags with per_region setting", () => {
    const annotations = [
      createMockAnnotation({
        versions: {
          result: [{ from_name: "regionLabel", to_name: "text", type: "choices", value: { choices: ["label1"] } }],
        },
      }),
    ];
    const controlWithPerRegion: [string, MockControlTag] = [
      "regionLabel",
      {
        isControlTag: true,
        type: "choices",
        toname: "text",
        perregion: true,
        children: [{ value: "label1", background: "#ff0000" }],
      },
    ];
 
    const store = createMockStore({
      names: new Map([controlWithPerRegion]),
    });
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    expect(screen.getByText("regionLabel")).toBeInTheDocument();
  });
 
  it("filters object tags correctly (only those with $ in value)", () => {
    const annotations = [createMockAnnotation()];
    const store = createMockStore({
      names: new Map([
        createMockControlTag("label"),
        createMockObjectTag("text", "text"), // has $ prefix - should be included
        ["invalidObject", { isObjectTag: true, value: "noDollarPrefix", type: "text" }], // no $ - should be excluded
        ["nonObject", { isObjectTag: false, value: "$text", type: "text" }], // not object tag - should be excluded
      ]),
    });
 
    render(<TaskSummary annotations={annotations} store={store} />);
 
    // Only valid object tags with $ prefix should appear (as header and badge)
    expect(screen.getAllByText("text")).toHaveLength(2); // header + badge
    expect(screen.queryByText("invalidObject")).not.toBeInTheDocument();
    expect(screen.queryByText("nonObject")).not.toBeInTheDocument();
  });
});