-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2632 lines (2234 loc) · 109 KB
/
script.js
File metadata and controls
2632 lines (2234 loc) · 109 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// static/script.js
const PIXELS_PER_SECOND = 100;
const WORD_ZOOM_THRESHOLD = 2.5; // Nível de zoom para mostrar palavras
const CHAR_ZOOM_THRESHOLD = 50; // Nível de zoom BEM ALTO para mostrar caracteres
document.addEventListener('DOMContentLoaded', () => {
// --- Referências ao DOM ---
const app = document.querySelector('.app');
const importJsonBtn = document.getElementById('import-json');
const importMediaBtn = document.getElementById('import-media');
const addSubtitleBtn = document.getElementById('add-subtitle');
const saveJsonBtn = document.getElementById('save-json');
const playPauseBtn = document.getElementById('play-pause');
const timelineFrame = document.getElementById('timeline-frame');
const timelineContent = document.getElementById('timeline-content');
const timelineRuler = document.getElementById('timeline-ruler');
const timelineScrollContainer = document.getElementById('timeline-scroll-container');
const cursor = document.getElementById('cursor');
const mediaPlayer = document.getElementById('media-player');
const videoPlaceholder = document.getElementById('video-placeholder');
const subtitleOverlay = document.getElementById('subtitle-overlay');
const previewArea = document.getElementById('preview-area');
const contextMenu = document.getElementById('context-menu');
const waveformCanvas = document.getElementById('waveform-canvas');
const waveformCtx = waveformCanvas.getContext('2d');
const autoGenerateCharsCheckbox = document.getElementById('auto-generate-chars');
const zoomIndicator = document.getElementById('zoom-indicator');
const trackSelector = document.getElementById('track-selector');
const addTrackBtn = document.getElementById('add-track');
// Referências do Modal de Exportação
const exportModal = document.getElementById('export-modal');
const exportFormatSelect = document.getElementById('export-format');
const exportTrackModeSelect = document.getElementById('export-track-mode');
const confirmExportBtn = document.getElementById('confirm-export');
const cancelExportBtn = document.getElementById('cancel-export');
const resizerH = document.getElementById('resizer-h');
const resizerV = document.getElementById('resizer-v');
const workspace = document.getElementById('workspace');
const editorPane = document.getElementById('editor-pane');
const toggleLayoutBtn = document.getElementById('toggle-layout');
const videoPreview = document.getElementById('video-preview');
const languageSelector = document.getElementById('language-selector');
const splitPunctuationBtn = document.getElementById('split-by-punctuation');
// Referências do Modal de Busca/Substituição
const findModal = document.getElementById('find-modal');
const findInput = document.getElementById('find-input');
const findNextBtn = document.getElementById('find-next-btn');
const findPreviousBtn = document.getElementById('find-previous-btn');
const findStatus = document.getElementById('find-status');
const closeFindBtn = document.getElementById('close-find');
const replaceModal = document.getElementById('replace-modal');
const replaceFindInput = document.getElementById('replace-find-input');
const replaceWithInput = document.getElementById('replace-with-input');
const replaceNextBtn = document.getElementById('replace-next-btn');
const replacePreviousBtn = document.getElementById('replace-previous-btn');
const replaceOneBtn = document.getElementById('replace-one-btn');
const replaceAllBtn = document.getElementById('replace-all-btn');
const replaceStatus = document.getElementById('replace-status');
const closeReplaceBtn = document.getElementById('close-replace');
// Referências Menu Mobile
const mobileMenuBtn = document.getElementById('mobile-menu-btn');
const mainControls = document.getElementById('main-controls');
if (mobileMenuBtn && mainControls) {
mobileMenuBtn.addEventListener('click', () => {
mainControls.classList.toggle('open');
});
}
// --- Helpers de Touch/Mouse ---
function getClientX(e) { return e.touches && e.touches.length > 0 ? e.touches[0].clientX : e.clientX; }
function getClientY(e) { return e.touches && e.touches.length > 0 ? e.touches[0].clientY : e.clientY; }
// --- Estado da Aplicação ---
let state = {
subtitles: [],
selectedSubtitles: [],
history: [],
historyIndex: -1,
copiedSubtitles: [],
zoomLevel: 1,
cursorPosition: 0,
isPlaying: false,
mediaUrl: null,
mediaDuration: 0,
lastSelected: null,
isDraggingCursor: false,
lastAdjustRequest: null,
waveformData: null,
audioDuration: 0,
autoGenerateChars: true,
tracks: ['Track 1'],
activeTrack: 'Track 1',
hiddenTracks: [], // Trilhas ocultas no preview
language: 'pt-br'
};
// --- Internacionalização (i18n) ---
let translations = {};
async function initI18n() {
// 1. Tenta carregar da variável global (languages.js) - Funciona localmente sem server
if (typeof I18N_DATA !== 'undefined') {
translations = I18N_DATA;
console.log('Traduções carregadas via languages.js (Global)');
} else {
// 2. Fallback: tenta fetch no JSON (caso use servidor)
try {
const response = await fetch('languages.json');
if (response.ok) {
translations = await response.json();
}
} catch (error) {
console.warn('Não foi possível carregar traduções.', error);
}
}
// Popula o seletor de idiomas dinamicamente
if (languageSelector) {
languageSelector.innerHTML = ''; // Limpa opções existentes
Object.keys(translations).forEach(lang => {
const option = document.createElement('option');
option.value = lang;
option.textContent = lang.toUpperCase();
languageSelector.appendChild(option);
});
}
// Tenta detectar o idioma do navegador ou usa o padrão
const browserLang = navigator.language.toLowerCase();
let defaultLang = 'en';
// Verifica se temos tradução para a lingua exata ou só para o prefixo (pt-br vs pt)
if (translations[browserLang]) defaultLang = browserLang;
else if (translations[browserLang.split('-')[0]]) defaultLang = browserLang.split('-')[0];
else if (translations['pt-br']) defaultLang = 'pt-br'; // Preferência por PT-BR se disponível
// Garante que o idioma selecionado existe nas traduções, senão usa o primeiro disponível
if (!translations[defaultLang]) {
defaultLang = Object.keys(translations)[0];
}
updateState({ language: defaultLang });
if (languageSelector) languageSelector.value = defaultLang;
applyTranslations();
}
function t(key) {
if (translations[state.language] && translations[state.language][key]) {
return translations[state.language][key];
}
// Fallback para inglês se não houver na lingua selecionada
if (translations['en'] && translations['en'][key]) {
return translations['en'][key];
}
return key;
}
function applyTranslations() {
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
el.textContent = t(key);
});
document.querySelectorAll('[data-i18n-title]').forEach(el => {
const key = el.getAttribute('data-i18n-title');
el.title = t(key);
});
document.querySelectorAll('[data-i18n-placeholder]').forEach(el => {
const key = el.getAttribute('data-i18n-placeholder');
el.placeholder = t(key);
});
updateIndicators();
}
function updateIndicators() {
// Atualiza indicadores dinâmicos
if (zoomIndicator) {
zoomIndicator.innerHTML = `<span data-i18n="zoom">${t('zoom')}</span>: ${state.zoomLevel.toFixed(1)}x`;
}
if (toggleLayoutBtn) {
const is916 = workspace.classList.contains('layout-916');
toggleLayoutBtn.textContent = is916 ? t('mode_169') : t('mode_916');
}
}
// --- Funções de Atualização de Estado e Renderização ---
function updateState(newState) {
// Debug: rastreia mudanças no waveformData
if ('waveformData' in newState && newState.waveformData !== state.waveformData) {
console.log('[State] waveformData mudou:', {
antes: state.waveformData ? state.waveformData.length + ' peaks' : 'null',
depois: newState.waveformData ? newState.waveformData.length + ' peaks' : 'null',
zoom: state.zoomLevel
});
}
Object.assign(state, newState);
// Atualiza indicadores e traduções se a linguagem mudar
if (newState.language) {
applyTranslations();
} else {
updateIndicators();
}
// Atualiza seletor de tracks se necessário
if (newState.tracks || newState.activeTrack || newState.hiddenTracks) {
renderTrackSelector();
}
}
function recordHistory() {
const newHistory = state.history.slice(0, state.historyIndex + 1);
newHistory.push(JSON.parse(JSON.stringify(state.subtitles))); // Deep copy
updateState({ history: newHistory, historyIndex: newHistory.length - 1 });
}
function updateSubtitles(newSubs, record = true) {
updateState({ subtitles: newSubs });
if (record) {
recordHistory();
}
renderTimeline();
renderPreviewArea();
}
function renderTrackSelector() {
if (!trackSelector) return;
trackSelector.innerHTML = '';
state.tracks.forEach(track => {
const option = document.createElement('option');
option.value = track;
option.textContent = track;
option.selected = (track === state.activeTrack);
trackSelector.appendChild(option);
});
}
// --- Lógica de Renderização ---
function generateId() {
return Date.now() + Math.random().toString(36).substr(2, 9);
}
// Gera caracteres automaticamente a partir das palavras
function generateCharsFromWords(subtitle) {
// Lista de pontuações que devem receber menos tempo
const punctuationChars = '.,;:!?¡¿‽⁇⁈⁉…-–—―()[]{}«»""\'\'`´';
if (!subtitle.words || subtitle.words.length === 0) {
// Se não tem words, gera chars do texto uniformemente
const chars = [];
const text = subtitle.text || '';
const duration = subtitle.end - subtitle.start;
// Calcula pesos: pontuação = 0.05, letras/números/espaços = 1.0
const weights = [];
let totalWeight = 0;
for (let i = 0; i < text.length; i++) {
const char = text[i];
const isPunctuation = punctuationChars.includes(char);
const weight = isPunctuation ? 0.05 : 1.0;
weights.push(weight);
totalWeight += weight;
}
let currentTime = subtitle.start;
for (let i = 0; i < text.length; i++) {
const charDuration = (weights[i] / totalWeight) * duration;
chars.push({
char: text[i],
start: currentTime,
end: currentTime + charDuration
});
currentTime += charDuration;
}
return chars;
}
// Gera chars a partir das palavras
const chars = [];
subtitle.words.forEach(word => {
const wordText = word.word || '';
const wordDuration = word.end - word.start;
// Calcula pesos para cada caractere da palavra
const weights = [];
let totalWeight = 0;
for (let i = 0; i < wordText.length; i++) {
const char = wordText[i];
const isPunctuation = punctuationChars.includes(char);
const weight = isPunctuation ? 0.05 : 1.0;
weights.push(weight);
totalWeight += weight;
}
let currentTime = word.start;
for (let i = 0; i < wordText.length; i++) {
const charDuration = (weights[i] / totalWeight) * wordDuration;
chars.push({
char: wordText[i],
start: currentTime,
end: currentTime + charDuration
});
currentTime += charDuration;
}
});
return chars;
}
function renderTimeline() {
// Limpa a timeline
timelineContent.innerHTML = '';
timelineContent.appendChild(cursor);
const totalDuration = Math.max(...state.subtitles.map(s => s.end), 10) + 60;
const totalTracks = state.tracks.length;
const rowHeight = 60; // Altura de cada "camada"
timelineFrame.style.width = `${totalDuration * PIXELS_PER_SECOND * state.zoomLevel}px`;
timelineFrame.style.height = `${75 + totalTracks * rowHeight}px`; // Ajusta altura total
timelineContent.style.height = `${totalTracks * rowHeight}px`;
// Renderiza fundos das camadas
state.tracks.forEach((track, i) => {
const isHidden = state.hiddenTracks.includes(track);
const trackBg = document.createElement('div');
trackBg.className = 'track-bg';
if (track === state.activeTrack) {
trackBg.classList.add('active');
}
// Não aplica mais opacity - hidden afeta APENAS o preview
trackBg.style.top = `${i * rowHeight}px`;
trackBg.style.height = `${rowHeight}px`;
trackBg.style.pointerEvents = 'auto'; // Permite clique
// Toggle de camada ao clicar no fundo
trackBg.addEventListener('click', (e) => {
// Impede que o clique no fundo mude o cursor de tempo (seek)
e.stopPropagation();
updateState({ activeTrack: track });
renderTimeline();
});
const trackLabel = document.createElement('div');
trackLabel.className = 'track-label-container';
trackLabel.style.display = 'flex';
trackLabel.style.alignItems = 'center';
trackLabel.style.gap = '8px';
trackLabel.style.padding = '4px 8px';
trackLabel.style.position = 'absolute'; // Muda para absolute
trackLabel.style.left = '0'; // Será atualizado pelo scroll
trackLabel.style.top = '0';
trackLabel.style.zIndex = '1000';
trackLabel.style.background = '#2f3136';
trackLabel.style.boxShadow = '2px 0 4px rgba(0,0,0,0.3)';
trackLabel.style.width = 'fit-content';
trackLabel.style.pointerEvents = 'none';
trackLabel.dataset.trackLabel = 'true'; // Marca para atualizar no scroll
const visibilityBtn = document.createElement('span');
visibilityBtn.innerHTML = isHidden ? '❌' : '👁️';
visibilityBtn.style.cursor = 'pointer';
visibilityBtn.style.pointerEvents = 'auto'; // Reativa cliques no botão
visibilityBtn.title = isHidden ? 'Mostrar no preview' : 'Ocultar no preview';
visibilityBtn.addEventListener('click', (e) => {
e.stopPropagation();
let newHidden = [...state.hiddenTracks];
if (isHidden) {
newHidden = newHidden.filter(t => t !== track);
} else {
newHidden.push(track);
}
updateState({ hiddenTracks: newHidden });
renderTimeline();
renderCursor();
});
const textLabel = document.createElement('span');
textLabel.className = 'track-label';
textLabel.textContent = track;
textLabel.style.pointerEvents = 'auto'; // Reativa cliques no texto
trackLabel.appendChild(visibilityBtn);
trackLabel.appendChild(textLabel);
trackBg.appendChild(trackLabel);
timelineContent.appendChild(trackBg);
});
// Renderiza legendas
state.subtitles.forEach((sub, index) => {
const block = document.createElement('div');
block.className = 'subtitle-block';
if (state.selectedSubtitles.includes(sub)) {
block.classList.add('selected');
}
const trackIndex = state.tracks.indexOf(sub.track || state.tracks[0]);
block.style.top = `${trackIndex * rowHeight + 10}px`; // 10px de margem interna
block.style.left = `${sub.start * PIXELS_PER_SECOND * state.zoomLevel}px`;
block.style.width = `${(sub.end - sub.start) * PIXELS_PER_SECOND * state.zoomLevel}px`;
// Handles de redimensionamento do bloco
const leftHandle = document.createElement('div');
leftHandle.className = 'resize-handle left';
leftHandle.addEventListener('mousedown', (e) => handleResizeStart(e, index, 'left'));
leftHandle.addEventListener('touchstart', (e) => handleResizeStart(e, index, 'left'), { passive: false });
const rightHandle = document.createElement('div');
rightHandle.className = 'resize-handle right';
rightHandle.addEventListener('mousedown', (e) => handleResizeStart(e, index, 'right'));
rightHandle.addEventListener('touchstart', (e) => handleResizeStart(e, index, 'right'), { passive: false });
// Área de arrastar que conterá a visualização apropriada
const dragArea = document.createElement('div');
dragArea.className = 'drag-area';
dragArea.addEventListener('mousedown', (e) => handleMoveStart(e, index));
// Mobile: segurar para arrastar (estilo CapCut)
let holdTimer = null;
let holdActivated = false;
dragArea.addEventListener('touchstart', (te) => {
holdActivated = false;
const startTouch = { x: te.touches[0].clientX, y: te.touches[0].clientY };
// Espera 200ms de hold sem mover para ativar arraste
holdTimer = setTimeout(() => {
holdActivated = true;
// Feedback visual: borda brilhante
block.style.outline = '2px solid #7289da';
block.style.transform = 'scale(1.02)';
block.style.zIndex = '100';
// Vibração tátil se disponível
if (navigator.vibrate) navigator.vibrate(30);
handleMoveStart(te, index);
}, 200);
const cancelHold = (me) => {
if (!holdActivated) {
const dx = me.touches[0].clientX - startTouch.x;
const dy = me.touches[0].clientY - startTouch.y;
if (Math.abs(dx) > 8 || Math.abs(dy) > 8) {
clearTimeout(holdTimer);
holdTimer = null;
document.removeEventListener('touchmove', cancelHold);
}
}
};
document.addEventListener('touchmove', cancelHold, { passive: true });
const cleanupHold = () => {
clearTimeout(holdTimer);
holdTimer = null;
block.style.outline = '';
block.style.transform = '';
block.style.zIndex = '';
document.removeEventListener('touchmove', cancelHold);
document.removeEventListener('touchend', cleanupHold);
document.removeEventListener('touchcancel', cleanupHold);
};
document.addEventListener('touchend', cleanupHold, { once: true });
document.addEventListener('touchcancel', cleanupHold, { once: true });
}, { passive: true });
// --- LÓGICA DE VISUALIZAÇÃO DE 3 NÍVEIS ---
const showCharLevel = state.zoomLevel >= CHAR_ZOOM_THRESHOLD;
const showWordLevel = state.zoomLevel >= WORD_ZOOM_THRESHOLD && sub.words && sub.words.length > 0;
// Se deve mostrar chars mas não existem, gera automaticamente (se habilitado)
let charsToShow = sub.chars;
if (showCharLevel && state.autoGenerateChars && (!sub.chars || sub.chars.length === 0)) {
charsToShow = generateCharsFromWords(sub);
}
if (showCharLevel && charsToShow && charsToShow.length > 0) {
// NÍVEL 3: CARACTERES
const charContainer = document.createElement('div');
charContainer.className = 'char-container';
charsToShow.forEach((char, charIdx) => {
if (char.start === undefined || char.end === undefined) return; // Ignora caracteres sem tempo
const charEl = document.createElement('div');
charEl.className = 'char';
charEl.textContent = char.char;
const charWidth = (char.end - char.start) * PIXELS_PER_SECOND * state.zoomLevel;
charEl.style.width = `${charWidth}px`;
// Adiciona handle entre caracteres
if (charIdx < charsToShow.length - 1) {
const nextChar = charsToShow[charIdx + 1];
if (nextChar.start !== undefined && nextChar.end !== undefined) {
const charHandle = document.createElement('div');
charHandle.className = 'char-handle';
charHandle.addEventListener('mousedown', (e) => handleCharResizeStart(e, index, charIdx));
charHandle.addEventListener('touchstart', (e) => handleCharResizeStart(e, index, charIdx), { passive: false });
charEl.appendChild(charHandle);
}
}
charContainer.appendChild(charEl);
});
dragArea.appendChild(charContainer);
} else if (showWordLevel) {
// NÍVEL 2: PALAVRAS
const wordContainer = document.createElement('div');
wordContainer.className = 'word-container';
const wordsToShow = sub.words;
// Calcula tempo TOTAL das palavras (sem lacunas inter-word)
// para que as palavras preencham 100% do bloco visualmente
let totalWordTime = 0;
wordsToShow.forEach(w => {
let ws = w.start, we = w.end;
if (ws === undefined || we === undefined) {
const subDur = sub.end - sub.start;
ws = sub.start + (subDur / wordsToShow.length) * wordsToShow.indexOf(w);
we = sub.start + (subDur / wordsToShow.length) * (wordsToShow.indexOf(w) + 1);
}
totalWordTime += (we - ws);
});
if (totalWordTime <= 0) totalWordTime = sub.end - sub.start;
wordsToShow.forEach((word, wordIdx) => {
const wordEl = document.createElement('div');
wordEl.className = 'word';
let wStart = word.start;
let wEnd = word.end;
if (wStart === undefined || wEnd === undefined) {
const sStart = sub.start;
const sEnd = sub.end;
const subDuration = sEnd - sStart;
wStart = sStart + (subDuration / wordsToShow.length) * wordIdx;
wEnd = sStart + (subDuration / wordsToShow.length) * (wordIdx + 1);
}
const wordDuration = wEnd - wStart;
const widthPercent = (wordDuration / totalWordTime) * 100;
wordEl.style.width = `${widthPercent}%`;
wordEl.textContent = word.word;
// Adiciona a classe de busca se aplicável
if (typeof searchResults !== 'undefined' && currentSearchIndex >= 0 && searchResults.length > 0) {
const isMatch = searchResults.some(res =>
res.subtitle.id === sub.id &&
res.type === 'word' &&
res.index === wordIdx
);
if (isMatch) wordEl.classList.add('search-highlight-word');
}
wordContainer.appendChild(wordEl);
// Só adiciona a alça (resizer) caso seja adjacente perfeitamente à próxima palavra,
// ou simplesmente se houver palavra seguinte, podemos permitir o redimensionamento.
if (wordIdx < wordsToShow.length - 1) {
const wordHandle = document.createElement('div');
wordHandle.className = 'word-handle';
wordHandle.addEventListener('mousedown', (e) => handleWordResizeStart(e, index, wordIdx));
wordHandle.addEventListener('touchstart', (e) => handleWordResizeStart(e, index, wordIdx), { passive: false });
wordEl.appendChild(wordHandle);
}
});
dragArea.appendChild(wordContainer);
} else {
// NÍVEL 1: TEXTO COMPLETO
const plainText = document.createElement('div');
plainText.className = 'plain-text';
plainText.textContent = sub.text;
dragArea.appendChild(plainText);
}
block.appendChild(leftHandle);
block.appendChild(dragArea);
block.appendChild(rightHandle);
block.addEventListener('click', (e) => handleSelectSubtitle(e, sub));
block.addEventListener('contextmenu', (e) => handleContextMenu(e, sub));
// Touch handlers para mobile: tap para selecionar, long press para context menu
let pressTimer;
let touchStartTime = 0;
let touchStartPos = { x: 0, y: 0 };
let touchMoved = false;
block.addEventListener('touchstart', (e) => {
touchStartTime = Date.now();
touchStartPos = { x: e.touches[0].clientX, y: e.touches[0].clientY };
touchMoved = false;
pressTimer = setTimeout(() => {
handleContextMenu(e, sub);
}, 500);
}, { passive: true });
block.addEventListener('touchmove', (e) => {
const dx = e.touches[0].clientX - touchStartPos.x;
const dy = e.touches[0].clientY - touchStartPos.y;
if (Math.abs(dx) > 10 || Math.abs(dy) > 10) {
touchMoved = true;
clearTimeout(pressTimer);
}
}, { passive: true });
block.addEventListener('touchend', (e) => {
clearTimeout(pressTimer);
const elapsed = Date.now() - touchStartTime;
// Tap rápido sem mover = selecionar
if (!touchMoved && elapsed < 300) {
e.preventDefault();
handleSelectSubtitle(e, sub);
}
});
timelineContent.appendChild(block);
});
renderRuler(totalDuration);
renderWaveform();
// Atualiza posição dos labels de track baseado no scroll atual
const scrollLeft = timelineScrollContainer.scrollLeft;
document.querySelectorAll('[data-track-label="true"]').forEach(label => {
label.style.left = `${scrollLeft}px`;
});
}
function renderRuler(duration) {
timelineRuler.innerHTML = '';
for (let i = 0; i <= duration; i += 1) {
const marker = document.createElement('div');
marker.className = 'time-marker';
marker.style.left = `${i * PIXELS_PER_SECOND * state.zoomLevel}px`;
marker.textContent = `${i}s`;
timelineRuler.appendChild(marker);
}
}
function renderCursor() {
const cursorPx = state.cursorPosition * PIXELS_PER_SECOND * state.zoomLevel;
cursor.style.left = `${cursorPx}px`;
// Sincroniza video/audio
if (mediaPlayer.src) {
const diff = Math.abs(mediaPlayer.currentTime - state.cursorPosition);
if (diff > 0.1 || (!state.isPlaying && diff > 0.01)) {
mediaPlayer.currentTime = state.cursorPosition;
}
}
// Atualiza overlay (Mostra legendas de TODAS as tracks juntas, exceto ocultas)
const activeSubs = state.subtitles.filter(s => {
const track = s.track || 'Track 1';
return state.cursorPosition >= s.start && state.cursorPosition <= s.end && !state.hiddenTracks.includes(track);
});
if (activeSubs.length > 0) {
// Ordena por track para manter consistência visual
activeSubs.sort((a, b) => {
const idxA = state.tracks.indexOf(a.track || 'Track 1');
const idxB = state.tracks.indexOf(b.track || 'Track 1');
return idxA - idxB;
});
subtitleOverlay.innerHTML = activeSubs.map(s => s.text).join('<br>');
subtitleOverlay.style.display = 'block';
} else {
subtitleOverlay.style.display = 'none';
}
}
function renderPreviewArea() {
if (state.selectedSubtitles.length !== 1) {
previewArea.innerHTML = t('no_selection');
return;
}
// Tenta pegar sempre a versão mais atualizada da legenda pelo ID
const selectedId = state.selectedSubtitles[0].id;
const subtitle = state.subtitles.find(s => s.id === selectedId) || state.selectedSubtitles[0];
if (!previewArea.querySelector('textarea')) {
previewArea.innerHTML = '';
const textarea = document.createElement('textarea');
textarea.rows = 4;
textarea.style.width = '100%';
textarea.addEventListener('input', handleTextChange);
previewArea.appendChild(textarea);
}
const textarea = previewArea.querySelector('textarea');
if (textarea && textarea !== document.activeElement && textarea.value !== subtitle.text) {
textarea.value = subtitle.text;
}
}
// --- Lógica de Waveform ---
async function processAudioForWaveform(audioBuffer) {
console.warn('[Audio] Iniciando processamento para waveform...', {
canais: audioBuffer.numberOfChannels,
amostras: audioBuffer.length,
duração: audioBuffer.duration.toFixed(2) + 's',
sampleRate: audioBuffer.sampleRate + 'Hz'
});
const rawData = audioBuffer.getChannelData(0); // Canal mono ou primeiro canal
const samples = audioBuffer.length;
const duration = audioBuffer.duration;
// Calcula quantas amostras por pixel no zoom 1x
const samplesPerPixel = Math.floor(samples / (duration * PIXELS_PER_SECOND));
console.warn('[Audio] samplesPerPixel:', samplesPerPixel);
const peaks = [];
for (let i = 0; i < samples; i += samplesPerPixel) {
let min = 1.0;
let max = -1.0;
for (let j = 0; j < samplesPerPixel && i + j < samples; j++) {
const val = rawData[i + j];
if (val < min) min = val;
if (val > max) max = val;
}
peaks.push({ min, max });
}
console.warn('[Audio] Waveform processado com sucesso!', {
totalPeaks: peaks.length,
primeiroPeak: peaks[0],
ultimoPeak: peaks[peaks.length - 1]
});
updateState({
waveformData: peaks,
audioDuration: duration
});
renderWaveform();
}
function renderWaveform() {
if (!state.waveformData || !waveformCanvas || !waveformCtx) {
// Log apenas se já tivermos duração (já importou algo)
if (state.audioDuration > 0) {
console.warn('[Waveform] Dados não disponíveis:', {
hasData: !!state.waveformData,
hasCanvas: !!waveformCanvas,
hasCtx: !!waveformCtx
});
}
return;
}
try {
const scrollLeft = timelineScrollContainer.scrollLeft || 0;
const viewportWidth = timelineScrollContainer.clientWidth || 1000;
const height = 60;
// --- OTIMIZAÇÃO CRÍTICA PARA ZOOM ALTO ---
// Em vez de criar um canvas gigante (que crasha o browser > 32k px),
// criamos um canvas do tamanho da tela e o movemos conforme o scroll.
waveformCanvas.width = viewportWidth;
waveformCanvas.height = height;
waveformCanvas.style.width = `${viewportWidth}px`;
waveformCanvas.style.left = `${scrollLeft}px`; // Segue o scroll
waveformCtx.clearRect(0, 0, viewportWidth, height);
waveformCtx.fillStyle = '#7289da';
const peaks = state.waveformData;
const middleY = height / 2;
const amplitudeScale = height / 2;
// Calcula a escala de tempo
const totalWidth = state.audioDuration * PIXELS_PER_SECOND * state.zoomLevel;
const pixelsPerPeak = totalWidth / peaks.length;
if (!isFinite(pixelsPerPeak) || pixelsPerPeak <= 0) return;
// Determina quais picos desenhar baseado no scroll
const startIndex = Math.max(0, Math.floor(scrollLeft / pixelsPerPeak));
const endIndex = Math.min(peaks.length, Math.ceil((scrollLeft + viewportWidth) / pixelsPerPeak));
console.log('[Waveform] Renderizando viewport:', {
zoom: state.zoomLevel.toFixed(1) + 'x',
totalWidth: totalWidth.toFixed(0) + 'px',
viewportWidth,
peaksInRange: endIndex - startIndex
});
for (let i = startIndex; i < endIndex; i++) {
// Posição X relativa ao início da timeline
const xTimeline = i * pixelsPerPeak;
// Posição X relativa ao canvas (viewport)
const xCanvas = xTimeline - scrollLeft;
const peak = peaks[i];
if (!peak) continue;
const minY = middleY + (peak.min * amplitudeScale);
const maxY = middleY + (peak.max * amplitudeScale);
const peakHeight = Math.max(1, maxY - minY);
waveformCtx.fillRect(xCanvas, minY, Math.max(1, pixelsPerPeak), peakHeight);
}
} catch (err) {
console.error('[Waveform] Erro fatal na renderização:', err);
}
}
// --- Handlers de Eventos ---
importJsonBtn.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = (event) => {
let json = JSON.parse(event.target.result);
// Detecta formato e converte se for Premiere
const format = detectJSONFormat(json);
if (format === 'premiere') {
console.log('[Import] Detectado formato Premiere, convertendo...');
json = convertPremiereToWhisperX(json);
}
const newSubs = (json.segments || []).map((s, i) => ({
...s,
id: generateId() + "_import_" + Date.now() + i, // ID único para evitar conflitos no merge
track: state.activeTrack // Força a importação para a camada ativa
}));
// Mantém legendas das OUTRAS tracks, mas limpa a track ATIVA para evitar sobreposição
const otherTracksSubs = state.subtitles.filter(s => (s.track || 'Track 1') !== state.activeTrack);
const mergedSubs = [...otherTracksSubs, ...newSubs].sort((a, b) => a.start - b.start);
updateSubtitles(mergedSubs);
// Limpa o input para permitir importar o mesmo arquivo novamente se necessário
importJsonBtn.value = '';
};
reader.readAsText(file);
});
importMediaBtn.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
console.log('[Media] Arquivo selecionado:', {
nome: file.name,
tipo: file.type,
tamanho: (file.size / 1024 / 1024).toFixed(2) + 'MB'
});
const url = URL.createObjectURL(file);
updateState({ mediaUrl: url });
mediaPlayer.src = url;
mediaPlayer.style.display = 'block';
videoPlaceholder.style.display = 'none';
mediaPlayer.addEventListener('loadedmetadata', () => {
console.log('[Media] Metadata carregado:', {
duração: mediaPlayer.duration.toFixed(2) + 's'
});
updateState({ mediaDuration: mediaPlayer.duration });
renderTimeline();
});
// Processa o áudio para gerar o waveform
console.log('[Media] Iniciando processamento de áudio...');
try {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
const arrayBuffer = await file.arrayBuffer();
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
await processAudioForWaveform(audioBuffer);
} catch (err) {
console.error('[Media] ERRO ao processar waveform:', err);
}
});
saveJsonBtn.addEventListener('click', () => {
exportModal.style.display = 'flex';
});
cancelExportBtn.addEventListener('click', () => {
exportModal.style.display = 'none';
});
confirmExportBtn.addEventListener('click', () => {
const format = exportFormatSelect.value;
const trackMode = exportTrackModeSelect.value;
let segmentsToSave = state.subtitles;
if (trackMode === 'active') {
segmentsToSave = state.subtitles.filter(s => (s.track || 'Track 1') === state.activeTrack);
}
// Ordena por tempo de início para garantir integridade em formatos sequenciais
segmentsToSave.sort((a, b) => a.start - b.start);
let content = '';
let mimeType = '';
let fileName = '';
if (format === 'json') {
const cleanSegments = segmentsToSave.map(({ id, ...rest }) => ({
...rest,
track: undefined
}));
content = JSON.stringify({ segments: cleanSegments }, null, 2);
mimeType = 'application/json';
fileName = (trackMode === 'active' ? `subtitles-whisperx-${state.activeTrack}` : 'subtitles-whisperx-all') + '.json';
} else if (format === 'premiere') {
const premiereData = convertWhisperXToPremiere({ segments: segmentsToSave });
content = JSON.stringify(premiereData, null, 2);
mimeType = 'application/json';
fileName = (trackMode === 'active' ? `subtitles-premiere-${state.activeTrack}` : 'subtitles-premiere-all') + '.json';
} else if (format === 'srt') {
content = convertToSRT(segmentsToSave);
mimeType = 'text/plain';
fileName = (trackMode === 'active' ? `subtitles-${state.activeTrack}` : 'subtitles-all') + '.srt';
} else if (format === 'tsv') {
content = convertToTSV(segmentsToSave);
mimeType = 'text/tab-separated-values';
fileName = (trackMode === 'active' ? `subtitles-${state.activeTrack}` : 'subtitles-all') + '.tsv';
}
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
exportModal.style.display = 'none';
});
function formatTimeSRT(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
const ms = Math.floor((seconds % 1) * 1000);
return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')},${ms.toString().padStart(3, '0')}`;
}
function convertToSRT(segments) {
return segments.map((s, i) => {
return `${i + 1}\n${formatTimeSRT(s.start)} --> ${formatTimeSRT(s.end)}\n${s.text}\n`;
}).join('\n');
}
function convertToTSV(segments) {
const header = "start\tend\ttext\n";
const rows = segments.map(s => `${s.start.toFixed(3)}\t${s.end.toFixed(3)}\t${s.text.replace(/\t/g, ' ').replace(/\n/g, ' ')}`);
return header + rows.join('\n');
}
// --- Helpers de Conversão de Formato (Adobe Premiere) ---
function detectJSONFormat(data) {
if (!data || !data.segments || data.segments.length === 0) return 'unknown';
const first = data.segments[0];
if (first.words && first.words.length > 0) {
const firstWord = first.words[0];
if ('confidence' in firstWord && 'eos' in firstWord) return 'premiere';
if ('score' in firstWord || 'word' in firstWord) return 'whisperx';
}
if (first.start !== undefined && first.end !== undefined && first.text !== undefined) return 'whisperx';
return 'unknown';
}
function convertPremiereToWhisperX(data) {
const whisperData = { segments: [] };
data.segments.forEach(seg => {
const words = (seg.words || []).map(w => ({
word: w.text,
start: w.start,
end: Number((w.start + w.duration).toFixed(3)),
score: w.confidence || 1.0
}));
if (words.length > 0) {
whisperData.segments.push({
start: words[0].start,
end: words[words.length - 1].end,
text: words.map(w => w.word).join(' '),
words: words