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
import { observer } from "mobx-react";
import { getRoot } from "mobx-state-tree";
import { Button, Tooltip } from "@humansignal/ui";
import { PauseCircleOutlined, PlayCircleOutlined } from "@ant-design/icons";
import styles from "./Paragraphs.module.scss";
import { FF_LSDV_E_278, FF_NER_SELECT_ALL, isFF } from "../../../utils/feature-flags";
import { IconPause, IconPlay, IconLsLabeling } from "@humansignal/icons";
import { useRef, useCallback, useEffect, useState } from "react";
 
const formatTime = (seconds) => {
  if (isNaN(seconds)) return "";
 
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = Math.round(seconds % 60);
 
  const formattedHours = String(hours).padStart(2, "0");
  const formattedMinutes = String(minutes).padStart(2, "0");
  const formattedSeconds = String(remainingSeconds).padStart(2, "0");
 
  return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
};
 
export const Phrases = observer(({ item, playingId, activeRef, setIsInViewPort, hasSelectedLabels }) => {
  const [animationKeyFrame, setAnimationKeyFrame] = useState(null);
  const [seek, setSeek] = useState(0);
  const [isSeek, setIsSeek] = useState(null);
  const cls = item.layoutClasses;
  const withAudio = !!item.audio;
  let observer;
 
  const phraseRefs = useRef([]);
 
  // Helper function to calculate phrase timing with fallback to audio duration
  const getPhraseTiming = useCallback(
    (phrase) => {
      if (!phrase) return { start: 0, end: 0, duration: 0 };
 
      const start = phrase.start ?? 0;
      let end;
 
      if (phrase.end !== undefined) {
        end = phrase.end;
      } else if (phrase.duration !== undefined) {
        end = start + phrase.duration;
      } else if (start !== 0) {
        // If no end or duration, default to audio duration
        end = item.audioDuration || start;
      } else {
        end = 0;
      }
 
      const duration = end - start;
 
      return { start, end, duration };
    },
    [item.audioDuration],
  );
 
  // default function to animate the reading line
  const animateElement = useCallback(
    (element, start, duration, isPlaying = true) => {
      if (!element || !isFF(FF_LSDV_E_278) || !item.contextscroll) return;
 
      const _animationKeyFrame = element.animate([{ top: `${start}%` }, { top: "100%" }], {
        easing: "linear",
        duration: duration * 1000,
      });
 
      if (isPlaying) _animationKeyFrame.play();
      else _animationKeyFrame.pause();
 
      setAnimationKeyFrame(_animationKeyFrame);
    },
    [animationKeyFrame, setAnimationKeyFrame],
  );
 
  // this function is used to animate the reading line when user seek audio
  const setSeekAnimation = useCallback(
    (isSeeking) => {
      if (!isFF(FF_LSDV_E_278) || !item.contextscroll) return;
 
      const phrase = item._value[playingId];
      const { start, end, duration } = getPhraseTiming(phrase);
      const seekDuration = end - seek.time;
      const startValue = 100 - (seekDuration * 100) / duration;
 
      if (startValue > 0 && startValue < 100)
        animateElement(activeRef.current?.querySelector(".reading-line"), startValue, seekDuration, seek.playing);
      else setIsSeek(isSeeking);
    },
    [seek, playingId, getPhraseTiming],
  );
 
  // useRef to get the reading line element
  const readingLineRef = useCallback(
    (node) => {
      if (observer) {
        observer.disconnect();
      }
 
      if (node !== null) {
        const phrase = item._value[playingId];
        const { duration } = getPhraseTiming(phrase);
 
        if (!isNaN(duration) && duration > 0) {
          animateElement(node, 0, duration, item.playing);
        }
 
        observer = new IntersectionObserver(
          (entries) => {
            setIsInViewPort(entries[0].isIntersecting);
          },
          {
            rootMargin: "0px",
          },
        );
 
        observer.observe(node);
      }
    },
    [playingId, getPhraseTiming],
  );
 
  useEffect(() => {
    if (!isFF(FF_LSDV_E_278) || !item.contextscroll) return;
 
    item.syncHandlers?.set("seek", (seek) => {
      item.handleSyncPlay(seek);
      setSeek(seek);
      setIsInViewPort(true);
    });
 
    return () => {
      observer?.disconnect();
    };
  }, []);
 
  // when user seek audio, the useEffect will be triggered and animate the reading line to the seek position
  useEffect(() => {
    setSeekAnimation(true);
  }, [seek]);
 
  // when user seek audio to a different playing phrase, the useEffect will be triggered and animate the reading line to the seek position
  useEffect(() => {
    if (!isSeek) return;
 
    setSeekAnimation(false);
  }, [playingId]);
 
  // when user click on play/pause button, the useEffect will be triggered and pause or play the reading line animation
  useEffect(() => {
    if (!isFF(FF_LSDV_E_278) || !item.contextscroll) return;
 
    if (item.playing) animationKeyFrame?.play();
    else animationKeyFrame?.pause();
  }, [item.playing]);
 
  useEffect(() => {
    // Scroll the active phrase into view and focus it when playingId changes
    if (isFF(FF_NER_SELECT_ALL) && phraseRefs.current[playingId]) {
      const element = phraseRefs.current[playingId];
      element?.focus?.();
    }
  }, [playingId]);
 
  if (!item._value) return null;
 
  const val = item._value.map((v, idx) => {
    const isActive = playingId === idx;
    const isPlaying = isActive && item.playing;
    const style = isFF(FF_LSDV_E_278) && !isActive ? item.layoutStyles(v).inactive : item.layoutStyles(v);
    const classNames = [cls.phrase];
 
    // Add newUI class when FF_LSDV_E_278 is enabled
    if (isFF(FF_LSDV_E_278)) {
      classNames.push(styles.newUI);
    }
 
    // Add extra padding class when select all button is present (FF_NER_SELECT_ALL)
    if (isFF(FF_NER_SELECT_ALL)) {
      classNames.push(styles.withSelectAllButton);
    }
 
    const isContentVisible = item.isVisibleForAuthorFilter(v);
 
    const withFormattedTime = (item) => {
      const phrase = item._value[idx];
      const { start, end } = getPhraseTiming(phrase);
 
      const startTime = formatTime(start);
      const endTime = formatTime(end);
 
      return `${startTime} - ${endTime}`;
    };
 
    if (withAudio) classNames.push(styles.withAudio);
    if (!isContentVisible) classNames.push(styles.collapsed);
    if (getRoot(item).settings.showLineNumbers) classNames.push(styles.numbered);
 
    // Add active phrase class when FF_NER_SELECT_ALL is enabled and phrase is active
    if (isFF(FF_NER_SELECT_ALL) && isActive) {
      classNames.push(styles.activePhrase);
    }
 
    // Define onClick handler based on feature flag
    const handlePhraseClick = isFF(FF_NER_SELECT_ALL) ? () => item.seekToPhrase(idx) : undefined;
 
    return (
      <div className={styles.phraseContainer}>
        {isContentVisible && !isNaN(v.start) && (
          <Button
            look="string"
            className={isFF(FF_LSDV_E_278) ? styles.playNewUi : styles.play}
            aria-label={isPlaying ? "pause" : "play"}
            disabled={!withAudio}
            icon={
              isPlaying ? (
                isFF(FF_LSDV_E_278) ? (
                  <IconPause />
                ) : (
                  <PauseCircleOutlined />
                )
              ) : isFF(FF_LSDV_E_278) ? (
                <IconPlay />
              ) : (
                <PlayCircleOutlined />
              )
            }
            onClick={(e) => {
              e.stopPropagation();
              setIsInViewPort(true);
              if (withAudio) {
                item.play(idx);
              }
            }}
          />
        )}
        {/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */}
        <div
          key={`${item.name}-${idx}`}
          ref={(el) => {
            phraseRefs.current[idx] = el;
            if (isActive && activeRef) activeRef.current = el;
          }}
          tabIndex={idx}
          data-testid={`phrase:${idx}`}
          className={classNames.join(" ")}
          style={style?.phrase}
          onClick={handlePhraseClick}
        >
          {isFF(FF_NER_SELECT_ALL) && (
            <Tooltip
              title={hasSelectedLabels ? "Label whole utterance" : "Select a label first to enable labeling"}
              placement="top"
            >
              <span className={styles.selectAllBtnWrapper}>
                <Button
                  size="small"
                  look="outlined"
                  variant="neutral"
                  disabled={!hasSelectedLabels}
                  className={styles.selectAllBtn}
                  aria-label={hasSelectedLabels ? "Label whole utterance" : "Label whole utterance (disabled)"}
                  onClick={(e) => {
                    if (hasSelectedLabels) {
                      item.selectAndAnnotatePhrase?.(idx);
                    }
                  }}
                >
                  <IconLsLabeling />
                </Button>
              </span>
            </Tooltip>
          )}
 
          {isFF(FF_LSDV_E_278) ? (
            <span className={styles.titleWrapper} data-skip-node="true">
              <span className={cls?.name} style={style?.name}>
                {v[item.namekey]}
              </span>
              <span className={styles.time}>{withFormattedTime(item)}</span>
            </span>
          ) : (
            <span className={cls?.name} data-skip-node="true" style={style?.name}>
              {v[item.namekey]}
            </span>
          )}
 
          {isFF(FF_LSDV_E_278) ? (
            <span className={styles.wrapperText}>
              {isActive && (
                <span ref={readingLineRef} className={`${styles.readingLine} reading-line`} data-skip-node="true" />
              )}
              <span className={`${cls?.text}`}>{v[item.textkey]}</span>
            </span>
          ) : (
            <span className={`${cls?.text}`}>{v[item.textkey]}</span>
          )}
        </div>
      </div>
    );
  });
 
  return val;
});