@kangsicj/nexussync 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,7 @@
8
8
  // @icon https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/assets/icon.svg
9
9
  // @updateURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.meta.js
10
10
  // @downloadURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.user.js
11
- // @version 1.4.0
11
+ // @version 1.5.0
12
12
  // @description Watch any web video together in perfect sync: cinema mode, live AI subtitles & translation, chat bubbles with auto-translation, quick ink, cover, go-together to the next episode.
13
13
  // @description:ko 어떤 웹 영상이든 완벽한 싱크로 함께 보기: 시네마 모드, 실시간 AI 자막·번역, 자동 번역 말풍선 채팅, 잠깐 그리기, 가리기, 다음 화도 함께.
14
14
  // @match *://*/*
@@ -34,6 +34,7 @@
34
34
  // @connect api.deepl.com
35
35
  // @connect rest.opensubtitles.org
36
36
  // @connect dl.opensubtitles.org
37
+ // @connect www.themoviedb.org
37
38
  // ==/UserScript==
38
39
 
39
40
  (async function () {
@@ -45,12 +46,12 @@
45
46
 
46
47
  // The version of the code that is actually running (the manager's metadata can lag
47
48
  // behind when an old copy is still installed).
48
- const NXU_VERSION = '1.4.0';
49
+ const NXU_VERSION = '1.5.0';
49
50
  // Rank used by the one-instance guard below and to tell newer builds apart in a room.
50
51
  // It is independent of the public version (1.0.0 is the first public release, after
51
52
  // private builds that reached ranks up to 10.2.0), so every older copy still installed
52
53
  // steps aside instead of this release.
53
- const NXU_RANK = '11.4.0';
54
+ const NXU_RANK = '11.5.0';
54
55
  const NXU_SESSION = Math.random().toString(36).slice(2, 10); // this page load // raise with every release
55
56
  // App icon (same artwork as assets/icon.svg / @icon), inlined so it shows offline too.
56
57
  const NXU_ICON = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9Ik5leHVzU3luYyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJueGJnIiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNWIyZWZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmY0ZmEzIi8+PC9saW5lYXJHcmFkaWVudD48cmFkaWFsR3JhZGllbnQgaWQ9Im54Z2xvdyIgY3g9IjAuODIiIGN5PSIwLjE0IiByPSIwLjciPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iIzdjZjlmZiIgc3RvcC1vcGFjaXR5PSIwLjU1Ii8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjN2NmOWZmIiBzdG9wLW9wYWNpdHk9IjAiLz48L3JhZGlhbEdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0ibnhwbGF5IiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjZmZmZmZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmZlM2YxIi8+PC9saW5lYXJHcmFkaWVudD48Y2xpcFBhdGggaWQ9Im54ciI+PHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIHJ4PSI1OCIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNueHIpIj48cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgZmlsbD0idXJsKCNueGJnKSIvPjxyZWN0IHdpZHRoPSIyNTYiIGhlaWdodD0iMjU2IiBmaWxsPSJ1cmwoI254Z2xvdykiLz48ZyBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMTUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTYwIDExNiBBNzAgNzAgMCAwIDEgMTc4IDcyIi8+PHBhdGggZD0iTTE5NiAxNDAgQTcwIDcwIDAgMCAxIDc4IDE4NCIvPjwvZz48cGF0aCBkPSJNMTg2IDUwIEwyMDAgOTIgTDE1NyA4NiBaIiBmaWxsPSIjZmZmZmZmIi8+PHBhdGggZD0iTTcwIDIwNiBMNTYgMTY0IEw5OSAxNzAgWiIgZmlsbD0iI2ZmZmZmZiIvPjxwYXRoIGQ9Ik0xMTAgOTIgUTEwNCA4OCAxMDQgOTYgTDEwNCAxNjAgUTEwNCAxNjggMTEwIDE2NCBMMTYyIDEzMiBRMTY4IDEyOCAxNjIgMTI0IFoiIGZpbGw9InVybCgjbnhwbGF5KSIvPjwvZz48L3N2Zz4=';
@@ -342,7 +343,7 @@
342
343
  case 'NXU_CINEMA':
343
344
  return typeof data.on === 'boolean' && bool(data.ambient) && (data.fit === undefined || ['contain', 'cover', 'fill'].includes(data.fit)) && bool(data.nexus);
344
345
  case 'NXU_MEDIA_CMD':
345
- return ['play', 'pause', 'toggle', 'seek', 'seekBy', 'volume', 'mute', 'boost'].includes(data.action) && num(data.value);
346
+ return ['play', 'pause', 'toggle', 'seek', 'seekBy', 'volume', 'mute'].includes(data.action) && num(data.value);
346
347
  case 'NXU_SYNC_CMD':
347
348
  return ['play', 'pause', 'rate'].includes(data.cmd) && num(data.time) && num(data.rate) && str(data.eventId) && str(data.action) && num(data.startIn);
348
349
  case 'NXU_TUNE':
@@ -673,27 +674,29 @@
673
674
  canvas: 'Canvas', bookmark: 'Bookmark', bookmarkTitle: 'Bookmark the current position', chat: 'Chat', aiSub: 'AI Sub', aiSubTitle: 'Live subtitles & translation (Alt+Shift+T)',
674
675
  subLog: 'Sub Log', debug: 'Debug', hideOnSite: 'Hide on this site', hideOnSiteTitle: 'Hide the floating button on this site (restore with Alt+Shift+N or the userscript menu)',
675
676
  hiddenOnSite: '🙈 Hidden on this site · Alt+Shift+N to show', shownOnSite: '⚙️ Button shown on this site',
676
- roomChat: 'Room Chat', nickname: 'Nickname (optional)', chatPlaceholder: 'Message…', newMessages: 'New', latest: 'Latest',
677
+ roomChat: 'Room Chat', chatLog: 'Chat history', chatCleared: '🧹 Chat history cleared', nickname: 'Nickname (optional)', chatPlaceholder: 'Message…', newMessages: 'New', latest: 'Latest',
677
678
  subHistory: 'Subtitle History', export: 'Export', clear: 'Clear', logCleared: '🧹 Subtitle history cleared', logExported: '💾 Subtitle history exported',
678
679
  createRoom: 'Create a room', copyPin: 'Copy PIN', enterPin: 'Enter PIN', joinRoom: 'Join Room', viewerMode: 'Viewer mode (follow without controlling)',
679
680
  aiSubSettings: 'AI Subtitles', debugConsole: 'Debug Console', uiHide: 'Auto-hide', keepOpen: 'Keep open',
680
681
  bmLibrary: 'Bookmarks', bmAddHere: 'Bookmark this moment', bmSearch: 'Search bookmarks', bmEmpty: 'No bookmarks yet. Tap “Bookmark this moment” while watching.', bmLive: 'LIVE', bmOpening: '📌 Opening the bookmark…', bmJumped: '📌 Back to {time}', bmLiveOpened: '🔴 Playing the live stream', bmDelete: 'Delete', bmThisPage: 'this page', bmCopy: 'Copy link', bmCopied: '📋 Link copied',
681
682
  tuneTitle: 'Sync timing', tuneMenu: 'Sync timing', tuneOffset: 'My offset', tuneOffsetZero: 'Same timing as the room', tuneAhead: 'My video runs {s} ahead of the room', tuneBehind: 'My video runs {s} behind the room',
682
683
  tuneResync: 'Re-sync now', tuneReset: 'Reset', tuneHelp: 'Different site, different version (an extra studio logo, a shorter intro)? Move your own timing until the pictures match. Only your device changes.',
683
- tuneCompare: 'Compare pictures', tuneMine: 'Me', tuneTheirs: '{name}', tuneNoPicture: 'No picture (protected video)', tuneWaiting: 'Waiting for the picture…',
684
+ tuneCompare: 'Compare pictures', tuneMine: 'Me', tuneTheirs: '{name}', tuneNoPicture: 'Protected video — compare by time', tuneDiffSame: 'Same position as the other device', tuneDiffAhead: 'You are {s} ahead of {name}', tuneDiffBehind: 'You are {s} behind {name}', tuneWaiting: 'Waiting for the picture…',
684
685
  tuneMark: 'Same scene', tuneMarkHint: 'Each of you pauses on the same moment (e.g. the first shot after the logos) and taps “This scene”.', tuneMarkBtn: '📍 This scene', tuneMarkMine: 'Mine: {t}', tuneMarkTheirs: '{name}: {t}', tuneApply: 'Apply',
685
686
  tuneAuto: 'Automatic', tuneAutoBtn: '🤖 Find the timing automatically', tuneAutoHint: 'Uses the sound (or the picture) of what both of you have played over the last minutes. Play together for a little while first.',
686
687
  tuneAutoNeed: 'Not enough to compare yet — play together for a little longer and try again.', tuneAutoFound: 'Found: {s} ({c}% sure)', tuneAutoNone: 'No clear match. Try “Same scene” instead.', tuneAsking: 'Asking the others…', tuneApplied: '⏱ Timing set: {s}',
687
688
  tuneMarkReceived: '📍 {name} marked a scene', tuneNoPeer: 'Nobody else is in the room yet.',
689
+ tuneSrcSame: '🟢 Same video on every device — kept in step automatically, frame by frame.', tuneSrcDiff: '🟠 Different versions (length differs by {s}) — the timing is found automatically after a little playing, or set it here.', tuneSrcUnknown: 'Waiting for the others’ video…',
690
+ tuneSameReset: '⏱ Same video as the others: timing correction removed.', tuneAutoApplied: 'Different version: timing set to {s} automatically (tap to undo).', tuneSuggest: 'Your videos differ by {s}. Tap to line them up.',
688
691
  subMenu: 'Subtitles', xsubOff: 'Off', subTrack: 'From the video', subSearch: '🔎 Find subtitles (OpenSubtitles)', subFile: '📂 Open a subtitle file…', subAi: '🧠 AI live subtitles', subDelay: 'Timing', subLater: 'later', subEarlier: 'earlier', xsubSize: 'Size',
689
- subLoaded: '💬 Subtitles: {name}', subNone: 'No subtitles found in this video.', subSuggest: '💬 No subtitles? Find them', subLoadFail: 'Could not load these subtitles.',
690
- osTitle: 'Find subtitles', osQuery: 'Title (English titles work best)', osSeason: 'Season', osEpisode: 'Episode', osLang: 'Language', osSearch: 'Search', osSearching: 'Searching…', osNone: 'Nothing found. Try the English title, or remove the year.', osError: 'OpenSubtitles did not answer. Try again in a moment.', osDownloads: '{n} downloads', osLoading: 'Loading…', osHint: 'Subtitles come from OpenSubtitles.org and are shown in NexusSync’s own style; use “Timing” in the subtitle menu if they are early or late.',
691
- viewMenu: 'Picture & sound', viewBright: 'Brightness', viewBoost: 'Volume boost', viewReset: 'Reset', boostBlocked: 'This video’s sound cannot be boosted here (it comes from another site).',
692
+ subLoaded: '💬 Subtitles: {name}', subMulti: 'Several subtitles at once — tap one to take it away.', subNone: 'No subtitles found in this video.', subSuggest: '💬 No subtitles? Find them', subLoadFail: 'Could not load these subtitles.',
693
+ osTitle: 'Find subtitles', osTmdbLooking: 'Looking up the English title on TMDB…', osTmdbNone: 'No English title found on TMDB — type it yourself if you know it.', osQuery: 'Title (English titles work best)', osSeason: 'Season', osEpisode: 'Episode', osLang: 'Language', osSearch: 'Search', osSearching: 'Searching…', osNone: 'Nothing found. Try the English title, or remove the year.', osError: 'OpenSubtitles did not answer. Try again in a moment.', osDownloads: '{n} downloads', osLoading: 'Loading…', osHint: 'Subtitles come from OpenSubtitles.org and are shown in NexusSync’s own style; use “Timing” in the subtitle menu if they are early or late.',
694
+ viewMenu: 'Picture', viewAudio: 'Soundtrack', viewBright: 'Brightness', viewBoost: 'Volume boost', viewReset: 'Reset', boostBlocked: 'This video’s sound cannot be boosted here (it comes from another site).',
692
695
  settings: 'Settings', setProfile: 'Profile', setAvatar: 'Avatar', setStatus: 'Status message', setStatusPh: 'e.g. Popcorn ready 🍿', setReactions: 'My reactions',
693
- setReactionsHint: 'Tap a slot, then pick an emoji (or type any emoji).', setReactionsReset: 'Back to the default reactions', setPlayback: 'Playback', setAutoNext: 'Next episode automatically',
696
+ setReactionsHint: 'Tap a slot, then pick an emoji (or type any emoji). Add or remove slots (1–16).', setReactionsReset: 'Back to the default reactions', setPlayback: 'Playback', setAutoNext: 'Next episode automatically',
694
697
  setTogether: 'Watching together', setRecvReact: 'Show others’ reactions', setRecvNudge: 'Receive nudges (shake)', setRecvInk: 'Show others’ sketches', setRecvChat: 'Show chat bubbles', setRecvPing: 'Show pointers',
695
698
  setPeople: 'People in this room', setMute: 'Hide', setUnmute: 'Show', setMutedHint: 'Hidden people’s messages, reactions and sketches are not shown on this device (only for this room).',
696
- setAdvanced: 'Advanced', setEmojiPh: 'Any emoji', setNobody: 'Nobody else is here yet.',
699
+ setAdvanced: 'Advanced', setAvatarCustom: 'Any emoji or initials', setAvatarPhoto: 'Photo', setAvatarClear: 'Remove', setAvatarFail: 'Could not use this picture.', setSlotAdd: '+ Add a slot', setSlotRemove: '- Remove this slot', setEmojiPh: 'Any emoji', setNobody: 'Nobody else is here yet.',
697
700
  speakerLanguage: 'Spoken language', speakerHelp: 'The language spoken in the video or by you. Recognition only understands this language.',
698
701
  subtitleLanguage: 'Translate subtitles to', audioSource: 'Audio source', audioAuto: 'Auto (video audio when possible + mic)', audioMic: 'Microphone only',
699
702
  audioMedia: 'Video / tab audio only', audioDual: 'Microphone + video audio',
@@ -710,7 +713,7 @@
710
713
  subUsingMicFallback: 'The video sound could not be heard directly — listening through the microphone (turn the speakers up).',
711
714
  subTabShareEnded: 'Tab audio sharing stopped, so subtitles were turned off.',
712
715
  subHearVideo: '🎧 Listening to the video', subHearMic: '🎧 Listening through the microphone', subVideoSilent: '🔇 No sound reaches the subtitles from this video',
713
- subIssueNet: '⚠️ Speech service connection is unstable — retrying', subIssueNoResult: '⚠️ Sound arrives but no words are recognised', subTryMic: '🎤 Listen through the mic', subTryKey: '🔑 Use an AI recognition key', subShareTab: '🎬 Connect tab sound', subTabNotShared: 'Tab audio was not shared. Choose this tab and turn on “Share tab audio”.',
716
+ subIssueNet: '⚠️ Speech service connection is unstable — retrying', subIssueNoResult: '⚠️ Sound arrives but no words are recognised', subSiteBlocksSpeech: 'This site does not allow the browser’s speech recognition. Add an OpenAI or Groq key (AI subtitles → Advanced) to use AI subtitles here.', subSiteBlocksSpeechKey: 'This site blocks the browser’s speech recognition — switching to cloud recognition with your key.', subTryMic: '🎤 Listen through the mic', subTryKey: '🔑 Use an AI recognition key', subShareTab: '🎬 Connect tab sound', subTabNotShared: 'Tab audio was not shared. Choose this tab and turn on “Share tab audio”.',
714
717
  subPosition: 'Subtitle position', posVideo: 'Over the video', posScreen: 'Bottom of the screen', subSize: 'Size', subOpacity: 'Opacity',
715
718
  advanced: 'Advanced', translationEngine: 'Translation engine', providerAuto: 'Google first, on-device as backup (best quality)', providerBrowser: 'On-device only (private)',
716
719
  providerGoogle: 'Google only', providerHelp: 'Online translation reads whole sentences far better; the on-device model shows the live line and steps in when offline.',
@@ -734,7 +737,7 @@
734
737
  noVideo: '⚠️ No video detected', noPlayingVideo: '⚠️ No playing video found', pipUnsupported: '⚠️ Picture-in-Picture not supported', pipBlocked: '⚠️ Picture-in-Picture was blocked',
735
738
  mediaFound: '✅ Media detected', mediaNotFound: '🔎 No media yet — start the video and try again',
736
739
  canvasOn: '🎨 Canvas ON', canvasOff: '🎨 Canvas OFF', canvasViewOnly: '🎨 Canvas (view only)', nothingToUndo: '↩️ Nothing to undo', undo: 'Undo (Ctrl+Z)',
737
- pen: 'Pen', eraser: 'Eraser', clearCanvas: 'Clear canvas', watching: '{n} watching', meTag: '(me)', whoViewer: 'watching only', whoAway: 'away (screen off or another tab)', whoOldVer: 'different version — please update', whoTitle: 'Watching together',
740
+ pen: 'Pen', eraser: 'Eraser', clearCanvas: 'Clear canvas', watching: '{n} watching', meTag: '(me)', whoViewer: 'watching only', whoAway: 'away (screen off or another tab)', whoOldVer: 'different version — please update', whoTitle: 'Watching together', whoSleeping: 'screen off — still in the room, back when it wakes', whoReconnecting: 'Reconnecting…',
738
741
  shieldTitle: 'Connected', shieldText: 'Tap to enable synchronized playback in this tab.', shieldButton: 'START SYNC ▶️',
739
742
  menuCinema: 'Toggle cinema mode', menuSubtitles: 'Start / stop AI subtitles', menuShowButton: 'Show / hide the NexusSync button on this site'
740
743
  },
@@ -786,27 +789,29 @@
786
789
  canvas: '캔버스', bookmark: '북마크', bookmarkTitle: '현재 위치를 북마크', chat: '채팅', aiSub: 'AI 자막', aiSubTitle: '실시간 자막·번역 (Alt+Shift+T)',
787
790
  subLog: '자막 기록', debug: '디버그', hideOnSite: '이 사이트에서 숨기기', hideOnSiteTitle: '이 사이트에서 떠 있는 버튼 숨기기 (Alt+Shift+N 또는 유저스크립트 메뉴로 복원)',
788
791
  hiddenOnSite: '🙈 이 사이트에서 숨김 · Alt+Shift+N으로 표시', shownOnSite: '⚙️ 이 사이트에서 버튼 표시',
789
- roomChat: '방 채팅', nickname: '닉네임 (선택)', chatPlaceholder: '메시지…', newMessages: '새 메시지', latest: '최신',
792
+ roomChat: '방 채팅', chatLog: '채팅 기록', chatCleared: '🧹 채팅 기록을 지웠어요', nickname: '닉네임 (선택)', chatPlaceholder: '메시지…', newMessages: '새 메시지', latest: '최신',
790
793
  subHistory: '자막 기록', export: '내보내기', clear: '지우기', logCleared: '🧹 자막 기록을 지웠습니다', logExported: '💾 자막 기록을 저장했습니다',
791
794
  createRoom: '방 만들기', copyPin: 'PIN 복사', enterPin: 'PIN 입력', joinRoom: '방 참여', viewerMode: '시청자 모드 (조작 없이 따라보기)',
792
795
  aiSubSettings: 'AI 자막', debugConsole: '디버그 콘솔', uiHide: '자동 숨김', keepOpen: '고정',
793
796
  bmLibrary: '북마크', bmAddHere: '지금 장면 북마크', bmSearch: '북마크 검색', bmEmpty: '아직 북마크가 없어요. 보는 중에 “지금 장면 북마크”를 눌러 보세요.', bmLive: '라이브', bmOpening: '📌 북마크를 여는 중…', bmJumped: '📌 {time}(으)로 돌아왔어요', bmLiveOpened: '🔴 라이브 방송을 바로 재생해요', bmDelete: '삭제', bmThisPage: '이 페이지', bmCopy: '링크 복사', bmCopied: '📋 링크를 복사했어요',
794
797
  tuneTitle: '싱크 맞추기', tuneMenu: '싱크 맞추기', tuneOffset: '내 시간 보정', tuneOffsetZero: '방과 같은 타이밍', tuneAhead: '내 영상이 방보다 {s} 앞서 재생돼요', tuneBehind: '내 영상이 방보다 {s} 늦게 재생돼요',
795
798
  tuneResync: '지금 다시 맞추기', tuneReset: '초기화', tuneHelp: '사이트가 달라 영상 길이가 다른가요? (배급사 로고·인트로 차이) 화면이 같아질 때까지 내 타이밍만 옮기면 돼요. 다른 사람에겐 영향이 없어요.',
796
- tuneCompare: '화면 비교', tuneMine: '나', tuneTheirs: '{name}', tuneNoPicture: '화면을 가져올 수 없어요 (보호된 영상)', tuneWaiting: '화면을 받는 중…',
799
+ tuneCompare: '화면 비교', tuneMine: '나', tuneTheirs: '{name}', tuneNoPicture: '보호된 영상이라 화면 대신 시간으로 비교해요', tuneDiffSame: '상대와 같은 위치예요', tuneDiffAhead: '내가 {name}님보다 {s} 앞서 있어요', tuneDiffBehind: '내가 {name}님보다 {s} 뒤에 있어요', tuneWaiting: '화면을 받는 중…',
797
800
  tuneMark: '같은 장면', tuneMarkHint: '각자 같은 장면(예: 로고가 끝난 첫 장면)에서 멈춘 뒤 “이 장면”을 누르세요.', tuneMarkBtn: '📍 이 장면', tuneMarkMine: '나: {t}', tuneMarkTheirs: '{name}: {t}', tuneApply: '적용',
798
801
  tuneAuto: '자동', tuneAutoBtn: '🤖 자동으로 맞추기', tuneAutoHint: '최근 몇 분 동안 서로 재생한 소리(또는 화면)를 비교해요. 먼저 잠시 함께 재생해 주세요.',
799
802
  tuneAutoNeed: '아직 비교할 내용이 부족해요 — 조금 더 함께 재생한 뒤 다시 시도하세요.', tuneAutoFound: '찾았어요: {s} (확신 {c}%)', tuneAutoNone: '뚜렷한 일치를 못 찾았어요. “같은 장면”으로 맞춰 보세요.', tuneAsking: '다른 사람에게 요청하는 중…', tuneApplied: '⏱ 타이밍 보정: {s}',
800
803
  tuneMarkReceived: '📍 {name}님이 장면을 표시했어요', tuneNoPeer: '아직 방에 다른 사람이 없어요.',
804
+ tuneSrcSame: '🟢 모두 같은 영상이에요 — 프레임 단위로 자동으로 맞추고 있어요.', tuneSrcDiff: '🟠 서로 다른 버전이에요 (길이 차이 {s}) — 잠시 재생하면 자동으로 맞추고, 여기서 직접 맞출 수도 있어요.', tuneSrcUnknown: '다른 사람의 영상 정보를 기다리는 중…',
805
+ tuneSameReset: '⏱ 상대와 같은 영상이라 타이밍 보정을 해제했어요.', tuneAutoApplied: '다른 버전이라 타이밍을 {s} 자동 보정했어요 (누르면 되돌리기).', tuneSuggest: '서로 영상 길이가 {s} 달라요. 눌러서 맞춰 보세요.',
801
806
  subMenu: '자막', xsubOff: '끄기', subTrack: '영상에 포함된 자막', subSearch: '🔎 자막 찾기 (OpenSubtitles)', subFile: '📂 자막 파일 열기…', subAi: '🧠 AI 실시간 자막', subDelay: '싱크', subLater: '늦게', subEarlier: '빠르게', xsubSize: '크기',
802
- subLoaded: '💬 자막: {name}', subNone: '이 영상에는 포함된 자막이 없어요.', subSuggest: '💬 자막이 없나요? 찾아보기', subLoadFail: '자막을 불러오지 못했어요.',
803
- osTitle: '자막 찾기', osQuery: '제목 (영어 제목이 가장 잘 찾아져요)', osSeason: '시즌', osEpisode: '회차', osLang: '언어', osSearch: '검색', osSearching: '찾는 중…', osNone: '찾지 못했어요. 영어 제목으로 바꾸거나 연도를 빼 보세요.', osError: 'OpenSubtitles가 응답하지 않아요. 잠시 후 다시 시도하세요.', osDownloads: '다운로드 {n}회', osLoading: '불러오는 중…', osHint: '자막은 OpenSubtitles.org에서 가져와 NexusSync 스타일로 보여 줘요. 빠르거나 늦으면 자막 메뉴의 “싱크”로 맞추세요.',
804
- viewMenu: '화면 · 소리', viewBright: '밝기', viewBoost: '볼륨 부스트', viewReset: '초기화', boostBlocked: '이 영상은 다른 사이트에서 오는 소리라 여기서 키울 수 없어요.',
807
+ subLoaded: '💬 자막: {name}', subMulti: '자막 여러 개를 함께 보는 중 — 누르면 그 자막만 꺼져요.', subNone: '이 영상에는 포함된 자막이 없어요.', subSuggest: '💬 자막이 없나요? 찾아보기', subLoadFail: '자막을 불러오지 못했어요.',
808
+ osTitle: '자막 찾기', osTmdbLooking: 'TMDB에서 영어 제목을 찾는 중…', osTmdbNone: 'TMDB에서 영어 제목을 찾지 못했어요 — 알고 있다면 직접 입력하세요.', osQuery: '제목 (영어 제목이 가장 잘 찾아져요)', osSeason: '시즌', osEpisode: '회차', osLang: '언어', osSearch: '검색', osSearching: '찾는 중…', osNone: '찾지 못했어요. 영어 제목으로 바꾸거나 연도를 빼 보세요.', osError: 'OpenSubtitles가 응답하지 않아요. 잠시 후 다시 시도하세요.', osDownloads: '다운로드 {n}회', osLoading: '불러오는 중…', osHint: '자막은 OpenSubtitles.org에서 가져와 NexusSync 스타일로 보여 줘요. 빠르거나 늦으면 자막 메뉴의 “싱크”로 맞추세요.',
809
+ viewMenu: '화면', viewAudio: '오디오 트랙', viewBright: '밝기', viewBoost: '볼륨 부스트', viewReset: '초기화', boostBlocked: '이 영상은 다른 사이트에서 오는 소리라 여기서 키울 수 없어요.',
805
810
  settings: '설정', setProfile: '프로필', setAvatar: '아바타', setStatus: '상태 메시지', setStatusPh: '예: 팝콘 준비 완료 🍿', setReactions: '내 리액션',
806
- setReactionsHint: '칸을 누른 뒤 이모지를 고르세요 (아무 이모지나 입력해도 돼요).', setReactionsReset: '기본 리액션으로', setPlayback: '재생', setAutoNext: '다음 화 자동으로 넘기기',
811
+ setReactionsHint: '칸을 누른 뒤 이모지를 고르세요 (아무 이모지나 입력해도 돼요). 칸은 1~16개로 늘리거나 줄일 수 있어요.', setReactionsReset: '기본 리액션으로', setPlayback: '재생', setAutoNext: '다음 화 자동으로 넘기기',
807
812
  setTogether: '함께 보기', setRecvReact: '다른 사람 리액션 보기', setRecvNudge: '찌르기 받기 (흔들림)', setRecvInk: '다른 사람 그림 보기', setRecvChat: '말풍선 보기', setRecvPing: '포인터 보기',
808
813
  setPeople: '이 방의 사람들', setMute: '숨기기', setUnmute: '보이기', setMutedHint: '숨긴 사람의 메시지·리액션·그림은 이 기기에서 보이지 않아요 (이 방에서만).',
809
- setAdvanced: '고급', setEmojiPh: '이모지 입력', setNobody: '아직 다른 사람이 없어요.',
814
+ setAdvanced: '고급', setAvatarCustom: '이모지나 이니셜 입력', setAvatarPhoto: '사진', setAvatarClear: '지우기', setAvatarFail: '이 사진은 사용할 수 없어요.', setSlotAdd: '+ 칸 추가', setSlotRemove: '- 선택한 칸 삭제', setEmojiPh: '이모지 입력', setNobody: '아직 다른 사람이 없어요.',
810
815
  speakerLanguage: '말하는 언어', speakerHelp: '영상(또는 말하는 사람)의 언어를 선택하세요. 음성 인식은 이 언어만 알아듣습니다.',
811
816
  subtitleLanguage: '자막 번역 언어', audioSource: '오디오 입력', audioAuto: '자동 (가능하면 영상 소리 + 마이크)', audioMic: '마이크만',
812
817
  audioMedia: '영상/탭 소리만', audioDual: '마이크 + 영상 소리',
@@ -823,7 +828,7 @@
823
828
  subUsingMicFallback: '영상 소리를 직접 들을 수 없어 마이크로 들어요. 스피커 소리를 키워 주세요.',
824
829
  subTabShareEnded: '탭 오디오 공유가 끝나서 자막을 껐어요.',
825
830
  subHearVideo: '🎧 영상 소리 듣는 중', subHearMic: '🎧 마이크로 듣는 중', subVideoSilent: '🔇 이 영상의 소리가 자막에 전달되지 않아요',
826
- subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subIssueNoResult: '⚠️ 소리는 들어오는데 말이 인식되지 않아요', subTryMic: '🎤 마이크로 듣기', subTryKey: '🔑 AI 인식 키 사용', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
831
+ subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subIssueNoResult: '⚠️ 소리는 들어오는데 말이 인식되지 않아요', subSiteBlocksSpeech: '이 사이트는 브라우저 음성 인식을 막아 두었어요. AI 자막 → 고급에서 OpenAI 또는 Groq 키를 넣으면 여기서도 쓸 수 있어요.', subSiteBlocksSpeechKey: '이 사이트는 브라우저 음성 인식을 막아 두어서, 넣어 둔 키로 클라우드 인식으로 바꿀게요.', subTryMic: '🎤 마이크로 듣기', subTryKey: '🔑 AI 인식 키 사용', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
827
832
  subPosition: '자막 위치', posVideo: '영상 위', posScreen: '화면 하단', subSize: '크기', subOpacity: '불투명도',
828
833
  advanced: '고급', translationEngine: '번역 엔진', providerAuto: 'Google 우선, 기기 내 번역 보조 (최고 품질)', providerBrowser: '기기 내 번역만 (개인정보 보호)',
829
834
  providerGoogle: 'Google만', providerHelp: '문장 번역 품질은 온라인(Google)이 훨씬 좋습니다. 기기 내 모델은 실시간 임시 줄과 오프라인 상황을 맡습니다.',
@@ -847,7 +852,7 @@
847
852
  noVideo: '⚠️ 감지된 영상이 없습니다', noPlayingVideo: '⚠️ 재생 중인 영상이 없습니다', pipUnsupported: '⚠️ PiP를 지원하지 않습니다', pipBlocked: '⚠️ PiP가 차단되었습니다',
848
853
  mediaFound: '✅ 미디어 감지됨', mediaNotFound: '🔎 아직 미디어가 없습니다 — 영상을 재생한 뒤 다시 시도하세요',
849
854
  canvasOn: '🎨 캔버스 켜짐', canvasOff: '🎨 캔버스 꺼짐', canvasViewOnly: '🎨 캔버스 (보기 전용)', nothingToUndo: '↩️ 되돌릴 내용이 없습니다', undo: '되돌리기 (Ctrl+Z)',
850
- pen: '펜', eraser: '지우개', clearCanvas: '모두 지우기', watching: '{n}명 시청 중', meTag: '(나)', whoViewer: '보기 전용', whoAway: '자리 비움 (화면 꺼짐·다른 탭)', whoOldVer: '다른 버전 — 업데이트가 필요해요', whoTitle: '함께 보는 사람',
855
+ pen: '펜', eraser: '지우개', clearCanvas: '모두 지우기', watching: '{n}명 시청 중', meTag: '(나)', whoViewer: '보기 전용', whoAway: '자리 비움 (화면 꺼짐·다른 탭)', whoOldVer: '다른 버전 — 업데이트가 필요해요', whoTitle: '함께 보는 사람', whoSleeping: '화면 꺼짐 — 방에 그대로 있고, 화면이 켜지면 돌아와요', whoReconnecting: '다시 연결하는 중…',
851
856
  shieldTitle: '연결됨', shieldText: '눌러서 이 탭의 동기화 재생을 활성화하세요.', shieldButton: '동기화 시작 ▶️',
852
857
  menuCinema: '시네마 모드 켜기/끄기', menuSubtitles: 'AI 자막 시작/중지', menuShowButton: '이 사이트에서 NexusSync 버튼 표시/숨기기'
853
858
  }
