Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

feat: rebuild the Identify Speakers modal with speaking-time sorting, a filter to one speaker, grouped short speakers that can be merged, name suggestions on focus with keyboard support, per-speaker samples and a playing-segment highlight (#395)

Murtaza Nasirda38b9ceeda7
diff --git a/static/css/styles.css b/static/css/styles.css
index e4d749c5..71eb1190 100644
--- a/static/css/styles.css
+++ b/static/css/styles.css
@@ -4686,3 +4686,269 @@ select:disabled {
.chat-ts-chip:hover {
border-color: var(--border-focus);
}
+
+/* ------------------------------------------------------------------ */
+/* Identify Speakers modal (templates/modals/speaker-modal.html, #395) */
+/* ------------------------------------------------------------------ */
+
+.spk-modal .spk-tab {
+ flex: 1;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: var(--sp-1);
+ padding: var(--sp-2);
+ font-size: 0.75rem;
+ font-weight: 500;
+ color: var(--text-muted);
+ border-bottom: 2px solid transparent;
+ min-width: 0;
+}
+.spk-modal .spk-tab span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.spk-modal .spk-tab.is-active { color: var(--text-accent); border-bottom-color: var(--bg-button); }
+
+.spk-modal .spk-toolbar {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-2);
+ padding: var(--sp-3) var(--sp-4);
+ border-bottom: var(--border-hairline) solid var(--border-primary);
+ flex-shrink: 0;
+}
+.spk-modal .spk-toolbar select { flex: 1; min-width: 0; }
+
+.spk-modal .spk-list {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ padding: var(--sp-2);
+}
+
+/* A speaker's color class sets a readable text color in both themes;
+ the dot and share bar reuse it. */
+.spk-modal .spk-dot {
+ width: 10px;
+ height: 10px;
+ border-radius: 9999px;
+ background-color: currentColor;
+ flex-shrink: 0;
+}
+
+.spk-modal .spk-row {
+ padding: var(--sp-2) var(--sp-3);
+ border-radius: var(--radius-md);
+ border: var(--border-hairline) solid transparent;
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin-bottom: 2px;
+}
+.spk-modal .spk-row:hover { background: var(--bg-tertiary); }
+.spk-modal .spk-row.is-selected {
+ background: var(--bg-tertiary);
+ border-color: var(--border-accent, var(--bg-button));
+}
+.spk-modal .spk-row.is-minor { margin-left: var(--sp-3); }
+
+.spk-modal .spk-row-head { display: flex; align-items: center; gap: var(--sp-2); min-width: 0; }
+.spk-modal .spk-label {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.75rem;
+ color: var(--text-muted);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.spk-modal .spk-repeat { font-size: 9px; padding: 1px 6px; }
+.spk-modal .spk-me {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 0.75rem;
+ color: var(--text-muted);
+ cursor: pointer;
+ flex-shrink: 0;
+}
+
+.spk-modal .spk-row-stats { display: flex; align-items: center; gap: var(--sp-2); min-height: 24px; }
+.spk-modal .spk-share {
+ flex: 1;
+ height: 4px;
+ border-radius: 2px;
+ background: var(--bg-tertiary);
+ overflow: hidden;
+ display: block;
+}
+.spk-modal .spk-row.is-selected .spk-share,
+.spk-modal .spk-row:hover .spk-share { background: var(--bg-secondary); }
+.spk-modal .spk-share > span {
+ display: block;
+ height: 100%;
+ background-color: currentColor;
+ border-radius: 2px;
+}
+
+.spk-modal .spk-name { cursor: default; display: flex; flex-direction: column; gap: 4px; }
+.spk-modal .spk-voice-pill {
+ position: absolute;
+ right: 4px;
+ top: 50%;
+ transform: translateY(-50%);
+ height: 20px;
+ padding: 0 8px;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 10px;
+ border-radius: 4px;
+ background: var(--bg-button);
+ color: var(--text-button);
+}
+.spk-modal .spk-voice-pill:hover { background: var(--bg-button-hover, var(--bg-button)); }
+
+.spk-modal .spk-options {
+ list-style: none;
+ margin: 0;
+ padding: var(--sp-1);
+ border: var(--border-hairline) solid var(--border-primary);
+ border-radius: var(--radius-md);
+ background: var(--bg-secondary);
+ max-height: 220px;
+ overflow-y: auto;
+}
+.spk-modal .spk-option {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-2);
+ padding: 6px var(--sp-2);
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ font-size: 0.8125rem;
+}
+.spk-modal .spk-option i { width: 12px; font-size: 10px; color: var(--text-muted); }
+.spk-modal .spk-option-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-primary); }
+.spk-modal .spk-option:hover,
+.spk-modal .spk-option.is-active { background: var(--bg-accent); }
+.spk-modal .spk-option.is-taken .spk-option-name { color: var(--text-muted); }
+
+.spk-modal .spk-spelling { display: flex; align-items: center; gap: var(--sp-2); }
+.spk-modal .spk-merge { width: 100%; }
+
+.spk-modal .spk-minor-header {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: var(--sp-2) var(--sp-3);
+ margin: var(--sp-2) 0 2px;
+ border-top: var(--border-hairline) solid var(--border-primary);
+}
+.spk-modal .spk-minor-toggle {
+ display: flex;
+ align-items: baseline;
+ flex-wrap: wrap;
+ gap: 2px var(--sp-2);
+ text-align: left;
+ color: var(--text-primary);
+}
+.spk-modal .spk-minor-toggle i { font-size: 10px; width: 10px; color: var(--text-muted); }
+
+.spk-modal .spk-add { margin-top: var(--sp-3); }
+
+.spk-modal .spk-right { padding: var(--sp-4); gap: var(--sp-3); }
+
+.spk-modal .spk-player { display: flex; align-items: center; gap: var(--sp-2); }
+.spk-modal .spk-play {
+ width: 32px;
+ height: 32px;
+ border-radius: 9999px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg-button);
+ color: var(--text-button);
+ flex-shrink: 0;
+}
+.spk-modal .spk-play:hover { background: var(--bg-button-hover, var(--bg-button)); }
+.spk-modal .spk-time {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.75rem;
+ color: var(--text-muted);
+ white-space: nowrap;
+}
+.spk-modal .spk-seek {
+ flex: 1;
+ height: 6px;
+ border-radius: 3px;
+ background: var(--bg-tertiary);
+ cursor: pointer;
+ overflow: hidden;
+}
+.spk-modal .spk-seek > div { height: 100%; background: var(--bg-button); border-radius: 3px; }
+.spk-modal .spk-volume { width: 72px; accent-color: var(--bg-button); }
+.spk-modal .spk-video { max-height: 30vh; object-fit: contain; background: #000; }
+
+.spk-modal .spk-filter {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-2);
+ min-height: 36px;
+ padding: var(--sp-1) var(--sp-3);
+ border-radius: var(--radius-md);
+ background: var(--bg-tertiary);
+ flex-shrink: 0;
+ min-width: 0;
+}
+.spk-modal .spk-filter-actions { margin-left: auto; display: flex; align-items: center; gap: var(--sp-1); flex-shrink: 0; }
+
+.spk-modal .spk-seg {
+ display: grid;
+ grid-template-columns: auto minmax(0, 7rem) minmax(0, 1fr) auto;
+ align-items: start;
+ column-gap: var(--sp-2);
+ margin-bottom: 2px;
+ padding: 6px var(--sp-2);
+ border-radius: var(--radius-sm);
+}
+.spk-modal .spk-seg:hover { background: var(--bg-tertiary); }
+.spk-modal .spk-seg.is-playing { background: var(--bg-accent); }
+.spk-modal .spk-seg.is-dimmed { opacity: 0.45; }
+.spk-modal .spk-seg-time {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 0.6875rem;
+ color: var(--text-muted);
+ padding-top: 2px;
+ font-variant-numeric: tabular-nums;
+}
+.spk-modal .spk-seg-time:hover { color: var(--text-accent); }
+.spk-modal .spk-seg-speaker {
+ justify-self: start;
+ max-width: 100%;
+ font-size: 0.75rem;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.spk-modal .spk-seg-text {
+ font-size: 0.875rem;
+ line-height: 1.55;
+ color: var(--text-primary);
+ cursor: pointer;
+}
+.spk-modal .spk-seg-actions { display: flex; gap: 2px; }
+.spk-modal .spk-seg-reassign { grid-column: 2 / -1; margin-top: var(--sp-1); max-width: 18rem; }
+
+@media (hover: hover) and (min-width: 640px) {
+ .spk-modal .spk-seg-actions { opacity: 0; transition: opacity 0.15s; }
+ .spk-modal .spk-seg:hover .spk-seg-actions,
+ .spk-modal .spk-seg:focus-within .spk-seg-actions { opacity: 1; }
+}
+
+@media (max-width: 639px) {
+ .spk-modal .spk-seg { grid-template-columns: auto minmax(0, 1fr) auto; }
+ .spk-modal .spk-seg-speaker { grid-column: 2; grid-row: 1; }
+ .spk-modal .spk-seg-text { grid-column: 1 / -1; }
+ .spk-modal .spk-seg-actions { grid-column: 3; grid-row: 1; }
+ .spk-modal .spk-right { padding: var(--sp-3); }
+}
diff --git a/static/js/app.modular.js b/static/js/app.modular.js
index 162addd7..98968724 100644
--- a/static/js/app.modular.js
+++ b/static/js/app.modular.js
@@ -10,6 +10,7 @@ import { useSharing } from './modules/composables/sharing.js';
import { useReprocess } from './modules/composables/reprocess.js';
import { useTranscription } from './modules/composables/transcription.js';
import { useSpeakers } from './modules/composables/speakers.js';
+import { useSpeakerModal } from './modules/composables/speaker-modal.js';
import { useChat } from './modules/composables/chat.js';
import { useTags } from './modules/composables/tags.js';
import { usePWA } from './modules/composables/pwa.js';
@@ -742,7 +743,6 @@ document.addEventListener('DOMContentLoaded', async () => {
// declared). Declared here so the rest of this state block
// can reference them without temporal-dead-zone errors.
const asrEditorHydratedRows = ref(new Set());
- const speakerModalHydratedRows = ref(new Set());
const showCustomizeSummaryModal = ref(false);
const customizeSummaryPrompt = ref('');
const customizeSummaryMode = ref('append'); // 'append' | 'replace'
@@ -794,11 +794,7 @@ document.addEventListener('DOMContentLoaded', async () => {
const speakerMap = ref({});
const speakerColorMap = ref({}); // Stable mapping of speaker ID → color class
const modalSpeakers = ref([]);
- const speakerDisplayMap = ref({});
const regenerateSummaryAfterSpeakerUpdate = ref(true);
- const speakerSuggestions = ref({});
- const loadingSuggestions = ref({});
- const activeSpeakerInput = ref(null);
const voiceSuggestions = ref({});
const loadingVoiceSuggestions = ref(false);
@@ -1360,7 +1356,6 @@ document.addEventListener('DOMContentLoaded', async () => {
const playbackSpeeds = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0];
const speedMenuPosition = ref({});
const showVolumeSlider = ref(false);
- const showModalVolumeSlider = ref(false);
const showDuplicatesModal = ref(false);
const videoCollapsed = ref(false);
// Desktop docked-video panel: shows the video in a strip across
@@ -1497,10 +1492,6 @@ document.addEventListener('DOMContentLoaded', async () => {
// --- Reprocessing Polls ---
const reprocessingPolls = ref(new Map());
- // --- Speaker Groups State ---
- const currentSpeakerGroupIndex = ref(0);
- const speakerGroups = ref([]);
-
// --- Virtual Scroll Container Refs ---
const speakerModalTranscriptRef = ref(null);
const mainTranscriptRef = ref(null);
@@ -1520,7 +1511,6 @@ document.addEventListener('DOMContentLoaded', async () => {
// win is preserved. Keep the hydrate stubs as no-ops in case
// any leftover template reference still calls them.
const hydrateAsrEditorRow = () => {};
- const hydrateSpeakerModalRow = () => {};
// --- Computed properties needed by composables ---
const isMobileScreen = computed(() => windowWidth.value < 1024);
@@ -1854,7 +1844,7 @@ document.addEventListener('DOMContentLoaded', async () => {
// Modals
showEditModal, showDeleteModal, showEditTagsModal, selectedNewTagId, tagSearchFilter,
showReprocessModal, showResetModal, showSpeakerModal, speakerModalTab, speakerModalVideoCollapsed, toggleSpeakerModalVideo, showShareModal, showSharesListModal,
- showTextEditorModal, showAsrEditorModal, asrEditorHydratedRows, hydrateAsrEditorRow, speakerModalHydratedRows, hydrateSpeakerModalRow, showCustomizeSummaryModal, customizeSummaryPrompt, customizeSummaryMode, editingRecording, editingTranscriptionContent,
+ showTextEditorModal, showAsrEditorModal, asrEditorHydratedRows, hydrateAsrEditorRow, showCustomizeSummaryModal, customizeSummaryPrompt, customizeSummaryMode, editingRecording, editingTranscriptionContent,
editingSegments, availableSpeakers, showEditSpeakersModal, editingSpeakersList,
databaseSpeakers, editingSpeakerSuggestions,
showEditParticipantsModal, editingParticipantsList, editingParticipantSuggestions, allParticipants,
@@ -1864,8 +1854,8 @@ document.addEventListener('DOMContentLoaded', async () => {
shareToDelete, showShareDeleteModal, recordingToDelete, recordingToReset,
reprocessType, reprocessRecording, reprocessPromptVariables, isAutoIdentifying, asrReprocessOptions,
summaryReprocessPromptSource, summaryReprocessSelectedTagId, summaryReprocessCustomPrompt, summaryReprocessPromptMode,
- speakerMap, speakerColorMap, modalSpeakers, speakerDisplayMap, regenerateSummaryAfterSpeakerUpdate, speakerSuggestions,
- loadingSuggestions, activeSpeakerInput, voiceSuggestions, loadingVoiceSuggestions,
+ speakerMap, speakerColorMap, modalSpeakers, regenerateSummaryAfterSpeakerUpdate,
+ voiceSuggestions, loadingVoiceSuggestions,
// DateTime Picker
showDateTimePicker, pickerMonth, pickerYear, pickerHour, pickerMinute,
@@ -1902,7 +1892,7 @@ document.addEventListener('DOMContentLoaded', async () => {
// Audio Player
playerVolume, audioIsPlaying, audioCurrentTime, audioDuration, audioIsMuted, audioIsLoading, asrEditorAudio,
modalAudioCurrentTime, modalAudioDuration, modalAudioIsPlaying, modalPlaybackRate,
- playbackRate, showSpeedMenu, playbackSpeeds, speedMenuPosition, showVolumeSlider, showModalVolumeSlider,
+ playbackRate, showSpeedMenu, playbackSpeeds, speedMenuPosition, showVolumeSlider,
videoFullscreen, fullscreenControlsVisible, fullscreenControlsTimer, videoCollapsed,
videoDockEnabled, isVideoRecording, toggleVideoDock,
videoDockPosition, cycleVideoDockColumn, cycleVideoDockVertical,
@@ -1926,9 +1916,6 @@ document.addEventListener('DOMContentLoaded', async () => {
// Reprocessing
reprocessingPolls,
- // Speaker Groups
- currentSpeakerGroupIndex, speakerGroups,
-
// Virtual Scroll
speakerModalTranscriptRef, mainTranscriptRef, asrEditorRef, asrEditorSaveFlash, asrEditorHighlightIndex
};
@@ -2284,7 +2271,7 @@ document.addEventListener('DOMContentLoaded', async () => {
const simpleSegments = transcriptionData.map(segment => ({
speakerId: segment.speaker,
- speaker: speakerMap.value[segment.speaker]?.name || segment.speaker,
+ speaker: segment.speaker,
sentence: segment.sentence,
// Use nullish coalescing so a real 0 (recording's first segment)
// is preserved rather than falling through to segment.startTime.
@@ -2359,7 +2346,7 @@ document.addEventListener('DOMContentLoaded', async () => {
simpleSegmentRuns: simpleSegmentRuns,
bubbleRows: bubbleRows,
speakers: speakers.map(speaker => ({
- name: speakerMap.value[speaker]?.name || speaker,
+ name: speaker,
color: speakerColors[speaker]
}))
};
@@ -2411,7 +2398,7 @@ document.addEventListener('DOMContentLoaded', async () => {
if (currentSpeakerId && currentText.trim()) {
segments.push({
speakerId: currentSpeakerId,
- speaker: speakerMap.value[currentSpeakerId]?.name || currentSpeakerId,
+ speaker: currentSpeakerId,
sentence: currentText.trim(),
color: speakerColors[currentSpeakerId] || 'speaker-color-1'
});
@@ -2433,7 +2420,7 @@ document.addEventListener('DOMContentLoaded', async () => {
if (currentSpeakerId && currentText.trim()) {
segments.push({
speakerId: currentSpeakerId,
- speaker: speakerMap.value[currentSpeakerId]?.name || currentSpeakerId,
+ speaker: currentSpeakerId,
sentence: currentText.trim(),
color: speakerColors[currentSpeakerId] || 'speaker-color-1'
});
@@ -2477,7 +2464,7 @@ document.addEventListener('DOMContentLoaded', async () => {
simpleSegments: simpleSegments,
bubbleRows: bubbleRows,
speakers: speakerList.map(speaker => ({
- name: speakerMap.value[speaker]?.name || speaker,
+ name: speaker,
color: speakerColors[speaker] || 'speaker-color-1'
}))
};
@@ -2651,14 +2638,6 @@ document.addEventListener('DOMContentLoaded', async () => {
// Create a computed ref for the segments array
const transcriptSegments = computed(() => processedTranscription.value.simpleSegments || []);
- // Virtual scroll for speaker modal transcript (main performance bottleneck)
- const speakerModalVirtualScroll = useVirtualScroll({
- items: transcriptSegments,
- itemHeight: 52, // Approximate height of each segment row
- containerRef: speakerModalTranscriptRef,
- overscan: 8
- });
-
// Virtual scroll for main transcription panel
const mainTranscriptVirtualScroll = useVirtualScroll({
items: transcriptSegments,
@@ -2748,42 +2727,9 @@ document.addEventListener('DOMContentLoaded', async () => {
asrEditorRef.value.scrollTop = scrollTop;
}
};
- utils.resetSpeakerModalScroll = () => {
- if (speakerModalTranscriptRef.value) {
- speakerModalTranscriptRef.value.scrollTop = 0;
- }
- };
- // Compute the visible segment range from the DOM rather than
- // from a virtual scroller. Walks the rendered segments inside
- // the speaker modal's transcript container, comparing each
- // element's bounding rect to the container's; returns the
- // [start, end) range of segment indices currently in view.
- // Used by speakers.js to decide whether the highlighted
- // speaker's nearest group is already visible (and we can skip
- // the scroll). O(n) walk; only called when the user picks a
- // new speaker to highlight, not on every scroll event.
- utils.getSpeakerModalVisibleRange = () => {
- const container = speakerModalTranscriptRef.value;
- if (!container) return null;
- const segments = container.querySelectorAll('[data-segment-index]');
- if (!segments.length) return { start: 0, end: 0 };
- const cTop = container.getBoundingClientRect().top;
- const cBottom = cTop + container.clientHeight;
- let start = -1, end = 0;
- for (const el of segments) {
- const r = el.getBoundingClientRect();
- if (r.bottom < cTop) continue; // above viewport
- if (r.top > cBottom) break; // below viewport (segments are in document order)
- const idx = parseInt(el.dataset.segmentIndex, 10);
- if (Number.isNaN(idx)) continue;
- if (start === -1) start = idx;
- end = idx + 1;
- }
- return start === -1 ? { start: 0, end: 0 } : { start, end };
- };
-
// Speakers composable needs processedTranscription and scrollToSegmentIndex
const speakersComposable = useSpeakers(state, utils, processedTranscription);
+ const speakerModalComposable = useSpeakerModal(state, utils);
const groupedRecordings = computed(() => {
const groups = {};
@@ -4479,10 +4425,6 @@ document.addEventListener('DOMContentLoaded', async () => {
mainTranscriptRef,
asrEditorRef,
asrEditorSaveFlash,
- speakerModalVisibleSegments: speakerModalVirtualScroll.visibleItems,
- speakerModalSpacerBefore: speakerModalVirtualScroll.spacerBefore,
- speakerModalSpacerAfter: speakerModalVirtualScroll.spacerAfter,
- onSpeakerModalScroll: speakerModalVirtualScroll.onScroll,
mainTranscriptVisibleSegments: mainTranscriptVirtualScroll.visibleItems,
mainTranscriptSpacerBefore: mainTranscriptVirtualScroll.spacerBefore,
mainTranscriptSpacerAfter: mainTranscriptVirtualScroll.spacerAfter,
@@ -4515,6 +4457,7 @@ document.addEventListener('DOMContentLoaded', async () => {
...reprocessComposable,
...transcriptionComposable,
...speakersComposable,
+ ...speakerModalComposable,
...chatComposable,
...tagsComposable,
...foldersComposable,
diff --git a/static/js/modules/composables/speaker-modal.js b/static/js/modules/composables/speaker-modal.js
new file mode 100644
index 00000000..20c28e5f
--- /dev/null
+++ b/static/js/modules/composables/speaker-modal.js
@@ -0,0 +1,441 @@
+/**
+ * Identify Speakers modal: list, filter, name fields and player (#395).
+ *
+ * Saving, auto-identify, voice suggestions and the per-line edits stay in
+ * speakers.js; this composable owns what the rebuilt modal shows and how the
+ * user moves through it. It reads the stored transcription directly instead
+ * of processedTranscription, so typing a name re-renders only that speaker's
+ * rows, not every segment of the recording.
+ */
+
+import {
+ parseModalSegments, computeSpeakerStats, orderSpeakers, splitMinorSpeakers,
+ buildNameOptions, findSavedSpelling, playingSegmentPosition, turnStarts,
+ formatClock, mergeSpeakerSegments, MINOR_SPEAKER_SECONDS,
+} from '../utils/speaker-modal-model.js';
+
+const SORT_KEY = 'speakerModalSort';
+const SORT_MODES = ['duration', 'appearance', 'name'];
+const EMPTY = { isJson: false, segments: [], plainText: '' };
+
+export function useSpeakerModal(state, utils) {
+ const { ref, computed, watch, nextTick } = Vue;
+ const {
+ showSpeakerModal, selectedRecording, speakerMap, speakerColorMap, modalSpeakers,
+ speakerModalTab, voiceSuggestions, editedTranscriptData, playerVolume, audioIsMuted,
+ modalAudioCurrentTime, modalPlaybackRate, playbackSpeeds, speakerModalTranscriptRef,
+ } = state;
+ const { showToast } = utils;
+ const t = (key, params) => (window.i18n ? window.i18n.t(key, params) : key);
+ const tc = (key, count, params) => (window.i18n ? window.i18n.tc(key, count, params) : key);
+
+ let storedSort = null;
+ try { storedSort = localStorage.getItem(SORT_KEY); } catch (e) { /* storage blocked */ }
+
+ const speakerModalPlayer = ref(null);
+ const speakerSort = ref(SORT_MODES.includes(storedSort) ? storedSort : 'duration');
+ const selectedSpeaker = ref(null);
+ const onlySelectedSpeaker = ref(true);
+ const showMinorSpeakers = ref(false);
+ const currentTurn = ref(0);
+ const savedSpeakers = ref([]);
+ const nameSearchResults = ref({});
+ const openNameField = ref(null);
+ const nameOptionIndex = ref(-1);
+ // Names as they were when the list was last ordered. Sorting by name, and
+ // deciding who counts as a minor speaker, uses this snapshot so a row
+ // does not jump away while its name is being typed.
+ const nameSnapshot = ref({});
+
+ let sampleStopAt = null;
+ let searchTimer = null;
+ let searchAbort = null;
+ let blurTimer = null;
+
+ const nameOf = (id) => speakerMap.value[id]?.name || '';
+ const labelOf = (id) => nameOf(id).trim() || id;
+ const snapshotNames = () => {
+ const snap = {};
+ for (const id of modalSpeakers.value) snap[id] = nameOf(id).trim();
+ nameSnapshot.value = snap;
+ };
+
+ // ---------------------------------------------------------------- data
+
+ const speakerModalData = computed(() =>
+ showSpeakerModal.value ? parseModalSegments(selectedRecording.value?.transcription) : EMPTY);
+
+ const speakerStats = computed(() => computeSpeakerStats(speakerModalData.value.segments));
+
+ const orderedSpeakers = computed(() =>
+ orderSpeakers(modalSpeakers.value, speakerStats.value, speakerSort.value, id => nameSnapshot.value[id]));
+
+ const speakerGroupsSplit = computed(() =>
+ splitMinorSpeakers(orderedSpeakers.value, speakerStats.value, MINOR_SPEAKER_SECONDS, id => !!nameSnapshot.value[id]));
+
+ const mainSpeakers = computed(() => speakerGroupsSplit.value.main);
+ const minorSpeakers = computed(() => speakerGroupsSplit.value.minor);
+ const minorSpeakersSeconds = computed(() =>
+ minorSpeakers.value.reduce((sum, id) => sum + (speakerStats.value.bySpeaker[id]?.seconds || 0), 0));
+
+ // One flat list for the template: main speakers, then the minor group's
+ // header, then (when expanded) the minor speakers.
+ const speakerListEntries = computed(() => {
+ const rows = mainSpeakers.value.map(id => ({ key: id, id, minor: false }));
+ if (minorSpeakers.value.length) {
+ rows.push({ key: '__minor__', header: true });
+ if (showMinorSpeakers.value) {
+ minorSpeakers.value.forEach(id => rows.push({ key: id, id, minor: true }));
+ }
+ }
+ return rows;
+ });
+
+ const canPlayModalAudio = computed(() =>
+ !!selectedRecording.value && !selectedRecording.value.audio_deleted_at && !selectedRecording.value.incognito);
+
+ const visibleModalSegments = computed(() => {
+ const segs = speakerModalData.value.segments;
+ if (!selectedSpeaker.value || !onlySelectedSpeaker.value) return segs;
+ return segs.filter(s => s.speakerId === selectedSpeaker.value);
+ });
+
+ const selectedSpeakerTurns = computed(() =>
+ selectedSpeaker.value && !onlySelectedSpeaker.value
+ ? turnStarts(visibleModalSegments.value, selectedSpeaker.value)
+ : []);
+
+ const playingSegmentIndex = computed(() => {
+ const segs = speakerModalData.value.segments;
+ const pos = playingSegmentPosition(segs, modalAudioCurrentTime.value);
+ return pos === -1 ? -1 : segs[pos].index;
+ });
+
+ const speakerColor = (id) => speakerMap.value[id]?.color || speakerColorMap.value[id] || 'speaker-color-1';
+
+ const speakerMeta = (id) => {
+ const agg = speakerStats.value.bySpeaker[id];
+ if (!agg) return t('speakerModal.noSegmentsYet');
+ if (!speakerStats.value.hasTimes) return tc('speakerModal.segmentCount', agg.segments, { count: agg.segments });
+ return t('speakerModal.speakingTime', { time: formatClock(agg.seconds), share: agg.share });
+ };
+
+ const speakerShare = (id) => speakerStats.value.bySpeaker[id]?.share || 0;
+
+ // --------------------------------------------------------- name fields
+
+ const loadSavedSpeakers = async () => {
+ try {
+ const response = await fetch('/speakers/search?top=1');
+ savedSpeakers.value = response.ok ? await response.json() : [];
+ } catch (e) {
+ savedSpeakers.value = [];
+ }
+ };
+
+ const searchSavedSpeakers = (id, query) => {
+ clearTimeout(searchTimer);
+ if (searchAbort) searchAbort.abort();
+ const q = (query || '').trim();
+ if (!q) {
+ nameSearchResults.value = { ...nameSearchResults.value, [id]: [] };
+ return;
+ }
+ searchTimer = setTimeout(async () => {
+ const controller = new AbortController();
+ searchAbort = controller;
+ try {
+ const response = await fetch(`/speakers/search?q=${encodeURIComponent(q)}`, { signal: controller.signal });
+ const results = response.ok ? await response.json() : [];
+ if (!controller.signal.aborted) {
+ nameSearchResults.value = { ...nameSearchResults.value, [id]: Array.isArray(results) ? results : [] };
+ }
+ } catch (e) {
+ // Aborted by a newer keystroke, or offline: keep the last results.
+ }
+ }, 200);
+ };
+
+ const nameOptions = (id) => {
+ const typed = nameOf(id);
+ const taken = modalSpeakers.value.filter(other => other !== id).map(nameOf).filter(Boolean);
+ return buildNameOptions({
+ voice: voiceSuggestions.value[id] || [],
+ saved: [...(nameSearchResults.value[id] || []), ...savedSpeakers.value],
+ query: typed,
+ takenNames: taken,
+ }).filter(opt => opt.name.trim() !== typed.trim());
+ };
+
+ const savedSpellingFor = (id) => {
+ const known = [...savedSpeakers.value, ...(nameSearchResults.value[id] || [])].map(s => s.name);
+ return findSavedSpelling(nameOf(id), known);
+ };
+
+ const topVoiceMatch = (id) => {
+ if (speakerMap.value[id]?.isMe || nameOf(id).trim()) return null;
+ return (voiceSuggestions.value[id] || [])[0] || null;
+ };
+
+ const onNameFocus = (id) => {
+ clearTimeout(blurTimer);
+ openNameField.value = id;
+ nameOptionIndex.value = -1;
+ selectSpeaker(id, { keep: true });
+ };
+
+ const onNameInput = (id) => {
+ openNameField.value = id;
+ nameOptionIndex.value = -1;
+ searchSavedSpeakers(id, nameOf(id));
+ };
+
+ const onNameBlur = () => {
+ blurTimer = setTimeout(() => {
+ openNameField.value = null;
+ nameOptionIndex.value = -1;
+ snapshotNames();
+ }, 150);
+ };
+
+ const chooseName = (id, name) => {
+ if (!speakerMap.value[id]) return;
+ speakerMap.value[id].name = name;
+ openNameField.value = null;
+ nameOptionIndex.value = -1;
+ snapshotNames();
+ };
+
+ const onNameKeydown = (id, event) => {
+ const options = nameOptions(id);
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ if (!options.length) return;
+ event.preventDefault();
+ openNameField.value = id;
+ const last = options.length - 1;
+ const i = nameOptionIndex.value;
+ nameOptionIndex.value = event.key === 'ArrowDown'
+ ? (i < last ? i + 1 : 0)
+ : (i > 0 ? i - 1 : last);
+ } else if (event.key === 'Enter') {
+ if (openNameField.value === id && nameOptionIndex.value >= 0 && options[nameOptionIndex.value]) {
+ event.preventDefault();
+ chooseName(id, options[nameOptionIndex.value].name);
+ } else {
+ openNameField.value = null;
+ snapshotNames();
+ }
+ } else if (event.key === 'Escape') {
+ if (openNameField.value === id) {
+ event.preventDefault();
+ event.stopPropagation();
+ openNameField.value = null;
+ nameOptionIndex.value = -1;
+ }
+ }
+ };
+
+ // ------------------------------------------------------- list & filter
+
+ const scrollTranscriptTo = (index, block = 'start') => {
+ nextTick(() => {
+ const container = speakerModalTranscriptRef.value;
+ if (!container) return;
+ if (index === null) { container.scrollTop = 0; return; }
+ const el = container.querySelector(`[data-segment-index="${index}"]`);
+ if (el) el.scrollIntoView({ block, behavior: 'auto' });
+ });
+ };
+
+ const selectSpeaker = (id, { keep = false, openTranscript = false } = {}) => {
+ if (!keep && selectedSpeaker.value === id) {
+ clearSelectedSpeaker();
+ return;
+ }
+ const changed = selectedSpeaker.value !== id;
+ selectedSpeaker.value = id;
+ currentTurn.value = 0;
+ if (changed) {
+ if (onlySelectedSpeaker.value) scrollTranscriptTo(null);
+ else {
+ const first = selectedSpeakerTurns.value[0];
+ if (first !== undefined) scrollTranscriptTo(visibleModalSegments.value[first].index, 'center');
+ }
+ }
+ if (openTranscript) speakerModalTab.value = 'transcript';
+ };
+
+ const clearSelectedSpeaker = () => {
+ selectedSpeaker.value = null;
+ currentTurn.value = 0;
+ };
+
+ const showAllSegments = () => {
+ onlySelectedSpeaker.value = false;
+ const first = selectedSpeakerTurns.value[0];
+ if (first !== undefined) scrollTranscriptTo(visibleModalSegments.value[first].index, 'center');
+ };
+
+ const showOnlySelectedSpeaker = () => {
+ onlySelectedSpeaker.value = true;
+ scrollTranscriptTo(null);
+ };
+
+ const goToTurn = (delta) => {
+ const turns = selectedSpeakerTurns.value;
+ if (!turns.length) return;
+ currentTurn.value = (currentTurn.value + delta + turns.length) % turns.length;
+ scrollTranscriptTo(visibleModalSegments.value[turns[currentTurn.value]].index, 'center');
+ };
+
+ const setSpeakerSort = (mode) => {
+ if (!SORT_MODES.includes(mode)) return;
+ snapshotNames();
+ speakerSort.value = mode;
+ try { localStorage.setItem(SORT_KEY, mode); } catch (e) { /* storage blocked */ }
+ };
+
+ /**
+ * Stage a merge: every segment of `sourceIds` moves to `targetId`, and
+ * the sources leave the list. Nothing is saved until Save.
+ */
+ const mergeSpeakersInto = (sourceIds, targetId) => {
+ if (!targetId || !selectedRecording.value?.transcription) return;
+ const sources = sourceIds.filter(id => id && id !== targetId);
+ if (!sources.length) return;
+ let data;
+ try {
+ data = JSON.parse(selectedRecording.value.transcription);
+ } catch (e) {
+ return;
+ }
+ if (!Array.isArray(data)) return;
+ const { data: merged, moved } = mergeSpeakerSegments(data, sources, targetId);
+ editedTranscriptData.value = merged;
+ selectedRecording.value.transcription = JSON.stringify(merged);
+
+ const removed = new Set(sources);
+ modalSpeakers.value = modalSpeakers.value.filter(id => !removed.has(id));
+ const map = { ...speakerMap.value };
+ sources.forEach(id => delete map[id]);
+ speakerMap.value = map;
+ if (removed.has(selectedSpeaker.value)) selectedSpeaker.value = targetId;
+ snapshotNames();
+ if (moved > 0) {
+ showToast(tc('speakerModal.mergedSpeakers', sources.length, { count: sources.length, name: labelOf(targetId) }), 'fa-object-group');
+ }
+ };
+
+ // --------------------------------------------------------------- player
+
+ const player = () => speakerModalPlayer.value;
+
+ const toggleModalPlayback = () => {
+ const el = player();
+ if (!el) return;
+ if (el.paused) { sampleStopAt = null; el.play(); } else el.pause();
+ };
+
+ const playFrom = (seconds, stopAt = null) => {
+ const el = player();
+ if (!el || seconds === null || !isFinite(seconds)) return;
+ el.currentTime = Math.max(0, seconds);
+ sampleStopAt = stopAt;
+ el.play();
+ };
+
+ const playModalSegment = (segment) => playFrom(segment.start);
+
+ const playSpeakerSample = (id) => {
+ const agg = speakerStats.value.bySpeaker[id];
+ if (!agg) return;
+ const seg = speakerModalData.value.segments[agg.longestIndex];
+ if (seg) playFrom(seg.start, seg.end);
+ };
+
+ const onModalTimeUpdate = (event) => {
+ const el = event.target;
+ modalAudioCurrentTime.value = el.currentTime;
+ if (sampleStopAt !== null && el.currentTime >= sampleStopAt) {
+ sampleStopAt = null;
+ el.pause();
+ }
+ };
+
+ const seekModalPlayer = (event, duration) => {
+ const el = player();
+ if (!el || !duration) return;
+ const rect = event.currentTarget.getBoundingClientRect();
+ const pct = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width));
+ sampleStopAt = null;
+ el.currentTime = pct * duration;
+ };
+
+ const setModalVolume = (value) => {
+ const volume = Math.min(1, Math.max(0, parseFloat(value)));
+ if (!isFinite(volume)) return;
+ playerVolume.value = volume;
+ const el = player();
+ if (el) {
+ el.volume = volume;
+ el.muted = volume === 0;
+ }
+ audioIsMuted.value = volume === 0;
+ try { localStorage.setItem('playerVolume', String(volume)); } catch (e) { /* storage blocked */ }
+ };
+
+ const toggleModalMute = () => {
+ const el = player();
+ if (!el) return;
+ el.muted = !el.muted;
+ audioIsMuted.value = el.muted;
+ };
+
+ const cycleSpeakerModalRate = () => {
+ const speeds = playbackSpeeds;
+ const next = speeds[(speeds.indexOf(modalPlaybackRate.value) + 1) % speeds.length];
+ modalPlaybackRate.value = next;
+ const el = player();
+ if (el) el.playbackRate = next;
+ };
+
+ // ------------------------------------------------------------ lifecycle
+
+ watch(showSpeakerModal, (open) => {
+ if (open) {
+ selectedSpeaker.value = null;
+ onlySelectedSpeaker.value = true;
+ showMinorSpeakers.value = false;
+ currentTurn.value = 0;
+ openNameField.value = null;
+ nameOptionIndex.value = -1;
+ nameSearchResults.value = {};
+ modalAudioCurrentTime.value = 0;
+ sampleStopAt = null;
+ nextTick(snapshotNames);
+ loadSavedSpeakers();
+ scrollTranscriptTo(null);
+ } else {
+ const el = player();
+ if (el) el.pause();
+ clearTimeout(searchTimer);
+ if (searchAbort) searchAbort.abort();
+ }
+ });
+
+ return {
+ speakerModalPlayer,
+ speakerSort, setSpeakerSort,
+ speakerModalData, speakerStats, orderedSpeakers, mainSpeakers, minorSpeakers, minorSpeakersSeconds, showMinorSpeakers,
+ speakerListEntries, canPlayModalAudio, minorSpeakerSeconds: MINOR_SPEAKER_SECONDS,
+ visibleModalSegments, selectedSpeaker, onlySelectedSpeaker, selectedSpeakerTurns, currentTurn,
+ playingSegmentIndex, speakerColor, speakerMeta, speakerShare, labelOf,
+ selectSpeaker, clearSelectedSpeaker, showAllSegments, showOnlySelectedSpeaker, goToTurn,
+ mergeSpeakersInto,
+ openNameField, nameOptionIndex, nameOptions, savedSpellingFor, topVoiceMatch,
+ onNameFocus, onNameInput, onNameBlur, onNameKeydown, chooseName,
+ toggleModalPlayback, playModalSegment, playSpeakerSample, onModalTimeUpdate, seekModalPlayer,
+ setModalVolume, toggleModalMute, cycleSpeakerModalRate,
+ formatClock,
+ };
+}
diff --git a/static/js/modules/composables/speakers.js b/static/js/modules/composables/speakers.js
index 8d164253..f1bd069f 100644
--- a/static/js/modules/composables/speakers.js
+++ b/static/js/modules/composables/speakers.js
@@ -8,14 +8,12 @@ export function useSpeakers(state, utils, processedTranscription) {
const {
showSpeakerModal, speakerModalTab, showAddSpeakerModal, showEditSpeakersModal,
showEditTextModal, selectedRecording, recordings,
- speakerMap, speakerColorMap, modalSpeakers, speakerDisplayMap, speakerSuggestions, loadingSuggestions,
- activeSpeakerInput, regenerateSummaryAfterSpeakerUpdate,
+ speakerMap, speakerColorMap, modalSpeakers, regenerateSummaryAfterSpeakerUpdate,
editingSpeakersList, databaseSpeakers, editingSpeakerSuggestions,
editSpeakerDropdownPositions, newSpeakerName, newSpeakerIsMe,
newSpeakerSuggestions, loadingNewSpeakerSuggestions, showNewSpeakerSuggestions,
- editingSegmentIndex, editingSpeakerIndex, editedText, editedTranscriptData, highlightedSpeaker,
- isAutoIdentifying, availableSpeakers, editingSegments,
- currentSpeakerGroupIndex, speakerGroups, currentUserName,
+ editingSegmentIndex, editingSpeakerIndex, editedText, editedTranscriptData,
+ isAutoIdentifying, availableSpeakers, editingSegments, currentUserName,
voiceSuggestions, loadingVoiceSuggestions
} = state;
@@ -25,9 +23,6 @@ export function useSpeakers(state, utils, processedTranscription) {
const t = (key, params, fallback) => window.i18n ? window.i18n.t(key, params) : (fallback || key);
const tc = (key, count, params) => window.i18n ? window.i18n.tc(key, count, params) : (params && params.count != null ? `${params.count}` : key);
- // Current speaker highlight state
- let currentSpeakerId = null;
-
// Snapshot of the recording's transcription taken when the modal opens.
// Per-line speaker/text edits are now STAGED in memory (changeSpeaker /
// saveEditedText mutate selectedRecording.transcription for live preview
@@ -67,6 +62,9 @@ export function useSpeakers(state, utils, processedTranscription) {
// Speaker Identification Modal
// =========================================
+ // The modal's list, filter, name fields and player live in
+ // speaker-modal.js; this file keeps opening, saving, auto-identify and
+ // the per-line edits.
const openSpeakerModal = () => {
if (!selectedRecording.value) return;
@@ -78,10 +76,6 @@ export function useSpeakers(state, utils, processedTranscription) {
originalTranscriptionSnapshot = selectedRecording.value.transcription || null;
editedTranscriptData.value = null;
- // Clear any existing speaker map data first
- speakerMap.value = {};
- speakerDisplayMap.value = {};
-
// Get the same speaker order used in processedTranscription
const transcription = selectedRecording.value?.transcription;
let speakers = [];
@@ -102,23 +96,17 @@ export function useSpeakers(state, utils, processedTranscription) {
// Initialize speaker map FIRST with colors from shared color map
// Clear existing map and rebuild it
speakerMap.value = {};
- speakerDisplayMap.value = {};
speakers.forEach(speaker => {
speakerMap.value[speaker] = {
name: '',
isMe: false,
color: getSpeakerColor(speaker)
};
- speakerDisplayMap.value[speaker] = speaker;
});
// Set modalSpeakers AFTER speakerMap is populated (triggers render)
modalSpeakers.value = speakers;
- highlightedSpeaker.value = null;
- speakerSuggestions.value = {};
- loadingSuggestions.value = {};
- activeSpeakerInput.value = null;
isAutoIdentifying.value = false;
regenerateSummaryAfterSpeakerUpdate.value = true;
voiceSuggestions.value = {};
@@ -126,11 +114,6 @@ export function useSpeakers(state, utils, processedTranscription) {
showSpeakerModal.value = true;
- // Reset virtual scroll state for fresh modal render
- if (utils.resetSpeakerModalScroll) {
- utils.resetSpeakerModalScroll();
- }
-
// Load voice-based suggestions if embeddings are available
loadVoiceSuggestions();
};
@@ -181,12 +164,8 @@ export function useSpeakers(state, utils, processedTranscription) {
};
const closeSpeakerModal = () => {
- // Pause any playing modal audio before closing
- const modalAudio = document.querySelector('.fixed.z-50 audio') || document.querySelector('.fixed.z-50 video');
- if (modalAudio) {
- modalAudio.pause();
- }
- // Reset modal audio state (keep main player independent)
+ // The modal composable pauses its player when showSpeakerModal turns
+ // false. Reset modal audio state (keep main player independent)
if (utils.resetModalAudioState) {
utils.resetModalAudioState();
}
@@ -203,12 +182,8 @@ export function useSpeakers(state, utils, processedTranscription) {
showSpeakerModal.value = false;
showAutoIdDropdown.value = false;
- highlightedSpeaker.value = null;
// Clear the speaker map to prevent stale data from persisting
speakerMap.value = {};
- speakerSuggestions.value = {};
- loadingSuggestions.value = {};
- clearSpeakerHighlight();
};
const saveTranscriptImmediately = async (transcriptData) => {
@@ -519,259 +494,6 @@ export function useSpeakers(state, utils, processedTranscription) {
}
};
- // Determine if voice suggestion pill should be shown inside the input field
- const shouldShowVoiceSuggestionPill = (speakerId) => {
- // Don't show if no suggestions available
- if (!voiceSuggestions.value[speakerId] || voiceSuggestions.value[speakerId].length === 0) {
- return false;
- }
-
- // Don't show if "This is Me" is checked
- if (speakerMap.value[speakerId]?.isMe) {
- return false;
- }
-
- // Only show when the input field is empty
- const typedName = speakerMap.value[speakerId]?.name?.trim();
- if (typedName && typedName.length > 0) {
- return false;
- }
-
- return true;
- };
-
- const searchSpeakers = async (query, speakerId) => {
- if (!query || query.length < 2) {
- speakerSuggestions.value[speakerId] = [];
- return;
- }
-
- loadingSuggestions.value[speakerId] = true;
-
- try {
- const response = await fetch(`/speakers/search?q=${encodeURIComponent(query)}`);
- if (!response.ok) throw new Error('Failed to search speakers');
-
- const speakers = await response.json();
- speakerSuggestions.value[speakerId] = speakers;
- } catch (error) {
- console.error('Error searching speakers:', error);
- speakerSuggestions.value[speakerId] = [];
- } finally {
- loadingSuggestions.value[speakerId] = false;
- }
- };
-
- const selectSpeakerSuggestion = (speakerId, suggestion) => {
- if (speakerMap.value[speakerId]) {
- speakerMap.value[speakerId].name = suggestion.name;
- speakerSuggestions.value[speakerId] = [];
- activeSpeakerInput.value = null;
- }
- };
-
- const closeSpeakerSuggestionsOnClick = (event) => {
- // Check if the click was on an input field or dropdown
- const clickedInput = event.target.closest('input[type="text"]');
- const clickedDropdown = event.target.closest('.absolute.z-10');
-
- // If not clicking on input or dropdown, close all suggestions
- if (!clickedInput && !clickedDropdown) {
- Object.keys(speakerSuggestions.value).forEach(speakerId => {
- speakerSuggestions.value[speakerId] = [];
- });
- }
- };
-
- // =========================================
- // Speaker Navigation (Index-Based for Virtual Scroll)
- // =========================================
-
- /**
- * Find speaker groups by analyzing segment data (not DOM).
- * Returns groups with startIndex instead of startElement for virtual scroll compatibility.
- */
- const findSpeakerGroups = (speakerId) => {
- if (!speakerId) return [];
-
- // Get segments from processedTranscription
- const segments = processedTranscription.value?.simpleSegments || [];
- if (segments.length === 0) return [];
-
- const groups = [];
- let currentGroup = null;
- let lastSpeakerId = null;
-
- segments.forEach((segment, index) => {
- const segmentSpeakerId = segment.speakerId;
-
- if (segmentSpeakerId === speakerId) {
- // If this is a new group (not consecutive with previous)
- if (lastSpeakerId !== speakerId) {
- currentGroup = {
- startIndex: index,
- indices: [index]
- };
- groups.push(currentGroup);
- } else if (currentGroup) {
- // Add to existing group
- currentGroup.indices.push(index);
- }
- }
- lastSpeakerId = segmentSpeakerId;
- });
-
- return groups;
- };
-
- const highlightSpeakerInTranscript = (speakerId) => {
- highlightedSpeaker.value = speakerId;
-
- if (speakerId) {
- // Find all speaker groups for navigation (index-based, no DOM queries)
- speakerGroups.value = findSpeakerGroups(speakerId);
-
- if (speakerGroups.value.length > 0) {
- // Get the current visible range from the virtual scroll
- const visibleRange = utils.getSpeakerModalVisibleRange ? utils.getSpeakerModalVisibleRange() : null;
-
- if (visibleRange) {
- const { start: visibleStart, end: visibleEnd } = visibleRange;
- const visibleCenter = Math.floor((visibleStart + visibleEnd) / 2);
-
- // Check if any group is already visible
- const visibleGroupIndex = speakerGroups.value.findIndex(group =>
- group.startIndex >= visibleStart && group.startIndex < visibleEnd
- );
-
- if (visibleGroupIndex !== -1) {
- // A group is already visible, just set it as current (no scroll needed)
- currentSpeakerGroupIndex.value = visibleGroupIndex;
- } else {
- // No group visible - find the nearest group to the visible center
- let nearestIndex = 0;
- let nearestDistance = Infinity;
-
- speakerGroups.value.forEach((group, index) => {
- const distance = Math.abs(group.startIndex - visibleCenter);
- if (distance < nearestDistance) {
- nearestDistance = distance;
- nearestIndex = index;
- }
- });
-
- currentSpeakerGroupIndex.value = nearestIndex;
-
- // Scroll to the nearest group
- const nearestGroup = speakerGroups.value[nearestIndex];
- if (nearestGroup && typeof nearestGroup.startIndex === 'number' && utils.scrollToSegmentIndex) {
- utils.scrollToSegmentIndex(nearestGroup.startIndex);
- }
- }
- } else {
- // Fallback: no visible range available, scroll to first group
- currentSpeakerGroupIndex.value = 0;
- const firstGroup = speakerGroups.value[0];
- if (firstGroup && typeof firstGroup.startIndex === 'number' && utils.scrollToSegmentIndex) {
- utils.scrollToSegmentIndex(firstGroup.startIndex);
- }
- }
- } else {
- currentSpeakerGroupIndex.value = -1;
- }
- } else {
- speakerGroups.value = [];
- currentSpeakerGroupIndex.value = -1;
- }
- };
-
- /**
- * Select a speaker for navigation from the dropdown.
- * Uses index-based navigation compatible with virtual scrolling.
- */
- const selectSpeakerForNavigation = (speakerId) => {
- if (!speakerId) {
- highlightedSpeaker.value = null;
- speakerGroups.value = [];
- currentSpeakerGroupIndex.value = -1;
- return;
- }
-
- highlightedSpeaker.value = speakerId;
-
- // Find groups immediately (no DOM dependency)
- speakerGroups.value = findSpeakerGroups(speakerId);
- currentSpeakerGroupIndex.value = 0;
-
- // Scroll to first occurrence
- if (speakerGroups.value.length > 0) {
- const firstGroup = speakerGroups.value[0];
- if (firstGroup && typeof firstGroup.startIndex === 'number') {
- if (utils.scrollToSegmentIndex) {
- utils.scrollToSegmentIndex(firstGroup.startIndex);
- }
- }
- }
- };
-
- const navigateToNextSpeakerGroup = () => {
- if (speakerGroups.value.length === 0) return;
-
- // Update the index
- currentSpeakerGroupIndex.value = (currentSpeakerGroupIndex.value + 1) % speakerGroups.value.length;
- const group = speakerGroups.value[currentSpeakerGroupIndex.value];
- if (group && typeof group.startIndex === 'number') {
- if (utils.scrollToSegmentIndex) {
- utils.scrollToSegmentIndex(group.startIndex);
- }
- }
- };
-
- const navigateToPrevSpeakerGroup = () => {
- if (speakerGroups.value.length === 0) return;
-
- // Update the index
- currentSpeakerGroupIndex.value = currentSpeakerGroupIndex.value <= 0
- ? speakerGroups.value.length - 1
- : currentSpeakerGroupIndex.value - 1;
- const group = speakerGroups.value[currentSpeakerGroupIndex.value];
- if (group && typeof group.startIndex === 'number') {
- if (utils.scrollToSegmentIndex) {
- utils.scrollToSegmentIndex(group.startIndex);
- }
- }
- };
-
- const focusSpeaker = (speakerId) => {
- // Set this as the active speaker input
- activeSpeakerInput.value = speakerId;
- // Only highlight if not already highlighted (to preserve navigation state)
- if (highlightedSpeaker.value !== speakerId) {
- highlightSpeakerInTranscript(speakerId);
- }
- };
-
- const blurSpeaker = () => {
- // Clear the active speaker input after a delay to allow clicking
- // on suggestions before the dropdown collapses.
- setTimeout(() => {
- activeSpeakerInput.value = null;
- speakerSuggestions.value = {};
- }, 200);
- // DO NOT clear the speaker highlight here. The highlight + the
- // prev/next nav buttons should remain usable while the user
- // walks through the speaker's segments — clicking Prev/Next
- // moves focus off the input and would otherwise clear the
- // navigation state mid-action. Highlight is now released only
- // when a DIFFERENT speaker is focused (focusSpeaker overwrites
- // highlightedSpeaker), the user picks the default "Navigate
- // to speaker…" option, or the modal closes.
- };
-
- const clearSpeakerHighlight = () => {
- highlightedSpeaker.value = null;
- };
-
// =========================================
// Auto-Identify Speakers
// =========================================
@@ -868,25 +590,20 @@ export function useSpeakers(state, utils, processedTranscription) {
// Apply Suggested Names
// =========================================
- /** True when any unnamed, non-isMe speaker has voice or autocomplete suggestions */
+ /** True when any unnamed, non-isMe speaker has a voice-match suggestion */
const hasAnySuggestions = Vue.computed(() => {
for (const speakerId of modalSpeakers.value) {
const data = speakerMap.value[speakerId];
if (!data || data.isMe) continue;
if (data.name && data.name.trim() !== '') continue;
- // Check voice suggestions
if (voiceSuggestions.value[speakerId] && voiceSuggestions.value[speakerId].length > 0) {
return true;
}
- // Check autocomplete suggestions
- if (speakerSuggestions.value[speakerId] && speakerSuggestions.value[speakerId].length > 0) {
- return true;
- }
}
return false;
});
- /** Bulk-apply voice suggestions (priority) then autocomplete suggestions to empty names only */
+ /** Apply the best voice match to every speaker whose name is still empty */
const applySuggestedNames = () => {
let appliedCount = 0;
for (const speakerId of modalSpeakers.value) {
@@ -894,19 +611,10 @@ export function useSpeakers(state, utils, processedTranscription) {
if (!data || data.isMe) continue;
if (data.name && data.name.trim() !== '') continue;
- // Priority 1: voice suggestions
const voice = voiceSuggestions.value[speakerId];
if (voice && voice.length > 0) {
data.name = voice[0].name;
appliedCount++;
- continue;
- }
-
- // Priority 2: autocomplete suggestions
- const auto = speakerSuggestions.value[speakerId];
- if (auto && auto.length > 0) {
- data.name = auto[0].name;
- appliedCount++;
}
}
@@ -1003,9 +711,6 @@ export function useSpeakers(state, utils, processedTranscription) {
color: getSpeakerColor(newSpeakerId)
};
- // Add to speakerDisplayMap
- speakerDisplayMap.value[newSpeakerId] = newSpeakerId;
-
// Add to modalSpeakers LAST (triggers re-render, but speakerMap is already populated)
modalSpeakers.value.push(newSpeakerId);
@@ -1239,20 +944,6 @@ export function useSpeakers(state, utils, processedTranscription) {
loadVoiceSuggestions,
applyVoiceSuggestion,
handleIsMeChange,
- shouldShowVoiceSuggestionPill,
- searchSpeakers,
- selectSpeakerSuggestion,
- closeSpeakerSuggestionsOnClick,
-
- // Navigation
- findSpeakerGroups,
- highlightSpeakerInTranscript,
- selectSpeakerForNavigation,
- navigateToNextSpeakerGroup,
- navigateToPrevSpeakerGroup,
- focusSpeaker,
- blurSpeaker,
- clearSpeakerHighlight,
// Auto-identify
autoIdentifySpeakers,
diff --git a/static/locales/de.json b/static/locales/de.json
index f85fe295..32465ba4 100644
--- a/static/locales/de.json
+++ b/static/locales/de.json
@@ -1693,6 +1693,55 @@
"upcoming": "Bevorstehend",
"yesterday": "Gestern"
},
+ "speakerModal": {
+ "alreadyAssigned": "Bereits einem anderen Sprecher zugewiesen",
+ "changeSpeaker": "Sprecher ändern",
+ "clearSelection": "Auswahl aufheben",
+ "colorRepeats": "Farbe wiederholt",
+ "editText": "Text bearbeiten",
+ "hideVideo": "Video ausblenden",
+ "incognitoAudio": "Bei Inkognito-Aufnahmen wird kein Audio gespeichert.",
+ "mergeAllInto": "Alle zusammenführen mit…",
+ "mergeInto": "Zusammenführen mit…",
+ "mergedSpeakers": "{{count}} Sprecher mit {{name}} zusammengeführt. Speichern, um die Änderung zu übernehmen.",
+ "mergedSpeakersPlural": "{{count}} Sprecher mit {{name}} zusammengeführt. Speichern, um die Änderung zu übernehmen.",
+ "minorSpeakers": "{{count}} kurzer Sprecher",
+ "minorSpeakersHint": "jeweils unter {{seconds}} s, insgesamt {{time}}",
+ "minorSpeakersPlural": "{{count}} kurze Sprecher",
+ "mute": "Stummschalten",
+ "namePlaceholder": "Name für {{label}}",
+ "nextTurn": "Nächster Redebeitrag",
+ "noSegmentsYet": "Manuell hinzugefügt",
+ "onlyThisSpeaker": "Nur dieser Sprecher",
+ "pause": "Pause",
+ "play": "Abspielen",
+ "playSample": "Längsten Abschnitt dieses Sprechers abspielen",
+ "playbackSpeed": "Wiedergabegeschwindigkeit",
+ "previousTurn": "Vorheriger Redebeitrag",
+ "savedSpelling": "Gespeichert als {{name}}",
+ "seek": "Wiedergabeposition",
+ "segmentCount": "{{count}} Abschnitt",
+ "segmentCountPlural": "{{count}} Abschnitte",
+ "selectHint": "Wählen Sie einen Sprecher aus, um nur seine Abschnitte zu sehen.",
+ "showAll": "Alle Abschnitte anzeigen",
+ "showVideo": "Video anzeigen",
+ "sortAppearance": "Erstes Auftreten",
+ "sortBy": "Sortieren nach",
+ "sortDuration": "Redezeit",
+ "sortName": "Name",
+ "speakerCount": "{{count}} Sprecher",
+ "speakerCountPlural": "{{count}} Sprecher",
+ "speakersTab": "Sprecher",
+ "speakingTime": "{{time}} · {{share}} %",
+ "transcriptTab": "Transkript",
+ "unmute": "Ton einschalten",
+ "useSavedSpelling": "Übernehmen",
+ "usedTimes": "Einmal verwendet",
+ "usedTimesPlural": "{{count}}-mal verwendet",
+ "voiceMatch": "Stimmübereinstimmung",
+ "voiceMatchTitle": "Stimmübereinstimmung: {{name}} ({{similarity}} %)",
+ "volume": "Lautstärke"
+ },
"speakers": {
"filterBySpeaker": "Nach Sprecher filtern",
"noMatchingSpeakers": "Keine passenden Sprecher",
diff --git a/static/locales/en.json b/static/locales/en.json
index 663fca1d..f556008a 100644
--- a/static/locales/en.json
+++ b/static/locales/en.json
@@ -1693,6 +1693,55 @@
"allRecordings": "All Recordings",
"unfiled": "Unfiled"
},
+ "speakerModal": {
+ "alreadyAssigned": "Already given to another speaker",
+ "changeSpeaker": "Change speaker",
+ "clearSelection": "Clear selection",
+ "colorRepeats": "Color repeats",
+ "editText": "Edit text",
+ "hideVideo": "Hide video",
+ "incognitoAudio": "Audio is not stored for incognito recordings.",
+ "mergeAllInto": "Merge all into…",
+ "mergeInto": "Merge into…",
+ "mergedSpeakers": "Merged {{count}} speaker into {{name}}. Save to keep the change.",
+ "mergedSpeakersPlural": "Merged {{count}} speakers into {{name}}. Save to keep the change.",
+ "minorSpeakers": "{{count}} short speaker",
+ "minorSpeakersHint": "under {{seconds}} s each, {{time}} in total",
+ "minorSpeakersPlural": "{{count}} short speakers",
+ "mute": "Mute",
+ "namePlaceholder": "Name for {{label}}",
+ "nextTurn": "Next turn",
+ "noSegmentsYet": "Added by hand",
+ "onlyThisSpeaker": "Only this speaker",
+ "pause": "Pause",
+ "play": "Play",
+ "playSample": "Play this speaker’s longest segment",
+ "playbackSpeed": "Playback speed",
+ "previousTurn": "Previous turn",
+ "savedSpelling": "Saved as {{name}}",
+ "seek": "Playback position",
+ "segmentCount": "{{count}} segment",
+ "segmentCountPlural": "{{count}} segments",
+ "selectHint": "Select a speaker to see only their segments.",
+ "showAll": "Show all segments",
+ "showVideo": "Show video",
+ "sortAppearance": "First appearance",
+ "sortBy": "Sort by",
+ "sortDuration": "Speaking time",
+ "sortName": "Name",
+ "speakerCount": "{{count}} speaker",
+ "speakerCountPlural": "{{count}} speakers",
+ "speakersTab": "Speakers",
+ "speakingTime": "{{time}} · {{share}}%",
+ "transcriptTab": "Transcript",
+ "unmute": "Unmute",
+ "useSavedSpelling": "Use",
+ "usedTimes": "Used once",
+ "usedTimesPlural": "Used {{count}} times",
+ "voiceMatch": "Voice match",
+ "voiceMatchTitle": "Voice match: {{name}} ({{similarity}}%)",
+ "volume": "Volume"
+ },
"speakers": {
"filterBySpeaker": "Filter by speaker",
"noMatchingSpeakers": "No matching speakers",
diff --git a/static/locales/es.json b/static/locales/es.json
index 40ce76ab..38c3f9e7 100644
--- a/static/locales/es.json
+++ b/static/locales/es.json
@@ -1693,6 +1693,55 @@
"upcoming": "Próximo",
"yesterday": "Ayer"
},
+ "speakerModal": {
+ "alreadyAssigned": "Ya asignado a otro hablante",
+ "changeSpeaker": "Cambiar hablante",
+ "clearSelection": "Quitar selección",
+ "colorRepeats": "Color repetido",
+ "editText": "Editar texto",
+ "hideVideo": "Ocultar vídeo",
+ "incognitoAudio": "El audio no se guarda en las grabaciones de incógnito.",
+ "mergeAllInto": "Combinar todos con…",
+ "mergeInto": "Combinar con…",
+ "mergedSpeakers": "{{count}} hablante combinado con {{name}}. Guarde para conservar el cambio.",
+ "mergedSpeakersPlural": "{{count}} hablantes combinados con {{name}}. Guarde para conservar el cambio.",
+ "minorSpeakers": "{{count}} hablante breve",
+ "minorSpeakersHint": "menos de {{seconds}} s cada uno, {{time}} en total",
+ "minorSpeakersPlural": "{{count}} hablantes breves",
+ "mute": "Silenciar",
+ "namePlaceholder": "Nombre para {{label}}",
+ "nextTurn": "Siguiente intervención",
+ "noSegmentsYet": "Añadido manualmente",
+ "onlyThisSpeaker": "Solo este hablante",
+ "pause": "Pausa",
+ "play": "Reproducir",
+ "playSample": "Reproducir el segmento más largo de este hablante",
+ "playbackSpeed": "Velocidad de reproducción",
+ "previousTurn": "Intervención anterior",
+ "savedSpelling": "Guardado como {{name}}",
+ "seek": "Posición de reproducción",
+ "segmentCount": "{{count}} segmento",
+ "segmentCountPlural": "{{count}} segmentos",
+ "selectHint": "Seleccione un hablante para ver solo sus segmentos.",
+ "showAll": "Mostrar todos los segmentos",
+ "showVideo": "Mostrar vídeo",
+ "sortAppearance": "Primera aparición",
+ "sortBy": "Ordenar por",
+ "sortDuration": "Tiempo de habla",
+ "sortName": "Nombre",
+ "speakerCount": "{{count}} hablante",
+ "speakerCountPlural": "{{count}} hablantes",
+ "speakersTab": "Hablantes",
+ "speakingTime": "{{time}} · {{share}} %",
+ "transcriptTab": "Transcripción",
+ "unmute": "Activar sonido",
+ "useSavedSpelling": "Usar",
+ "usedTimes": "Usado una vez",
+ "usedTimesPlural": "Usado {{count}} veces",
+ "voiceMatch": "Coincidencia de voz",
+ "voiceMatchTitle": "Coincidencia de voz: {{name}} ({{similarity}} %)",
+ "volume": "Volumen"
+ },
"speakers": {
"filterBySpeaker": "Filtrar por orador",
"noMatchingSpeakers": "No hay oradores coincidentes",
diff --git a/static/locales/fr.json b/static/locales/fr.json
index 4dfe1ecb..3865cf98 100644
--- a/static/locales/fr.json
+++ b/static/locales/fr.json
@@ -1693,6 +1693,55 @@
"upcoming": "À venir",
"yesterday": "Hier"
},
+ "speakerModal": {
+ "alreadyAssigned": "Déjà attribué à un autre intervenant",
+ "changeSpeaker": "Changer d’intervenant",
+ "clearSelection": "Effacer la sélection",
+ "colorRepeats": "Couleur répétée",
+ "editText": "Modifier le texte",
+ "hideVideo": "Masquer la vidéo",
+ "incognitoAudio": "L’audio n’est pas conservé pour les enregistrements en mode incognito.",
+ "mergeAllInto": "Tout fusionner avec…",
+ "mergeInto": "Fusionner avec…",
+ "mergedSpeakers": "{{count}} intervenant fusionné avec {{name}}. Enregistrez pour conserver la modification.",
+ "mergedSpeakersPlural": "{{count}} intervenants fusionnés avec {{name}}. Enregistrez pour conserver la modification.",
+ "minorSpeakers": "{{count}} intervenant bref",
+ "minorSpeakersHint": "moins de {{seconds}} s chacun, {{time}} au total",
+ "minorSpeakersPlural": "{{count}} intervenants brefs",
+ "mute": "Couper le son",
+ "namePlaceholder": "Nom pour {{label}}",
+ "nextTurn": "Intervention suivante",
+ "noSegmentsYet": "Ajouté manuellement",
+ "onlyThisSpeaker": "Uniquement cet intervenant",
+ "pause": "Pause",
+ "play": "Lire",
+ "playSample": "Lire le plus long segment de cet intervenant",
+ "playbackSpeed": "Vitesse de lecture",
+ "previousTurn": "Intervention précédente",
+ "savedSpelling": "Enregistré sous {{name}}",
+ "seek": "Position de lecture",
+ "segmentCount": "{{count}} segment",
+ "segmentCountPlural": "{{count}} segments",
+ "selectHint": "Sélectionnez un intervenant pour n’afficher que ses segments.",
+ "showAll": "Afficher tous les segments",
+ "showVideo": "Afficher la vidéo",
+ "sortAppearance": "Première apparition",
+ "sortBy": "Trier par",
+ "sortDuration": "Temps de parole",
+ "sortName": "Nom",
+ "speakerCount": "{{count}} intervenant",
+ "speakerCountPlural": "{{count}} intervenants",
+ "speakersTab": "Intervenants",
+ "speakingTime": "{{time}} · {{share}} %",
+ "transcriptTab": "Transcription",
+ "unmute": "Rétablir le son",
+ "useSavedSpelling": "Utiliser",
+ "usedTimes": "Utilisé une fois",
+ "usedTimesPlural": "Utilisé {{count}} fois",
+ "voiceMatch": "Correspondance vocale",
+ "voiceMatchTitle": "Correspondance vocale : {{name}} ({{similarity}} %)",
+ "volume": "Volume"
+ },
"speakers": {
"filterBySpeaker": "Filtrer par intervenant",
"noMatchingSpeakers": "Aucun intervenant correspondant",
diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.json
index c0d14a99..60fc042d 100644
--- a/static/locales/pt-BR.json
+++ b/static/locales/pt-BR.json
@@ -1693,6 +1693,55 @@
"upcoming": "Próximos",
"yesterday": "Ontem"
},
+ "speakerModal": {
+ "alreadyAssigned": "Já atribuído a outro locutor",
+ "changeSpeaker": "Alterar locutor",
+ "clearSelection": "Limpar seleção",
+ "colorRepeats": "Cor repetida",
+ "editText": "Editar texto",
+ "hideVideo": "Ocultar vídeo",
+ "incognitoAudio": "O áudio não é armazenado em gravações anônimas.",
+ "mergeAllInto": "Mesclar todos com…",
+ "mergeInto": "Mesclar com…",
+ "mergedSpeakers": "{{count}} locutor mesclado com {{name}}. Salve para manter a alteração.",
+ "mergedSpeakersPlural": "{{count}} locutores mesclados com {{name}}. Salve para manter a alteração.",
+ "minorSpeakers": "{{count}} locutor breve",
+ "minorSpeakersHint": "menos de {{seconds}} s cada, {{time}} no total",
+ "minorSpeakersPlural": "{{count}} locutores breves",
+ "mute": "Silenciar",
+ "namePlaceholder": "Nome para {{label}}",
+ "nextTurn": "Próxima fala",
+ "noSegmentsYet": "Adicionado manualmente",
+ "onlyThisSpeaker": "Apenas este locutor",
+ "pause": "Pausar",
+ "play": "Reproduzir",
+ "playSample": "Reproduzir o trecho mais longo deste locutor",
+ "playbackSpeed": "Velocidade de reprodução",
+ "previousTurn": "Fala anterior",
+ "savedSpelling": "Salvo como {{name}}",
+ "seek": "Posição de reprodução",
+ "segmentCount": "{{count}} trecho",
+ "segmentCountPlural": "{{count}} trechos",
+ "selectHint": "Selecione um locutor para ver apenas os trechos dele.",
+ "showAll": "Mostrar todos os trechos",
+ "showVideo": "Mostrar vídeo",
+ "sortAppearance": "Primeira aparição",
+ "sortBy": "Ordenar por",
+ "sortDuration": "Tempo de fala",
+ "sortName": "Nome",
+ "speakerCount": "{{count}} locutor",
+ "speakerCountPlural": "{{count}} locutores",
+ "speakersTab": "Locutores",
+ "speakingTime": "{{time}} · {{share}}%",
+ "transcriptTab": "Transcrição",
+ "unmute": "Ativar som",
+ "useSavedSpelling": "Usar",
+ "usedTimes": "Usado uma vez",
+ "usedTimesPlural": "Usado {{count}} vezes",
+ "voiceMatch": "Correspondência de voz",
+ "voiceMatchTitle": "Correspondência de voz: {{name}} ({{similarity}}%)",
+ "volume": "Volume"
+ },
"speakers": {
"filterBySpeaker": "Filtrar por orador",
"noMatchingSpeakers": "Nenhum orador correspondente",
diff --git a/static/locales/ru.json b/static/locales/ru.json
index b4328347..80305e44 100644
--- a/static/locales/ru.json
+++ b/static/locales/ru.json
@@ -1693,6 +1693,55 @@
"upcoming": "Предстоящие",
"yesterday": "Вчера"
},
+ "speakerModal": {
+ "alreadyAssigned": "Уже назначено другому говорящему",
+ "changeSpeaker": "Сменить говорящего",
+ "clearSelection": "Снять выбор",
+ "colorRepeats": "Цвет повторяется",
+ "editText": "Изменить текст",
+ "hideVideo": "Скрыть видео",
+ "incognitoAudio": "Для записей в режиме инкогнито аудио не сохраняется.",
+ "mergeAllInto": "Объединить всех с…",
+ "mergeInto": "Объединить с…",
+ "mergedSpeakers": "{{count}} говорящий объединён с {{name}}. Сохраните, чтобы применить изменение.",
+ "mergedSpeakersPlural": "Говорящих объединено с {{name}}: {{count}}. Сохраните, чтобы применить изменение.",
+ "minorSpeakers": "Коротких говорящих: {{count}}",
+ "minorSpeakersHint": "меньше {{seconds}} с каждый, всего {{time}}",
+ "minorSpeakersPlural": "Коротких говорящих: {{count}}",
+ "mute": "Выключить звук",
+ "namePlaceholder": "Имя для {{label}}",
+ "nextTurn": "Следующая реплика",
+ "noSegmentsYet": "Добавлен вручную",
+ "onlyThisSpeaker": "Только этот говорящий",
+ "pause": "Пауза",
+ "play": "Воспроизвести",
+ "playSample": "Воспроизвести самый длинный фрагмент этого говорящего",
+ "playbackSpeed": "Скорость воспроизведения",
+ "previousTurn": "Предыдущая реплика",
+ "savedSpelling": "Сохранено как {{name}}",
+ "seek": "Позиция воспроизведения",
+ "segmentCount": "Фрагментов: {{count}}",
+ "segmentCountPlural": "Фрагментов: {{count}}",
+ "selectHint": "Выберите говорящего, чтобы видеть только его фрагменты.",
+ "showAll": "Показать все фрагменты",
+ "showVideo": "Показать видео",
+ "sortAppearance": "Порядок появления",
+ "sortBy": "Сортировка",
+ "sortDuration": "Время речи",
+ "sortName": "Имя",
+ "speakerCount": "Говорящих: {{count}}",
+ "speakerCountPlural": "Говорящих: {{count}}",
+ "speakersTab": "Говорящие",
+ "speakingTime": "{{time}} · {{share}} %",
+ "transcriptTab": "Расшифровка",
+ "unmute": "Включить звук",
+ "useSavedSpelling": "Использовать",
+ "usedTimes": "Использовано 1 раз",
+ "usedTimesPlural": "Использовано раз: {{count}}",
+ "voiceMatch": "Совпадение голоса",
+ "voiceMatchTitle": "Совпадение голоса: {{name}} ({{similarity}} %)",
+ "volume": "Громкость"
+ },
"speakers": {
"filterBySpeaker": "Фильтр по спикеру",
"noMatchingSpeakers": "Нет подходящих спикеров",
diff --git a/static/locales/zh.json b/static/locales/zh.json
index ffa9123e..3eb09ebe 100644
--- a/static/locales/zh.json
+++ b/static/locales/zh.json
@@ -1693,6 +1693,55 @@
"upcoming": "即将到来",
"yesterday": "昨天"
},
+ "speakerModal": {
+ "alreadyAssigned": "已分配给其他发言人",
+ "changeSpeaker": "更改发言人",
+ "clearSelection": "取消选择",
+ "colorRepeats": "颜色重复",
+ "editText": "编辑文本",
+ "hideVideo": "隐藏视频",
+ "incognitoAudio": "隐身录音不保存音频。",
+ "mergeAllInto": "全部合并到…",
+ "mergeInto": "合并到…",
+ "mergedSpeakers": "已将 {{count}} 位发言人合并到 {{name}}。保存后生效。",
+ "mergedSpeakersPlural": "已将 {{count}} 位发言人合并到 {{name}}。保存后生效。",
+ "minorSpeakers": "{{count}} 位短时发言人",
+ "minorSpeakersHint": "每位不足 {{seconds}} 秒,共 {{time}}",
+ "minorSpeakersPlural": "{{count}} 位短时发言人",
+ "mute": "静音",
+ "namePlaceholder": "{{label}} 的名称",
+ "nextTurn": "下一段发言",
+ "noSegmentsYet": "手动添加",
+ "onlyThisSpeaker": "仅此发言人",
+ "pause": "暂停",
+ "play": "播放",
+ "playSample": "播放该发言人最长的片段",
+ "playbackSpeed": "播放速度",
+ "previousTurn": "上一段发言",
+ "savedSpelling": "已保存为 {{name}}",
+ "seek": "播放位置",
+ "segmentCount": "{{count}} 个片段",
+ "segmentCountPlural": "{{count}} 个片段",
+ "selectHint": "选择一位发言人以仅查看其片段。",
+ "showAll": "显示所有片段",
+ "showVideo": "显示视频",
+ "sortAppearance": "首次出现",
+ "sortBy": "排序方式",
+ "sortDuration": "发言时长",
+ "sortName": "名称",
+ "speakerCount": "{{count}} 位发言人",
+ "speakerCountPlural": "{{count}} 位发言人",
+ "speakersTab": "发言人",
+ "speakingTime": "{{time}} · {{share}}%",
+ "transcriptTab": "转录文本",
+ "unmute": "取消静音",
+ "useSavedSpelling": "使用",
+ "usedTimes": "使用过 1 次",
+ "usedTimesPlural": "使用过 {{count}} 次",
+ "voiceMatch": "声纹匹配",
+ "voiceMatchTitle": "声纹匹配:{{name}}({{similarity}}%)",
+ "volume": "音量"
+ },
"speakers": {
"filterBySpeaker": "按发言人筛选",
"noMatchingSpeakers": "没有匹配的发言人",
diff --git a/templates/modals/speaker-modal.html b/templates/modals/speaker-modal.html
index 096dec7a..ba1095a4 100644
--- a/templates/modals/speaker-modal.html
+++ b/templates/modals/speaker-modal.html
@@ -1,60 +1,38 @@
-<!-- Identify Speakers Modal — design-system rebuild.
+<!-- Identify Speakers modal, rebuilt for #395.
- PERFORMANCE NOTES (issue #157):
- The previous implementation used a fixed-itemHeight virtual scroller
- (only ~30 of the ~4500 segments mounted at a time) to keep Vue's
- reactivity cheap during edits. That solved the slowdown but broke
- position math: real segment heights vary 40 px → 600+ px so
- scrollTop = index * 52 landed at wrong positions, the scrollbar
- visibly jumped as scrollHeight recomputed mid-scroll, and smooth-
- scroll animations fought their own moving target.
+ State and behaviour: composables/speaker-modal.js (list order, filter,
+ name fields, player) and composables/speakers.js (save, auto-identify,
+ per-line speaker and text edits, voice suggestions). Pure helpers with
+ unit tests: utils/speaker-modal-model.js.
- This rewrite drops the virtual scroller and uses three browser-
- native primitives that handle variable heights correctly:
+ Layout: speakers on the left, sorted by speaking time by default, with
+ speakers under 30 seconds collapsed into one group that can be merged
+ into a main speaker. Selecting a speaker shows only their segments on
+ the right; "Show all segments" keeps the highlight and adds Previous /
+ Next turn buttons. On phones the two panes are tabs.
- 1. content-visibility: auto + contain-intrinsic-size: auto 60px
- on .speaker-segment (defined in styles.css). All ~4500
- segments stay in the DOM with a 60-px placeholder size for
- off-screen elements, so the document's total scroll height
- is stable AND scrollIntoView / querySelector / mouse-wheel
- scrolling work against real measured positions. Browser
- skips paint + layout for off-screen segments — same perf
- benefit virtual scroll was after.
+ Performance: every segment stays in the DOM. .speaker-segment carries
+ content-visibility: auto (styles.css), so off-screen rows skip layout
+ and paint, and v-memo keys each row on its own speaker's name, so typing
+ a name re-renders only that speaker's rows.
- 2. v-memo on each row — Vue 3's per-row render skip. Only re-
- renders a row when its specific dependencies change
- (segment data, highlightedSpeaker for this row, edit-mode
- for this row). Typing a name into speakerMap[X] no longer
- fans out to all 4500 rows — only the rows whose displayed
- speaker label is X re-render.
-
- 3. scrollToSegmentIndex (in app.modular.js) = querySelector +
- scrollIntoView({ block: 'center', behavior: 'smooth' }).
- Uses measured positions; no math, no race conditions, no
- spacer drift.
-
- UX NOTES:
- - modal-overlay / modal-panel primitives so the modal matches
- the rest of the app's design language. Height locked to 90vh
- via inline style so the inner flex column has a stable size.
- - field primitive for the name inputs.
- - btn primitives for footer actions.
- - pill-status for the "3 / 5" navigation position indicator.
- - empty primitive when there's no transcript to navigate. -->
+ Template rules: no object literals inside ${ } (use v-text), no window.*
+ in expressions. -->
<div v-if="showSpeakerModal" @click.self="closeSpeakerModal" class="modal-overlay">
- <div @click="closeSpeakerSuggestionsOnClick"
- class="modal-panel modal-panel--xl"
- style="height: 90vh; max-height: 90vh;">
+ <div class="modal-panel modal-panel--xl spk-modal" style="height: 90vh; max-height: 90vh;">
<div class="modal-header">
- <h3 class="modal-title" v-text="t('modal.identifySpeakers')"></h3>
- <button @click="closeSpeakerModal" class="modal-close" :title="t('buttons.close')">
+ <div class="flex-1 min-w-0">
+ <h3 class="modal-title" v-text="t('modal.identifySpeakers')"></h3>
+ <p class="t-meta" v-if="modalSpeakers.length"
+ v-text="tc('speakerModal.speakerCount', modalSpeakers.length, { count: modalSpeakers.length })"></p>
+ </div>
+ <button @click="closeSpeakerModal" class="modal-close" :title="t('buttons.close')" :aria-label="t('buttons.close')">
<i class="fas fa-times"></i>
</button>
</div>
- <!-- Warning for too many speakers -->
<div v-if="modalSpeakers.length > 16"
class="banner banner--warn"
style="margin: var(--sp-3) var(--sp-5) 0;">
@@ -65,325 +43,296 @@
</div>
</div>
- <!-- Mobile Tab Switcher (hidden on lg) -->
- <div class="lg:hidden flex border-b border-[var(--border-primary)] flex-shrink-0">
- <button @click="speakerModalTab = 'speakers'"
- class="flex-1 py-2 text-xs font-medium transition-colors relative"
- :class="speakerModalTab === 'speakers' ? 'text-[var(--text-accent)]' : 'text-[var(--text-muted)]'">
- <i class="fas fa-users mr-1"></i>Speakers
- <span v-if="speakerModalTab === 'speakers'" class="absolute bottom-0 left-0 right-0 h-0.5 bg-[var(--bg-accent)]"></span>
+ <!-- Phone tabs -->
+ <div class="lg:hidden flex border-b border-[var(--border-primary)] flex-shrink-0" role="tablist">
+ <button @click="speakerModalTab = 'speakers'" role="tab" :aria-selected="speakerModalTab === 'speakers'"
+ class="spk-tab" :class="{ 'is-active': speakerModalTab === 'speakers' }">
+ <i class="fas fa-users"></i>
+ <span v-text="t('speakerModal.speakersTab')"></span>
</button>
- <button @click="speakerModalTab = 'transcript'"
- class="flex-1 py-2 text-xs font-medium transition-colors relative"
- :class="speakerModalTab === 'transcript' ? 'text-[var(--text-accent)]' : 'text-[var(--text-muted)]'">
- <i class="fas fa-file-lines mr-1"></i>Transcript
- <span v-if="speakerModalTab === 'transcript'" class="absolute bottom-0 left-0 right-0 h-0.5 bg-[var(--bg-accent)]"></span>
+ <button @click="speakerModalTab = 'transcript'" role="tab" :aria-selected="speakerModalTab === 'transcript'"
+ class="spk-tab" :class="{ 'is-active': speakerModalTab === 'transcript' }">
+ <i class="fas fa-file-lines"></i>
+ <span v-text="selectedSpeaker ? labelOf(selectedSpeaker) : t('speakerModal.transcriptTab')"></span>
</button>
</div>
- <!-- Main two-column content. flex: 1 1 auto + min-height: 0 so
- this region absorbs ALL the remaining vertical space inside
- the fixed-height modal-panel. Inner panes own their own
- overflow. -->
<div class="flex flex-col lg:flex-row overflow-hidden" style="flex: 1 1 auto; min-height: 0;">
- <!-- LEFT — Speaker list -->
- <div class="lg:w-1/3 overflow-y-auto custom-scrollbar lg:border-r border-[var(--border-primary)]"
- style="padding: var(--sp-4);"
- :class="{ 'hidden lg:block': speakerModalTab !== 'speakers', 'flex-1': speakerModalTab === 'speakers' }">
+ <!-- LEFT: speakers -->
+ <div class="lg:w-[38%] flex flex-col overflow-hidden lg:border-r border-[var(--border-primary)]"
+ :class="{ 'hidden lg:flex': speakerModalTab !== 'speakers', 'flex-1': speakerModalTab === 'speakers' }">
- <div v-for="(speaker, index) in modalSpeakers"
- :key="`${selectedRecording.id}-speaker-${index}-${speaker}`"
- class="space-y-2"
- style="margin-bottom: var(--sp-4);">
+ <div class="spk-toolbar">
+ <label class="t-label" for="spk-sort" v-text="t('speakerModal.sortBy')"></label>
+ <select id="spk-sort" class="field field--sm" :value="speakerSort" @change="setSpeakerSort($event.target.value)">
+ <option value="duration" :disabled="!speakerStats.hasTimes" v-text="t('speakerModal.sortDuration')"></option>
+ <option value="appearance" v-text="t('speakerModal.sortAppearance')"></option>
+ <option value="name" v-text="t('speakerModal.sortName')"></option>
+ </select>
+ </div>
- <!-- Speaker color swatch + label + Me toggle -->
- <div class="flex items-center justify-between gap-2">
- <div class="flex items-center gap-2 min-w-0">
- <div :class="speakerMap[speaker].color"
- class="w-3 h-3 sm:w-4 sm:h-4 rounded-full border border-white/30 shadow-sm flex-shrink-0"></div>
- <span class="t-meta font-mono truncate">${ speakerDisplayMap[speaker] || speaker }</span>
- <span v-if="index >= 16"
- class="pill-status pill-status--warn"
- style="font-size: 9px; padding: 1px 6px;"
- :title="`Color repeats from speaker ${((index % 16) + 1)}`">
- Repeat
- </span>
+ <div class="spk-list custom-scrollbar">
+ <template v-for="entry in speakerListEntries" :key="entry.key">
+
+ <!-- Minor speakers group header -->
+ <div v-if="entry.header" class="spk-minor-header">
+ <button class="spk-minor-toggle" @click="showMinorSpeakers = !showMinorSpeakers"
+ :aria-expanded="showMinorSpeakers">
+ <i class="fas" :class="showMinorSpeakers ? 'fa-chevron-down' : 'fa-chevron-right'"></i>
+ <span class="t-body-strong" v-text="tc('speakerModal.minorSpeakers', minorSpeakers.length, { count: minorSpeakers.length })"></span>
+ <span class="t-meta" v-text="t('speakerModal.minorSpeakersHint', { seconds: minorSpeakerSeconds, time: formatClock(minorSpeakersSeconds) })"></span>
+ </button>
+ <select class="field field--sm" :aria-label="t('speakerModal.mergeAllInto')"
+ @change="mergeSpeakersInto(minorSpeakers, $event.target.value); $event.target.value = ''">
+ <option value="" v-text="t('speakerModal.mergeAllInto')"></option>
+ <option v-for="target in mainSpeakers" :key="target" :value="target">${ labelOf(target) }</option>
+ </select>
</div>
- <label class="flex items-center text-xs cursor-pointer text-[var(--text-muted)] hover:text-[var(--text-primary)] transition-colors flex-shrink-0">
- <input type="checkbox"
- v-model="speakerMap[speaker].isMe"
- @change="handleIsMeChange(speaker)"
- @focus="highlightSpeakerInTranscript(speaker)"
- class="speaker-checkbox w-4 h-4">
- <span class="ml-1.5 select-none" v-text="t('help.me')"></span>
- </label>
- </div>
- <!-- Name input + autocomplete -->
- <div class="relative">
- <input type="text"
- v-model="speakerMap[speaker].name"
- @input="searchSpeakers($event.target.value, speaker)"
- @focus="focusSpeaker(speaker)"
- @blur="blurSpeaker()"
- :disabled="speakerMap[speaker].isMe"
- class="field field--sm"
- :class="{ 'pr-28': shouldShowVoiceSuggestionPill(speaker) }"
- :placeholder="speakerMap[speaker].isMe ? currentUserName : t('help.enterNameFor') + ' ' + (speakerDisplayMap[speaker] || speaker)"
- autocomplete="off">
+ <!-- Speaker row -->
+ <div v-else
+ class="spk-row"
+ :class="{ 'is-selected': selectedSpeaker === entry.id, 'is-minor': entry.minor }"
+ @click="selectSpeaker(entry.id, { openTranscript: true })">
- <!-- Voice match suggestion pill. Uses the PRIMARY
- BUTTON token pair (--bg-button/--text-button):
- it is an actionable "apply this suggestion"
- control, and the subtle --bg-accent tint is
- indistinguishable from the input background in
- the dark schemes. Geometry is concentric with
- the input: the field's radius is 8px
- (--radius-md) and the pill is inset 4px on all
- sides (right-1 + h-5 in the 28px field--sm), so
- its radius is 8-4=4px (rounded) — the
- nested-corner rule. -->
- <button v-if="shouldShowVoiceSuggestionPill(speaker)"
- @click.stop="applyVoiceSuggestion(speaker, voiceSuggestions[speaker][0])"
- class="absolute right-1 top-1/2 -translate-y-1/2 h-5 px-2 bg-[var(--bg-button)] hover:bg-[var(--bg-button-hover)] text-[var(--text-button)] text-[10px] rounded flex items-center gap-1 transition-all shadow-sm active:scale-95">
- <i class="fas fa-waveform-lines text-[9px]"></i>
- <span class="font-medium truncate max-w-[50px] sm:max-w-[80px]">${ voiceSuggestions[speaker][0].name }</span>
- <span class="opacity-75">${ voiceSuggestions[speaker][0].similarity }%</span>
- </button>
+ <div class="spk-row-head">
+ <span :class="speakerColor(entry.id)" class="spk-dot"></span>
+ <span class="spk-label" :title="entry.id">${ entry.id }</span>
+ <span v-if="modalSpeakers.indexOf(entry.id) >= 16" class="pill-status pill-status--warn spk-repeat"
+ v-text="t('speakerModal.colorRepeats')"></span>
+ <label class="spk-me" @click.stop>
+ <input type="checkbox"
+ v-model="speakerMap[entry.id].isMe"
+ @change="handleIsMeChange(entry.id)"
+ class="speaker-checkbox w-4 h-4">
+ <span v-text="t('help.me')"></span>
+ </label>
+ </div>
- <!-- Loading indicator -->
- <div v-if="loadingSuggestions[speaker] && !speakerMap[speaker].isMe"
- class="absolute right-2 top-1/2 -translate-y-1/2">
- <i class="fas fa-spinner fa-spin text-[var(--text-muted)] text-xs"></i>
- </div>
+ <div class="spk-row-stats">
+ <span class="t-meta" v-text="speakerMeta(entry.id)"></span>
+ <span v-if="speakerStats.hasTimes" class="spk-share" aria-hidden="true">
+ <span :class="speakerColor(entry.id)" :style="{ width: speakerShare(entry.id) + '%' }"></span>
+ </span>
+ <button v-if="canPlayModalAudio && speakerStats.hasTimes && speakerStats.bySpeaker[entry.id]"
+ @click.stop="playSpeakerSample(entry.id)"
+ class="btn btn--icon btn--sm"
+ :title="t('speakerModal.playSample')" :aria-label="t('speakerModal.playSample')">
+ <i class="fas fa-play text-[10px]"></i>
+ </button>
+ </div>
+
+ <div class="spk-name" @click.stop>
+ <div class="relative">
+ <input type="text"
+ v-model="speakerMap[entry.id].name"
+ @focus="onNameFocus(entry.id)"
+ @input="onNameInput(entry.id)"
+ @blur="onNameBlur()"
+ @keydown="onNameKeydown(entry.id, $event)"
+ :disabled="speakerMap[entry.id].isMe"
+ class="field field--sm"
+ :class="{ 'pr-28': topVoiceMatch(entry.id) }"
+ :placeholder="speakerMap[entry.id].isMe ? currentUserName : t('speakerModal.namePlaceholder', { label: entry.id })"
+ role="combobox"
+ :aria-expanded="openNameField === entry.id && nameOptions(entry.id).length > 0"
+ :aria-controls="'spk-options-' + entry.id"
+ autocomplete="off">
+ <button v-if="topVoiceMatch(entry.id)"
+ @mousedown.prevent
+ @click="chooseName(entry.id, topVoiceMatch(entry.id).name)"
+ class="spk-voice-pill"
+ :title="t('speakerModal.voiceMatchTitle', { name: topVoiceMatch(entry.id).name, similarity: topVoiceMatch(entry.id).similarity })">
+ <i class="fas fa-waveform-lines text-[9px]"></i>
+ <span class="truncate max-w-[80px]">${ topVoiceMatch(entry.id).name }</span>
+ <span class="opacity-75">${ topVoiceMatch(entry.id).similarity }%</span>
+ </button>
+ </div>
+
+ <!-- Options render in the flow of the row, so the
+ scrolling list never clips them. -->
+ <ul v-if="openNameField === entry.id && !speakerMap[entry.id].isMe && nameOptions(entry.id).length"
+ :id="'spk-options-' + entry.id"
+ class="spk-options" role="listbox">
+ <li v-for="(option, i) in nameOptions(entry.id)" :key="option.source + option.name"
+ role="option" :aria-selected="nameOptionIndex === i"
+ class="spk-option" :class="{ 'is-active': nameOptionIndex === i, 'is-taken': option.taken }"
+ @mousedown.prevent
+ @click="chooseName(entry.id, option.name)">
+ <i class="fas" :class="option.source === 'voice' ? 'fa-waveform-lines' : 'fa-user'"></i>
+ <span class="spk-option-name">${ option.name }</span>
+ <span v-if="option.source === 'voice'" class="t-meta" v-text="t('speakerModal.voiceMatch') + ' ' + option.similarity + '%'"></span>
+ <span v-else-if="option.taken" class="t-meta" v-text="t('speakerModal.alreadyAssigned')"></span>
+ <span v-else class="t-meta" v-text="tc('speakerModal.usedTimes', option.useCount, { count: option.useCount })"></span>
+ </li>
+ </ul>
- <!-- Suggestions dropdown -->
- <div v-if="activeSpeakerInput === speaker && speakerSuggestions[speaker] && speakerSuggestions[speaker].length > 0 && !speakerMap[speaker].isMe"
- @click.stop
- class="absolute z-10 w-full mt-1 surface-raised max-h-40 overflow-y-auto"
- style="padding: var(--sp-1);">
- <div v-for="suggestion in speakerSuggestions[speaker]"
- :key="suggestion.id"
- @click="selectSpeakerSuggestion(speaker, suggestion)"
- class="px-2 py-1.5 cursor-pointer hover:bg-[var(--bg-tertiary)] rounded flex items-center justify-between">
- <div class="flex-grow min-w-0">
- <div class="text-xs font-medium text-[var(--text-primary)] truncate">${ suggestion.name }</div>
- <div class="text-[10px] text-[var(--text-muted)]">Used ${ suggestion.use_count }x</div>
+ <div v-if="savedSpellingFor(entry.id) && !speakerMap[entry.id].isMe" class="spk-spelling">
+ <span class="t-meta" v-text="t('speakerModal.savedSpelling', { name: savedSpellingFor(entry.id) })"></span>
+ <button class="btn btn--quiet btn--sm" @click="chooseName(entry.id, savedSpellingFor(entry.id))"
+ v-text="t('speakerModal.useSavedSpelling')"></button>
</div>
- <i class="fas fa-user text-[var(--text-muted)] ml-1.5 flex-shrink-0 text-[10px]"></i>
+
+ <select v-if="entry.minor" class="field field--sm spk-merge"
+ :aria-label="t('speakerModal.mergeInto')"
+ @change="mergeSpeakersInto([entry.id], $event.target.value); $event.target.value = ''">
+ <option value="" v-text="t('speakerModal.mergeInto')"></option>
+ <option v-for="target in mainSpeakers" :key="target" :value="target">${ labelOf(target) }</option>
+ </select>
</div>
</div>
- </div>
- </div>
+ </template>
- <!-- Add Speaker -->
- <div style="padding-top: var(--sp-3); border-top: var(--border-hairline) solid var(--border-primary);">
- <button @click="openAddSpeakerModal" class="btn btn--ghost btn--sm w-full">
+ <button @click="openAddSpeakerModal" class="btn btn--ghost btn--sm w-full spk-add">
<i class="fas fa-plus"></i>
<span v-text="t('buttons.addSpeaker')"></span>
</button>
</div>
</div>
- <!-- RIGHT — Audio player + transcript + navigation -->
- <div class="lg:w-2/3 flex flex-col overflow-hidden"
- style="padding: var(--sp-4); gap: var(--sp-3);"
+ <!-- RIGHT: player, filter bar, transcript -->
+ <div class="lg:w-[62%] flex flex-col overflow-hidden spk-right"
:class="{ 'hidden lg:flex': speakerModalTab !== 'transcript', 'flex-1': speakerModalTab === 'transcript' }">
- <!-- Audio player -->
<div class="flex-shrink-0">
- <div v-if="selectedRecording.audio_deleted_at"
- class="text-[var(--text-muted)] text-xs flex items-center gap-2">
+ <div v-if="selectedRecording.audio_deleted_at" class="t-meta flex items-center gap-2">
<i class="fas fa-info-circle"></i>
<span v-text="t('help.audioDeletedMessage')"></span>
</div>
- <div v-else-if="selectedRecording.incognito"
- class="text-[var(--text-muted)] text-xs flex items-center gap-2">
+ <div v-else-if="selectedRecording.incognito" class="t-meta flex items-center gap-2">
<i class="fas fa-user-secret"></i>
- <span>Audio not stored in incognito mode</span>
+ <span v-text="t('speakerModal.incognitoAudio')"></span>
</div>
<div v-else>
<component :is="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') ? 'video' : 'audio'"
- ref="speakerModalAudioRef"
- :class="(selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') && !speakerModalVideoCollapsed) ? 'w-full rounded-lg mb-2' : 'hidden'"
- :key="'speaker-modal-' + selectedRecording.id"
- :src="'/audio/' + selectedRecording.id"
- :volume="playerVolume"
- @play="handleModalAudioPlayPause"
- @pause="handleModalAudioPlayPause"
- @timeupdate="handleModalAudioTimeUpdate"
- @loadedmetadata="handleModalAudioLoadedMetadata"
- @ended="modalAudioIsPlaying = false">
+ ref="speakerModalPlayer"
+ :class="(selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/') && !speakerModalVideoCollapsed) ? 'w-full rounded-lg mb-2 spk-video' : 'hidden'"
+ :key="'speaker-modal-' + selectedRecording.id"
+ :src="'/audio/' + selectedRecording.id"
+ :volume="playerVolume"
+ preload="metadata"
+ @play="handleModalAudioPlayPause"
+ @pause="handleModalAudioPlayPause"
+ @timeupdate="onModalTimeUpdate"
+ @loadedmetadata="handleModalAudioLoadedMetadata"
+ @ended="modalAudioIsPlaying = false">
</component>
- <div class="flex items-center gap-2">
- <!-- Round play button to match the other audio
- players in the app (main player, mobile
- player, etc.). btn--icon is square-ish by
- default; we override with rounded-full +
- explicit w-8 h-8 sizing for circularity. -->
- <button @click="$refs.speakerModalAudioRef?.paused ? $refs.speakerModalAudioRef.play() : $refs.speakerModalAudioRef.pause()"
- class="w-8 h-8 rounded-full flex items-center justify-center bg-[var(--bg-accent)] hover:bg-[var(--bg-accent-hover)] text-white transition-all flex-shrink-0 shadow-sm"
- :title="modalAudioIsPlaying ? 'Pause' : 'Play'">
- <i :class="modalAudioIsPlaying ? 'fas fa-pause' : 'fas fa-play'" class="text-xs" :style="!modalAudioIsPlaying ? 'margin-left: 1px' : ''"></i>
+ <div class="spk-player">
+ <button @click="toggleModalPlayback" class="spk-play"
+ :title="modalAudioIsPlaying ? t('speakerModal.pause') : t('speakerModal.play')"
+ :aria-label="modalAudioIsPlaying ? t('speakerModal.pause') : t('speakerModal.play')">
+ <i :class="modalAudioIsPlaying ? 'fas fa-pause' : 'fas fa-play'" class="text-xs"></i>
</button>
- <div class="flex flex-col items-end flex-shrink-0 leading-none">
- <span class="text-xs text-[var(--text-primary)] font-mono">${ formatAudioTime(modalAudioCurrentTime) }</span>
- <span class="text-[10px] text-[var(--text-muted)] font-mono">${ formatAudioTime(modalAudioDuration) }</span>
- </div>
- <div class="flex-1 h-1.5 bg-[var(--bg-tertiary)] rounded-full cursor-pointer group relative"
- @click="(e) => { const rect = e.currentTarget.getBoundingClientRect(); const pct = (e.clientX - rect.left) / rect.width; if ($refs.speakerModalAudioRef) $refs.speakerModalAudioRef.currentTime = pct * modalAudioDuration; }">
- <div class="h-full bg-[var(--bg-accent)] rounded-full transition-all duration-100"
- :style="{ width: modalAudioProgressPercent + '%' }"></div>
- </div>
- <div class="relative flex items-center flex-shrink-0"
- @mouseenter="showModalVolumeSlider = true"
- @mouseleave="showModalVolumeSlider = false">
- <button @click="if ($refs.speakerModalAudioRef) { $refs.speakerModalAudioRef.muted = !$refs.speakerModalAudioRef.muted; audioIsMuted = $refs.speakerModalAudioRef.muted; }"
- class="btn btn--icon btn--sm"
- :class="audioIsMuted || playerVolume === 0 ? 'text-[var(--text-muted)]' : 'text-[var(--text-primary)]'">
- <i :class="audioIsMuted || playerVolume === 0 ? 'fas fa-volume-mute' : playerVolume < 0.5 ? 'fas fa-volume-down' : 'fas fa-volume-up'"></i>
- </button>
- <div class="absolute top-full left-1/2 -translate-x-1/2 pt-2 z-[9999] transition-all duration-200"
- :class="showModalVolumeSlider ? 'opacity-100 pointer-events-auto scale-100' : 'opacity-0 pointer-events-none scale-95'"
- @mouseenter="showModalVolumeSlider = true"
- @mouseleave="showModalVolumeSlider = false">
- <div class="surface-raised flex flex-col items-center gap-1" style="padding: var(--sp-2) var(--sp-3);">
- <span class="text-[9px] font-mono text-[var(--text-muted)]">${ Math.round(playerVolume * 100) }</span>
- <input type="range" min="0" max="1" step="0.05"
- :value="audioIsMuted ? 0 : playerVolume"
- @input="(e) => setAudioVolume(parseFloat(e.target.value))"
- class="volume-slider-vertical"
- style="height: 70px;">
- </div>
- </div>
+ <span class="spk-time">${ formatClock(modalAudioCurrentTime) } / ${ formatClock(modalAudioDuration) }</span>
+ <div class="spk-seek" role="slider" :aria-label="t('speakerModal.seek')"
+ :aria-valuenow="Math.round(modalAudioProgressPercent)" aria-valuemin="0" aria-valuemax="100"
+ @click="seekModalPlayer($event, modalAudioDuration)">
+ <div :style="{ width: modalAudioProgressPercent + '%' }"></div>
</div>
- <button @click="cycleModalPlaybackRate(); if ($refs.speakerModalAudioRef) $refs.speakerModalAudioRef.playbackRate = modalPlaybackRate"
- class="btn btn--icon btn--sm"
- title="Playback speed (tap to change)">
+ <button @click="toggleModalMute" class="btn btn--icon btn--sm"
+ :title="audioIsMuted ? t('speakerModal.unmute') : t('speakerModal.mute')"
+ :aria-label="audioIsMuted ? t('speakerModal.unmute') : t('speakerModal.mute')">
+ <i :class="audioIsMuted || playerVolume === 0 ? 'fas fa-volume-mute' : playerVolume < 0.5 ? 'fas fa-volume-down' : 'fas fa-volume-up'"></i>
+ </button>
+ <input type="range" min="0" max="1" step="0.05"
+ class="spk-volume hidden sm:block"
+ :value="audioIsMuted ? 0 : playerVolume"
+ @input="setModalVolume($event.target.value)"
+ :aria-label="t('speakerModal.volume')" :title="t('speakerModal.volume')">
+ <button @click="cycleSpeakerModalRate" class="btn btn--icon btn--sm"
+ :title="t('speakerModal.playbackSpeed')" :aria-label="t('speakerModal.playbackSpeed')">
<span class="text-[10px] font-semibold font-mono">${ formatPlaybackRate(modalPlaybackRate) }</span>
</button>
<button v-if="selectedRecording.mime_type && selectedRecording.mime_type.startsWith('video/')"
- @click="toggleSpeakerModalVideo"
- class="btn btn--icon btn--sm"
- :title="speakerModalVideoCollapsed ? 'Show video' : 'Hide video (audio-only view)'">
+ @click="toggleSpeakerModalVideo" class="btn btn--icon btn--sm"
+ :title="speakerModalVideoCollapsed ? t('speakerModal.showVideo') : t('speakerModal.hideVideo')"
+ :aria-label="speakerModalVideoCollapsed ? t('speakerModal.showVideo') : t('speakerModal.hideVideo')">
<i :class="speakerModalVideoCollapsed ? 'fas fa-video' : 'fas fa-video-slash'"></i>
</button>
</div>
</div>
</div>
- <!-- Transcript — see top-of-file comment for the
- content-visibility + v-memo design. -->
+ <!-- Filter bar -->
+ <div class="spk-filter">
+ <template v-if="selectedSpeaker">
+ <span :class="speakerColor(selectedSpeaker)" class="spk-dot"></span>
+ <span class="t-body-strong truncate">${ labelOf(selectedSpeaker) }</span>
+ <span class="t-meta hidden sm:inline" v-text="speakerMeta(selectedSpeaker)"></span>
+ <div class="spk-filter-actions">
+ <template v-if="!onlySelectedSpeaker && selectedSpeakerTurns.length > 0">
+ <button class="btn btn--icon btn--sm" @click="goToTurn(-1)"
+ :title="t('speakerModal.previousTurn')" :aria-label="t('speakerModal.previousTurn')">
+ <i class="fas fa-chevron-up"></i>
+ </button>
+ <span class="pill-status pill-status--info tabular-nums">${ currentTurn + 1 } / ${ selectedSpeakerTurns.length }</span>
+ <button class="btn btn--icon btn--sm" @click="goToTurn(1)"
+ :title="t('speakerModal.nextTurn')" :aria-label="t('speakerModal.nextTurn')">
+ <i class="fas fa-chevron-down"></i>
+ </button>
+ </template>
+ <button v-if="onlySelectedSpeaker" class="btn btn--quiet btn--sm" @click="showAllSegments"
+ v-text="t('speakerModal.showAll')"></button>
+ <button v-else class="btn btn--quiet btn--sm" @click="showOnlySelectedSpeaker"
+ v-text="t('speakerModal.onlyThisSpeaker')"></button>
+ <button class="btn btn--icon btn--sm" @click="clearSelectedSpeaker"
+ :title="t('speakerModal.clearSelection')" :aria-label="t('speakerModal.clearSelection')">
+ <i class="fas fa-times"></i>
+ </button>
+ </div>
+ </template>
+ <span v-else class="t-meta" v-text="t('speakerModal.selectHint')"></span>
+ </div>
+
+ <!-- Transcript -->
<div ref="speakerModalTranscriptRef"
class="speaker-modal-transcript custom-scrollbar"
- style="flex: 1 1 auto; min-height: 0; overflow-y: auto;"
- @click="(e) => { const t = e.target.closest('[data-start-time]')?.dataset.startTime; if (t && $refs.speakerModalAudioRef) { $refs.speakerModalAudioRef.currentTime = parseFloat(t); $refs.speakerModalAudioRef.play(); } }">
- <div v-if="processedTranscription.isJson">
- <!-- Each segment is mounted in full (no hydrated/
- placeholder split). The hydration scheme was
- introduced for perf but made speaker-highlight
- intermittent because the two template branches
- interacted oddly with v-memo when the
- IntersectionObserver promoted/demoted rows
- mid-selection. The browser still skips paint
- for off-screen rows via content-visibility:
- auto on .speaker-segment (see styles.css), so
- we keep most of the perf win without the
- rendering regressions. v-memo per row stops
- Vue from re-rendering unrelated rows when
- one row's data changes. -->
- <div v-for="segment in processedTranscription.simpleSegments"
- :key="segment._originalIndex"
- v-memo="[segment._originalIndex, segment.speakerId, segment.speaker, segment.sentence, highlightedSpeaker === segment.speakerId, editingSpeakerIndex === segment._originalIndex]"
- class="speaker-segment group relative"
- :data-start-time="segment.startTime"
- :data-segment-index="segment._originalIndex">
- <div class="flex items-start gap-2">
- <span :class="[segment.color, 'speaker-tag', { 'speaker-highlight': highlightedSpeaker === segment.speakerId }]"
- :data-speaker-id="segment.speakerId"
- class="inline-block flex-shrink-0 truncate text-xs sm:text-sm font-medium w-16 sm:w-24"
- :title="segment.speaker">${ segment.speaker }</span>
- <span class="word cursor-pointer hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] rounded px-0.5 flex-1 text-xs sm:text-sm leading-relaxed">${ segment.sentence }</span>
- <span class="flex items-center gap-0.5 flex-shrink-0 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity">
- <button @click.stop="openSpeakerChangeDropdown(segment._originalIndex)" class="btn btn--icon btn--sm" title="Change speaker">
- <i class="fas fa-user-edit text-[10px]"></i>
- </button>
- <button @click.stop="openEditTextModal(segment._originalIndex)" class="btn btn--icon btn--sm" title="Edit text">
- <i class="fas fa-edit text-[10px]"></i>
- </button>
- </span>
- </div>
- <div v-if="editingSpeakerIndex === segment._originalIndex"
- @click.stop
- class="surface-raised"
- style="margin-top: var(--sp-2); padding: var(--sp-2);">
- <p class="t-label" style="margin-bottom: var(--sp-2);">Select speaker:</p>
- <div class="flex flex-wrap gap-1">
- <button v-for="speaker in modalSpeakers"
- :key="speaker"
- @click="changeSpeaker(segment._originalIndex, speaker)"
- class="px-2 py-1 rounded-md hover:bg-[var(--bg-accent)] hover:text-[var(--text-accent)] active:scale-[0.98] transition-all flex items-center gap-1 text-xs bg-[var(--bg-tertiary)]">
- <div :class="speakerMap[speaker].color" class="w-2.5 h-2.5 rounded-full flex-shrink-0"></div>
- <span class="truncate max-w-[60px]">${ speakerMap[speaker].name || speaker }</span>
- </button>
- </div>
+ style="flex: 1 1 auto; min-height: 0; overflow-y: auto;">
+ <div v-if="speakerModalData.isJson">
+ <div v-for="segment in visibleModalSegments"
+ :key="segment.index"
+ v-memo="[segment.index, segment.speakerId, segment.sentence, speakerMap[segment.speakerId] ? speakerMap[segment.speakerId].name : '', selectedSpeaker === segment.speakerId, !!selectedSpeaker, onlySelectedSpeaker, playingSegmentIndex === segment.index, editingSpeakerIndex === segment.index]"
+ class="speaker-segment spk-seg group"
+ :class="{ 'is-playing': playingSegmentIndex === segment.index, 'is-dimmed': selectedSpeaker && !onlySelectedSpeaker && selectedSpeaker !== segment.speakerId }"
+ :data-segment-index="segment.index">
+ <button v-if="segment.start !== null" class="spk-seg-time" @click="playModalSegment(segment)"
+ :title="t('speakerModal.play')">${ formatClock(segment.start) }</button>
+ <span v-else></span>
+ <span :class="[speakerColor(segment.speakerId), 'speaker-tag']"
+ class="spk-seg-speaker" :title="segment.speakerId">${ labelOf(segment.speakerId) }</span>
+ <span class="spk-seg-text" @click="playModalSegment(segment)">${ segment.sentence }</span>
+ <span class="spk-seg-actions">
+ <button @click.stop="openSpeakerChangeDropdown(segment.index)" class="btn btn--icon btn--sm"
+ :title="t('speakerModal.changeSpeaker')" :aria-label="t('speakerModal.changeSpeaker')">
+ <i class="fas fa-user-edit text-[10px]"></i>
+ </button>
+ <button @click.stop="openEditTextModal(segment.index)" class="btn btn--icon btn--sm"
+ :title="t('speakerModal.editText')" :aria-label="t('speakerModal.editText')">
+ <i class="fas fa-edit text-[10px]"></i>
+ </button>
+ </span>
+ <div v-if="editingSpeakerIndex === segment.index" class="spk-seg-reassign" @click.stop>
+ <select class="field field--sm" :aria-label="t('speakerModal.changeSpeaker')"
+ @change="changeSpeaker(segment.index, $event.target.value)">
+ <option value="" v-text="t('speakerModal.changeSpeaker')"></option>
+ <option v-for="id in orderedSpeakers" :key="id" :value="id" :disabled="id === segment.speakerId">${ labelOf(id) }</option>
+ </select>
</div>
</div>
</div>
- <div v-else class="whitespace-pre-wrap text-sm text-[var(--text-primary)]">${ processedTranscription.plainText }</div>
- </div>
-
- <!-- Navigation: speaker picker + Prev/Next + position pill -->
- <div class="flex-shrink-0 surface" style="padding: var(--sp-2) var(--sp-3); display: flex; flex-direction: column; gap: var(--sp-2);">
- <div class="flex items-center gap-2">
- <select :value="highlightedSpeaker"
- @change="selectSpeakerForNavigation($event.target.value)"
- class="field field--sm flex-1">
- <option value="">Navigate to speaker…</option>
- <option v-for="speaker in modalSpeakers" :key="speaker" :value="speaker">
- ${ speakerMap[speaker]?.name || speakerDisplayMap[speaker] || speaker }
- </option>
- </select>
- <span v-if="highlightedSpeaker && speakerGroups.length > 0"
- class="pill-status pill-status--info flex-shrink-0 tabular-nums"
- style="font-size: 10px;">
- ${ currentSpeakerGroupIndex + 1 } / ${ speakerGroups.length }
- </span>
- </div>
- <div class="flex items-center gap-2" :class="{ 'opacity-50': !highlightedSpeaker || speakerGroups.length <= 1 }">
- <button @mousedown.prevent
- @click="navigateToPrevSpeakerGroup"
- class="btn btn--quiet btn--sm flex-1"
- :disabled="!highlightedSpeaker || speakerGroups.length <= 1">
- <i class="fas fa-chevron-up"></i>
- <span>Prev</span>
- </button>
- <button @mousedown.prevent
- @click="navigateToNextSpeakerGroup"
- class="btn btn--quiet btn--sm flex-1"
- :disabled="!highlightedSpeaker || speakerGroups.length <= 1">
- <span>Next</span>
- <i class="fas fa-chevron-down"></i>
- </button>
- </div>
+ <div v-else class="whitespace-pre-wrap text-sm text-[var(--text-primary)]">${ speakerModalData.plainText }</div>
</div>
</div>
</div>
- <!-- Regenerate summary opt-in row -->
<div class="flex-shrink-0" style="padding: var(--sp-3) var(--sp-5); background: var(--bg-tertiary); border-top: var(--border-hairline) solid var(--border-primary);">
<label class="flex items-center text-xs sm:text-sm text-[var(--text-muted)] cursor-pointer hover:text-[var(--text-primary)] transition-colors">
- <input type="checkbox"
- v-model="regenerateSummaryAfterSpeakerUpdate"
- class="mr-2 w-4 h-4">
+ <input type="checkbox" v-model="regenerateSummaryAfterSpeakerUpdate" class="mr-2 w-4 h-4">
<span v-text="t('help.regenerateSummaryAfterNames')"></span>
</label>
</div>
- <!-- flex-wrap + gap-y: on narrow (phone) widths the three-button
- footer wraps to two rows instead of clipping Save Names at the
- panel edge. -->
<div class="modal-footer modal-footer--between flex-wrap gap-y-2">
<div class="flex items-center gap-2">
<div class="relative inline-flex" ref="autoIdSplitBtn">
@@ -399,7 +348,8 @@
<button @click="showAutoIdDropdown = !showAutoIdDropdown"
class="btn btn--primary btn--icon"
style="border-top-left-radius: 0; border-bottom-left-radius: 0; border-left: 1px solid rgba(255,255,255,0.2);"
- :disabled="isAutoIdentifying">
+ :disabled="isAutoIdentifying"
+ :aria-label="t('help.identifyAllSpeakers')">
<i class="fas fa-caret-down"></i>
</button>
<div v-if="showAutoIdDropdown"