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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
import React, { Component, useCallback } from "react";
import { inject, observer } from "mobx-react";
 
import ObjectTag from "../../../components/Tags/Object";
import { FF_DEV_2669, FF_DEV_2918, FF_LSDV_E_278, FF_NER_SELECT_ALL, isFF } from "../../../utils/feature-flags";
import { findNodeAt, matchesSelector, splitBoundaries } from "../../../utils/html";
import { patchPlayPauseMethods } from "../../../utils/patchPlayPauseMethods";
import { isSelectionContainsSpan } from "../../../utils/selection-tools";
import { useUpdateBuffering } from "../../../hooks/useUpdateBuffering";
import styles from "./Paragraphs.module.scss";
import { AuthorFilter } from "./AuthorFilter";
import { Phrases } from "./Phrases";
import { IconHelp } from "@humansignal/icons";
import { Toggle, Tooltip } from "@humansignal/ui";
import { cn } from "../../../utils/bem";
import { cnm } from "@humansignal/shad/utils";
import { ff } from "@humansignal/core";
import { useHotkey } from "../../../hooks/useHotkey";
 
const audioDefaultProps = { crossOrigin: "anonymous" };
const isSyncedBuffering = ff.isActive(ff.FF_SYNCED_BUFFERING);
 
// Separate functional component to handle hotkeys
const ParagraphHotkeys = ({ item }) => {
  if (!isFF(FF_NER_SELECT_ALL)) return null;
 
  useHotkey("phrases:next-phrase", () => {
    item._viewRef?.handleNextPhrase();
  });
  useHotkey("phrases:previous-phrase", () => {
    item._viewRef?.handlePreviousPhrase();
  });
  useHotkey("phrases:select_all_annotate", () => {
    item.selectAllAndAnnotateCurrentPhrase();
  });
  useHotkey("phrases:next-region", () => {
    item._viewRef?.handleNextRegion();
  });
  useHotkey("phrases:previous-region", () => {
    item._viewRef?.handlePreviousRegion();
  });
 
  return null; // This component renders nothing
};
 
const ParagraphAudio = observer(({ item }) => {
  const isBuffering = isSyncedBuffering && item.isBuffering;
 
  const updateBuffering = useUpdateBuffering(item.audioRef, item.handleBuffering);
 
  const attachRef = useCallback(
    (audio) => {
      if (audio) {
        audio = patchPlayPauseMethods(audio);
      }
      if (item.audioRef instanceof Function) {
        item.audioRef(audio);
      } else if (item.audioRef) {
        item.audioRef.current = audio;
      }
    },
    [item],
  );
 
  return (
    <>
      {isBuffering && <div className="lsf-timeline-controls__buffering" aria-label="Buffering Media Source" />}
      <audio
        {...audioDefaultProps}
        controls={item.showplayer && !item.syncedAudio}
        className={styles.audio}
        src={item.audio}
        ref={attachRef}
        onLoadedMetadata={item.handleAudioLoaded}
        onEnded={item.reset}
        onError={item.handleError}
        {...(isSyncedBuffering
          ? {
            onCanPlay: updateBuffering,
            onWaiting: updateBuffering,
          }
          : {})}
      />
    </>
  );
});
 
class HtxParagraphsView extends Component {
  // Constants for scroll behavior
  static SCROLL_FLAG_TIMEOUT = 100;
 