@@ -1175,6 +1180,7 @@
1175
1180
  visibility: hidden !important; pointer-events: none !important; transition: none !important; animation: none !important; }
1176
1181
  .nxu-site-ui-off :is([class*="caption" i], [class*="subtitle" i], [class*="text-track" i], [class*="cue" i], [class*="danmaku" i]) { visibility: visible !important; }
1177
1182
  .nxu-site-ui-off .nxu-site-hide { visibility: hidden !important; pointer-events: none !important; transition: none !important; animation: none !important; }
1183
+ .nxu-site-ui-off .nxu-dsub-src, .nxu-site-ui-off .nxu-dsub-src * { visibility: hidden !important; }
1178
1184
  .nxu-cue-mirror { position: absolute !important; left: calc(50% + var(--nxu-cue-shift, 0px)) !important; right: auto !important; top: auto !important; bottom: var(--nxu-cue-bottom, 6%) !important; transform: translateX(-50%) !important;
1179
1185
  width: var(--nxu-cue-width, 90%) !important; max-width: 96% !important; height: auto !important; margin: 0 !important; padding: 0 !important; border: 0 !important; background: none !important;
1180
1186
  flex-direction: column !important; align-items: center !important; gap: 3px !important; z-index: 2147483646 !important; transition: bottom 0.3s ease !important; pointer-events: none !important; visibility: visible !important; opacity: 1 !important; }
@@ -1460,6 +1466,7 @@
1460
1466
  };
1461
1467
  if (!hide || !root || !video || root === video) { undo(); return; }
1462
1468
  const run = () => {
1469
+ const textLayers = [];
1463
1470
  const chain = new Set();
1464
1471
  for (let n = video; n && n !== root; n = n.parentElement) chain.add(n);
1465
1472
  const hidden = [];
@@ -1474,13 +1481,14 @@
1474
1481
  const interactive = child.matches(CTRL) || !!child.querySelector(CTRL);
1475
1482
  const text = (child.textContent || '').trim();
1476
1483
  // Text without any control: most likely the site's own subtitles.
1477
- if (!interactive && text) continue;
1484
+ if (!interactive && text) { textLayers.push(child); continue; }
1478
1485
  child.classList.add('nxu-site-hide');
1479
1486
  hidden.push(child);
1480
1487
  }
1481
1488
  }
1482
1489
  (this._hidden || []).forEach(n => { if (!hidden.includes(n)) n.classList.remove('nxu-site-hide'); });
1483
1490
  this._hidden = hidden;
1491
+ this._textLayers = textLayers;
1484
1492
  };
1485
1493
  run();
1486
1494
  if (!this._hideObs || this._hideObsRoot !== root) {
@@ -2747,6 +2755,7 @@
2747
2755
  }
2748
2756
  } catch (_) { }
2749
2757
  },
2758
+ _diag: { sound: 0, results: 0, err: '' },
2750
2759
  _createRecognizer() {
2751
2760
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
2752
2761
  const r = new SR();
@@ -2779,10 +2788,10 @@
2779
2788
  this._appleRestoreTimer = setTimeout(() => this._setAppleSession('playback'), 220);
2780
2789
  }
2781
2790
  };
2782
- r.onsoundstart = () => { if (alive()) { this._touch(); this._soundHeard = true; } };
2791
+ r.onsoundstart = () => { if (alive()) { this._touch(); this._soundHeard = true; this._diag.sound++; } };
2783
2792
  r.onspeechstart = () => { if (alive()) this._touch(); };
2784
- r.onresult = (event) => { if (alive()) this._onResult(event); };
2785
- r.onerror = (event) => { if (alive()) this._onError(event); };
2793
+ r.onresult = (event) => { if (alive()) { this._diag.results++; this._onResult(event); } };
2794
+ r.onerror = (event) => { if (alive()) { this._diag.err = event?.error || '?'; this._onError(event); } };
2786
2795
  r.onend = () => { if (alive()) this._onEnd(); };
2787
2796
  this.recognizer = r;
2788
2797
  },
@@ -2881,7 +2890,7 @@
2881
2890
  this._scheduleRestart('track-fallback', 150, true);
2882
2891
  }
2883
2892
  // Plenty of sound but not a single word back: say so, with a one-tap way out.
2884
- if (this._useWebSpeech && !this._issue && this._soundMs > 25000 && (this._lastResultAt || 0) < (this._startedAt || 0)) this._issue = 'noresult';
2893
+ if (this._useWebSpeech && !this._issue && this._soundMs > 15000 && (this._lastResultAt || 0) < (this._startedAt || 0)) this._issue = 'noresult';
2885
2894
  this._updateListenChip();
2886
2895
  updateAIBtnUX();
2887
2896
  },
@@ -3152,10 +3161,26 @@
3152
3161
  switch (error) {
3153
3162
  case 'aborted':
3154
3163
  return;
3155
- case 'not-allowed':
3156
- logDebug('AI Sub: microphone permission denied.', 'error');
3157
- this.stop(t('subMicDenied'));
3164
+ case 'not-allowed': {
3165
+ // Fed from a captured track, try once more with the engine's own input
3166
+ // (some browsers refuse a track); then say exactly why it cannot listen.
3167
+ if (this._recognitionInput === 'track' && !this._trackDisabled) {
3168
+ this._trackDisabled = true;
3169
+ logDebug('AI Sub: the speech engine refused the captured audio, trying its own input.', 'warn');
3170
+ this._destroyRecognizer(); this._createRecognizer(); this._scheduleRestart('track-refused', 200, true);
3171
+ return;
3172
+ }
3173
+ const policy = this._micBlockedByPolicy();
3174
+ logDebug('AI Sub: speech recognition not allowed' + (policy ? ' (blocked by this site)' : ''), 'error');
3175
+ const cloudKey = AI.key('openai') || AI.key('groq');
3176
+ this.stop(t(policy ? (cloudKey ? 'subSiteBlocksSpeechKey' : 'subSiteBlocksSpeech') : 'subMicDenied'));
3177
+ // With a key, cloud recognition does not need the browser's speech engine.
3178
+ if (policy && cloudKey && STORE.get('nxu_asr_provider', 'browser') === 'browser') {
3179
+ STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai');
3180
+ setTimeout(() => this.start().catch(() => { }), 400);
3181
+ }
3158
3182
  return;
3183
+ }
3159
3184
  case 'service-not-allowed':
3160
3185
  if (this.recognizer?.processLocally) {
3161
3186
  this._localSpeechReady = false;
@@ -3771,6 +3796,7 @@
3771
3796
  if (this._useWebSpeech) await this._prepareLocalSpeech(SR).catch(() => { });
3772
3797
  if (token !== this._startToken) return;
3773
3798
  this.state = 'running';
3799
+ this._diag = { sound: 0, results: 0, err: '' };
3774
3800
  this._startedAt = Date.now();
3775
3801
  this._soundMs = 0;
3776
3802
  this.active = true;
@@ -3940,7 +3966,9 @@
3940
3966
  const engine = T._cloud ? AI.asrModel() + (T._useWebSpeech ? ' + live' : '') : (T._sttProvider === 'web-speech-local' ? t('engineLocal') : t('engineOnline'));
3941
3967
  const tx = T._providerStatus ? ` · ${t('translation')}: ${T._providerStatus}` : '';
3942
3968
  const level = T.audioNodes ? ` · 🎚 ${Math.round(Math.max(T._levels.mic, T._levels.media) * 400)}` : '';
3943
- status.textContent = `● ${t('subListening')} · ${lang} → ${T._label(T.outLang)} · ${input} · ${engine}${tx}${level}`;
3969
+ // What the speech engine reports (helps tell "no sound" from "no words").
3970
+ const dg = T._useWebSpeech ? ` · 🔎 ${T._diag.sound}/${T._diag.results}${T._diag.err ? ' · ⚠ ' + T._diag.err : ''}` : '';
3971
+ status.textContent = `● ${t('subListening')} · ${lang} → ${T._label(T.outLang)} · ${input} · ${engine}${tx}${level}${dg}`;
3944
3972
  }
3945
3973
  }
3946
3974
  }
@@ -5180,6 +5208,7 @@
5180
5208
  if (uid && typeof d.sess === 'string' && cur && typeof cur.sess === 'string' && cur.sess !== d.sess) break;
