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
import type React from "react";
import { type FC, type MouseEvent, useContext, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Toggle } from "@humansignal/ui";
import { cn } from "../../../utils/bem";
 
import { IconConfig } from "@humansignal/icons";
import { TimelineContext } from "../Context";
import { ControlButton } from "../Controls";
import { Slider } from "./Slider";
import { SpectrogramControl } from "./SpectrogramControl";
import "./ConfigControl.scss";
import { FF_AUDIO_SPECTROGRAMS, isFF } from "../../../utils/feature-flags";
 
// Define Scale Options Type
type SpectrogramScale = "linear" | "log" | "mel";
 
const MAX_SPEED = 2.5;
const MAX_ZOOM = 150;
const MIN_SPEED = 0.5;
const MIN_ZOOM = 1;
 
export interface ConfigControlProps {
  configModal: boolean;
  speed: number;
  amp: number;
  onSetModal?: (e: MouseEvent<HTMLButtonElement>) => void;
  onSpeedChange: (speed: number) => void;
  onAmpChange: (amp: number) => void;
  toggleVisibility?: (layerName: string, isVisible: boolean) => void;
  layerVisibility?: Map<string, boolean>;
  waveform: Waveform;
}
 
type Waveform = {};
 
export const ConfigControl: FC<ConfigControlProps> = ({
  configModal,
  speed,
  amp,
  onSpeedChange,
  onSetModal,
  onAmpChange,
  toggleVisibility,
  layerVisibility,
  waveform,
}) => {
  const { settings, changeSetting } = useContext(TimelineContext);
  const playbackSpeed = speed ?? 1;
  const [isTimeline, setTimeline] = useState(true);
  const [isAudioWave, setAudioWave] = useState(true);
  const [isSpectrogram, setSpectrogram] = useState(false);
 
  // Refs for positioning
  const modalRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
 
  // Effect to dynamically position the modal within the viewport
  useEffect(() => {
    // Check if modal is open and refs are attached
    if (configModal && modalRef.current && buttonRef.current) {
      const buttonRect = buttonRef.current.getBoundingClientRect();
      const modal = modalRef.current;
      // Temporarily make it visible off-screen to measure its actual size
      modal.style.opacity = "0";
      modal.style.position = "fixed"; // Ensure fixed for measurement
      modal.style.top = "-9999px";
      modal.style.left = "-9999px";
 
      const calculatePosition = () => {
        if (!modalRef.current || !buttonRef.current) return; // Refs might detach
        const modalRect = modal.getBoundingClientRect();
        const viewportHeight = window.innerHeight;
        const viewportWidth = window.innerWidth;
        const margin = 10; // Margin from viewport edges
 
        // Default position: below the button, aligned left
        let top = buttonRect.bottom + 5;
        let left = buttonRect.left;
 
        // Adjust top if modal goes below viewport
        if (top + modalRect.height > viewportHeight - margin) {
          // Try placing above the button first
          const topAbove = buttonRect.top - modalRect.height - 5;
          if (topAbove > margin) {
            top = topAbove; // Place above if enough space
          } else {
            top = viewportHeight - modalRect.height - margin; // Stick to bottom edge
          }
        }
 
        // Adjust top if modal goes above viewport
        if (top < margin) {
          top = margin;
        }
 
        // Adjust left if modal goes beyond right edge
        if (left + modalRect.width > viewportWidth - margin) {
          left = viewportWidth - modalRect.width - margin;
        }
 
        // Adjust left if modal goes beyond left edge
        if (left < margin) {
          left = margin;
        }
 
        // Apply calculated styles
        modal.style.top = `${top}px`;
        modal.style.left = `${left}px`;
        modal.style.opacity = "1"; // Make visible after positioning
      };
 
      // Calculate after a short delay or next frame to allow measurement
      requestAnimationFrame(calculatePosition);
    } else if (modalRef.current) {
      // Reset opacity when closing
      modalRef.current.style.opacity = "0";
    }
  }, [configModal]); // Rerun effect when modal visibility changes
 
  useEffect(() => {
    if (layerVisibility) {
      const defaultDisplay = true;
      setTimeline(layerVisibility?.get?.("timeline") ?? defaultDisplay);
      setAudioWave(layerVisibility?.get?.("waveform") ?? defaultDisplay);
      setSpectrogram(layerVisibility?.get?.("spectrogram") ?? false);
    }
  }, [layerVisibility]);
 
  const handleSetTimeline = () => {
    setTimeline(!isTimeline);
    toggleVisibility?.("timeline", !isTimeline);
  };
 
  const handleSetAudioWave = () => {
    setAudioWave(!isAudioWave);
    toggleVisibility?.("waveform", !isAudioWave);
    toggleVisibility?.("regions", !isAudioWave);
  };
 
  const handleSetSpectrogram = () => {
    setSpectrogram(!isSpectrogram);
    toggleVisibility?.("spectrogram", !isSpectrogram);
  };
 
  const handleChangePlaybackSpeed = (e: React.FormEvent<HTMLInputElement>) => {
    const _playbackSpeed = Number.parseFloat(e.currentTarget.value);
    if (isNaN(_playbackSpeed)) return;
    onSpeedChange(_playbackSpeed);
  };
 
  const handleChangeAmp = (e: React.FormEvent<HTMLInputElement>) => {
    const _amp = Number.parseFloat(e.currentTarget.value);
    onAmpChange(_amp);
  };
 
  const renderLayerToggles = () => {
    return (
      <div className={cn("audio-config").elem("buttons").toClassName()}>
        <div className={cn("audio-config").elem("menu-button").toClassName()} onClick={handleSetTimeline}>
          {isTimeline ? "Hide" : "Show"} timeline
        </div>
        <div className={cn("audio-config").elem("menu-button").toClassName()} onClick={handleSetAudioWave}>
          {isAudioWave ? "Hide" : "Show"} audio wave
        </div>
        {isFF(FF_AUDIO_SPECTROGRAMS) && (
          <div className={cn("audio-config").elem("menu-button").toClassName()} onClick={handleSetSpectrogram}>
            {isSpectrogram ? "Hide" : "Show"} spectrogram
          </div>
        )}
      </div>
    );
  };
 
  const renderModal = () => {
    const modalJSX = (
      <div
        className={cn("audio-config").elem("modal").toClassName()}
        ref={modalRef}
        onClick={(e: MouseEvent<HTMLDivElement>) => e.stopPropagation()}
        style={{ opacity: 0, position: "fixed" }}
      >
        <div className={cn("audio-config").elem("scroll-content").toClassName()}>
          <div className={cn("audio-config").elem("section-header").toClassName()}>Playback Settings</div>
          <Slider
            min={MIN_SPEED}
            max={MAX_SPEED}
            step={0.1}
            value={speed}
            description={"Playback speed"}
            info={"Increase or decrease the playback speed"}
            onChange={handleChangePlaybackSpeed}
          />
          <Slider
            min={MIN_ZOOM}
            max={MAX_ZOOM}
            step={0.1}
            value={amp}
            description={"Audio zoom y-axis"}
            info={"Increase or decrease the appearance of amplitude"}
            onChange={handleChangeAmp}
          />
          <div className={cn("audio-config").elem("toggle").toClassName()}>
            <Toggle
              checked={settings?.loopRegion}
              onChange={(e) => changeSetting?.("loopRegion", e.target.checked)}
              label="Loop Regions"
              labelProps={{ size: "small" }}
            />
          </div>
          <div className={cn("audio-config").elem("toggle").toClassName()}>
            <Toggle
              checked={settings?.autoPlayNewSegments}
              onChange={(e) => changeSetting?.("autoPlayNewSegments", e.target.checked)}
              label="Auto-play New Regions"
              labelProps={{ size: "small" }}
            />
          </div>
 
          {isFF(FF_AUDIO_SPECTROGRAMS) && (
            <>
              <div className={cn("audio-config").elem("section-header").toClassName()}>Spectrogram Settings</div>
              <SpectrogramControl waveform={waveform} />
            </>
          )}
        </div>
        {renderLayerToggles()}
      </div>
    );
 
    return typeof document !== "undefined" ? createPortal(modalJSX, document.body) : null;
  };
 
  return (
    <div
      className={cn("audio-config").toClassName()}
      ref={buttonRef as any}
      onClick={(e: MouseEvent<HTMLButtonElement>) => e.stopPropagation()}
    >
      <ControlButton look={configModal ? "filled" : undefined} onClick={onSetModal} aria-label="Audio settings">
        {<IconConfig />}
      </ControlButton>
      {configModal && renderModal()}
    </div>
  );
};