  _regionSpanSelector = ".htx-highlight";
  mainContentSelector = `.${cn("main-content").toClassName()}`;
  mainViewAnnotationSelector = `.${cn("main-view").elem("annotation").toClassName()}`;
 
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.activeRef = React.createRef();
    this.lastPlayingId = -1;
    this.scrollTimeout = [];
    this.isPlaying = false;
    this.isProgrammaticScroll = false;
    this.state = {
      canScroll: true,
      inViewPort: true,
    };
  }
 
  // Helper method to safely perform programmatic scrolling
  performProgrammaticScroll(top) {
    this.isProgrammaticScroll = true;
    this.myRef.current.scrollTo({
      top: Math.max(0, top),
      behavior: "smooth",
    });
    setTimeout(() => {
      this.isProgrammaticScroll = false;
    }, HtxParagraphsView.SCROLL_FLAG_TIMEOUT);
  }
 
  // Helper method to check if scrolling should happen
  shouldScroll() {
    return (
      isFF(FF_LSDV_E_278) &&
      this.props.item.contextscroll &&
      this.props.item.playingId >= 0 &&
      this.lastPlayingId !== this.props.item.playingId &&
      this.state.canScroll &&
      this.state.inViewPort
    );
  }
 
  // Helper method to get container padding
  getContainerPadding() {
    return Number.parseInt(window.getComputedStyle(this.myRef.current)?.getPropertyValue("padding-top")) || 0;
  }
 
  // Helper method to calculate precise phrase position
  calculatePhraseScrollPosition(playingId) {
    const root = this.myRef.current;
    const phraseElement = root.querySelector(`[data-testid="phrase:${playingId}"]`);
 
    if (!phraseElement) return 0;
 
    const phraseRect = phraseElement.getBoundingClientRect();
    const containerRect = root.getBoundingClientRect();
 
    return phraseRect.top - containerRect.top + root.scrollTop;
  }
 
  // Helper method to handle tall phrases that need multiple scroll steps
  handleTallPhraseScroll(phraseHeight, duration) {
    const padding = this.getContainerPadding();
    const wrapperOffsetTop = this.activeRef.current?.offsetTop - padding;
    const splitSteps = Math.ceil(this.activeRef.current?.offsetHeight / this.myRef.current?.offsetHeight) + 1;
 
    for (let i = 0; i < splitSteps; i++) {
      this.scrollTimeout.push(
        setTimeout(
          () => {
            const scrollPosition = wrapperOffsetTop + phraseHeight * (i * (1 / splitSteps));
            if (this.state.inViewPort && this.state.canScroll) {
              this.performProgrammaticScroll(scrollPosition);
            }
          },
          (duration / splitSteps) * i * 1000,
        ),
      );
    }
  }
 
  // Helper method to handle normal-sized phrases
  handleNormalPhraseScroll() {
    if (!this.state.inViewPort) return;
 
    if (this.props.item.playingId <= 0) {
      // Special case: scroll to top with padding for beginning
      this.performProgrammaticScroll(this.getContainerPadding());
    } else {
      // Use precise positioning to ensure phrase is at the top
      const targetScrollTop = this.calculatePhraseScrollPosition(this.props.item.playingId);
      this.performProgrammaticScroll(targetScrollTop);
    }
  }
 
  getSelectionText(sel) {
    return sel.toString();
  }
 
  getPhraseElement(node) {
    const cls = this.props.item.layoutClasses;
 
    while (node && (!node.classList || !node.classList.contains(cls.text))) node = node.parentNode;
    return node;
  }
 
  get phraseElements() {
    return [...this.myRef.current.getElementsByClassName(this.props.item.layoutClasses.text)];
  }
 
  /**
   * Check for the selection in the phrase and return the offset and index.
   *
   * @param {HTMLElement} node
   * @param {number} offset
   * @param {boolean} [isStart=true]
   * @return {Array} [offset, node, index, originalIndex]
   */
  getOffsetInPhraseElement(container, offset, isStart = true) {
    const node = this.getPhraseElement(container);
    const range = document.createRange();
 
    range.setStart(node, 0);
    range.setEnd(container, offset);
    const fullOffset = range.toString().length;
    const phraseIndex = this.phraseElements.indexOf(node);
    let phraseNode = node;
 
    // if the selection is made from the very end of a given phrase, we need to
    // move the offset to the beginning of the next phrase
    if (isStart && fullOffset === phraseNode.textContent.length) {
      return [0, phraseNode, phraseIndex + 1, phraseIndex];
    }
    // if the selection is made to the very beginning of the next phrase, we need to
    // move the offset to the end of the previous phrase
    if (!isStart && fullOffset === 0) {
      phraseNode = this.phraseElements[phraseIndex - 1];
      return [phraseNode.textContent.length, phraseNode, phraseIndex - 1, phraseIndex];
    }
 
    return [fullOffset, phraseNode, phraseIndex, phraseIndex];
  }
 
  removeSurroundingNewlines(text) {
    return text.replace(/^\n+/, "").replace(/\n+$/, "");
  }
 
  captureDocumentSelection() {
    const item = this.props.item;
    const cls = item.layoutClasses;
    const names = [...this.myRef.current.getElementsByClassName(cls.name)];
 
    names.forEach((el) => {
      el.style.visibility = "hidden";
    });
 
    let i;
 
    const ranges = [];
    const selection = window.getSelection();
 
    if (selection.isCollapsed) {
      names.forEach((el) => {
        el.style.visibility = "unset";
      });
      return [];
    }
 
    for (i = 0; i < selection.rangeCount; i++) {
      const r = selection.getRangeAt(i);
 
      if (r.endContainer.nodeType !== Node.TEXT_NODE) {
        // offsets work differently for nodes and texts, so we have to find #text.
        // lastChild because most probably this is div of the whole paragraph,
        // and it has author div and phrase div.
        const el = this.getPhraseElement(r.endContainer.lastChild);
        let textNode = el;
 
        while (textNode && textNode.nodeType !== Node.TEXT_NODE) {
          textNode = textNode.firstChild;
        }
 
        // most probably this div is out of Paragraphs
        // @todo maybe select till the end of Paragraphs?
        if (!textNode) continue;
 
        r.setEnd(textNode, 0);
      }
 
      if (r.collapsed || /^\s*$/.test(r.toString())) continue;
 
      try {
        splitBoundaries(r);
        const [startOffset, , start, originalStart] = this.getOffsetInPhraseElement(r.startContainer, r.startOffset);
        const [endOffset, , end, _originalEnd] = this.getOffsetInPhraseElement(r.endContainer, r.endOffset, false);
 
        // if this shifts backwards, we need to take the lesser index.
        const originalEnd = Math.min(end, _originalEnd);
 
        if (isFF(FF_DEV_2918)) {
          const visibleIndexes = item._value.reduce((visibleIndexes, v, idx) => {
            const isContentVisible = item.isVisibleForAuthorFilter(v);
 
            if (isContentVisible && originalStart <= idx && originalEnd >= idx) {
              visibleIndexes.push(idx);
            }
 
            return visibleIndexes;
          }, []);
 
          if (visibleIndexes.length !== originalEnd - originalStart + 1) {
            const texts = this.phraseElements;
            let fromIdx = originalStart;
 
            for (let k = 0; k < visibleIndexes.length; k++) {
              const curIdx = visibleIndexes[k];
              const isLastVisibleIndex = k === visibleIndexes.length - 1;
 
              if (isLastVisibleIndex || visibleIndexes[k + 1] !== curIdx + 1) {
                let anchorOffset;
                let focusOffset;
 
                const _range = r.cloneRange();
 
                if (fromIdx === originalStart) {
                  fromIdx = start;
                  anchorOffset = startOffset;
                } else {
                  anchorOffset = 0;
 
                  const walker = texts[fromIdx].ownerDocument.createTreeWalker(texts[fromIdx], NodeFilter.SHOW_ALL);
 
                  while (walker.firstChild());
 
                  _range.setStart(walker.currentNode, anchorOffset);
                }
                if (curIdx === end) {
                  focusOffset = endOffset;
                } else {
                  const curRange = document.createRange();
 
                  curRange.selectNode(texts[curIdx]);
                  focusOffset = curRange.toString().length;
 
                  const walker = texts[curIdx].ownerDocument.createTreeWalker(texts[curIdx], NodeFilter.SHOW_ALL);
 
                  while (walker.lastChild());
 
                  _range.setEnd(walker.currentNode, walker.currentNode.length);
                }
 
                selection.removeAllRanges();
                selection.addRange(_range);
 
                const text = this.removeSurroundingNewlines(selection.toString());
 
                // Sometimes the selection is empty, which is the case for dragging from the end of a line above the
                // target line, while having collapsed lines between.
                if (text) {
                  ranges.push({
                    startOffset: anchorOffset,
                    start: String(fromIdx),
                    endOffset: focusOffset,
                    end: String(curIdx),
                    _range,
                    text,
                  });
                }
 
                if (visibleIndexes.length - 1 > k) {
                  fromIdx = visibleIndexes[k + 1];
                }
              }
            }
          } else {
            // user selection always has only one range, so we can use selection's text
            // which doesn't contain hidden elements (names in our case)
            ranges.push({
              startOffset,
              start: String(start),
              endOffset,
              end: String(end),
              _range: r,
              text: this.removeSurroundingNewlines(selection.toString()),
            });
          }
        } else {
          // user selection always has only one range, so we can use selection's text
          // which doesn't contain hidden elements (names in our case)
          ranges.push({
            startOffset,
            start: String(start),
            endOffset,
            end: String(end),
            _range: r,
            text: this.removeSurroundingNewlines(selection.toString()),
          });
        }
      } catch (err) {
        console.error("Can not get selection", err);
      }
    }
 
    names.forEach((el) => {
      el.style.visibility = "unset";
    });
 
    // BrowserRange#normalize() modifies the DOM structure and deselects the
    // underlying text as a result. So here we remove the selected ranges and
    // reapply the new ones.
    selection.removeAllRanges();
 
    return ranges;
  }
 
  // Removed unused expandSelectionForTripleClickSync and expandSelectionForTripleClickDebounced methods
 
  _selectRegions = (additionalMode) => {
    const { item } = this.props;
    const root = this.myRef.current;
    const selection = window.getSelection();
    const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
    const regions = [];
 
    while (walker.nextNode()) {
      const node = walker.currentNode;
 
      if (node.nodeName === "SPAN" && node.matches(this._regionSpanSelector) && isSelectionContainsSpan(node)) {
        const region = this._determineRegion(node);
 
        regions.push(region);
      }
    }
    if (regions.length) {
      if (additionalMode) {
        item.annotation.extendSelectionWith(regions);
      } else {
        item.annotation.selectAreas(regions);
      }
      selection.removeAllRanges();
    }
  };
 
  _determineRegion(element) {
    if (matchesSelector(element, this._regionSpanSelector)) {
      const span = element.tagName === "SPAN" ? element : element.closest(this._regionSpanSelector);
      const { item } = this.props;
 
      return item.regs.find((region) => region.find(span));
    }
  }
 
  _disposeTimeout() {
    if (this.scrollTimeout.length > 0) {
      this.scrollTimeout.forEach((timeout) => clearTimeout(timeout));
      this.scrollTimeout = [];
    }
  }
 
  // Removed unused processAnnotation method
 
  // Removed unused expandSelectionForTripleClick method
 
  /**
   * Capture document selection from a specific range
   */
  captureDocumentSelectionFromRange(range) {
    // Create a temporary selection with our expanded range
    const tempSelection = window.getSelection();
    tempSelection.removeAllRanges();
    tempSelection.addRange(range);
    // Use existing capture logic
    const result = this.captureDocumentSelection();
    return result;
  }
 
  /**
   * Check if creating a region would result in a duplicate
   * Only checks when FF_NER_SELECT_ALL is enabled
   * Prevents exact same position + exact same labels + exact same offsets
   */
  isDuplicateRegion(range, selectedLabels, control) {
    if (!isFF(FF_NER_SELECT_ALL)) {
      return false; // No duplicate detection when feature flag is off
    }
 
    const phraseStart = Number.parseInt(range.start, 10);
    const phraseEnd = Number.parseInt(range.end, 10);
    const startOffset = range.startOffset || 0;
    const endOffset = range.endOffset || 0;
 
    const item = this.props.item;
    const existingRegions = item.regs.filter((region) => {
      const regionStart = Number.parseInt(region.start, 10);
      const regionEnd = Number.parseInt(region.end, 10);
      const regionStartOffset = region.startOffset || 0;
      const regionEndOffset = region.endOffset || 0;
 
      // Only check for IDENTICAL boundaries AND offsets - allow any differences
      if (
        regionStart !== phraseStart ||
        regionEnd !== phraseEnd ||
        regionStartOffset !== startOffset ||
        regionEndOffset !== endOffset
      ) {
        return false; // Different boundaries or offsets = not a duplicate, allow it
      }
 
      // Boundaries and offsets are identical, now check if labels match exactly
      const labelingResult = region.results?.find((r) => r.from_name?.isLabeling);
      const regionLabels = labelingResult?.mainValue || [];
 
      // Check if labels match exactly
      if (selectedLabels.length !== regionLabels.length) {
        return false; // Different number of labels = not a duplicate
      }
 
      // Same boundaries + same offsets + same labels = true duplicate
      return selectedLabels.every((label) => regionLabels.includes(label));
    });
 
    return existingRegions.length > 0;
  }
 
  /**
   * Create annotation from selected ranges. If the enhanced feature is enabled,
   * the newly created region will be automatically selected.
   * @param {Array} selectedRanges - The ranges to create annotations from
   */
  createAnnotationFromRanges(selectedRanges) {
    const item = this.props.item;
 
    // Check for duplicates using centralized logic
    if (selectedRanges && selectedRanges.length > 0) {
      // Get currently selected labels - use same logic as addRegions (states[0])
      const states = item.activeStates && item.activeStates();
      if (states && states.length > 0) {
        const control = states[0]; // Match addRegions logic - use first control
        const selectedLabels = control.selectedValues() || [];
 
        // Check ALL ranges for duplicates, not just the first one
        for (const range of selectedRanges) {
          if (this.isDuplicateRegion(range, selectedLabels, control)) {
            return; // Block the entire operation if ANY range would be a duplicate
          }
        }
      }
    }
 
    item._currentSpan = null;
    let createdRegion = null;
    // Check if a label is selected
    const states = item.activeStates && item.activeStates();
    if (!states || states.length === 0) {
      console.warn("No label selected. Annotation will not be created.");
    }
    if (isFF(FF_DEV_2918)) {
      const htxRanges = item.addRegions(selectedRanges);
      if (htxRanges && htxRanges.length > 0) {
        createdRegion = htxRanges[0]; // Get the first created region
        for (const htxRange of htxRanges) {
          const spans = htxRange.createSpans();
          htxRange.addEventsToSpans(spans);
        }
      }
    } else {
      createdRegion = item.addRegion(selectedRanges[0]);
      if (createdRegion) {
        const spans = createdRegion.createSpans();
        createdRegion.addEventsToSpans(spans);
      }
    }
  }
 
  createAnnotationForPhrase = (phraseIndex) => {
    const item = this.props.item;
    const phrases = item._value;
    if (!phrases || phraseIndex < 0 || phraseIndex >= phrases.length) return;
    const cls = item.layoutClasses;
    const phraseElements = this.myRef.current?.getElementsByClassName(cls.text);
    if (!phraseElements) return;
    const phraseElement = phraseElements[phraseIndex];
    if (!phraseElement) return;
 
    // Find the first and last text nodes in the phrase
    const walker = document.createTreeWalker(phraseElement, NodeFilter.SHOW_TEXT, null, false);
    const firstTextNode = walker.nextNode();
    if (!firstTextNode) return;
    let lastTextNode = firstTextNode;
    let currentNode;
    while ((currentNode = walker.nextNode())) {
      lastTextNode = currentNode;
    }
    // Create a range that covers the entire phrase
    const range = document.createRange();
    range.setStart(firstTextNode, 0);
    range.setEnd(lastTextNode, lastTextNode.textContent.length);
    // Set the selection in the DOM for visual feedback
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
    // Use the same logic as manual selection to create the annotation
    const selectedRanges = this.captureDocumentSelectionFromRange(range);
    if (selectedRanges.length > 0) {
      this.createAnnotationFromRanges(selectedRanges);
    }
  };
 
  onMouseUp(ev) {
    const item = this.props.item;
    const states = item.activeStates();
 
    if (!states || states.length === 0 || ev.ctrlKey || ev.metaKey)
      return this._selectRegions(ev.ctrlKey || ev.metaKey);
 
    if (item.annotation.isReadOnly()) {
      return;
    }
 
    const selectedRanges = this.captureDocumentSelection();
    if (selectedRanges.length === 0) {
      return;
    }
    item._currentSpan = null;
 
    let createdRegion = null;
 
    if (isFF(FF_DEV_2918)) {
      const htxRanges = item.addRegions(selectedRanges);
      if (htxRanges && htxRanges.length > 0) {
        createdRegion = htxRanges[0];
      }
      for (const htxRange of htxRanges) {
        const spans = htxRange.createSpans();
        htxRange.addEventsToSpans(spans);
      }
    } else {
      createdRegion = item.addRegion(selectedRanges[0]);
      if (createdRegion) {
        const spans = createdRegion.createSpans();
        createdRegion.addEventsToSpans(spans);
      }
    }
  }
 
  /**
   * Generates a textual representation of the current selection range.
   *
   * @param {number} start
   * @param {number} end
   * @param {number} startOffset
   * @param {number} endOffset
   * @returns {string}
   */
  _getResultText(start, end, startOffset, endOffset) {
    const phrases = this.phraseElements;
 
    if (start === end) return phrases[start].innerText.slice(startOffset, endOffset);
 
    return [
      phrases[start].innerText.slice(startOffset),
      phrases.slice(start + 1, end).map((phrase) => phrase.innerText),
      phrases[end].innerText.slice(0, endOffset),
    ]
      .flat()
      .join("");
  }
 
  _handleUpdate() {
    const root = this.myRef.current;
    const { item } = this.props;
 
    // wait until text is loaded
    if (!item._value) return;
 
    item.regs.forEach((r, i) => {
      // spans can be totally missed if this is app init or undo/redo
      // or they can be disconnected from DOM on annotations switching
      // so we have to recreate them from regions data
      if (r._spans?.[0]?.isConnected) return;
 
      try {
        const phrases = root.children;
        const range = document.createRange();
        const startNode = phrases[r.start].getElementsByClassName(item.layoutClasses.text)[0];
        const endNode = phrases[r.end].getElementsByClassName(item.layoutClasses.text)[0];
 
        let { startOffset, endOffset } = r;
 
        range.setStart(...findNodeAt(startNode, startOffset));
        range.setEnd(...findNodeAt(endNode, endOffset));
 
        if (r.text && range.toString().replace(/\s+/g, "") !== r.text.replace(/\s+/g, "")) {
          console.info("Restore broken position", i, range.toString(), "->", r.text, r);
          if (
            // span breaks the mock-up by its end, so the start of next one is wrong
            item.regs.slice(0, i).some((other) => r.start === other.end) &&
            // for now there are no fallback for huge wrong regions
            r.start === r.end
          ) {
            // find region's text in the node (disregarding spaces)
            const match = startNode.textContent.match(new RegExp(r.text.replace(/\s+/g, "\\s+")));
 
            if (!match) console.warn("Can't find the text", r);
            const { index = 0 } = match || {};
 
            if (r.endOffset - r.startOffset !== r.text.length)
              console.warn("Text length differs from region length; possible regions overlap");
            startOffset = index;
            endOffset = startOffset + r.text.length;
 
            range.setStart(...findNodeAt(startNode, startOffset));
            range.setEnd(...findNodeAt(endNode, endOffset));
            r.fixOffsets(startOffset, endOffset);
          }
        } else if (!r.text && range.toString()) {
          r.setText(this._getResultText(+r.start, +r.end, startOffset, endOffset));
        }
 
        splitBoundaries(range);
 
        r._range = range;
        const spans = r.createSpans();
 
        r.addEventsToSpans(spans);
      } catch (err) {
        console.log(err, r);
      }
    });
 
    Array.from(this.myRef.current.getElementsByTagName("a")).forEach((a) => {
      a.addEventListener("click", (ev) => {
        ev.preventDefault();
        return false;
      });
    });
 
    if (this.shouldScroll()) {
      const playingItem = this.props.item._value[this.props.item.playingId];
      const phraseHeight = this.activeRef.current?.offsetHeight || 0;
      const duration = playingItem.duration || playingItem.end - playingItem.start;
      const wrapperHeight = root.offsetHeight;
 
      this._disposeTimeout();
 
      if (phraseHeight > wrapperHeight) {
        // Handle tall phrases that need multiple scroll steps
        this.handleTallPhraseScroll(phraseHeight, duration);
      } else {
        // Handle normal-sized phrases
        this.handleNormalPhraseScroll();
      }
      this.lastPlayingId = this.props.item.playingId;
    }
  }
 
  _handleScrollContainerHeight = () => {
    requestAnimationFrame(() => {
      const container = this.myRef.current;
      const mainContentView = document.querySelector(this.mainContentSelector);
      const mainRect = mainContentView.getBoundingClientRect();
      const visibleHeight = document.documentElement.clientHeight - mainRect.top;
      const annotationView = document.querySelector(this.mainViewAnnotationSelector);
      const totalVisibleSpace = Math.floor(
        visibleHeight < mainRect.height ? visibleHeight : mainContentView?.offsetHeight || 0,
      );
      const filledSpace = annotationView?.offsetHeight || mainContentView.firstChild?.offsetHeight || 0;
      const containerHeight = container?.offsetHeight || 0;
      const viewPadding =
        Number.parseInt(window.getComputedStyle(mainContentView)?.getPropertyValue("padding-bottom")) || 0;
      const height = totalVisibleSpace - (filledSpace - containerHeight) - viewPadding;
      const minHeight = 100;
 
      if (container) this.myRef.current.style.maxHeight = `${height < minHeight ? minHeight : height}px`;
    });
  };
 
  _resizeObserver = new ResizeObserver(this._handleScrollContainerHeight);
 
  componentDidUpdate() {
    this._handleUpdate();
  }
 
  componentDidMount() {
    if (isFF(FF_LSDV_E_278) && this.props.item.contextscroll)
      this._resizeObserver.observe(document.querySelector(this.mainContentSelector));
    this._handleUpdate();
 
    // Set default selection to first phrase when there's no audio
    const { item } = this.props;
    if (!item.audio && item._value && item._value.length > 0 && item.playingId === -1) {
      item.seekToPhrase(0);
    }
 
    if (isFF(FF_NER_SELECT_ALL)) {
      item.setViewRef(this);
    }
  }
 
  componentWillUnmount() {
    const target = document.querySelector(this.mainContentSelector);
 
    if (target) this._resizeObserver?.unobserve(target);
    this._resizeObserver?.disconnect();
    if (isFF(FF_NER_SELECT_ALL)) {
      this.props.item.setViewRef(null);
    }
  }
 
  // Check if any labels are selected for the current annotation (reactive to MobX changes)
  get hasSelectedLabels() {
    if (!isFF(FF_NER_SELECT_ALL)) return false;
 
    try {
      const { item } = this.props;
      const states = item.activeStates && item.activeStates();
 
      return !!(states && states.length > 0);
    } catch (error) {
      console.warn("Error checking selected labels:", error);
      return false;
    }
  }
 
  selectText = (phraseIndex) => {
    const item = this.props.item;
    const phrases = item._value;
    const cls = item.layoutClasses;
    const phraseElements = this.myRef.current?.getElementsByClassName(cls.text);
 
    if (!phrases || phraseIndex < 0 || phraseIndex >= phrases.length || !phraseElements) return;
 
    const phraseElement = phraseElements[phraseIndex];
    if (!phraseElement) return;
 
    const range = document.createRange();
    range.selectNodeContents(phraseElement);
    const selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  };
 
  setIsInViewPort(isInViewPort) {
    this.setState({ inViewPort: isInViewPort });
  }
 
  // Handle manual scrolling to disable auto-scroll
  onScroll = () => {
    // Only disable auto-scroll for user-initiated scrolling, not programmatic scrolling
    if (this.state.inViewPort && !this.isProgrammaticScroll) {
      this.setState({ inViewPort: false });
    }
  };
 
  // Helper to select all regions for a phrase index
  selectRegionsForPhrase = (phraseIdx) => {
    if (!isFF(FF_NER_SELECT_ALL)) return;
 
    const item = this.props.item;
    if (!item || !item.annotation || !item.annotation.results) return;
 
    // Only deselect regions, not labels
    item.annotation.unselectAreas();
 
    // Get all regions for this phrase
    const phraseRegions = this.getRegionsForPhrase(phraseIdx);
 
    // If there are regions, automatically select the first one
    if (phraseRegions.length > 0) {
      this.selectRegion(phraseRegions[0]);
    }
  };
 
  // Move to the next phrase
  handleNextPhrase = () => {
    const item = this.props.item;
    if (!item) return;
    item.goToNextPhrase();
    this.selectRegionsForPhrase(item.playingId);
  };
 
  // Move to the previous phrase
  handlePreviousPhrase = () => {
    const item = this.props.item;
    if (!item) return;
    item.goToPreviousPhrase();
    this.selectRegionsForPhrase(item.playingId);
  };
 
  // Select all text in the current phrase and annotate
  handleSelectAllAndAnnotate = () => {
    const item = this.props.item;
    if (!item) return;
    item.selectAllAndAnnotateCurrentPhrase();
  };
 
  // Get all regions for the current phrase
  getRegionsForPhrase = (phraseIdx) => {
    if (!isFF(FF_NER_SELECT_ALL)) return [];
 
    const item = this.props.item;
    if (!item || !item.annotation) return [];
 
    const regions = item.annotation.regionStore?.regions || item.annotation.regions;
    return regions.filter((region) => {
      const start = Number.parseInt(region.start, 10);
      const end = Number.parseInt(region.end, 10);
      return !isNaN(start) && !isNaN(end) && start <= phraseIdx && end >= phraseIdx;
    });
  };
 
  // Helper to select a region using the proper MobX-State-Tree action
  selectRegion = (region) => {
    if (!isFF(FF_NER_SELECT_ALL)) return false;
 
    const item = this.props.item;
 
    item.annotation.selectArea(region);
    return true;
  };
 
  // Cycle through regions in the current phrase (Ctrl+Right)
  handleNextRegion = () => {
    if (!isFF(FF_NER_SELECT_ALL)) return;
 
    const item = this.props.item;
    if (!item || typeof item.playingId !== "number" || item.playingId < 0) return;
 
    const phraseRegions = this.getRegionsForPhrase(item.playingId);
    if (phraseRegions.length === 0) return;
 
    const selectedRegions = item.annotation.selectedRegions || [];
    let currentIndex = -1;
    if (selectedRegions.length > 0) {
      currentIndex = phraseRegions.findIndex((region) => selectedRegions.includes(region));
    }
 
    const nextIndex = (currentIndex + 1) % phraseRegions.length;
    item.annotation.unselectAll();
    this.selectRegion(phraseRegions[nextIndex]);
  };
 
  // Cycle through regions in the current phrase (Ctrl+Left)
  handlePreviousRegion = () => {
    if (!isFF(FF_NER_SELECT_ALL)) return;
 
    const item = this.props.item;
    if (!item || typeof item.playingId !== "number" || item.playingId < 0) return;
 
    const phraseRegions = this.getRegionsForPhrase(item.playingId);
    if (phraseRegions.length === 0) return;
 
    const selectedRegions = item.annotation.selectedRegions || [];
    let currentIndex = -1;
    if (selectedRegions.length > 0) {
      currentIndex = phraseRegions.findIndex((region) => selectedRegions.includes(region));
    }
 
    const prevIndex = currentIndex <= 0 ? phraseRegions.length - 1 : currentIndex - 1;
    item.annotation.unselectAll();
    this.selectRegion(phraseRegions[prevIndex]);
  };
 
  renderWrapperHeader() {
    const { item } = this.props;
 
    return (
      <div className={styles.wrapper_header}>
        {isFF(FF_DEV_2669) && (
          <AuthorFilter
            item={item}
            onChange={() => {
              this.setState({
                canScroll: !this.state.canScroll,
              });
            }}
          />
        )}
        {item.contextscroll && (
          <div className={styles.wrapper_header__buttons}>
            <Toggle
              data-testid={"auto-scroll-toggle"}
              checked={this.state.canScroll}
              onChange={() => {
                this.setState({
                  canScroll: !this.state.canScroll,
                });
              }}
              label={"Auto-scroll"}
            />
            <Tooltip alignment="top-left" title="自动同步文本滚动与音频播放">
              <IconHelp />
            </Tooltip>
          </div>
        )}
      </div>
    );
  }
 
  render() {
    const { item } = this.props;
    const withAudio = !!item.audio;
    const contextScroll = isFF(FF_LSDV_E_278) && this.props.item.contextscroll;
 
    if (!item.playing && isFF(FF_LSDV_E_278)) this._disposeTimeout(); // dispose scroll timeout when the audio is not playing
 
    // current way to not render when we wait for data
    if (isFF(FF_DEV_2669) && !item._value) return null;
 
    return (
      <>
        <ParagraphHotkeys item={item} />
        <ObjectTag item={item} className={cnm(cn("paragraphs").toClassName(), styles.paragraphs)}>
          {withAudio && <ParagraphAudio item={item} />}
          {isFF(FF_LSDV_E_278) ? this.renderWrapperHeader() : isFF(FF_DEV_2669) && <AuthorFilter item={item} />}
          <div
            ref={this.myRef}
            data-testid="phrases-wrapper"
            data-update={item._update}
            className={contextScroll ? styles.scroll_container : styles.container}
            onMouseUp={this.onMouseUp.bind(this)}
            onScroll={this.onScroll.bind(this)}
          >
            <Phrases
              setIsInViewPort={this.setIsInViewPort.bind(this)}
              item={item}
              playingId={item.playingId}
              hasSelectedLabels={this.hasSelectedLabels}
              {...(isFF(FF_LSDV_E_278) ? { activeRef: this.activeRef } : {})}
            />
          </div>
        </ObjectTag>
      </>
    );
  }
}
 
export const HtxParagraphs = inject("store")(observer(HtxParagraphsView));