5181
5209
  if (uid && uid !== STATE.userId) {
5182
5210
  const name = participantName(uid);
5211
+ PRESENCE.left.add(uid);
5183
5212
  PRESENCE.seen.delete(uid);
5184
5213
  PRESENCE.refresh();
5185
5214
  showToast(t('peerLeft', { name }));
@@ -5240,12 +5269,12 @@
5240
5269
  if (ydoc && Array.isArray(d.data)) d.data.forEach(u => { try { Y.applyUpdate(ydoc, new Uint8Array(u), 'remote'); } catch (_) { } });
5241
5270
  break;
5242
5271
  case 'yjs_sync_request':
5243
- if (ydoc) sendFirebaseCmd('yjs_update', { data: Array.from(Y.encodeStateAsUpdate(ydoc)) }, 'nexus_rooms');
5272
+ if (ydoc) HEAL.pushFull('asked');
5244
5273
  break;
5245
5274
  case 'reaction':
5246
5275
  onRemoteReaction(d);
5247
5276
  break;
5248
- case 'nudge': case 'pointer': case 'countdown': case 'typing': case 'ink': case 'cover': case 'goto': case 'tune':
5277
+ case 'nudge': case 'pointer': case 'countdown': case 'typing': case 'ink': case 'cover': case 'goto': case 'tune': case 'avatar':
5249
5278
  SOCIAL.receive(p.t, d);
5250
5279
  break;
5251
5280
  }
@@ -5256,6 +5285,40 @@
5256
5285
  if (!RTC.sendData('yjs_sync_request', {})) sendFirebaseCmd('yjs_sync_request', {}, 'nexus_rooms');
5257
5286
  }
5258
5287
 
5288
+ // Room-state healing. An update sent just as a phone went to sleep can be lost; the
5289
+ // others then hold that device's later updates aside forever (they build on the lost
5290
+ // one), so its presence, play/pause and seeks stopped arriving while plain messages
5291
+ // (reactions) still did. Every device now resends its whole state after waking, and
5292
+ // anyone who notices missing pieces (or hears from someone it cannot see) asks for it.
5293
+ const HEAL = {
5294
+ _askAt: 0, _pushAt: 0,
5295
+ pushFull(reason) {
5296
+ if (!ydoc || !SOCIAL.live() || Date.now() - this._pushAt < 4000) return;
5297
+ this._pushAt = Date.now();
5298
+ const full = { data: Array.from(Y.encodeStateAsUpdate(ydoc)) };
5299
+ sendFirebaseCmd('yjs_update', full, 'nexus_rooms');
5300
+ if (STATE.connectionMode === 'WEBRTC_P2P') RTC.sendData('yjs_update', full);
5301
+ logDebug('Room state resent (' + reason + ').', 'info');
5302
+ },
5303
+ ask(reason) {
5304
+ if (!ydoc || !SOCIAL.live() || Date.now() - this._askAt < 8000) return;
5305
+ this._askAt = Date.now();
5306
+ requestRoomState();
5307
+ logDebug('Asked the room for its full state (' + reason + ').', 'info');
5308
+ },
5309
+ check() {
5310
+ if (!ydoc || !STATE.handshakeVerified) return;
5311
+ const st = ydoc.store;
5312
+ if (st && (st.pendingStructs || st.pendingDs)) this.ask('missing updates');
5313
+ },
5314
+ // A message from someone who is not in the list: their state did not reach us.
5315
+ heard(uid) {
5316
+ if (!uid || uid === STATE.userId || !STATE.handshakeVerified) return;
5317
+ if (!STATE.presenceMap?.[uid]) { this.ask('message from an unlisted device'); this.pushFull('peer unseen'); }
5318
+ }
5319
+ };
5320
+ if (IS_TOP) setInterval(() => { try { HEAL.check(); } catch (_) { } }, 10000);
5321
+
5259
5322
  // Sends room authority to the player inside a cross-origin frame.
5260
5323
  function sendStateToFrame(state, frame = STATE.cinemaIframe) {
5261
5324
  if (!frame || !state) return;
@@ -5270,7 +5333,7 @@
5270
5333
  rate,
5271
5334
  eventId: state.eventId,
5272
5335
  action: state.action,
5273
- startIn: state.play && wait > 40 ? Math.min(wait, 3000) : 0
5336
+ startIn: state.play && wait > 40 ? Math.min(wait, 10000) : 0
5274
5337
  });
5275
5338
  }
5276
5339
 
@@ -5371,7 +5434,7 @@
5371
5434
  const now = Date.now();
5372
5435
  // Freshness uses the time *we* received an update, not the sender's clock: phones and
5373
5436
  // PCs often disagree by many seconds, which made the head count differ per device.
5374
- event.changes.keys.forEach((change, uid) => { if (change.action !== 'delete') PRESENCE.seen.set(uid, now); else PRESENCE.seen.delete(uid); });
5437
+ event.changes.keys.forEach((change, uid) => { if (change.action !== 'delete') { PRESENCE.seen.set(uid, now); PRESENCE.left.delete(uid); } else PRESENCE.seen.delete(uid); });
5375
5438
  PRESENCE.refresh();
5376
5439
  // Someone on an older NexusSync: play/pause/seek from mixed versions do not line up
5377
5440
  // as well (older builds let heartbeats override other devices) — say so once.
@@ -5445,7 +5508,11 @@
5445
5508
  return;
5446
5509
  }
5447
5510
  }
5511
+ // A synchronized start (countdown, shared resume) is waiting: a heartbeat arriving
5512
+ // meanwhile must not cancel it (that left everyone paused after the countdown).
5513
+ if (STATE._scheduledPlay && action === 'heartbeat' && Date.now() < (STATE._scheduledPlayAt || 0) + 500) return;
5448
5514
  clearTimeout(STATE._scheduledPlay);
5515
+ STATE._scheduledPlay = null;
5449
5516
  STATE.remoteLockUntil = Date.now() + 100;
5450
5517
  STATE._remoteApplying = true;
5451
5518
  if (play) {
@@ -5454,13 +5521,21 @@
5454
5521
  if (wait > 40) {
5455
5522
  // Synchronized start: every device begins at the same shared instant.
5456
5523
  if (Math.abs(video.currentTime - time) > 0.25) remoteSeek(video, time);
5524
+ // This hold-and-wait pause is ours: when its event arrives late it must not be
5525
+ // taken for someone pausing (that stopped the room right after a countdown).
5526
+ video._nxuOwnPauseUntil = Date.now() + Math.min(wait, 10000) + 500;
5527
+ video._nxuOwnPauseSince = Date.now();
5457
5528
  if (!video.paused) { try { video.pause(); } catch (_) { } }
5458
5529
  RATE.apply(video, base);
5530
+ STATE._scheduledPlayAt = Date.now() + Math.min(wait, 10000);
5459
5531
  STATE._scheduledPlay = setTimeout(() => {
5532
+ STATE._scheduledPlay = null;
5460
5533
  STATE._remoteApplying = true;
5461
5534
  MEDIA_SAFE.play(video);
5462
5535
  setTimeout(() => { STATE._remoteApplying = false; }, 120);
5463
- }, Math.min(wait, 3000));
5536
+ // Some players refuse or swallow the first play(): check once more.
5537
+ setTimeout(() => { const r = _getVideoState(); if (r && r.play && video.paused && STATE.video === video) MEDIA_SAFE.play(video); }, 900);
5538
+ }, Math.min(wait, 10000));
5464
5539
  setTimeout(() => { STATE._remoteApplying = false; }, 80);
5465
5540
  return;
5466
5541
  }
@@ -5643,9 +5718,10 @@
5643
5718
  if (res) { this._frameWait.delete(data.rid); res(data); }
5644
5719
  },
5645
5720
  async _mySnap() {
5646
- if (STATE.video) return { img: this.snapshot(), t: STATE.video.currentTime };
5721
+ const playing = !(currentMediaInfo()?.paused ?? true);
5722
+ if (STATE.video) return { img: this.snapshot(), t: STATE.video.currentTime, playing, at: Date.now() };
5647
5723
  const d = await this._askFrame('snap');
5648
- return d ? { img: d.img || null, t: d.t } : null;
5724
+ return d ? { img: d.img || null, t: d.t, playing, at: Date.now() } : { img: null, t: this.mediaTime(), playing, at: Date.now() };
5649
5725
  },
5650
5726
  async _myEnv() {
5651
5727
  if (STATE.video) { this.arm(true); return this._envelope(); }
@@ -5664,7 +5740,7 @@
5664
5740
  this._peekUntil = Date.now() + 45000;
5665
5741
  this._startPeek();
5666
5742
  } else if (op === 'snap' && (d.img === null || (typeof d.img === 'string' && d.img.startsWith('data:image/jpeg') && d.img.length < 90000))) {
5667
- this._peer = { uid: d.uid, name: who.name, color: who.color, img: d.img, t: Number(d.t) || 0, off: Number(d.off) || 0, at: Date.now() };
5743
+ this._peer = { uid: d.uid, name: who.name, color: who.color, img: d.img, t: Number(d.t) || 0, playing: !!d.playing, off: Number(d.off) || 0, at: Date.now() };
5668
5744
  this.paint();
5669
5745
  } else if (op === 'mark' && Number.isFinite(d.t)) {
5670
5746
  this._marks.set(d.uid, { t: d.t, off: Number(d.off) || 0, name: who.name, color: who.color });
@@ -5693,7 +5769,7 @@
5693
5769
  const loop = async () => {
5694
5770
  if (Date.now() > this._peekUntil || !SOCIAL.live()) { this._peekTimer = null; return; }
5695
5771
  const s = await this._mySnap();
5696
- SOCIAL.send('tune', { op: 'snap', img: s ? s.img : null, t: s ? s.t : 0, off: this.offset() });
5772
+ SOCIAL.send('tune', { op: 'snap', img: s ? s.img : null, t: s ? s.t : 0, playing: !!(s && s.playing), off: this.offset() });
5697
5773
  this._peekTimer = setTimeout(loop, 1200);
5698
5774
  };
5699
5775
  this._peekTimer = setTimeout(loop, 50);
@@ -5778,16 +5854,16 @@
5778
5854
  const sd = Math.sqrt(fin.reduce((s, x) => s + (x - mean) ** 2, 0) / Math.max(1, fin.length)) || 1;
5779
5855
  return { d: best.d, score: best.score, second, z: (best.score - mean) / sd };
5780
5856
  },
5781
- async auto() {
5782
- if (!PRESENCE.others().length) { this._autoMsg = t('tuneNoPeer'); this.paint(); return; }
5783
- this._autoMsg = t('tuneAsking'); this.paint();
5857
+ async auto({ silent = false } = {}) {
5858
+ if (!PRESENCE.others().length) { if (!silent) { this._autoMsg = t('tuneNoPeer'); this.paint(); } return null; }
5859
+ if (!silent) { this._autoMsg = t('tuneAsking'); this.paint(); }
5784
5860
  const mine = await this._myEnv();
5785
5861
  const theirs = await new Promise((resolve) => {
5786
5862
  this._autoWait = resolve;
5787
5863
  SOCIAL.send('tune', { op: 'envreq' });
5788
5864
  setTimeout(() => { if (this._autoWait === resolve) { this._autoWait = null; resolve(null); } }, 9000);
5789
5865
  });
5790
- if (!mine || !theirs) { this._autoMsg = t('tuneAutoNeed'); this.paint(); return; }
5866
+ if (!mine || !theirs) { if (!silent) { this._autoMsg = t('tuneAutoNeed'); this.paint(); } return null; }
5791
5867
  let res = null;
5792
5868
  for (const luma of [false, true]) {
5793
5869
  const a = this._series(mine, luma), b = this._series(theirs.env, luma);
@@ -5796,14 +5872,80 @@
5796
5872
  if (Number.isFinite(r.score) && (!res || r.z > res.z)) res = r;
5797
5873
  }
5798
5874
  logDebug(`Sync timing: compared ${mine.ts.length} / ${theirs.env.ts.length} samples → ${res ? `lag ${res.d.toFixed(1)}s, r=${res.score.toFixed(2)}, next ${res.second.toFixed(2)}, z=${res.z.toFixed(1)}` : 'nothing comparable'}`, 'info');
5799
- if (!res || !(res.score > 0.3) || !(res.z >= 4)) { this._autoMsg = t('tuneAutoNone'); this._autoFound = null; this.paint(); return; }
5875
+ if (!res || !(res.score > 0.3) || !(res.z >= 4)) { if (!silent) { this._autoMsg = t('tuneAutoNone'); this._autoFound = null; this.paint(); } return null; }
5800
5876
  // d: my content at time x = theirs at x − d. With both following the room, my
5801
5877
  // offset must be theirs + d.
5802
5878
  const want = Math.round((theirs.off + res.d) * 10) / 10;
5803
5879
  const sure = Math.round(Math.min(0.99, Math.max(0.5, 0.5 + (res.z - 4) * 0.06 + (res.score - 0.3) * 0.4)) * 100);
5880
+ if (silent) return { want, sure, score: res.score, z: res.z };
5804
5881
  this._autoFound = want;
5805
5882
  this._autoMsg = t('tuneAutoFound', { s: this.fmt(want), c: sure });
5806
5883
  this.paint();
5884
+ return { want, sure, score: res.score, z: res.z };
5885
+ },
5886
+
5887
+ // ── same source or a different version? (decided from each device's media length)
5888
+ mediaSig() {
5889
+ const info = currentMediaInfo();
5890
+ if (!info) return null;
5891
+ if (info.live) return { d: -1 };
5892
+ return Number.isFinite(info.duration) && info.duration > 0 ? { d: Math.round(info.duration * 10) / 10 } : null;
5893
+ },
5894
+ source() {
5895
+ const mine = this.mediaSig();
5896
+ const others = PRESENCE.others().map(uid => STATE.presenceMap[uid]?.md).filter(m => m && Number.isFinite(m.d));
5897
+ if (!mine || !others.length) return { kind: 'unknown' };
5898
+ if (mine.d < 0 || others.some(m => m.d < 0)) return { kind: 'same' }; // live: one timeline
5899
+ const diffs = others.map(m => mine.d - m.d);
5900
+ const big = diffs.reduce((a, b) => (Math.abs(b) > Math.abs(a) ? b : a), 0);
5901
+ return Math.abs(big) < 1.5 ? { kind: 'same' } : { kind: 'different', diff: Math.round(big * 10) / 10 };
5902
+ },
5903
+ // Only one device shifts its timing: the one with the longer version (extra intro), or
5904
+ // with equal length the lowest id.
5905
+ _adjuster() {
5906
+ const mine = this.mediaSig();
5907
+ if (!mine) return false;
5908
+ const others = PRESENCE.others().map(uid => [uid, STATE.presenceMap[uid]?.md]).filter(([, m]) => m && Number.isFinite(m.d) && m.d > 0);
5909
+ return others.every(([uid, m]) => mine.d > m.d + 1.5 || (Math.abs(mine.d - m.d) <= 1.5 && STATE.userId < uid));
5910
+ },
5911
+ // Runs every few seconds in a room: same source → no shift (the room's own fine sync
5912
+ // does the frame-level work); different versions → find the shift by itself.
5913
+ _watchStart: 0, _tries: 0, _lastKind: '',
5914
+ async autoTick() {
5915
+ if (!IS_TOP || !STATE.handshakeVerified || STATE.isReadOnly || this._autoBusy) return;
5916
+ const src = this.source();
5917
+ if (src.kind !== this._lastKind) { this._lastKind = src.kind; this._tries = 0; this.paint(); }
5918
+ if (src.kind === 'same') {
5919
+ if (this.offset()) { this.set(0, { quiet: true }); showToast(t('tuneSameReset')); }
5920
+ return;
5921
+ }
5922
+ if (src.kind !== 'different' || this.offset() || this._autoDone === location.href || !this._adjuster()) return;
5923
+ const info = currentMediaInfo();
5924
+ if (!info || info.paused) return;
5925
+ const env = this._rec;
5926
+ if (STATE.video && (!env || env.ts.length < 450)) return; // ~45 s of history first
5927
+ if (this._tries >= 5) {
5928
+ if (!this._suggested) { this._suggested = true; BUBBLES.show({ icon: '🎯', name: 'NexusSync', color: '#ffca28', text: t('tuneSuggest', { s: this.fmt(src.diff) }), key: 'tune-suggest', ms: 12000, onTap: () => this.open() }); }
5929
+ return;
5930
+ }
5931
+ if (Date.now() - (this._lastTry || 0) < 30000) return;
5932
+ this._lastTry = Date.now();
5933
+ this._tries++;
5934
+ this._autoBusy = true;
5935
+ try {
5936
+ const r = await this.auto({ silent: true });
5937
+ // A very clear match is used at once; a fair one only when two tries agree.
5938
+ const prev = this._prevAuto;
5939
+ this._prevAuto = r;
5940
+ const clear = r && r.score > 0.45 && r.z >= 7;
5941
+ const agreed = r && prev && r.z >= 5 && prev.z >= 5 && Math.abs(r.want - prev.want) < 0.5;
5942
+ if ((clear || agreed) && Math.abs(r.want) <= this.LIMIT) {
5943
+ this._autoDone = location.href;
5944
+ const before = this.offset();
5945
+ this.set(r.want, { quiet: true });
5946
+ BUBBLES.show({ icon: '🎯', name: 'NexusSync', color: '#69f0ae', text: t('tuneAutoApplied', { s: this.fmt(r.want) }), key: 'tune-auto', ms: 12000, onTap: () => { this.set(before); this._autoDone = location.href; } });
5947
+ }
5948
+ } catch (_) { } finally { this._autoBusy = false; }
5807
5949
  },
5808
5950
 
5809
5951
  // ── panel
@@ -5830,16 +5972,36 @@
5830
5972
  if (!panel || panel.style.display !== 'flex') return;
5831
5973
  const off = this.offset();
5832
5974
  const q = s => panel.querySelector(s);
5975
+ const src = this.source();
5976
+ q('.tune-src').textContent = src.kind === 'same' ? t('tuneSrcSame') : src.kind === 'different' ? t('tuneSrcDiff', { s: this.fmt(src.diff) }) : t('tuneSrcUnknown');
5977
+ q('.tune-src').dataset.kind = src.kind;
5978
+ panel.querySelector('.tune-body').classList.toggle('same', src.kind === 'same');
5833
5979
  q('.tune-off-val').textContent = this.fmt(off);
5834
5980
  q('.tune-off-desc').textContent = !off ? t('tuneOffsetZero') : t(off > 0 ? 'tuneAhead' : 'tuneBehind', { s: Math.abs(off).toFixed(1) + 's' });
5981
+ // A protected or cross-site picture cannot be copied (the browser forbids reading
5982
+ // it): instead of a black box the card shows that device's position in large type,
5983
+ // so the two can still be compared by time.
5835
5984
  const pic = (box, data, label, waiting) => {
5836
- const img = box.querySelector('img'), cap = box.querySelector('.tune-cap');
5837
- if (data && data.img) { img.src = data.img; img.style.visibility = 'visible'; }
5985
+ const img = box.querySelector('img'), cap = box.querySelector('.tune-cap'), ph = box.querySelector('.tune-ph');
5986
+ const hasImg = !!(data && data.img);
5987
+ if (hasImg) { img.src = data.img; img.style.visibility = 'visible'; }
5838
5988
  else img.style.visibility = 'hidden';
5839
- cap.textContent = label + (data ? ' · ' + formatTime(data.t || 0) : '') + (data && !data.img ? ' · ' + t('tuneNoPicture') : !data && waiting ? ' · ' + t('tuneWaiting') : '');
5989
+ ph.style.display = hasImg ? 'none' : '';
5990
+ const age = data ? Math.max(0, (Date.now() - (data.at || Date.now())) / 1000) : 0;
5991
+ ph.querySelector('.tune-ph-time').textContent = data ? formatTime((data.t || 0) + (data.playing ? age : 0)) : '··:··';
5992
+ ph.querySelector('.tune-ph-note').textContent = !data ? (waiting ? t('tuneWaiting') : '') : t('tuneNoPicture');
5993
+ cap.textContent = label + (data ? ' · ' + formatTime(data.t || 0) : '');
5840
5994
  };
5841
- pic(q('.tune-pic.mine'), this._mine, t('tuneMine'), false);
5995
+ pic(q('.tune-pic.mine'), this._mine ? { ...this._mine, at: this._mine.at || Date.now() } : null, t('tuneMine'), false);
5842
5996
  const p = this._peer && Date.now() - this._peer.at < 8000 ? this._peer : null;
5997
+ // Time comparison (works for protected pictures too).
5998
+ const diffEl = q('.tune-diff');
5999
+ if (p && this._mine) {
6000
+ const mineNow = (this._mine.t || 0) + (this._mine.playing ? (Date.now() - (this._mine.at || Date.now())) / 1000 : 0);
6001
+ const theirNow = (p.t || 0) + (p.playing ? (Date.now() - p.at) / 1000 : 0);
6002
+ const d = Math.round((mineNow - theirNow) * 10) / 10;
6003
+ diffEl.textContent = Math.abs(d) < 0.3 ? t('tuneDiffSame') : t(d > 0 ? 'tuneDiffAhead' : 'tuneDiffBehind', { s: Math.abs(d).toFixed(1) + 's', name: p.name });
6004
+ } else diffEl.textContent = '';
5843
6005
  pic(q('.tune-pic.theirs'), p, p ? p.name : (PRESENCE.others().length ? participantName(PRESENCE.others()[0]) : '—'), !!PRESENCE.others().length);
5844
6006
  const theirs = [...this._marks.values()].pop();
5845
6007
  q('.tune-marks').textContent = [this._myMark ? t('tuneMarkMine', { t: formatTime(this._myMark.t) }) : '', theirs ? t('tuneMarkTheirs', { name: theirs.name, t: formatTime(theirs.t) }) : ''].filter(Boolean).join(' · ');
@@ -5863,15 +6025,17 @@
5863
6025
  nudges.appendChild(b);
5864
6026
  });
5865
6027
  const tools = createEl('div', 'tune-tools');
5866
- const resync = createEl('button', 'btn', '🔄 ' + t('tuneResync'), { type: 'button' });
6028
+ const resync = createEl('button', 'btn tune-keep', '🔄 ' + t('tuneResync'), { type: 'button' });
5867
6029
  resync.onclick = () => uiElements.btnSyncStatus?.click();
5868
6030
  const reset = createEl('button', 'btn subtle', '↺ ' + t('tuneReset'), { type: 'button' });
5869
6031
  reset.onclick = () => this.set(0);
5870
- tools.append(resync, reset);
6032
+ tools.append(reset);
5871
6033
  const pics = createEl('div', 'tune-pics');
5872
6034
  ['mine', 'theirs'].forEach(k => {
5873
6035
  const box = createEl('div', 'tune-pic ' + k);
5874
- box.append(createEl('img', '', '', { alt: '' }), createEl('div', 'tune-cap'));
6036
+ const ph = createEl('div', 'tune-ph');
6037
+ ph.append(createEl('div', 'tune-ph-time', '··:··'), createEl('div', 'tune-ph-note'));
6038
+ box.append(createEl('img', '', '', { alt: '' }), ph, createEl('div', 'tune-cap'));
5875
6039
  pics.appendChild(box);
5876
6040
  });
5877
6041
  const markBtn = createEl('button', 'btn', t('tuneMarkBtn'), { type: 'button' });
@@ -5883,12 +6047,14 @@
5883
6047
  const autoApply = createEl('button', 'btn primary tune-auto-apply', t('tuneApply'), { type: 'button' });
5884
6048
  autoApply.onclick = () => { if (this._autoFound != null) this.set(this._autoFound); };
5885
6049
  const h = text => createEl('div', 'field-label', text);
5886
- body.append(
5887
- h(t('tuneOffset')), offRow, nudges, tools, createEl('div', 'trans-help', t('tuneHelp')),
5888
- h(t('tuneCompare')), pics,
6050
+ // Version tools (offset, same scene, automatic) only matter for different versions.
6051
+ const ver = createEl('div', 'tune-ver');
6052
+ ver.append(
6053
+ h(t('tuneOffset')), offRow, nudges, reset, createEl('div', 'trans-help', t('tuneHelp')),
5889
6054
  h(t('tuneMark')), createEl('div', 'trans-help', t('tuneMarkHint')), markBtn, createEl('div', 'tune-marks trans-help'), markApply,
5890
6055
  h(t('tuneAuto')), createEl('div', 'trans-help', t('tuneAutoHint')), autoBtn, createEl('div', 'tune-auto-msg trans-help'), autoApply
5891
6056
  );
6057
+ body.append(createEl('div', 'tune-src'), resync, h(t('tuneCompare')), pics, createEl('div', 'tune-diff'), ver);
5892
6058
  return body;
5893
6059
  }
5894
6060
  };
@@ -5981,8 +6147,10 @@
5981
6147
  // Sync timing keeps a short history of what was played while in a room (on a computer
5982
6148
  // all the time; on phones only once the timing panel was opened, to save battery).
5983
6149
  if (IS_TOP) setInterval(() => {
6150
+ try { TUNE.autoTick(); } catch (_) { }
5984
6151
  try {
5985
- const want = STATE.handshakeVerified && (!IS_TOUCH || TUNE._armedByUser) && !!(STATE.video || STATE.cinemaIframe);
6152
+ // Different versions need the history; same source does not.
6153
+ const want = STATE.handshakeVerified && (!IS_TOUCH || TUNE._armedByUser || TUNE.source().kind === 'different') && !!(STATE.video || STATE.cinemaIframe);
5986
6154
  if (want && !TUNE._armed) { TUNE._armed = true; TUNE.arm(true); }
5987
6155
  else if (!want && TUNE._armed) { TUNE._armed = false; TUNE.arm(false); }
5988
6156
  else if (want && STATE.video && TUNE._rec && TUNE._rec.v !== STATE.video) TUNE.arm(true);
@@ -6267,12 +6435,19 @@
6267
6435
  const PRESENCE = {
6268
6436
  seen: new Map(),
6269
6437
  STALE_MS: 25000,
6438
+ // A device that went quiet (screen off, app in the background) stays in the room as
6439
+ // "sleeping" until it says goodbye or has been silent this long; it comes back by itself.
6440
+ LONG_MS: 30 * 60 * 1000,
6441
+ left: new Set(),
6270
6442
  refresh() {
6271
6443
  const now = Date.now();
6272
6444
  STATE.presenceMap = {};
6445
+ STATE.sleepingMap = {};
6273
6446
  if (yPresence) yPresence.forEach((val, uid) => {
6274
6447
  if (!val) return;
6275
- if (uid === STATE.userId || now - (this.seen.get(uid) || 0) < this.STALE_MS) STATE.presenceMap[uid] = val;
6448
+ const age = now - (this.seen.get(uid) || 0);
6449
+ if (uid === STATE.userId || age < this.STALE_MS) STATE.presenceMap[uid] = val;
6450
+ else if (this.seen.has(uid) && age < this.LONG_MS && !this.left.has(uid)) STATE.sleepingMap[uid] = val;
6276
6451
  });
6277
6452
  if (STATE.role !== 'IDLE' && !STATE.presenceMap[STATE.userId]) STATE.presenceMap[STATE.userId] = { nick: STATE.nickname || '', color: STATE.color, viewer: !!STATE.isViewer };
6278
6453
  updatePresenceUI();
@@ -6446,17 +6621,20 @@
6446
6621
  // small mark for "watching only", "away" (screen off / other tab) and an outdated version.
6447
6622
  function roomRoster() {
6448
6623
  const safeColor = c => (/^#[0-9a-f]{3,8}$/i.test(String(c || '')) ? c : '#7c4dff');
6449
- const list = Object.entries(STATE.presenceMap || {}).map(([uid, p]) => {
6624
+ const entries = [...Object.entries(STATE.presenceMap || {}), ...Object.entries(STATE.sleepingMap || {}).map(([u, p]) => [u, { ...p, _sleep: true }])];
6625
+ const list = entries.map(([uid, p]) => {
6450
6626
  const self = uid === STATE.userId;
6451
6627
  return {
6452
6628
  uid, self,
6453
6629
  name: self ? (STATE.nickname || t('you')) : (p?.nick || 'ID:' + String(uid).slice(0, 3)),
6454
6630
  color: safeColor(self ? STATE.color : p?.color),
6455
6631
  viewer: self ? !!STATE.isViewer : !!p?.viewer,
6456
- av: safeEmoji(self ? PROFILE.avatar() : p?.av),
6632
+ av: safeAvatar(self ? PROFILE.avatar() : p?.av),
6633
+ img: AVATAR_IMG.get(uid),
6457
6634
  st: String((self ? PROFILE.status() : p?.st) || '').slice(0, 40),
6458
6635
  muted: !self && SAFETY.muted.has(uid),
6459
- away: !self && !!p?.hid,
6636
+ away: !self && (!!p?.hid || !!p?._sleep),
6637
+ sleeping: !self && !!p?._sleep,
6460
6638
  oldVer: !self && !!(p?.v && p.v !== NXU_VERSION)
6461
6639
  };
6462
6640
  });
@@ -6465,23 +6643,27 @@
6465
6643
  }
6466
6644
  function renderRoster(box, max = 4) {
6467
6645
  const list = roomRoster();
6468
- const sig = max + '|' + list.map(m => [m.uid, m.name, m.color, m.viewer, m.away, m.oldVer, m.av, m.st, m.muted].join(',')).join(';');
6646
+ const issue = STATE.handshakeVerified && STATE.connectionMode !== 'WEBRTC_P2P' && typeof relayAlive === 'function' && !relayAlive();
6647
+ const sig = max + '|' + issue + '|' + list.map(m => [m.uid, m.name, m.color, m.viewer, m.away, m.sleeping, m.oldVer, m.av, m.img.length, m.st, m.muted].join(',')).join(';');
6469
6648
  if (box._rosterSig === sig) return list;
6470
6649
  box._rosterSig = sig;
6471
6650
  box.replaceChildren();
6651
+ // This device lost the room's channel: say so plainly (it reconnects by itself).
6652
+ if (issue) box.appendChild(createEl('span', 'nx-who warn', '⚠️ ' + t('whoReconnecting')));
6472
6653
  list.slice(0, max).forEach(m => {
6473
6654
  const chip = createEl('span', 'nx-who' + (m.away ? ' away' : '') + (m.self ? ' me' : ''));
6474
6655
  const dot = createEl('i', 'nx-who-dot');
6475
6656
  dot.style.background = m.color;
6476
- chip.append(dot);
6477
- if (m.av) chip.append(createEl('span', 'nx-who-av', m.av));
6657
+ if (m.img) { const im = createEl('img', 'nx-who-img', '', { alt: '' }); im.src = m.img; im.style.borderColor = m.color; chip.append(im); }
6658
+ else chip.append(dot);
6659
+ if (m.av && !m.img) chip.append(createEl('span', 'nx-who-av', m.av));
6478
6660
  chip.append(createEl('span', 'nx-who-name', m.name + (m.self && STATE.nickname ? ' ' + t('meTag') : '')));
6479
6661
  if (m.muted) chip.append(createEl('span', 'nx-who-tag', '🔇'));
6480
6662
  if (m.st && max > 4) chip.append(createEl('span', 'nx-who-st', m.st));
6481
6663
  if (m.viewer) chip.append(createEl('span', 'nx-who-tag', '👀'));
6482
6664
  if (m.away) chip.append(createEl('span', 'nx-who-tag', '💤'));
6483
6665
  if (m.oldVer) chip.append(createEl('span', 'nx-who-tag', '⚠️'));
6484
- chip.title = [m.name, m.st, m.viewer && t('whoViewer'), m.away && t('whoAway'), m.oldVer && t('whoOldVer')].filter(Boolean).join(' · ');
6666
+ chip.title = [m.name, m.st, m.viewer && t('whoViewer'), m.sleeping ? t('whoSleeping') : m.away && t('whoAway'), m.oldVer && t('whoOldVer')].filter(Boolean).join(' · ');
6485
6667
  box.appendChild(chip);
6486
6668
  });
6487
6669
  if (list.length > max) box.appendChild(createEl('span', 'nx-who more', '+' + (list.length - max)));
@@ -6612,130 +6794,9 @@
6612
6794
  }
6613
6795
  }
6614
6796
 
6615
- // ───────────────────────── Bookmark library (every site, kept in the userscript manager)
6616
- // Each bookmark remembers the page, the moment and the title; opening one goes back to
6617
- // that page and that moment. A live stream has no moment to return to: its bookmark
6618
- // plays the stream right away (the stream's own address when the page exposed one).
6619
- const LIBRARY = {
6620
- KEY: 'nxu_bm_lib',
6621
- MAX: 400,
6622
- pageUrl() { return location.href.split('#')[0]; },
6623
- all() { const v = STORE.get(this.KEY, []); return Array.isArray(v) ? v.filter(b => b && typeof b.url === 'string' && /^https?:/i.test(b.url)) : []; },
6624
- save(list) { STORE.set(this.KEY, list.slice(0, this.MAX)); },
6625
- // The stream address of a live channel, when the page loaded one directly (HLS / DASH).
6626
- streamUrl(info) {
6627
- try {
6628
- const v = info?.kind === 'video' ? info.el : null;
6629
- const src = v?.currentSrc || '';
6630
- if (/^https?:/i.test(src)) return src;
6631
- const hits = performance.getEntriesByType('resource').map(r => r.name).filter(n => /\.(m3u8|mpd)(\?|$)/i.test(n));
6632
- return hits.length ? hits[hits.length - 1] : '';
6633
- } catch (_) { return ''; }
6634
- },
6635
- add(info) {
6636
- const live = !!info.live;
6637
- const title = String(document.title || HOST).replace(/\s+/g, ' ').trim().slice(0, 120);
6638
- const entry = {
6639
- id: Date.now().toString(36) + Math.random().toString(36).slice(2, 6),
6640
- url: this.pageUrl(), host: HOST, title, live,
6641
- time: live ? 0 : Math.max(0, Math.round((info.time || 0) * 10) / 10),
6642
- dur: Number.isFinite(info.duration) ? Math.round(info.duration) : 0,
6643
- stream: live ? this.streamUrl(info).slice(0, 600) : '',
6644
- ts: Date.now()
6645
- };
6646
- const list = this.all().filter(b => !(b.url === entry.url && Math.abs((b.time || 0) - entry.time) < 2 && !!b.live === live));
6647
- list.unshift(entry);
6648
- this.save(list);
6649
- return entry;
6650
- },
6651
- remove(id) { this.save(this.all().filter(b => b.id !== id)); },
6652
- // Opening: on this page it simply jumps; elsewhere the moment is handed to the page
6653
- // that opens (through the manager's storage, so no address is changed).
6654
- open(b, newTab = false) {
6655
- if (b.url === this.pageUrl() && !newTab) {
6656
- if (b.live) { JUMP.playLive(); return; }
6657
- seekMedia(b.time); showToast(t('bmJumped', { time: formatTime(b.time) }));
6658
- return;
6659
- }
6660
- STORE.set('nxu_pending_jump', { url: b.url, time: b.time, live: !!b.live, at: Date.now() });
6661
- showToast(t('bmOpening'));
6662
- const target = b.live && b.stream && /\.(mp4|webm|m3u8)(\?|$)/i.test(b.stream) && /iP(hone|ad|od)|Macintosh.*Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) ? b.stream : b.url;
6663
- if (newTab) window.open(target, '_blank', 'noopener');
6664
- else location.href = target;
6665
- }
6666
- };
6667
- // Applies a bookmark opened from the library once this page's media is ready.
6668
- const JUMP = {
6669
- _pending: null,
6670
- init() {
6671
- if (!IS_TOP) return;
6672
- const p = STORE.get('nxu_pending_jump', null);
6673
- if (!p || typeof p.url !== 'string' || Date.now() - (p.at || 0) > 120000) return;
6674
- if (p.url !== LIBRARY.pageUrl()) return;
6675
- STORE.set('nxu_pending_jump', null);
6676
- this._pending = { ...p, until: Date.now() + 60000 };
6677
- },
6678
- playLive() {
6679
- const v = STATE.video;
6680
- try { if (v) { v.muted = false; MEDIA_SAFE.play(v); } else applyMediaCommand('play'); } catch (_) { }
6681
- if (!STATE.isCinema) try { CINEMA.set(true, { silent: true }); } catch (_) { }
6682
- showToast(t('bmLiveOpened'));
6683
- },
6684
- tick() {
6685
- const p = this._pending;
6686
- if (!p) return;
6687
- if (Date.now() > p.until) { this._pending = null; return; }
6688
- const info = currentMediaInfo();
6689
- if (!info) return;
6690
- if (info.kind === 'video' && info.el.readyState < 1) return;
6691
- this._pending = null;
6692
- if (p.live) { this.playLive(); return; }
6693
- seekMedia(p.time);
6694
- try { if (info.kind === 'video' && info.paused) MEDIA_SAFE.play(info.el); } catch (_) { }
6695
- showToast(t('bmJumped', { time: formatTime(p.time) }));
6696
- }
6697
- };
6698
- function buildBookmarkPanel() {
6699
- const body = createEl('div', 'manual-body nx-bm');
6700
- const addBtn = createEl('button', 'btn primary', '📌 ' + t('bmAddHere'), { type: 'button', id: 'nxu-bm-add' });
6701
- const search = createEl('input', 'nx-compose-input nx-bm-search', '', { type: 'search', placeholder: t('bmSearch'), autocomplete: 'off' });
6702
- const list = createEl('div', 'nx-bm-list');
6703
- const render = () => {
6704
- const q = search.value.trim().toLowerCase();
6705
- const here = LIBRARY.pageUrl();
6706
- addBtn.style.display = currentMediaInfo() ? '' : 'none';
6707
- const items = LIBRARY.all().filter(b => !q || (b.title + ' ' + b.host).toLowerCase().includes(q));
6708
- if (!items.length) { list.replaceChildren(createEl('div', 'trans-help', t('bmEmpty'))); return; }
6709
- list.replaceChildren(...items.map(b => {
6710
- const row = createEl('div', 'nx-bm-item');
6711
- const link = createEl('a', 'nx-bm-link', '', { href: b.url, rel: 'noopener', title: b.url });
6712
- const when = b.live ? createEl('span', 'nx-bm-live', '● ' + t('bmLive')) : createEl('span', 'nx-bm-time', formatTime(b.time) + (b.dur ? ' / ' + formatTime(b.dur) : ''));
6713
- const meta = createEl('span', 'nx-bm-meta', (b.url === here ? t('bmThisPage') : b.host) + ' · ' + new Date(b.ts).toLocaleDateString());
6714
- link.append(when, createEl('span', 'nx-bm-title', b.title || b.host), meta);
6715
- link.addEventListener('click', (ev) => {
6716
- ev.preventDefault(); ev.stopPropagation();
6717
- LIBRARY.open(b, ev.ctrlKey || ev.metaKey || ev.button === 1);
6718
- });
6719
- const copy = createEl('button', 'nx-bm-act', '🔗', { type: 'button', title: t('bmCopy') });
6720
- copy.onclick = (ev) => { ev.stopPropagation(); try { navigator.clipboard.writeText(b.live && b.stream ? b.stream : b.url); showToast(t('bmCopied')); } catch (_) { } };
6721
- const del = createEl('button', 'nx-bm-act', '✕', { type: 'button', title: t('bmDelete') });
6722
- del.onclick = (ev) => { ev.stopPropagation(); LIBRARY.remove(b.id); render(); };
6723
- row.append(link, copy, del);
6724
- return row;
6725
- }));
6726
- };
6727
- addBtn.onclick = () => { addBookmark(); render(); };
6728
- search.addEventListener('input', render);
6729
- search.addEventListener('keydown', (e) => e.stopPropagation());
6730
- body.append(addBtn, search, list);
6731
- body.render = render;
6732
- return body;
6733
- }
6734
-
6735
6797
  function addBookmark(label = '') {
6736
6798
  const info = currentMediaInfo();
6737
6799
  if (!info) { showToast(t('noVideo')); return; }
6738
- try { LIBRARY.add(info); } catch (_) { }
6739
6800
  const bm = { time: info.time || 0, label, color: STATE.color, userId: STATE.userId, ts: Date.now() };
6740
6801
  if (ydoc && yBookmarks && STATE.handshakeVerified) yBookmarks.push([bm]);
6741
6802
  else { STATE.bookmarks.push(bm); renderBookmarkPins(); }
@@ -7318,7 +7379,26 @@
7318
7379
  const status = createEl('input', 'nx-compose-input nx-status-input', '', { type: 'text', maxlength: '40', placeholder: t('setStatusPh'), autocomplete: 'off' });
7319
7380
  status.value = PROFILE.status();
7320
7381
  status.addEventListener('input', () => PROFILE.setStatus(status.value));
7321
- prof.append(createEl('div', 'field-label', t('setAvatar')), avRow, createEl('div', 'field-label', t('setStatus')), status);
7382
+ const preview = createEl('div', 'nx-av-preview');
7383
+ const paintPreview = () => {
7384
+ const img = PROFILE.image();
7385
+ preview.style.backgroundImage = img ? `url("${img}")` : '';
7386
+ preview.textContent = img ? '' : (PROFILE.avatar() || (STATE.nickname || '?').slice(0, 1).toUpperCase());
7387
+ paintAv();
7388
+ };
7389
+ const avCustom = createEl('input', 'nx-compose-input nx-av-input', '', { type: 'text', maxlength: '8', placeholder: t('setAvatarCustom'), autocomplete: 'off' });
7390
+ avCustom.value = PROFILE.avatar() && !PROFILE.AVATARS.includes(PROFILE.avatar()) ? PROFILE.avatar() : '';
7391
+ avCustom.addEventListener('input', () => { const a = safeAvatar(avCustom.value); if (a || !avCustom.value.trim()) { PROFILE.setImage(''); PROFILE.setAvatar(a); paintPreview(); } });
7392
+ avCustom.addEventListener('keydown', (ev) => ev.stopPropagation());
7393
+ const photoBtn = createEl('button', 'btn subtle', '🖼 ' + t('setAvatarPhoto'), { type: 'button' });
7394
+ photoBtn.onclick = () => { PROFILE._onImage = paintPreview; PROFILE.pickImage(); };
7395
+ const clearBtn = createEl('button', 'btn subtle', '✕', { type: 'button', title: t('setAvatarClear') });
7396
+ clearBtn.onclick = () => { PROFILE.setImage(''); PROFILE.setAvatar(''); avCustom.value = ''; paintPreview(); };
7397
+ const customRow = createEl('div', 'nx-av-custom');
7398
+ customRow.append(preview, avCustom, photoBtn, clearBtn);
7399
+ avRow.querySelectorAll('.nx-av').forEach(b => b.addEventListener('click', () => { PROFILE.setImage(''); avCustom.value = ''; paintPreview(); }));
7400
+ paintPreview();
7401
+ prof.append(createEl('div', 'field-label', t('setAvatar')), customRow, avRow, createEl('div', 'field-label', t('setStatus')), status);
7322
7402
  // My reactions
7323
7403
  const reac = section('😀', t('setReactions'));
7324
7404
  const slots = createEl('div', 'nx-react-slots');
@@ -7334,15 +7414,22 @@
7334
7414
  const pal = createEl('div', 'nx-react-pal');
7335
7415
  PALETTE.forEach(em => {
7336
7416
  const b = createEl('button', 'nx-react-pick', em, { type: 'button' });
7337
- b.onclick = (ev) => { ev.stopPropagation(); if (REACTIONS.set(pick, em)) { pick = (pick + 1) % 8; paintSlots(); } };
7417
+ b.onclick = (ev) => { ev.stopPropagation(); if (REACTIONS.set(pick, em)) { pick = (pick + 1) % REACTIONS.list().length; paintSlots(); } };
7338
7418
  pal.appendChild(b);
7339
7419
  });
7340
7420
  const custom = createEl('input', 'nx-compose-input nx-react-custom', '', { type: 'text', maxlength: '16', placeholder: t('setEmojiPh'), autocomplete: 'off' });
7341
- custom.addEventListener('input', () => { if (REACTIONS.set(pick, custom.value)) { custom.value = ''; pick = (pick + 1) % 8; paintSlots(); } });
7421
+ custom.addEventListener('input', () => { if (REACTIONS.set(pick, custom.value)) { custom.value = ''; pick = (pick + 1) % REACTIONS.list().length; paintSlots(); } });
7422
+ custom.addEventListener('keydown', (ev) => ev.stopPropagation());
7342
7423
  const resetBtn = createEl('button', 'btn subtle', '↺ ' + t('setReactionsReset'), { type: 'button' });
7343
7424
  resetBtn.onclick = () => { REACTIONS.reset(); pick = 0; paintSlots(); };
7425
+ const slotRow = createEl('div', 'nx-slot-row');
7426
+ const addSlot = createEl('button', 'btn subtle', t('setSlotAdd'), { type: 'button' });
7427
+ addSlot.onclick = () => { const i = REACTIONS.add(); if (i >= 0) pick = i; paintSlots(); };
7428
+ const delSlot = createEl('button', 'btn subtle', t('setSlotRemove'), { type: 'button' });
7429
+ delSlot.onclick = () => { if (REACTIONS.remove(pick)) pick = Math.min(pick, REACTIONS.list().length - 1); paintSlots(); };
7430
+ slotRow.append(addSlot, delSlot);
7344
7431
  paintSlots();
7345
- reac.append(slots, createEl('div', 'trans-help', t('setReactionsHint')), pal, custom, resetBtn);
7432
+ reac.append(slots, slotRow, createEl('div', 'trans-help', t('setReactionsHint')), pal, custom, resetBtn);
7346
7433
  // Playback
7347
7434
  const play = section('🎬', t('setPlayback'));
7348
7435
  play.append(parts.autoCinema, parts.adGuard, toggle(t('setAutoNext'), () => NEXT_EP.enabled(), on => STORE.set('nxu_auto_next', on)));
@@ -7366,7 +7453,7 @@
7366
7453
  tog.append(createEl('div', 'field-label', t('setPeople')), people, createEl('div', 'trans-help', t('setMutedHint')));
7367
7454
  // Advanced
7368
7455
  const adv = section('🔧', t('setAdvanced'));
7369
- adv.append(parts.subLog, parts.debug, parts.idleRow, parts.hideSite);
7456
+ adv.append(parts.chatLog, parts.subLog, parts.debug, parts.idleRow, parts.hideSite);
7370
7457
  body.refreshPeople = paintPeople;
7371
7458
  return body;
7372
7459
  }
@@ -7607,11 +7694,17 @@
7607
7694
  .presence-pill.open .nx-who { max-width:none; }
7608
7695
  .nx-who.me { background:rgba(255,255,255,0.18); }
7609
7696
  .nx-who.away { opacity:0.55; }
7697
+ .nx-who.warn { background:rgba(255,170,0,0.28); }
7610
7698
  .nx-who.more { padding:2px 7px; }
7611
7699
  .nx-who-dot { flex:none; width:8px; height:8px; border-radius:50%; box-shadow:0 0 5px currentColor; }
7612
7700
  .nx-who-name { overflow:hidden; text-overflow:ellipsis; }
7613
7701
  .nx-who-tag { font-size:10px; }
7614
7702
  .nx-who-av { font-size:12px; line-height:1; }
7703
+ .nx-who-img { width:16px; height:16px; border-radius:50%; object-fit:cover; border:1.5px solid; flex:none; }
7704
+ .nx-av-preview { width:44px; height:44px; border-radius:50%; background:rgba(255,255,255,0.1) center/cover; display:grid; place-items:center; font-size:22px; font-weight:800; border:2px solid var(--accent); flex:none; }
7705
+ .nx-av-custom { display:flex; gap:6px; align-items:center; }
7706
+ .nx-av-custom .nx-compose-input { flex:1; }
7707
+ .nx-av-custom .btn { width:auto; }
7615
7708
  .nx-who-st { font-weight:500; opacity:0.7; margin-left:4px; overflow:hidden; text-overflow:ellipsis; }
7616
7709
  .nx-talk-avatar.emoji { background:rgba(255,255,255,0.12) !important; font-size:16px; }
7617
7710
  .dock { position:absolute; background:var(--glass-strong); border-radius:16px; padding:10px; display:flex; flex-direction:column; gap:6px; pointer-events:none; opacity:0; border:1px solid rgba(255,255,255,0.1);
@@ -7630,9 +7723,12 @@
7630
7723
  border:1px solid rgba(255,255,255,0.18); overflow:hidden; box-shadow:0 15px 40px rgba(0,0,0,0.6); z-index:105; transition:opacity 0.4s ease;
7631
7724
  width:min(420px, calc(100vw - 24px)); width:min(420px, calc(100cqw - 24px)); max-height:calc(100vh - 24px); max-height:calc(100cqh - 24px); }
7632
7725
  #chat-panel, #sub-log-panel, #debug-panel { height:min(520px, calc(100vh - 24px)); height:min(520px, calc(100cqh - 24px)); }
7633
- #manual-modal, #trans-modal, #settings-modal, #bm-panel, #tune-panel, #os-panel { overflow-y:auto; }
7726
+ /* The window stays put and its body scrolls, so the resize grip stays in the corner
7727
+ (it used to scroll away with long content, e.g. every Settings section open). */
7728
+ #manual-modal, #trans-modal, #settings-modal, #tune-panel, #os-panel { overflow:hidden; }
7729
+ #manual-modal > .manual-body, #trans-modal > .manual-body, #settings-modal > .manual-body, #tune-panel > .manual-body, #os-panel > .manual-body { flex:1 1 auto; min-height:0; overflow-y:auto; overscroll-behavior:contain; }
7634
7730
  /* Windows you read and fill in stay legible over a busy picture. */
7635
- #manual-modal, #trans-modal, #settings-modal, #bm-panel, #tune-panel, #os-panel, #debug-panel { background:rgba(16,20,26,0.9); }
7731
+ #manual-modal, #trans-modal, #settings-modal, #tune-panel, #os-panel, #debug-panel { background:rgba(16,20,26,0.9); }
7636
7732
  .drag-header { background:rgba(0,0,0,0.3); padding:10px 14px; font-size:13px; color:#eee; font-weight:700; cursor:grab; display:flex; justify-content:space-between; align-items:center; border-bottom:1px solid rgba(255,255,255,0.06); user-select:none; touch-action:none; flex:0 0 auto; }
7637
7733
  .header-controls { display:flex; gap:10px; align-items:center; }
7638
7734
  .pin-btn, .close-btn { background:transparent; border:none; cursor:pointer; color:#fff; font-size:15px; line-height:1; padding:0; opacity:0.6; }
@@ -7686,6 +7782,8 @@
7686
7782
  /* NexusSync subtitles: soft plate, generous line height, clear of the controls. */
7687
7783
  .nx-xsub { position:absolute; left:50%; bottom:9%; transform:translateX(-50%); width:min(92%, 1100px); display:flex; flex-direction:column; align-items:center; gap:4px; z-index:66; pointer-events:none; opacity:0; transition:opacity 0.18s ease, bottom 0.3s ease; --xs:1; }
7688
7784
  .nx-xsub.on { opacity:1; }
7785
+ .nx-xsub-line.l1 { color:#ffe98a; }
7786
+ .nx-xsub-line.l2 { color:#9be7ff; font-size:calc(clamp(13px, 2.2cqw, 28px) * var(--xs)); }
7689
7787
  .nexus-container.cinema-nexus:not(.chrome-idle) .nx-xsub { bottom:calc(104px + env(safe-area-inset-bottom, 0px)); }
7690
7788
  .nx-xsub-line { display:inline-block; max-width:100%; padding:0.12em 0.55em; border-radius:0.35em; background:rgba(8,10,14,0.62); color:#fff; text-align:center; white-space:pre-line; overflow-wrap:anywhere;
7691
7789
  font:600 calc(clamp(15px, 2.6cqw, 34px) * var(--xs)) / 1.32 system-ui, -apple-system, "Apple SD Gothic Neo", "Pretendard", "Segoe UI", sans-serif; letter-spacing:0.01em; text-shadow:0 1px 2px rgba(0,0,0,0.85), 0 0 8px rgba(0,0,0,0.35); }
@@ -7699,6 +7797,11 @@
7699
7797
  .cc-menu-note { font-size:11.5px; opacity:0.6; padding:4px 10px 6px; max-width:240px; }
7700
7798
  .os-body { gap:8px; }
7701
7799
  .os-row { display:grid; grid-template-columns:1fr 1fr 1.4fr; gap:6px; }
7800
+ .os-tmdb { display:flex; flex-wrap:wrap; gap:5px; align-items:center; }
7801
+ .os-tmdb:empty { display:none; }
7802
+ .os-tmdb-label { font-size:10.5px; font-weight:800; opacity:0.6; letter-spacing:0.5px; }
7803
+ .os-chip { border:1px solid rgba(255,255,255,0.16); border-radius:99px; padding:4px 10px; background:rgba(255,255,255,0.06); color:inherit; font:inherit; font-size:12px; cursor:pointer; }
7804
+ .os-chip.on { border-color:var(--accent); background:var(--glass-active); }
7702
7805
  .os-results { display:flex; flex-direction:column; gap:4px; max-height:min(46vh, 380px); overflow-y:auto; }
7703
7806
  .os-item { display:flex; flex-direction:column; align-items:flex-start; gap:2px; text-align:left; padding:8px 10px; border-radius:10px; border:0; background:rgba(255,255,255,0.06); color:inherit; font:inherit; cursor:pointer; }
7704
7807
  .os-item:hover { background:rgba(255,255,255,0.12); }
@@ -7706,6 +7809,12 @@
7706
7809
  .os-name { font-size:12.5px; font-weight:700; word-break:break-all; }
7707
7810
  .os-meta { font-size:11px; opacity:0.65; }
7708
7811
  .tune-body { gap:7px; }
7812
+ .tune-src { padding:8px 10px; border-radius:10px; font-size:12.5px; font-weight:700; background:rgba(255,255,255,0.08); }
7813
+ .tune-src[data-kind="same"] { background:rgba(0,230,118,0.16); }
7814
+ .tune-src[data-kind="different"] { background:rgba(255,202,40,0.18); }
7815
+ /* Same source: the room's own frame-level sync does it all; the version tools step back. */
7816
+ .tune-ver { display:flex; flex-direction:column; gap:7px; }
7817
+ .tune-body.same .tune-ver { display:none; }
7709
7818
  .tune-off { display:flex; align-items:baseline; gap:10px; }
7710
7819
  .tune-off-val { font-size:24px; font-weight:800; font-variant-numeric:tabular-nums; color:var(--accent); }
7711
7820
  .tune-off-desc { font-size:12px; opacity:0.75; }
@@ -7715,6 +7824,10 @@
7715
7824
  .tune-pics { display:grid; grid-template-columns:1fr 1fr; gap:6px; }
7716
7825
  .tune-pic { position:relative; aspect-ratio:16/9; border-radius:10px; overflow:hidden; background:#000; border:1px solid rgba(255,255,255,0.12); }
7717
7826
  .tune-pic img { width:100%; height:100%; object-fit:cover; display:block; }
7827
+ .tune-ph { position:absolute; inset:0; display:flex; flex-direction:column; align-items:center; justify-content:center; gap:4px; background:linear-gradient(135deg, #1d2430, #11151c); text-align:center; padding:6px; }
7828
+ .tune-ph-time { font-size:22px; font-weight:800; font-variant-numeric:tabular-nums; letter-spacing:0.5px; }
7829
+ .tune-ph-note { font-size:10.5px; opacity:0.65; line-height:1.3; }
7830
+ .tune-diff { font-size:12.5px; font-weight:700; text-align:center; min-height:16px; }
7718
7831
  .tune-cap { position:absolute; left:0; right:0; bottom:0; padding:3px 6px; font-size:11px; font-weight:700; background:linear-gradient(transparent, rgba(0,0,0,0.75)); }
7719
7832
  .nx-bm { gap:8px; }
7720
7833
  .nx-bm-list { display:flex; flex-direction:column; gap:5px; max-height:min(52vh, 420px); overflow-y:auto; }
@@ -7739,6 +7852,7 @@
7739
7852
  .nx-av, .nx-react-pick { width:34px; height:34px; border-radius:9px; border:1px solid rgba(255,255,255,0.12); background:rgba(255,255,255,0.06); font-size:18px; cursor:pointer; padding:0; color:inherit; }
7740
7853
  .nx-av.on { border-color:var(--accent); background:var(--glass-active); }
7741
7854
  .nx-react-slots { display:grid; grid-template-columns:repeat(8, 1fr); gap:4px; }
7855
+ .nx-slot-row { display:grid; grid-template-columns:1fr 1fr; gap:6px; }
7742
7856
  .nx-react-slot { height:40px; border-radius:10px; border:1px solid rgba(255,255,255,0.14); background:rgba(255,255,255,0.08); font-size:20px; cursor:pointer; padding:0; }
7743
7857
  .nx-react-slot.on { border-color:var(--accent); box-shadow:0 0 0 2px rgba(0,230,118,0.35); }
7744
7858
  .nx-people { display:flex; flex-direction:column; gap:4px; }
@@ -8034,8 +8148,10 @@
8034
8148
  .cc-btn:hover { background:rgba(255,255,255,0.14); }
8035
8149
  .cc-btn:active { transform:scale(0.92); }
8036
8150
  .cc-btn:focus-visible { outline:2px solid var(--cc-accent); outline-offset:1px; }
8037
- .cc-btn.on { color:var(--cc-accent); }
8038
- .cc-btn.on::after { content:''; position:absolute; left:50%; bottom:5px; width:14px; height:2px; margin-left:-7px; border-radius:1px; background:var(--cc-accent); }
8151
+ /* On / off at a glance: an "on" button gets the accent colour, a tinted pill and a bar. */
8152
+ .cc-btn.on { color:var(--cc-accent); background:color-mix(in srgb, var(--cc-accent) 22%, transparent); }
8153
+ .cc-btn.on::after { content:''; position:absolute; left:50%; bottom:3px; width:16px; height:3px; margin-left:-8px; border-radius:2px; background:var(--cc-accent); box-shadow:0 0 6px var(--cc-accent); }
8154
+ .cc-btn:not(.on) { opacity:0.92; }
8039
8155
  .cc-sub.on::after { display:none; }
8040
8156
  .cc-rate { min-width:46px; font-variant-numeric:tabular-nums; font-size:13px; }
8041
8157
  .cc-rate.on { color:#fff; background:rgba(0,230,118,0.22); }
@@ -8208,6 +8324,7 @@
8208
8324
  const btnChat = mk('', '💬 ' + t('talkMenu'));
8209
8325
  const btnTranslate = mk('', '🌐 ' + t('aiSub'), t('aiSubTitle'));
8210
8326
  const btnSubLog = mk('', '📝 ' + t('subLog'));
8327
+ const btnChatLog = mk('nxu-chat-log', '💬 ' + t('chatLog'));
8211
8328
  const btnDebug = mk('', '🐛 ' + t('debug'));
8212
8329
  const btnHideSite = createEl('button', 'btn subtle', '🙈 ' + t('hideOnSite'), { title: t('hideOnSiteTitle') });
8213
8330
  const btnSettings = mk('nxu-settings', '⚙️ ' + t('settings'));
@@ -8217,7 +8334,7 @@
8217
8334
  // Chat panel
8218
8335
  const chatPanel = createEl('div', 'window-frame');
8219
8336
  chatPanel.id = 'chat-panel';
8220
- const chatHeader = createWindowHeader('💬 ' + t('roomChat'), [{ className: 'close-btn chat-tr-btn', text: '🌐', title: t('chatTrOn') }, { className: 'close-btn chat-close-btn', text: '✖' }]);
8337
+ const chatHeader = createWindowHeader('💬 ' + t('chatLog'), [{ className: 'close-btn chat-tr-btn', text: '🌐', title: t('chatTrOn') }, { className: 'close-btn chat-export-btn', text: '💾', title: t('export') }, { className: 'close-btn chat-clear-btn', text: '🧹', title: t('clear') }, { className: 'close-btn chat-close-btn', text: '✖' }]);
8221
8338
  const chatMessages = createEl('div');
8222
8339
  chatMessages.id = 'chat-messages';
8223
8340
  const nickRow = createEl('div', 'nick-row');
@@ -8246,7 +8363,9 @@
8246
8363
  quickRow.appendChild(chip);
8247
8364
  });
8248
8365
  const chatJumpBtn = createEl('button', 'jump-btn', '↓ ' + t('newMessages'));
8249
- chatPanel.append(chatHeader, nickRow, chatMessages, typingRow, quickRow, chatInputArea, chatJumpBtn);
8366
+ // The chat window is a history (like the subtitle log): reading, translating, saving.
8367
+ // Writing happens in the speech bubbles (💬 in the reaction bar, or Enter).
8368
+ chatPanel.append(chatHeader, chatMessages, typingRow, chatJumpBtn);
8250
8369
 
8251
8370
  // Subtitle history panel
8252
8371
  const subLogPanel = createEl('div', 'window-frame');
@@ -8320,18 +8439,12 @@
8320
8439
  const osHeader = createWindowHeader('💬 ' + t('osTitle'), [{ className: 'close-btn', text: '✖' }]);
8321
8440
  osPanel.append(osHeader, OPENSUBS.build());
8322
8441
 
8323
- // Bookmarks (every site)
8324
- const bmPanel = createEl('div', 'window-frame');
8325
- bmPanel.id = 'bm-panel';
8326
- const bmHeader = createWindowHeader('📌 ' + t('bmLibrary'), [{ className: 'close-btn', text: '✖' }]);
8327
- const bmBody = buildBookmarkPanel();
8328
- bmPanel.append(bmHeader, bmBody);
8329
8442
 
8330
8443
  // Settings (things that are set once live here, not in the menu)
8331
8444
  const settingsModal = createEl('div', 'window-frame');
8332
8445
  settingsModal.id = 'settings-modal';
8333
8446
  const settingsHeader = createWindowHeader('⚙️ ' + t('settings'), [{ className: 'close-btn', text: '✖' }]);
8334
- const settingsBody = buildSettingsPanel({ autoCinema: btnAutoCinema, adGuard: btnAdGuard, subLog: btnSubLog, debug: btnDebug, idleRow, hideSite: btnHideSite });
8447
+ const settingsBody = buildSettingsPanel({ autoCinema: btnAutoCinema, adGuard: btnAdGuard, subLog: btnSubLog, chatLog: btnChatLog, debug: btnDebug, idleRow, hideSite: btnHideSite });
8335
8448
  settingsModal.append(settingsHeader, settingsBody);
8336
8449
 
8337
8450
  const drawCanvas = createEl('canvas');
@@ -8343,9 +8456,9 @@
8343
8456
  // Sketching and chat live in the reaction bar (🖍️ 💬); the menu does not repeat them.
8344
8457
  // The menu keeps only what is used while watching; speed and PiP live in the cinema
8345
8458
  // controls, and everything that is set once lives in ⚙️ Settings.
8346
- dock.append(btnFindMedia, btnLink, btnInvite, btnTune, btnCinema, btnBookmark, btnTranslate, btnSettings);
8459
+ dock.append(btnFindMedia, btnLink, btnInvite, btnTune, btnCinema, btnTranslate, btnSettings);
8347
8460
  uiWrapper.append(dock, reactPill, fab);
8348
- nexusContainer.append(drawCanvas, uiWrapper, chatPanel, subLogPanel, manualModal, transModal, settingsModal, bmPanel, tunePanel, osPanel, toast, debugPanel);
8461
+ nexusContainer.append(drawCanvas, uiWrapper, chatPanel, subLogPanel, manualModal, transModal, settingsModal, tunePanel, osPanel, toast, debugPanel);
8349
8462
  shadow.appendChild(nexusContainer);
8350
8463
  promoteHost();
8351
8464
 
@@ -8365,9 +8478,9 @@
8365
8478
  attachJumpLogic(subLogMessages, subLogJumpBtn);
8366
8479
  attachJumpLogic(debugContent, debugJumpBtn);
8367
8480
  makeDraggable(uiWrapper, fab);
8368
- [[chatPanel, chatHeader], [subLogPanel, subLogHeader], [manualModal, manualHeader], [transModal, transHeader], [settingsModal, settingsHeader], [bmPanel, bmHeader], [tunePanel, tuneHeader], [osPanel, osHeader], [debugPanel, debugHeader]]
8481
+ [[chatPanel, chatHeader], [subLogPanel, subLogHeader], [manualModal, manualHeader], [transModal, transHeader], [settingsModal, settingsHeader], [tunePanel, tuneHeader], [osPanel, osHeader], [debugPanel, debugHeader]]
8369
8482
  .forEach(([panel, header]) => makePanelDraggable(panel, header));
8370
- [chatPanel, subLogPanel, debugPanel, transModal, settingsModal, bmPanel, tunePanel, osPanel].forEach(panel => PANEL_SIZE.attach(panel));
8483
+ [chatPanel, subLogPanel, debugPanel, transModal, settingsModal, tunePanel, osPanel].forEach(panel => PANEL_SIZE.attach(panel));
8371
8484
 
8372
8485
  shadow.querySelectorAll('.window-frame').forEach(panel => {
8373
8486
  const pinBtn = panel.querySelector('.pin-btn');
@@ -8385,6 +8498,23 @@
8385
8498
  chatMessages.querySelectorAll('.chat-msg:not(.mine) .chat-text').forEach(el => CHAT_TR.applyTo(el));
8386
8499
  };
8387
8500
  chatHeader.querySelector('.chat-close-btn').onclick = () => { STATE.chatActive = false; closePanel(chatPanel); btnChat.classList.remove('active'); };
8501
+ btnChatLog.onclick = () => { STATE.chatActive = true; openPanel(chatPanel); DOM_UTILS.forceScroll(chatMessages, chatJumpBtn); };
8502
+ chatHeader.querySelector('.chat-clear-btn').onclick = () => { chatMessages.replaceChildren(); showToast(t('chatCleared')); };
8503
+ chatHeader.querySelector('.chat-export-btn').onclick = () => {
8504
+ let text = 'NexusSync Chat\n==============\n\n';
8505
+ Array.from(chatMessages.children).forEach(row => {
8506
+ const who = row.querySelector('.chat-name')?.textContent || '';
8507
+ const at = row.querySelector('.chat-clock')?.textContent || '';
8508
+ const body = row.querySelector('.chat-text');
8509
+ text += `[${at}] ${who}: ${body?.dataset.orig || body?.textContent || ''}\n`;
8510
+ });
8511
+ const url = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }));
8512
+ const a = document.createElement('a');
8513
+ a.href = url;
8514
+ a.download = `NexusSync_Chat_${new Date().toISOString().replace(/[:T-]/g, '').slice(0, 14)}.txt`;
8515
+ document.body.appendChild(a); a.click(); a.remove();
8516
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
8517
+ };
8388
8518
  subLogHeader.querySelector('.btn-close-log').onclick = () => { STATE.subLogActive = false; closePanel(subLogPanel); btnSubLog.classList.remove('active'); };
8389
8519
  subLogHeader.querySelector('.btn-clear-log').onclick = () => { subLogMessages.replaceChildren(); showToast(t('logCleared')); };
8390
8520
  subLogHeader.querySelector('.btn-export-log').onclick = () => {
@@ -8616,9 +8746,7 @@
8616
8746
  if (uiElements.dock?.classList.contains('open')) toggleDock(false);
8617
8747
  INK.start();
8618
8748
  };
8619
- // 📌 opens the library (every site); "Bookmark this moment" is its first button.
8620
- btnBookmark.onclick = () => { bmBody.render(); openPanel(bmPanel); };
8621
- bmHeader.querySelector('.close-btn').onclick = () => closePanel(bmPanel);
8749
+ btnBookmark.onclick = () => addBookmark();
8622
8750
  btnHideSite.onclick = () => setFabHiddenOnSite(true);
8623
8751
 
8624
8752
  setupCanvasLogic();
@@ -8733,7 +8861,7 @@
8733
8861
  const color = /^(#[0-9a-f]{3,8}|hsl\([\d., %]+\))$/i.test(msg.color || '') ? msg.color : '#69f0ae';
8734
8862
  const row = createEl('div', 'chat-msg' + (msg.sender === STATE.userId ? ' mine' : ''));
8735
8863
  row.style.borderLeft = `4px solid ${color}`;
8736
- const av = safeEmoji(msg.av);
8864
+ const av = safeAvatar(msg.av);
8737
8865
  const name = createEl('span', 'chat-name', (av ? av + ' ' : '') + ((msg.nick && String(msg.nick).trim().slice(0, 16)) || ('ID:' + String(msg.sender || '').substring(0, 3))));
8738
8866
  name.style.color = color;
8739
8867
  row.appendChild(name);
@@ -8812,6 +8940,38 @@
8812
8940
  return first.length <= 16 && /\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(first) ? first : '';
8813
8941
  }
8814
8942
 
8943
+ // An avatar: one emoji, or one or two letters/digits (initials).
8944
+ function safeAvatar(s) {
8945
+ const e = safeEmoji(s);
8946
+ if (e) return e;
8947
+ const str = String(s || '').trim();
8948
+ return /^[\p{L}\p{N}]{1,2}$/u.test(str) ? str.toUpperCase() : '';
8949
+ }
8950
+
8951
+ // Photo avatars of the others: announced by a short fingerprint in presence, fetched
8952
+ // once by message, kept for the session.
8953
+ const AVATAR_IMG = {
8954
+ cache: new Map(), // uid → { h, img }
8955
+ _asked: new Map(),
8956
+ get(uid) {
8957
+ if (uid === STATE.userId) return PROFILE.image();
8958
+ const want = STATE.presenceMap?.[uid]?.avh || STATE.sleepingMap?.[uid]?.avh || '';
8959
+ const c = this.cache.get(uid);
8960
+ if (!want) return '';
8961
+ if (c && c.h === want) return c.img;
8962
+ if (Date.now() - (this._asked.get(uid + want) || 0) > 20000) { this._asked.set(uid + want, Date.now()); SOCIAL.send('avatar', { op: 'req', who: uid }); }
8963
+ return '';
8964
+ },
8965
+ mine() { const img = PROFILE.image(); if (img && SOCIAL.live()) SOCIAL.send('avatar', { op: 'img', h: PROFILE.imageHash(), img }); },
8966
+ onRemote(d) {
8967
+ if (d.op === 'req' && d.who === STATE.userId) { if (Date.now() - (this._sentAt || 0) > 5000) { this._sentAt = Date.now(); this.mine(); } return; }
8968
+ if (d.op === 'img' && typeof d.img === 'string' && /^data:image\/jpeg;base64,[A-Za-z0-9+/=]+$/.test(d.img) && d.img.length < 40000 && typeof d.h === 'string') {
8969
+ this.cache.set(d.uid, { h: d.h, img: d.img });
8970
+ updatePresenceUI();
8971
+ }
8972
+ }
8973
+ };
8974
+
8815
8975
  // What reaches this device from the others, and from whom: kinds of events can be turned
8816
8976
  // off, a person can be muted for this room, and floods of reactions are thinned out.
8817
8977
  const SAFETY = {
@@ -8839,10 +8999,12 @@
8839
8999
  // The eight reaction buttons: the user's own choice (any emoji), or the defaults.
8840
9000
  const REACTIONS = {
8841
9001
  DEFAULT: ['😂', '😭', '😡', '💦', '🍪', '☕', '😘', '🖕'],
9002
+ MAX: 16,
8842
9003
  list() {
8843
9004
  const saved = STORE.get('nxu_reactions', null);
8844
- const arr = Array.isArray(saved) ? saved.map(safeEmoji) : [];
8845
- return this.DEFAULT.map((d, i) => arr[i] || d);
9005
+ if (!Array.isArray(saved) || !saved.length) return this.DEFAULT.slice();
9006
+ const arr = saved.slice(0, this.MAX).map(safeEmoji);
9007
+ return arr.map((e, i) => e || this.DEFAULT[i % this.DEFAULT.length]);
8846
9008
  },
8847
9009
  set(i, emoji) {
8848
9010
  const list = this.list();
@@ -8853,6 +9015,23 @@
8853
9015
  this.apply();
8854
9016
  return true;
8855
9017
  },
9018
+ add() {
9019
+ const list = this.list();
9020
+ if (list.length >= this.MAX) return -1;
9021
+ const spare = ['❤️', '🔥', '👏', '😱', '👀', '🎉', '🤔', '💯'].find(x => !list.includes(x)) || '⭐';
9022
+ list.push(spare);
9023
+ STORE.set('nxu_reactions', list);
9024
+ this.apply();
9025
+ return list.length - 1;
9026
+ },
9027
+ remove(i) {
9028
+ const list = this.list();
9029
+ if (list.length <= 1 || i < 0 || i >= list.length) return false;
9030
+ list.splice(i, 1);
9031
+ STORE.set('nxu_reactions', list);
9032
+ this.apply();
9033
+ return true;
9034
+ },
8856
9035
  reset() { STORE.set('nxu_reactions', null); this.apply(); },
8857
9036
  apply() {
8858
9037
  CONFIG.emojis = this.list();
@@ -8883,12 +9062,37 @@
8883
9062
  },
8884
9063
  // What this device announces in the room (presence): name, colour, avatar, status.
8885
9064
  value() {
8886
- return { ts: Date.now(), color: STATE.color, viewer: !!STATE.isViewer, nick: STATE.nickname || '', av: this.avatar(), st: this.status(), v: NXU_VERSION, r: NXU_RANK, sess: NXU_SESSION, hid: !!document.hidden };
9065
+ return { ts: Date.now(), color: STATE.color, viewer: !!STATE.isViewer, nick: STATE.nickname || '', av: this.avatar(), avh: this.imageHash(), st: this.status(), md: TUNE.mediaSig(), v: NXU_VERSION, r: NXU_RANK, sess: NXU_SESSION, hid: !!document.hidden };
9066
+ },
9067
+ AVATARS: ['🙂', '😎', '🦊', '🐱', '🐶', '🐯', '🐵', '🐼', '🐸', '🦄', '🐧', '🍿', '🎧', '🌙', '🔥', '🌸', '👾', '🤖'],
9068
+ avatar() { return safeAvatar(STORE.get('nxu_avatar', '')); },
9069
+ // A photo avatar travels once (and on request), not in every presence note.
9070
+ image() { const v = String(STORE.get('nxu_avatar_img', '') || ''); return /^data:image\/jpeg;base64,[A-Za-z0-9+/=]+$/.test(v) && v.length < 40000 ? v : ''; },
9071
+ imageHash() { const v = this.image(); if (!v) return ''; let h = 0; for (let i = 0; i < v.length; i += 7) h = (h * 31 + v.charCodeAt(i)) | 0; return (h >>> 0).toString(36) + v.length.toString(36); },
9072
+ setImage(dataUrl) { STORE.set('nxu_avatar_img', dataUrl || ''); AVATAR_IMG.mine(); this.publish(); updatePresenceUI(); },
9073
+ async pickImage() {
9074
+ const input = document.createElement('input');
9075
+ input.type = 'file'; input.accept = 'image/*';
9076
+ input.onchange = async () => {
9077
+ const f = input.files?.[0];
9078
+ if (!f) return;
9079
+ try {
9080
+ const url = URL.createObjectURL(f);
9081
+ const img = await new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = url; });
9082
+ const c = document.createElement('canvas'); c.width = c.height = 96;
9083
+ const s = Math.min(img.naturalWidth, img.naturalHeight);
9084
+ c.getContext('2d').drawImage(img, (img.naturalWidth - s) / 2, (img.naturalHeight - s) / 2, s, s, 0, 0, 96, 96);
9085
+ URL.revokeObjectURL(url);
9086
+ let q = 0.82, out = c.toDataURL('image/jpeg', q);
9087
+ while (out.length > 30000 && q > 0.4) { q -= 0.12; out = c.toDataURL('image/jpeg', q); }
9088
+ this.setImage(out);
9089
+ this._onImage?.();
9090
+ } catch (_) { showToast(t('setAvatarFail')); }
9091
+ };
9092
+ input.click();
8887
9093
  },
8888
- AVATARS: ['🙂', '😎', '🦊', '🐱', '🐶', '🐼', '🐸', '🦄', '🐧', '🍿', '🎧', '🌙', '🔥', '🌸', '👾', '🤖'],
8889
- avatar() { return safeEmoji(STORE.get('nxu_avatar', '')); },
8890
9094
  status() { return String(STORE.get('nxu_status', '') || '').replace(/\s+/g, ' ').trim().slice(0, 40); },
8891
- setAvatar(a) { STORE.set('nxu_avatar', safeEmoji(a)); this.publish(); updatePresenceUI(); },
9095
+ setAvatar(a) { STORE.set('nxu_avatar', safeAvatar(a)); this.publish(); updatePresenceUI(); },
8892
9096
  setStatus(s) {
8893
9097
  STORE.set('nxu_status', String(s || '').replace(/\s+/g, ' ').slice(0, 40));
8894
9098
  clearTimeout(this._st); this._st = setTimeout(() => { this.publish(); updatePresenceUI(); }, 600);
@@ -9076,8 +9280,10 @@
9076
9280
  const text = String(msg.text).slice(0, 200);
9077
9281
  const card = createEl('button', 'nx-bubble nx-talk' + (mine ? ' mine' : ''), '', { type: 'button' });
9078
9282
  card.style.setProperty('--c', color);
9079
- const av = safeEmoji(mine ? PROFILE.avatar() : (msg.av || STATE.presenceMap?.[msg.sender]?.av));
9080
- const avatar = createEl('span', 'nx-talk-avatar' + (av ? ' emoji' : ''), av || (Array.from(name.replace(/^ID:/, ''))[0] || '?').toUpperCase());
9283
+ const av = safeAvatar(mine ? PROFILE.avatar() : (msg.av || STATE.presenceMap?.[msg.sender]?.av));
9284
+ const photo = AVATAR_IMG.get(mine ? STATE.userId : msg.sender);
9285
+ const avatar = createEl('span', 'nx-talk-avatar' + (av || photo ? ' emoji' : ''), photo ? '' : av || (Array.from(name.replace(/^ID:/, ''))[0] || '?').toUpperCase());
9286
+ if (photo) { avatar.style.backgroundImage = `url("${photo}")`; avatar.style.backgroundSize = 'cover'; }
9081
9287
  const body = createEl('span', 'nx-talk-body');
9082
9288
  body.append(createEl('span', 'nx-bubble-name', name), createEl('span', 'nx-bubble-text', text));
9083
9289
  card.append(avatar, body);
@@ -9542,54 +9748,13 @@
9542
9748
  restore() { const v = Number((STORE.get('nxu_bright', {}) || {})[HOST]); if (Number.isFinite(v) && v !== 1) this.set(v, { save: false }); }
9543
9749
  };
9544
9750
 
9545
- // Volume above 100 % (quiet films): the page's audio goes through a gain with a gentle
9546
- // limiter. Only possible when the sound may be read by the page (same site or a stream
9547
- // the page loaded itself); otherwise the browser would silence it, so it is refused.
9548
- const BOOST = {
9549
- level: 1,
9550
- _ctx: null, _gain: null, _el: null,
9551
- can(v) {
9552
- if (!v) return false;
9553
- const src = v.currentSrc || v.src || '';
9554
- if (/^(blob|data):/i.test(src) || v.srcObject) return true;
9555
- try { if (new URL(src, location.href).origin === location.origin) return true; } catch (_) { }
9556
- return !!v.crossOrigin;
9557
- },
9558
- set(x) {
9559
- const level = Math.round(Math.max(1, Math.min(3, Number(x) || 1)) * 100) / 100;
9560
- const v = STATE.video;
9561
- if (!v) {
9562
- if (STATE.cinemaIframe) FRAME.postToFrame(STATE.cinemaIframe, { type: 'NXU_MEDIA_CMD', action: 'boost', value: level });
9563
- this.level = level;
9564
- return true;
9565
- }
9566
- if (this._el && this._el !== v) { try { this._ctx?.close(); } catch (_) { } this._ctx = this._gain = this._el = null; }
9567
- if (level > 1 && !this._gain) {
9568
- if (!this.can(v)) { showToast(t('boostBlocked')); return false; }
9569
- try {
9570
- const Ctx = window.AudioContext || window.webkitAudioContext;
9571
- const ctx = new Ctx();
9572
- const src = ctx.createMediaElementSource(v);
9573
- const gain = ctx.createGain();
9574
- const lim = ctx.createDynamicsCompressor();
9575
- lim.threshold.value = -6; lim.knee.value = 6; lim.ratio.value = 12; lim.attack.value = 0.003; lim.release.value = 0.2;
9576
- src.connect(gain); gain.connect(lim); lim.connect(ctx.destination);
9577
- this._ctx = ctx; this._gain = gain; this._el = v;
9578
- } catch (_) { showToast(t('boostBlocked')); return false; }
9579
- }
9580
- if (this._ctx?.state === 'suspended') { try { this._ctx.resume(); } catch (_) { } }
9581
- if (this._gain) this._gain.gain.value = level;
9582
- this.level = level;
9583
- return true;
9584
- }
9585
- };
9586
-
9587
9751
  // ───────────────────────── Subtitles in cinema: the video's own tracks, a file, or
9588
9752
  // OpenSubtitles — drawn by NexusSync in one consistent style, with timing and size.
9589
9753
  const SUBS = {
9590
- cues: null, // [{ s, e, text }] for an external file
9591
- label: '',
9592
- track: null, // a TextTrack of the page's video
9754
+ // Up to three subtitle layers at once (e.g. Dutch + English + Korean for learning):
9755
+ // each is a track of the page's video or a loaded file, drawn in its own colour.
9756
+ layers: [], // { id, kind: 'track'|'cues', track?, cues?, label }
9757
+ MAX: 3,
9593
9758
  delay: 0,
9594
9759
  _box: null, _timer: 0, _last: '',
9595
9760
  size() { const v = Number(STORE.get('nxu_xsub_size', 1)); return Number.isFinite(v) ? Math.max(0.7, Math.min(1.8, v)) : 1; },
@@ -9598,7 +9763,8 @@
9598
9763
  if (!v || !v.textTracks) return [];
9599
9764
  return [...v.textTracks].filter(tr => tr.kind === 'subtitles' || tr.kind === 'captions');
9600
9765
  },
9601
- active() { return !!(this.cues || this.track); },
9766
+ active() { return this.layers.length > 0; },
9767
+ hasTrack(tr) { return this.layers.some(l => l.track === tr); },
9602
9768
  _ensureBox() {
9603
9769
  const c = getContainer();
9604
9770
  if (!c) return null;
@@ -9606,35 +9772,43 @@
9606
9772
  this._box.style.setProperty('--xs', String(this.size()));
9607
9773
  return this._box;
9608
9774
  },
9775
+ _drop(l) {
9776
+ if (l.track) { try { l.track.removeEventListener('cuechange', this._onCue); l.track.mode = 'disabled'; } catch (_) { } }
9777
+ },
9609
9778
  off() {
9610
- if (this.track) { try { this.track.mode = 'disabled'; this.track.removeEventListener('cuechange', this._onCue); } catch (_) { } }
9611
- this.track = null; this.cues = null; this.label = '';
9779
+ this.layers.forEach(l => this._drop(l));
9780
+ this.layers = [];
9612
9781
  clearInterval(this._timer); this._timer = 0;
9613
9782
  this._render('');
9614
9783
  try { CUE_MIRROR.render(); } catch (_) { }
9615
9784
  },
9616
- useTrack(tr) {
9617
- this.off();
9618
- this.tracks().forEach(x => { if (x !== tr && x.mode === 'showing') x.mode = 'disabled'; });
9619
- this.track = tr;
9620
- this.label = tr.label || tr.language || t('subTrack');
9621
- tr.mode = 'hidden'; // cues still arrive, the browser does not draw them itself
9785
+ remove(id) {
9786
+ const l = this.layers.find(x => x.id === id);
9787
+ if (!l) return;
9788
+ this._drop(l);
9789
+ this.layers = this.layers.filter(x => x !== l);
9790
+ if (!this.layers.length) this.off(); else this.tick(true);
9791
+ },
9792
+ _add(layer) {
9793
+ while (this.layers.length >= this.MAX) { this._drop(this.layers[0]); this.layers.shift(); }
9794
+ layer.id = Math.random().toString(36).slice(2, 8);
9795
+ this.layers.push(layer);
9622
9796
  try { CUE_MIRROR.render(); } catch (_) { }
9623
- this._onCue = () => this.tick();
9624
- tr.addEventListener('cuechange', this._onCue);
9625
9797
  this._loop();
9626
- showToast(t('subLoaded', { name: this.label }));
9798
+ showToast(t('subLoaded', { name: layer.label }));
9627
9799
  },
9628
- useCues(cues, label) {
9629
- this.off();
9630
- this.cues = cues.sort((a, b) => a.s - b.s);
9631
- this.label = label;
9632
- try { CUE_MIRROR.render(); } catch (_) { }
9633
- this._loop();
9634
- showToast(t('subLoaded', { name: label }));
9800
+ // A track of the video: tapping it again takes it away.
9801
+ useTrack(tr) {
9802
+ const has = this.layers.find(l => l.track === tr);
9803
+ if (has) { this.remove(has.id); return; }
9804
+ this._onCue = this._onCue || (() => this.tick());
9805
+ tr.mode = 'hidden'; // cues still arrive, the browser does not draw them itself
9806
+ tr.addEventListener('cuechange', this._onCue);
9807
+ this._add({ kind: 'track', track: tr, label: tr.label || tr.language || t('subTrack') });
9635
9808
  },
9636
- _loop() { clearInterval(this._timer); this._timer = setInterval(() => this.tick(), 150); this.tick(); },
9637
- setDelay(d) { this.delay = Math.round(Math.max(-120, Math.min(120, d)) * 10) / 10; this.tick(); },
9809
+ useCues(cues, label) { this._add({ kind: 'cues', cues: cues.sort((a, b) => a.s - b.s), label }); },
9810
+ _loop() { clearInterval(this._timer); this._timer = setInterval(() => this.tick(), 150); this.tick(true); },
9811
+ setDelay(d) { this.delay = Math.round(Math.max(-120, Math.min(120, d)) * 10) / 10; this.tick(true); },
9638
9812
  _now() {
9639
9813
  const info = currentMediaInfo();
9640
9814
  if (!info) return null;
@@ -9645,28 +9819,37 @@
9645
9819
  }
9646
9820
  return tm;
9647
9821
  },
9648
- tick() {
9822
+ _textOf(l, at) {
9823
+ if (l.kind === 'cues') {
9824
+ let lo = 0, hi = l.cues.length - 1, idx = -1;
9825
+ while (lo <= hi) { const mid = (lo + hi) >> 1; if (l.cues[mid].s <= at) { idx = mid; lo = mid + 1; } else hi = mid - 1; }
9826
+ const parts = [];
9827
+ for (let i = idx; i >= 0 && i > idx - 4; i--) { const c = l.cues[i]; if (c.s <= at && at < c.e) parts.unshift(c.text); }
9828
+ return this._clean(parts.join('\n'));
9829
+ }
9830
+ const list = l.track.cues ? [...l.track.cues] : [];
9831
+ const act = this.delay ? list.filter(c => c.startTime <= at && at < c.endTime) : [...(l.track.activeCues || [])];
9832
+ return this._clean(act.map(c => (c.text || '')).join('\n'));
9833
+ },
9834
+ tick(force = false) {
9649
9835
  if (!this.active()) return;
9650
9836
  const tm = this._now();
9651
9837
  if (tm == null) return;
9652
9838
  const at = tm - this.delay;
9653
- let text = '';
9654
- if (this.cues) {
9655
- // binary search for the last cue starting before `at`
9656
- let lo = 0, hi = this.cues.length - 1, idx = -1;
9657
- while (lo <= hi) { const mid = (lo + hi) >> 1; if (this.cues[mid].s <= at) { idx = mid; lo = mid + 1; } else hi = mid - 1; }
9658
- const parts = [];
9659
- for (let i = idx; i >= 0 && i > idx - 4; i--) { const c = this.cues[i]; if (c.s <= at && at < c.e) parts.unshift(c.text); }
9660
- text = parts.join('\n');
9661
- } else if (this.track) {
9662
- const list = this.track.cues ? [...this.track.cues] : [];
9663
- // With a delay the active cues are looked up by time instead of cuechange.
9664
- const act = this.delay ? list.filter(c => c.startTime <= at && at < c.endTime) : [...(this.track.activeCues || [])];
9665
- text = act.map(c => (c.text || '')).join('\n');
9666
- }
9667
- this._render(this._clean(text));
9839
+ const groups = this.layers.map((l, i) => ({ i, text: this._textOf(l, at) }));
9840
+ const sig = groups.map(g => g.text).join('\u0001');
9841
+ if (!force && sig === this._last && this._box?.isConnected) return;
9842
+ this._last = sig;
9843
+ const any = groups.some(g => g.text);
9844
+ const box = any ? this._ensureBox() : this._box;
9845
+ if (!box) return;
9846
+ const kids = [];
9847
+ groups.forEach(g => { if (g.text) g.text.split('\n').filter(Boolean).slice(0, 3).forEach(line => kids.push(createEl('span', 'nx-xsub-line l' + g.i, line))); });
9848
+ box.replaceChildren(...kids);
9849
+ box.classList.toggle('on', any);
9668
9850
  },
9669
9851
  _clean(s) { return String(s || '').replace(/<[^>]+>/g, '').replace(/\{\\[^}]*\}/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').trim(); },
9852
+ // Plain text into the layer (the site's own subtitles, see DOM_SUBS).
9670
9853
  _render(text) {
9671
9854
  if (text === this._last && this._box?.isConnected) return;
9672
9855
  this._last = text;
@@ -9717,7 +9900,7 @@
9717
9900
  },
9718
9901
  // A gentle offer when cinema has nothing to read: once per page.
9719
9902
  maybeSuggest() {
9720
- if (!IS_TOP || !STATE.isCinema || this.active() || this._suggested === location.href) return;
9903
+ if (!IS_TOP || !STATE.isCinema || this.active() || DOM_SUBS._src || this._suggested === location.href) return;
9721
9904
  if (this.tracks().length || (CUE_MIRROR.box?.textContent || '').trim() || TRANSLATOR.active) return;
9722
9905
  const info = currentMediaInfo();
9723
9906
  if (!info || info.live || info.paused) return;
@@ -9732,6 +9915,61 @@
9732
9915
  }
9733
9916
  };
9734
9917
 
9918
+ // The site's own subtitles drawn as page text (a separate subtitle file the site renders
9919
+ // itself, not a track of the video). With the NexusSync controls the player box is
9920
+ // stretched to the screen, and those lines kept their old position — often below the
9921
+ // visible screen on phones. Text in the player that keeps changing is recognised as
9922
+ // subtitles, hidden in place and shown in NexusSync's subtitle layer instead, which
9923
+ // always stays inside the visible screen and above the controls.
9924
+ const DOM_SUBS = {
9925
+ _obs: null, _root: null, _cands: new Map(), _src: null, _timer: 0,
9926
+ SEL: '[class*="caption" i], [class*="subtitle" i], [class*="cue" i], [class*="text-track" i], [class*="subs" i], [id*="subtitle" i], [id*="caption" i]',
9927
+ sync() {
9928
+ const root = STATE.isCinema && CINEMA.nexusControls() && CINEMA.applied?.chain?.[0]?.root;
9929
+ const v = CINEMA.applied?.video;
9930
+ if (!root || !v || root === v || root.ownerDocument !== document) { this.stop(); return; }
9931
+ if (this._root === root) return;
9932
+ this.stop();
9933
+ this._root = root;
9934
+ this._obs = new MutationObserver(() => { if (!this._timer) this._timer = setTimeout(() => { this._timer = 0; this.scan(); }, 80); });
9935
+ this._obs.observe(root, { childList: true, subtree: true, characterData: true });
9936
+ this.scan();
9937
+ },
9938
+ stop() {
9939
+ this._obs?.disconnect(); this._obs = null; this._root = null;
9940
+ clearTimeout(this._timer); this._timer = 0;
9941
+ document.querySelectorAll('.nxu-dsub-src').forEach(n => n.classList.remove('nxu-dsub-src'));
9942
+ if (this._src && !SUBS.active()) SUBS._render('');
9943
+ this._src = null; this._cands.clear();
9944
+ },
9945
+ _text(el) { return String(el.innerText || el.textContent || '').replace(/[ \t]+/g, ' ').replace(/\n{2,}/g, '\n').trim().slice(0, 300); },
9946
+ scan() {
9947
+ const root = this._root;
9948
+ if (!root || !root.isConnected) { this.stop(); return; }
9949
+ if (this._src && this._src.isConnected) { this._show(); return; }
9950
+ const v = CINEMA.applied?.video;
9951
+ const cands = new Set();
9952
+ try { root.querySelectorAll(this.SEL).forEach(el => cands.add(el)); } catch (_) { }
9953
+ (CINEMA._textLayers || []).forEach(el => cands.add(el));
9954
+ const now = Date.now();
9955
+ for (const el of cands) {
9956
+ if (!el.isConnected || el.contains(v) || el.closest('.nxu-cue-mirror') || el.querySelector('button, input, svg, [role="slider"]')) continue;
9957
+ const txt = this._text(el);
9958
+ const c = this._cands.get(el) || { last: null, changes: [], };
9959
+ if (txt !== c.last) { if (c.last !== null) c.changes.push(now); c.last = txt; }
9960
+ c.changes = c.changes.filter(ts => now - ts < 30000);
9961
+ this._cands.set(el, c);
9962
+ // Two changes of its text within half a minute: subtitles, not a title.
9963
+ if (c.changes.length >= 2) { this._src = el; el.classList.add('nxu-dsub-src'); logDebug('Site subtitles shown in the NexusSync layer.', 'info'); this._show(); return; }
9964
+ }
9965
+ },
9966
+ _show() {
9967
+ if (SUBS.active()) return; // the user picked other subtitles
9968
+ SUBS._render(this._text(this._src));
9969
+ }
9970
+ };
9971
+ setInterval(() => { try { DOM_SUBS.sync(); } catch (_) { } }, 1000);
9972
+
9735
9973
  // OpenSubtitles.org search (its public REST interface: no account needed).
9736
9974
  const OPENSUBS = {
9737
9975
  LANG3: { ko: 'kor', en: 'eng', ja: 'jpn', zh: 'chi', es: 'spa', fr: 'fre', de: 'ger', it: 'ita', pt: 'por', ru: 'rus', vi: 'vie', th: 'tha', id: 'ind', tr: 'tur', ar: 'ara', hi: 'hin', nl: 'dut', pl: 'pol', sv: 'swe', uk: 'ukr', ms: 'may', tl: 'tgl' },
@@ -9750,6 +9988,27 @@
9750
9988
  .replace(/[\[\](){}]/g, ' ').replace(/\b(19|20)\d{2}\b/g, ' ').replace(/\s+/g, ' ').trim();
9751
9989
  return { query: s, year, season, episode };
9752
9990
  },
9991
+ // OpenSubtitles knows films by their English titles; a Korean (or other) page title is
9992
+ // looked up on TMDB first, and its English titles are offered (the first one is used).
9993
+ async tmdb(query, year) {
9994
+ const url = 'https://www.themoviedb.org/search?query=' + encodeURIComponent(query) + '&language=en-US';
9995
+ const res = await httpRequest({ url, headers: { 'Accept-Language': 'en-US,en;q=0.9' }, timeout: 12000 });
9996
+ if (res.status !== 200) throw new Error('HTTP ' + res.status);
9997
+ const doc = new DOMParser().parseFromString(res.text || '', 'text/html');
9998
+ const out = [];
9999
+ doc.querySelectorAll('a[data-media-type] h2').forEach(h2 => {
10000
+ const a = h2.closest('a');
10001
+ const title = (h2.querySelector('span')?.textContent || h2.textContent || '').trim();
10002
+ if (!title || out.some(x => x.title === title)) return;
10003
+ const card = a.closest('[class*="media-card"]') || a.parentElement?.parentElement;
10004
+ const date = card?.querySelector('.release_date')?.textContent || '';
10005
+ const y = (date.match(/(19|20)\d{2}/) || [])[0] || '';
10006
+ out.push({ title, year: y, type: a.getAttribute('data-media-type') === 'tv' ? 'tv' : 'movie' });
10007
+ });
10008
+ // The page's year (if any) decides between same-named films.
10009
+ if (year) out.sort((p, q) => (q.year === year) - (p.year === year));
10010
+ return out.slice(0, 6);
10011
+ },
9753
10012
  async search({ query, season, episode, lang }) {
9754
10013
  const l3 = this.LANG3[lang] || 'eng';
9755
10014
  const parts = [];
@@ -9798,8 +10057,38 @@
9798
10057
  const q = panel.querySelector('.os-q'), se = panel.querySelector('.os-season'), ep = panel.querySelector('.os-episode'), lg = panel.querySelector('.os-lang');
9799
10058
  if (!q.value || q.dataset.page !== location.href) { q.value = g.query; se.value = g.season || ''; ep.value = g.episode || ''; q.dataset.page = location.href; }
9800
10059
  lg.value = this.LANG3[this.lang()] ? this.lang() : 'en';
10060
+ // Opened again after picking one: start at the top (it used to keep the old scroll
10061
+ // position past the end of a shorter list, which looked like an empty window).
10062
+ panel.scrollTop = 0;
10063
+ const body = panel.querySelector('.os-body'); if (body) body.scrollTop = 0;
10064
+ panel.querySelectorAll('.os-item.busy').forEach(b => b.classList.remove('busy'));
9801
10065
  openPanel(panel);
9802
- if (q.value && !panel.querySelector('.os-item')) this.run(panel);
10066
+ if (q.value && !panel.querySelector('.os-item')) this.prepare(panel, g);
10067
+ },
10068
+ // Non-Latin titles: English title from TMDB first, offered as one-tap choices.
10069
+ async prepare(panel, g) {
10070
+ const q = panel.querySelector('.os-q'), chips = panel.querySelector('.os-tmdb');
10071
+ chips.replaceChildren();
10072
+ if (/[^\u0000-\u024f\s\d\p{P}]/u.test(q.value)) {
10073
+ chips.append(createEl('span', 'trans-help', t('osTmdbLooking')));
10074
+ try {
10075
+ let list = await this.tmdb(q.value, g?.year || '');
10076
+ // Nothing for the whole title: try the part before a colon ("Title: Subtitle").
10077
+ if (!list.length && /[::]/.test(q.value)) list = await this.tmdb(q.value.split(/[::]/)[0].trim(), g?.year || '');
10078
+ chips.replaceChildren();
10079
+ if (list.length) {
10080
+ chips.append(createEl('span', 'os-tmdb-label', 'TMDB'));
10081
+ list.forEach((m, i) => {
10082
+ const b = createEl('button', 'os-chip' + (i === 0 ? ' on' : ''), m.title + (m.year ? ' (' + m.year + ')' : ''), { type: 'button' });
10083
+ b.onclick = () => { chips.querySelectorAll('.os-chip').forEach(c => c.classList.toggle('on', c === b)); q.value = m.title; this.run(panel); };
10084
+ chips.appendChild(b);
10085
+ });
10086
+ q.dataset.original = q.value;
10087
+ q.value = list[0].title;
10088
+ } else chips.append(createEl('span', 'trans-help', t('osTmdbNone')));
10089
+ } catch (err) { chips.replaceChildren(); logDebug('TMDB lookup failed: ' + (err.message || err), 'warn'); }
10090
+ }
10091
+ this.run(panel);
9803
10092
  },
9804
10093
  async run(panel) {
9805
10094
  const q = panel.querySelector('.os-q').value.trim();
@@ -9844,7 +10133,8 @@
9844
10133
  const out = createEl('div', 'os-results');
9845
10134
  go.onclick = () => this.run(body);
9846
10135
  [q, se, ep].forEach(i => i.addEventListener('keydown', (ev) => { ev.stopPropagation(); if (ev.key === 'Enter') this.run(body); }));
9847
- body.append(q, row, go, out, createEl('div', 'trans-help', t('osHint')));
10136
+ const tm = createEl('div', 'os-tmdb');
10137
+ body.append(q, tm, row, go, out, createEl('div', 'trans-help', t('osHint')));
9848
10138
  return body;
9849
10139
  }
9850
10140
  };
@@ -9881,23 +10171,31 @@
9881
10171
  const r = v.getBoundingClientRect();
9882
10172
  if (r.width < 240 || r.height < 135) return;
9883
10173
  const seen = new Set();
10174
+ // "Holds the video" across shadow roots (players often keep the <video> inside one:
10175
+ // a plain contains() said no, and a whole page section got hidden — black screen).
10176
+ const holds = (el) => { for (let n = v; n; n = n.parentNode || n.host) { if (n === el) return true; } return false; };
10177
+ const area = r.width * r.height;
9884
10178
  for (const fx of [0.15, 0.5, 0.85]) for (const fy of [0.15, 0.5, 0.85]) {
9885
10179
  const x = r.left + r.width * fx, y = r.top + r.height * fy;
9886
10180
  if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) continue;
9887
10181
  let stack;
9888
10182
  try { stack = document.elementsFromPoint(x, y); } catch (_) { continue; }
9889
10183
  for (const el of stack) {
9890
- if (el === v || el.contains(v)) break; // reached the picture
10184
+ if (el === v || holds(el)) break; // reached the picture
9891
10185
  if (seen.has(el) || this.hidden.has(el) || el.closest('#nxu-host') || el.id === 'nxu-host') continue;
9892
10186
  seen.add(el);
9893
10187
  // Climb to the whole overlay box (but never to something holding the video).
9894
10188
  let box = el;
9895
- while (box.parentElement && !box.parentElement.contains(v) && box.parentElement !== document.body) box = box.parentElement;
9896
- if (this.hidden.has(box)) continue;
10189
+ while (box.parentElement && !holds(box.parentElement) && box.parentElement !== document.body) box = box.parentElement;
10190
+ if (this.hidden.has(box) || holds(box) || box.querySelector?.('video')) continue;
9897
10191
  const sig = `${box.id} ${typeof box.className === 'string' ? box.className : ''}`;
9898
10192
  if (this.RX_CONTROL.test(sig)) continue;
9899
10193
  const br = box.getBoundingClientRect();
9900
- if (br.width * br.height > r.width * r.height * 0.92 && !box.querySelector?.('a[href], iframe')) continue; // likely the player's own click layer
10194
+ if (br.width * br.height > area * 0.92 && !box.querySelector?.('a[href], iframe')) continue; // likely the player's own click layer
10195
+ // Only boxes laid over the picture: never a page section much larger than
10196
+ // the video, never something in the normal flow of the page.
10197
+ if (br.width * br.height > area * 1.6) continue;
10198
+ try { if (getComputedStyle(box).position === 'static' && getComputedStyle(el).position === 'static') continue; } catch (_) { }
9901
10199
  if (!this._adLike(box) && !this._adLike(el)) continue;
9902
10200
  this.hide(box);
9903
10201
  }
@@ -10064,13 +10362,11 @@
10064
10362
  };
10065
10363
  setInterval(() => {
10066
10364
  try { AUTO_CINEMA.tick(); } catch (_) { }
10067
- try { JUMP.tick(); } catch (_) { }
10068
10365
  try {
10069
10366
  if (STATE.isCinema) { SUBS._cinemaSince = SUBS._cinemaSince || Date.now(); if (Date.now() - SUBS._cinemaSince > 6000) SUBS.maybeSuggest(); }
10070
10367
  else SUBS._cinemaSince = 0;
10071
10368
  } catch (_) { }
10072
10369
  }, 1200);
10073
- try { JUMP.init(); } catch (_) { }
10074
10370
 
10075
10371
  // ───────────────────────── Next episode
10076
10372
  // On series pages (drama/anime sites) the page usually has a "next episode" link or
@@ -10381,7 +10677,7 @@
10381
10677
  _typing: new Map(),
10382
10678
  _connectedAt: 0,
10383
10679
  _lastCanvasBubble: 0,
10384
- TYPES: ['nudge', 'pointer', 'countdown', 'typing', 'ink', 'cover', 'goto', 'tune'],
10680
+ TYPES: ['nudge', 'pointer', 'countdown', 'typing', 'ink', 'cover', 'goto', 'tune', 'avatar'],
10385
10681
  live() { return STATE.handshakeVerified && !STATE.isReadOnly && STATE.role !== 'IDLE'; },
10386
10682
  send(type, data = {}) {
10387
10683
  if (!this.live()) return false;
@@ -10392,6 +10688,7 @@
10392
10688
  },
10393
10689
  receive(type, d) {
10394
10690
  if (!d || typeof d !== 'object' || d.uid === STATE.userId || !this.live()) return;
10691
+ if (type !== 'typing' && type !== 'avatar') try { HEAL.heard(d.uid); } catch (_) { }
10395
10692
  // Muted people and switched-off kinds (the cover, countdowns and "go together"
10396
10693
  // always come through: they keep everyone watching the same thing).
10397
10694
  const kind = { nudge: 'nudge', ink: 'ink', pointer: 'ping', typing: 'chat' }[type];
@@ -10411,6 +10708,7 @@
10411
10708
  else if (type === 'cover') COVER.onRemote(who, d);
10412
10709
  else if (type === 'goto') TRAVEL.onRemote(who, d);
10413
10710
  else if (type === 'tune') TUNE.onRemote(who, d);
10711
+ else if (type === 'avatar') AVATAR_IMG.onRemote(d);
10414
10712
  },
10415
10713
  // Fresh events only: the history a newcomer downloads must not pop up as notifications.
10416
10714
  isFresh(ts) {
@@ -10616,8 +10914,6 @@
10616
10914
  // Remote chat message → bubble (unless the chat is already open).
10617
10915
  onChat(msg) {
10618
10916
  if (!msg || msg.sender === STATE.userId || !this.isFresh(msg.ts)) return;
10619
- const chatOpen = uiElements.chatPanel && uiElements.chatPanel.style.display === 'flex';
10620
- if (chatOpen && !document.hidden) return;
10621
10917
  TALK.say(msg);
10622
10918
  },
10623
10919
  // Remote drawing → shown on screen right away (view only) + bubble to join in.
@@ -10855,7 +11151,7 @@
10855
11151
  const PRESS_COLORS = { '😂': '#ffd54f', '😭': '#82b1ff', '😡': '#ff5252', '💦': '#4fc3f7', '🍪': '#d7a86e', '☕': '#bcaaa4', '😘': '#ff6fae', '🖕': '#ffb74d' };
10856
11152
  function pressFx(btn, emoji) {
10857
11153
  if (!btn) return;
10858
- btn.style.setProperty('--pop', PRESS_COLORS[emoji] || '#69f0ae');
11154
+ btn.style.setProperty('--pop', '#69f0ae');
10859
11155
  btn.classList.remove('pop');
10860
11156
  void btn.offsetWidth;
10861
11157
  btn.classList.add('pop');
@@ -10946,7 +11242,9 @@
10946
11242
  const sway = (Math.random() < 0.5 ? -1 : 1) * (10 + Math.random() * 14);
10947
11243
  const d = 1700 + Math.random() * 500;
10948
11244
  const base = { duration: d, delay };
10949
- const kind = { '❤️': 'heart', '💗': 'heart', '😂': 'laugh', '😭': 'cry', '😡': 'angry', '💦': 'splash', '🍪': 'munch', '☕': 'steam', '😘': 'kiss', '🖕': 'flip', '🫣': 'peek', '🌰': 'toss', '🚽': 'flush' }[e] || 'float';
11245
+ // Every reaction moves the same way now that anyone can pick any emoji (only the
11246
+ // nudge's 💗 keeps its heartbeat).
11247
+ const kind = e === '💗' ? 'heart' : 'float';
10950
11248
  if (this.reduced()) { this._run(el, [{ opacity: 0 }, { opacity: 1, offset: 0.2 }, { opacity: 0, transform: `translateY(${-R * 0.4}px)` }], base); return; }
10951
11249
  switch (kind) {
10952
11250
  case 'heart':
@@ -11208,6 +11506,7 @@
11208
11506
  function onRemoteReaction(d) {
11209
11507
  if (!d || typeof d.emoji !== 'string' || d.emoji.length > 8) return;
11210
11508
  const uid = typeof d.uid === 'string' ? d.uid.slice(0, 40) : 'peer';
11509
+ try { HEAL.heard(uid); } catch (_) { }
11211
11510
  if (!SAFETY.allows(uid, 'react') || SAFETY.flood(uid)) return;
11212
11511
  const color = typeof d.color === 'string' && /^(#[0-9a-f]{3,8}|hsl\([\d., %]+\))$/i.test(d.color) ? d.color : '#82b1ff';
11213
11512
  const name = (typeof d.nick === 'string' && d.nick.trim().slice(0, 16)) || participantName(uid);
@@ -11319,7 +11618,6 @@
11319
11618
  case 'seekBy': MEDIA_SAFE.seek(v, Math.max(0, v.currentTime + value)); break;
11320
11619
  case 'volume': v.volume = Math.max(0, Math.min(1, value)); v.muted = value === 0; break;
11321
11620
  case 'mute': v.muted = !v.muted; break;
11322
- case 'boost': BOOST.set(value); break;
11323
11621
  }
11324
11622
  }
11325
11623
 
@@ -11846,13 +12144,16 @@
11846
12144
  if (!open) return;
11847
12145
  const item = (label, sel, fn) => { const b = createEl('button', sel ? 'sel' : '', label, { type: 'button', role: 'menuitemradio' }); b.onclick = (ev) => { ev.stopPropagation(); fn(); }; return b; };
11848
12146
  const tracks = SUBS.tracks();
12147
+ const nothing = !SUBS.active() && !TRANSLATOR.active && !DOM_SUBS._src;
11849
12148
  const kids = [createEl('div', 'cc-menu-title', t('subMenu')),
11850
- item(t('xsubOff'), !SUBS.active(), () => { SUBS.off(); this.toggleSubMenu(false); })];
11851
- tracks.forEach((tr, i) => kids.push(item('🎞 ' + (tr.label || tr.language || t('subTrack') + ' ' + (i + 1)), SUBS.track === tr, () => { SUBS.useTrack(tr); this.toggleSubMenu(false); })));
11852
- if (SUBS.cues) kids.push(item('💬 ' + SUBS.label, true, () => this.toggleSubMenu(false)));
12149
+ item(t('xsubOff'), nothing, () => { SUBS.off(); if (TRANSLATOR.active) TRANSLATOR.stop(t('subOff')); this.toggleSubMenu(false); })];
12150
+ // Several can be on at once (up to three): tap to add, tap again to take away.
12151
+ tracks.forEach((tr, i) => kids.push(item('🎞 ' + (tr.label || tr.language || t('subTrack') + ' ' + (i + 1)), SUBS.hasTrack(tr), () => { SUBS.useTrack(tr); this.toggleSubMenu(true); })));
12152
+ SUBS.layers.filter(l => l.kind === 'cues').forEach(l => kids.push(item('💬 ' + l.label, true, () => { SUBS.remove(l.id); this.toggleSubMenu(true); })));
12153
+ if (SUBS.layers.length > 1) kids.push(createEl('div', 'cc-menu-note', t('subMulti')));
11853
12154
  kids.push(item(t('subSearch'), false, () => { this.toggleSubMenu(false); OPENSUBS.open(); }));
11854
12155
  kids.push(item(t('subFile'), false, () => { this.toggleSubMenu(false); SUBS.openFile(); }));
11855
- kids.push(item(t('subAi') + (TRANSLATOR.active ? ' ✓' : ''), false, () => { this.toggleSubMenu(false); TRANSLATOR.toggle(); }));
12156
+ kids.push(item(t('subAi'), !!TRANSLATOR.active, () => { this.toggleSubMenu(false); TRANSLATOR.toggle(); }));
11856
12157
  if (SUBS.active()) {
11857
12158
  const d = createEl('div', 'cc-menu-adjust');
11858
12159
  const val = createEl('span', 'cc-adj-val', (SUBS.delay > 0 ? '+' : '') + SUBS.delay.toFixed(1) + 's');
@@ -11888,11 +12189,22 @@
11888
12189
  return { row, r, out };
11889
12190
  };
11890
12191
  const pct = v => Math.round(v * 100) + '%';
11891
- const b = slider('☀️ ' + t('viewBright'), 30, 200, BRIGHTNESS.level, pct, v => BRIGHTNESS.set(v));
11892
- const s = slider('🔊 ' + t('viewBoost'), 100, 300, BOOST.level, pct, v => BOOST.set(v));
12192
+ const b = slider('☀️ ' + t('viewBright'), 30, 200, BRIGHTNESS.level, pct, v => { BRIGHTNESS.set(v); this.update(); });
11893
12193
  const reset = createEl('button', '', '↺ ' + t('viewReset'), { type: 'button' });
11894
- reset.onclick = (ev) => { ev.stopPropagation(); BRIGHTNESS.set(1); BOOST.set(1); b.r.value = '100'; s.r.value = '100'; b.out.textContent = s.out.textContent = '100%'; };
11895
- menu.replaceChildren(createEl('div', 'cc-menu-title', t('viewMenu')), b.row, s.row, reset);
12194
+ reset.onclick = (ev) => { ev.stopPropagation(); BRIGHTNESS.set(1); b.r.value = '100'; b.out.textContent = '100%'; this.update(); };
12195
+ const kids = [createEl('div', 'cc-menu-title', t('viewMenu')), b.row, reset];
12196
+ // Several soundtracks in the file (dubbed / original / commentary): pick one.
12197
+ const at = STATE.video?.audioTracks;
12198
+ if (at && at.length > 1) {
12199
+ kids.push(createEl('div', 'cc-menu-title', t('viewAudio')));
12200
+ for (let i = 0; i < at.length; i++) {
12201
+ const tr = at[i];
12202
+ const btn = createEl('button', tr.enabled ? 'sel' : '', '🔊 ' + (tr.label || tr.language || t('viewAudio') + ' ' + (i + 1)), { type: 'button', role: 'menuitemradio' });
12203
+ btn.onclick = (ev) => { ev.stopPropagation(); for (let j = 0; j < at.length; j++) at[j].enabled = j === i; this.toggleViewMenu(true); };
12204
+ kids.push(btn);
12205
+ }
12206
+ }
12207
+ menu.replaceChildren(...kids);
11896
12208
  resetIdleTimer(true);
11897
12209
  },
11898
12210
 
@@ -12023,7 +12335,11 @@
12023
12335
  const rate = +info.rate.toFixed(2);
12024
12336
  e.rateBtn.textContent = `${rate}x`;
12025
12337
  e.rateBtn.classList.toggle('on', Math.abs(rate - 1) > 0.01);
12026
- e.subBtn.classList.toggle('on', TRANSLATOR.state !== 'idle');
12338
+ e.subBtn.classList.toggle('on', TRANSLATOR.state !== 'idle' || SUBS.active());
12339
+ e.viewBtn?.classList.toggle('on', Math.abs(BRIGHTNESS.level - 1) > 0.01);
12340
+ e.pipBtn.classList.toggle('on', !!document.pictureInPictureElement);
12341
+ e.fsBtn.classList.toggle('on', fullscreenActive());
12342
+ [e.rateBtn, e.subBtn, e.viewBtn, e.ambientBtn, e.fitBtn, e.pipBtn, e.fsBtn, this.els.rotateBtn].forEach(b => b && b.setAttribute('aria-pressed', String(b.classList.contains('on'))));
12027
12343
  const canStyle = info.kind === 'video' || !!STATE.cinemaIframe;
12028
12344
  e.ambientBtn.classList.toggle('on', CINEMA.ambientEnabled());
12029
12345
  e.ambientBtn.style.display = canStyle ? '' : 'none';
@@ -12199,7 +12515,13 @@
12199
12515
  }
12200
12516
  stopPauseEnforcement();
12201
12517
  }
12202
- if (e.type === 'play' || e.type === 'pause' || e.type === 'seeked') clearTimeout(STATE._scheduledPlay);
12518
+ // The hold before a shared start (countdown) is ours. The tap that started the
12519
+ // countdown is still a "recent gesture" when the hold's pause event arrives, which
12520
+ // used to cancel the start and send a pause to everyone (intermittently, depending
12521
+ // on how late the event came). Only a tap made after the hold began counts.
12522
+ const freshTap = (STATE._lastUserGestureTs || 0) > (video._nxuOwnPauseSince || 0) + 30;
12523
+ if ((e.type === 'pause' || e.type === 'seeked') && Date.now() < (video._nxuOwnPauseUntil || 0) && !freshTap) return;
12524
+ if ((e.type === 'play' || e.type === 'pause' || e.type === 'seeked') && gesture && (freshTap || !STATE._scheduledPlay)) { clearTimeout(STATE._scheduledPlay); STATE._scheduledPlay = null; }
12203
12525
  const isPause = e.type === 'pause';
12204
12526
  if (isPause && document.hidden) return;
12205
12527
  // A click or key that slipped through the NexusSync UI to the site's player.
@@ -12675,9 +12997,12 @@
12675
12997
  // Events this command causes are tagged so they are not sent back as decisions.
12676
12998
  // A heartbeat usually changes nothing, so it only tags when it actually seeks or
12677
12999
  // pauses — otherwise a real pause right after a heartbeat would be swallowed.
12678
- const mark = (kinds) => { video._nxuRemoteEventId = data.eventId || null; video._nxuRemoteUntil = Date.now() + 700; video._nxuRemoteKinds = kinds; };
13000
+ const mark = (kinds, ms = 700) => { video._nxuRemoteEventId = data.eventId || null; video._nxuRemoteUntil = Date.now() + ms; video._nxuRemoteKinds = kinds; };
13001
+ // A shared start is waiting (countdown): heartbeats meanwhile must not cancel it.
13002
+ if (heartbeat && video._nxuStartTimer && Date.now() < (video._nxuStartAt || 0) + 500) return;
12679
13003
  if (!heartbeat) mark(data.cmd === 'play' ? 'play seeked ratechange' : data.cmd === 'rate' ? 'ratechange' : 'pause seeked ratechange');
12680
13004
  clearTimeout(video._nxuStartTimer);
13005
+ video._nxuStartTimer = null;
12681
13006
  if (data.cmd === 'rate') {
12682
13007
  RATE.apply(video, rate);
12683
13008
  return;
@@ -12690,15 +13015,22 @@
12690
13015
  const changes = !heartbeat || video.paused || Math.abs(hbDrift) > CONFIG.hardSyncTolerance;
12691
13016
  if (changes) STATE._remoteApplying = true;
12692
13017
  if (data.startIn > 40) {
12693
- // Synchronized start shared with the other devices.
13018
+ // Synchronized start shared with the other devices. The hold's own pause
13019
+ // and seek are tagged as caused by the room for the whole wait (they used
13020
+ // to go back up as someone pausing, which stopped the countdown).
13021
+ const waitMs = Math.min(data.startIn, 10000);
13022
+ mark('pause play seeked ratechange', waitMs + 1500);
12694
13023
  if (!video.paused) { try { video.pause(); } catch (_) { } }
12695
13024
  if (Number.isFinite(data.time) && Math.abs(video.currentTime - data.time) > 0.25) MEDIA_SAFE.seek(video, data.time);
12696
13025
  RATE.apply(video, rate);
13026
+ video._nxuStartAt = Date.now() + waitMs;
12697
13027
  video._nxuStartTimer = setTimeout(() => {
13028
+ video._nxuStartTimer = null;
12698
13029
  STATE._remoteApplying = true;
12699
13030
  MEDIA_SAFE.play(video);
12700
13031
  setTimeout(() => { STATE._remoteApplying = false; }, 150);
12701
- }, Math.min(data.startIn, 3000));
13032
+ setTimeout(() => { if (video.paused) MEDIA_SAFE.play(video); }, 900);
13033
+ }, waitMs);
12702
13034
  setTimeout(() => { STATE._remoteApplying = false; }, 150);
12703
13035
  return;
12704
13036
  }
@@ -12909,7 +13241,7 @@
12909
13241
  updateRateButton();
12910
13242
  if (uiElements.btnCinema) uiElements.btnCinema.style.display = hasMedia || STATE.isCinema ? '' : 'none';
12911
13243
  if (uiElements.btnAutoCinema) { uiElements.btnAutoCinema.style.display = hasMedia || STATE.isCinema ? '' : 'none'; AUTO_CINEMA.paintButton(); }
12912
- if (uiElements.btnBookmark) uiElements.btnBookmark.style.display = ''; // the library is useful anywhere
13244
+ if (uiElements.btnBookmark) uiElements.btnBookmark.style.display = 'none';
12913
13245
  if (uiElements.btnFindMedia) uiElements.btnFindMedia.style.display = hasMedia ? 'none' : '';
12914
13246
  if (uiElements.btnLink) uiElements.btnLink.style.display = hasMedia || connected ? '' : 'none';
12915
13247
  updateDockMenuState();
@@ -12961,6 +13293,11 @@
12961
13293
  if (STATE.handshakeVerified) {
12962
13294
  try { if (ydoc && yPresence) ydoc.transact(() => yPresence.set(STATE.userId, { ts: Date.now(), color: STATE.color, viewer: !!STATE.isViewer, nick: STATE.nickname || '', v: NXU_VERSION, r: NXU_RANK, sess: NXU_SESSION, hid: !!document.hidden }), 'local'); } catch (_) { }
12963
13295
  sendFirebaseCmd('heartbeat', { ts: Date.now() }, 'nexus_rooms');
13296
+ // What this device sent while falling asleep may have been lost: resend everything,
13297
+ // and fetch what the others did meanwhile.
13298
+ HEAL._pushAt = 0; HEAL._askAt = 0;
13299
+ HEAL.pushFull('woke up');
13300
+ HEAL.ask('woke up');
12964
13301
  syncServerClock();
12965
13302
  if (RTC.isHost && STATE.connectionMode === 'HTTP_RELAY') RTC.init();
12966
13303
  }