@kangsicj/nexussync 1.4.0 → 1.6.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.6.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.6.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.6.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':
@@ -672,28 +673,31 @@
672
673
  rotateDenied: '📱 Motion access was declined, so tilting cannot switch to landscape. Use the ↻ button in cinema mode.', menuRotate: 'Tilt-to-landscape for videos on/off (iPhone)',
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
- 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',
676
+ hiddenOnSite: '🙈 ⚙️ button hidden on this site · turn it back on in Settings or with Alt+Shift+N', shownOnSite: '⚙️ Button shown on this site',
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
+ setAutoCinemaSw: 'Auto cinema on this site', setAdGuardSw: 'Ad guard', setHideFab: 'Hide the ⚙️ button on this site', setHideFabHelp: 'On: the floating ⚙️ button no longer appears on this site. To bring it back, turn this switch off — or press Alt+Shift+N, or use the userscript manager’s menu.', setAvatarPh: 'Type any emoji not in the list', setAvatarReset: 'No avatar',
700
+ 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
701
  speakerLanguage: 'Spoken language', speakerHelp: 'The language spoken in the video or by you. Recognition only understands this language.',
698
702
  subtitleLanguage: 'Translate subtitles to', audioSource: 'Audio source', audioAuto: 'Auto (video audio when possible + mic)', audioMic: 'Microphone only',
699
703
  audioMedia: 'Video / tab audio only', audioDual: 'Microphone + video audio',
@@ -710,7 +714,9 @@
710
714
  subUsingMicFallback: 'The video sound could not be heard directly — listening through the microphone (turn the speakers up).',
711
715
  subTabShareEnded: 'Tab audio sharing stopped, so subtitles were turned off.',
712
716
  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”.',
717
+ subDiagCopy: 'Copy a problem report', subDiagCopied: '🔬 Report copied — paste it in your message', subDiagInDebug: '🔬 Report written to the debug console (Settings → Advanced → Debug)',
718
+ subNoTrackInput: '⚠️ This browser’s speech engine cannot listen to the video sound directly — it only hears the microphone (play the sound through speakers, not headphones), or add a free Groq key in AI Sub → Advanced.', subIssueNoTrack: 'The speech engine only hears the microphone here', subNoService: '⚠️ This browser has no working speech recognition service (it works in Chrome). Add a free Groq or an OpenAI key in AI Sub → Advanced to use AI recognition instead.', subNoServiceKey: '⚠️ This browser has no working speech recognition service — switching to AI recognition with your key.',
719
+ 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
720
  subPosition: 'Subtitle position', posVideo: 'Over the video', posScreen: 'Bottom of the screen', subSize: 'Size', subOpacity: 'Opacity',
715
721
  advanced: 'Advanced', translationEngine: 'Translation engine', providerAuto: 'Google first, on-device as backup (best quality)', providerBrowser: 'On-device only (private)',
716
722
  providerGoogle: 'Google only', providerHelp: 'Online translation reads whole sentences far better; the on-device model shows the live line and steps in when offline.',
@@ -722,7 +728,7 @@
722
728
  speakerMic: 'Mic', speakerMedia: 'Video', speakerMixed: 'Mixed',
723
729
  subOn: '🎙️ AI subtitles ON', subOff: '🔇 AI subtitles OFF', subUnsupported: 'This browser has no speech recognition. Use Chrome, Edge or Safari.',
724
730
  subNeedsHttps: 'Subtitles need a secure (https) page.', subMicDenied: '🎤 Microphone access is off. Click the 🔒 icon left of the address bar, set Microphone to “Allow”, then try again.',
725
- subMicUnavailable: '🎙️ No audio input available.', subNoMic: '🎙️ No microphone found.', subServiceBlocked: 'The speech service is not available in this browser.',
731
+ subMicUnavailable: '🎙️ No audio input available.', subNoMic: '🎙️ No microphone found.', subServiceBlocked: 'The speech service is not available in this browser. On iPhone/iPad turn on Settings → Siri (and Dictation in Keyboard settings); elsewhere use Chrome, or add a free Groq key in AI Sub → Advanced.',
726
732
  subNetworkFailed: 'Speech service unreachable. Check the connection and start again.', subLangUnsupported: 'This language is not supported for recognition.',
727
733
  subStalled: 'Speech recognition keeps failing. Please start again.', subWebAudioUnavailable: 'Video audio unavailable here — using the microphone.',
728
734
  p2pActive: '⚡ Direct P2P connection active', p2pLost: '⚠️ P2P lost — using relay', roomConnected: '🟢 Room connected', guestJoined: '👋 A guest joined',
@@ -734,7 +740,7 @@
734
740
  noVideo: '⚠️ No video detected', noPlayingVideo: '⚠️ No playing video found', pipUnsupported: '⚠️ Picture-in-Picture not supported', pipBlocked: '⚠️ Picture-in-Picture was blocked',
735
741
  mediaFound: '✅ Media detected', mediaNotFound: '🔎 No media yet — start the video and try again',
736
742
  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',
743
+ 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
744
  shieldTitle: 'Connected', shieldText: 'Tap to enable synchronized playback in this tab.', shieldButton: 'START SYNC ▶️',
739
745
  menuCinema: 'Toggle cinema mode', menuSubtitles: 'Start / stop AI subtitles', menuShowButton: 'Show / hide the NexusSync button on this site'
740
746
  },
@@ -785,28 +791,31 @@
785
791
  rotateDenied: '📱 동작·방향 접근이 거부되어 기울여서 가로 보기를 쓸 수 없습니다. 시네마 화면의 ↻ 버튼으로 돌릴 수 있습니다.', menuRotate: '동영상 기울이면 가로 보기 켜기/끄기 (아이폰)',
786
792
  canvas: '캔버스', bookmark: '북마크', bookmarkTitle: '현재 위치를 북마크', chat: '채팅', aiSub: 'AI 자막', aiSubTitle: '실시간 자막·번역 (Alt+Shift+T)',
787
793
  subLog: '자막 기록', debug: '디버그', hideOnSite: '이 사이트에서 숨기기', hideOnSiteTitle: '이 사이트에서 떠 있는 버튼 숨기기 (Alt+Shift+N 또는 유저스크립트 메뉴로 복원)',
788
- hiddenOnSite: '🙈 이 사이트에서 숨김 · Alt+Shift+N으로 표시', shownOnSite: '⚙️ 이 사이트에서 버튼 표시',
789
- roomChat: '방 채팅', nickname: '닉네임 (선택)', chatPlaceholder: '메시지…', newMessages: '새 메시지', latest: '최신',
794
+ hiddenOnSite: '🙈 이 사이트에서 ⚙️ 버튼을 숨겼어요 · 설정이나 Alt+Shift+N으로 다시 켤 수 있어요', shownOnSite: '⚙️ 이 사이트에서 버튼 표시',
795
+ roomChat: '방 채팅', chatLog: '채팅 기록', chatCleared: '🧹 채팅 기록을 지웠어요', nickname: '닉네임 (선택)', chatPlaceholder: '메시지…', newMessages: '새 메시지', latest: '최신',
790
796
  subHistory: '자막 기록', export: '내보내기', clear: '지우기', logCleared: '🧹 자막 기록을 지웠습니다', logExported: '💾 자막 기록을 저장했습니다',
791
797
  createRoom: '방 만들기', copyPin: 'PIN 복사', enterPin: 'PIN 입력', joinRoom: '방 참여', viewerMode: '시청자 모드 (조작 없이 따라보기)',
792
798
  aiSubSettings: 'AI 자막', debugConsole: '디버그 콘솔', uiHide: '자동 숨김', keepOpen: '고정',
793
799
  bmLibrary: '북마크', bmAddHere: '지금 장면 북마크', bmSearch: '북마크 검색', bmEmpty: '아직 북마크가 없어요. 보는 중에 “지금 장면 북마크”를 눌러 보세요.', bmLive: '라이브', bmOpening: '📌 북마크를 여는 중…', bmJumped: '📌 {time}(으)로 돌아왔어요', bmLiveOpened: '🔴 라이브 방송을 바로 재생해요', bmDelete: '삭제', bmThisPage: '이 페이지', bmCopy: '링크 복사', bmCopied: '📋 링크를 복사했어요',
794
800
  tuneTitle: '싱크 맞추기', tuneMenu: '싱크 맞추기', tuneOffset: '내 시간 보정', tuneOffsetZero: '방과 같은 타이밍', tuneAhead: '내 영상이 방보다 {s} 앞서 재생돼요', tuneBehind: '내 영상이 방보다 {s} 늦게 재생돼요',
795
801
  tuneResync: '지금 다시 맞추기', tuneReset: '초기화', tuneHelp: '사이트가 달라 영상 길이가 다른가요? (배급사 로고·인트로 차이) 화면이 같아질 때까지 내 타이밍만 옮기면 돼요. 다른 사람에겐 영향이 없어요.',
796
- tuneCompare: '화면 비교', tuneMine: '나', tuneTheirs: '{name}', tuneNoPicture: '화면을 가져올 수 없어요 (보호된 영상)', tuneWaiting: '화면을 받는 중…',
802
+ tuneCompare: '화면 비교', tuneMine: '나', tuneTheirs: '{name}', tuneNoPicture: '보호된 영상이라 화면 대신 시간으로 비교해요', tuneDiffSame: '상대와 같은 위치예요', tuneDiffAhead: '내가 {name}님보다 {s} 앞서 있어요', tuneDiffBehind: '내가 {name}님보다 {s} 뒤에 있어요', tuneWaiting: '화면을 받는 중…',
797
803
  tuneMark: '같은 장면', tuneMarkHint: '각자 같은 장면(예: 로고가 끝난 첫 장면)에서 멈춘 뒤 “이 장면”을 누르세요.', tuneMarkBtn: '📍 이 장면', tuneMarkMine: '나: {t}', tuneMarkTheirs: '{name}: {t}', tuneApply: '적용',
798
804
  tuneAuto: '자동', tuneAutoBtn: '🤖 자동으로 맞추기', tuneAutoHint: '최근 몇 분 동안 서로 재생한 소리(또는 화면)를 비교해요. 먼저 잠시 함께 재생해 주세요.',
799
805
  tuneAutoNeed: '아직 비교할 내용이 부족해요 — 조금 더 함께 재생한 뒤 다시 시도하세요.', tuneAutoFound: '찾았어요: {s} (확신 {c}%)', tuneAutoNone: '뚜렷한 일치를 못 찾았어요. “같은 장면”으로 맞춰 보세요.', tuneAsking: '다른 사람에게 요청하는 중…', tuneApplied: '⏱ 타이밍 보정: {s}',
800
806
  tuneMarkReceived: '📍 {name}님이 장면을 표시했어요', tuneNoPeer: '아직 방에 다른 사람이 없어요.',
807
+ tuneSrcSame: '🟢 모두 같은 영상이에요 — 프레임 단위로 자동으로 맞추고 있어요.', tuneSrcDiff: '🟠 서로 다른 버전이에요 (길이 차이 {s}) — 잠시 재생하면 자동으로 맞추고, 여기서 직접 맞출 수도 있어요.', tuneSrcUnknown: '다른 사람의 영상 정보를 기다리는 중…',
808
+ tuneSameReset: '⏱ 상대와 같은 영상이라 타이밍 보정을 해제했어요.', tuneAutoApplied: '다른 버전이라 타이밍을 {s} 자동 보정했어요 (누르면 되돌리기).', tuneSuggest: '서로 영상 길이가 {s} 달라요. 눌러서 맞춰 보세요.',
801
809
  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: '이 영상은 다른 사이트에서 오는 소리라 여기서 키울 수 없어요.',
810
+ subLoaded: '💬 자막: {name}', subMulti: '자막 여러 개를 함께 보는 중 — 누르면 그 자막만 꺼져요.', subNone: '이 영상에는 포함된 자막이 없어요.', subSuggest: '💬 자막이 없나요? 찾아보기', subLoadFail: '자막을 불러오지 못했어요.',
811
+ osTitle: '자막 찾기', osTmdbLooking: 'TMDB에서 영어 제목을 찾는 중…', osTmdbNone: 'TMDB에서 영어 제목을 찾지 못했어요 — 알고 있다면 직접 입력하세요.', osQuery: '제목 (영어 제목이 가장 잘 찾아져요)', osSeason: '시즌', osEpisode: '회차', osLang: '언어', osSearch: '검색', osSearching: '찾는 중…', osNone: '찾지 못했어요. 영어 제목으로 바꾸거나 연도를 빼 보세요.', osError: 'OpenSubtitles가 응답하지 않아요. 잠시 후 다시 시도하세요.', osDownloads: '다운로드 {n}회', osLoading: '불러오는 중…', osHint: '자막은 OpenSubtitles.org에서 가져와 NexusSync 스타일로 보여 줘요. 빠르거나 늦으면 자막 메뉴의 “싱크”로 맞추세요.',
812
+ viewMenu: '화면', viewAudio: '오디오 트랙', viewBright: '밝기', viewBoost: '볼륨 부스트', viewReset: '초기화', boostBlocked: '이 영상은 다른 사이트에서 오는 소리라 여기서 키울 수 없어요.',
805
813
  settings: '설정', setProfile: '프로필', setAvatar: '아바타', setStatus: '상태 메시지', setStatusPh: '예: 팝콘 준비 완료 🍿', setReactions: '내 리액션',
806
- setReactionsHint: '칸을 누른 뒤 이모지를 고르세요 (아무 이모지나 입력해도 돼요).', setReactionsReset: '기본 리액션으로', setPlayback: '재생', setAutoNext: '다음 화 자동으로 넘기기',
814
+ setReactionsHint: '칸을 누른 뒤 이모지를 고르세요 (아무 이모지나 입력해도 돼요). 칸은 1~16개로 늘리거나 줄일 수 있어요.', setReactionsReset: '기본 리액션으로', setPlayback: '재생', setAutoNext: '다음 화 자동으로 넘기기',
807
815
  setTogether: '함께 보기', setRecvReact: '다른 사람 리액션 보기', setRecvNudge: '찌르기 받기 (흔들림)', setRecvInk: '다른 사람 그림 보기', setRecvChat: '말풍선 보기', setRecvPing: '포인터 보기',
808
816
  setPeople: '이 방의 사람들', setMute: '숨기기', setUnmute: '보이기', setMutedHint: '숨긴 사람의 메시지·리액션·그림은 이 기기에서 보이지 않아요 (이 방에서만).',
809
- setAdvanced: '고급', setEmojiPh: '이모지 입력', setNobody: '아직 다른 사람이 없어요.',
817
+ setAutoCinemaSw: '이 사이트에서 자동 시네마', setAdGuardSw: '광고 가리기', setHideFab: '이 사이트에서 ⚙️ 버튼 숨기기', setHideFabHelp: '켜면 이 사이트에서 화면에 떠 있는 ⚙️ 버튼이 보이지 않아요. 다시 보이게 하려면 이 스위치를 끄거나, Alt+Shift+N 또는 유저스크립트 관리자 메뉴를 쓰세요.', setAvatarPh: '목록에 없는 이모지 입력', setAvatarReset: '아바타 없음',
818
+ setAdvanced: '고급', setAvatarCustom: '이모지나 이니셜 입력', setAvatarPhoto: '사진', setAvatarClear: '지우기', setAvatarFail: '이 사진은 사용할 수 없어요.', setSlotAdd: '+ 칸 추가', setSlotRemove: '- 선택한 칸 삭제', setEmojiPh: '이모지 입력', setNobody: '아직 다른 사람이 없어요.',
810
819
  speakerLanguage: '말하는 언어', speakerHelp: '영상(또는 말하는 사람)의 언어를 선택하세요. 음성 인식은 이 언어만 알아듣습니다.',
811
820
  subtitleLanguage: '자막 번역 언어', audioSource: '오디오 입력', audioAuto: '자동 (가능하면 영상 소리 + 마이크)', audioMic: '마이크만',
812
821
  audioMedia: '영상/탭 소리만', audioDual: '마이크 + 영상 소리',
@@ -823,7 +832,9 @@
823
832
  subUsingMicFallback: '영상 소리를 직접 들을 수 없어 마이크로 들어요. 스피커 소리를 키워 주세요.',
824
833
  subTabShareEnded: '탭 오디오 공유가 끝나서 자막을 껐어요.',
825
834
  subHearVideo: '🎧 영상 소리 듣는 중', subHearMic: '🎧 마이크로 듣는 중', subVideoSilent: '🔇 이 영상의 소리가 자막에 전달되지 않아요',
826
- subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subIssueNoResult: '⚠️ 소리는 들어오는데 말이 인식되지 않아요', subTryMic: '🎤 마이크로 듣기', subTryKey: '🔑 AI 인식 키 사용', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
835
+ subDiagCopy: '문제 진단 보고서 복사', subDiagCopied: '🔬 진단 보고서를 복사했어요 — 메시지에 붙여 넣어 주세요', subDiagInDebug: '🔬 진단 보고서를 디버그 콘솔에 남겼어요 (설정 → 고급 → 디버그)',
836
+ subNoTrackInput: '⚠️ 이 브라우저의 음성 인식은 영상 소리를 직접 듣지 못하고 마이크로만 들어요. 이어폰 대신 스피커로 소리를 내거나, AI 자막 → 고급에서 무료 Groq 키를 넣어 주세요.', subIssueNoTrack: '이 브라우저는 마이크로만 들을 수 있어요', subNoService: '⚠️ 이 브라우저에는 동작하는 음성 인식 서비스가 없어요 (Chrome에서는 동작해요). AI 자막 → 고급에서 무료 Groq 키나 OpenAI 키를 넣으면 AI 인식으로 쓸 수 있어요.', subNoServiceKey: '⚠️ 이 브라우저에는 동작하는 음성 인식 서비스가 없어 입력한 키로 AI 인식을 시작해요.',
837
+ subIssueNet: '⚠️ 음성 인식 서버 연결이 불안정해요 — 다시 시도 중', subIssueNoResult: '⚠️ 소리는 들어오는데 말이 인식되지 않아요', subSiteBlocksSpeech: '이 사이트는 브라우저 음성 인식을 막아 두었어요. AI 자막 → 고급에서 OpenAI 또는 Groq 키를 넣으면 여기서도 쓸 수 있어요.', subSiteBlocksSpeechKey: '이 사이트는 브라우저 음성 인식을 막아 두어서, 넣어 둔 키로 클라우드 인식으로 바꿀게요.', subTryMic: '🎤 마이크로 듣기', subTryKey: '🔑 AI 인식 키 사용', subShareTab: '🎬 탭 소리 연결', subTabNotShared: '탭 오디오가 공유되지 않았어요. 이 탭을 고르고 “탭 오디오 공유”를 켜 주세요.',
827
838
  subPosition: '자막 위치', posVideo: '영상 위', posScreen: '화면 하단', subSize: '크기', subOpacity: '불투명도',
828
839
  advanced: '고급', translationEngine: '번역 엔진', providerAuto: 'Google 우선, 기기 내 번역 보조 (최고 품질)', providerBrowser: '기기 내 번역만 (개인정보 보호)',
829
840
  providerGoogle: 'Google만', providerHelp: '문장 번역 품질은 온라인(Google)이 훨씬 좋습니다. 기기 내 모델은 실시간 임시 줄과 오프라인 상황을 맡습니다.',
@@ -835,7 +846,7 @@
835
846
  speakerMic: '마이크', speakerMedia: '영상', speakerMixed: '혼합',
836
847
  subOn: '🎙️ AI 자막 켜짐', subOff: '🔇 AI 자막 꺼짐', subUnsupported: '이 브라우저는 음성 인식을 지원하지 않습니다. Chrome, Edge, Safari를 사용하세요.',
837
848
  subNeedsHttps: '자막은 보안(https) 페이지에서만 동작합니다.', subMicDenied: '🎤 마이크 권한이 꺼져 있어요. 주소창 왼쪽 🔒(사이트 정보)에서 마이크를 “허용”으로 바꾼 뒤 다시 눌러 주세요.',
838
- subMicUnavailable: '🎙️ 사용할 수 있는 오디오 입력이 없습니다.', subNoMic: '🎙️ 마이크를 찾을 수 없습니다.', subServiceBlocked: '이 브라우저에서는 음성 인식 서비스를 사용할 수 없습니다.',
849
+ subMicUnavailable: '🎙️ 사용할 수 있는 오디오 입력이 없습니다.', subNoMic: '🎙️ 마이크를 찾을 수 없습니다.', subServiceBlocked: '이 브라우저에서는 음성 인식 서비스를 쓸 수 없어요. 아이폰·아이패드는 설정 → Siri와 키보드 설정의 받아쓰기를 켜 주세요. 그 밖에는 Chrome을 쓰거나 AI 자막 → 고급에서 무료 Groq 키를 넣어 주세요.',
839
850
  subNetworkFailed: '음성 인식 서버에 연결할 수 없습니다. 연결을 확인하고 다시 시작하세요.', subLangUnsupported: '이 언어는 음성 인식을 지원하지 않습니다.',
840
851
  subStalled: '음성 인식이 계속 실패합니다. 다시 시작해 주세요.', subWebAudioUnavailable: '이 페이지에서는 영상 소리를 직접 받을 수 없어 마이크를 사용합니다.',
841
852
  p2pActive: '⚡ P2P 직접 연결됨', p2pLost: '⚠️ P2P 끊김 — 중계 서버로 전환', roomConnected: '🟢 방에 연결됨', guestJoined: '👋 게스트가 참여했습니다',
@@ -847,7 +858,7 @@
847
858
  noVideo: '⚠️ 감지된 영상이 없습니다', noPlayingVideo: '⚠️ 재생 중인 영상이 없습니다', pipUnsupported: '⚠️ PiP를 지원하지 않습니다', pipBlocked: '⚠️ PiP가 차단되었습니다',
848
859
  mediaFound: '✅ 미디어 감지됨', mediaNotFound: '🔎 아직 미디어가 없습니다 — 영상을 재생한 뒤 다시 시도하세요',
849
860
  canvasOn: '🎨 캔버스 켜짐', canvasOff: '🎨 캔버스 꺼짐', canvasViewOnly: '🎨 캔버스 (보기 전용)', nothingToUndo: '↩️ 되돌릴 내용이 없습니다', undo: '되돌리기 (Ctrl+Z)',
850
- pen: '펜', eraser: '지우개', clearCanvas: '모두 지우기', watching: '{n}명 시청 중', meTag: '(나)', whoViewer: '보기 전용', whoAway: '자리 비움 (화면 꺼짐·다른 탭)', whoOldVer: '다른 버전 — 업데이트가 필요해요', whoTitle: '함께 보는 사람',
861
+ pen: '펜', eraser: '지우개', clearCanvas: '모두 지우기', watching: '{n}명 시청 중', meTag: '(나)', whoViewer: '보기 전용', whoAway: '자리 비움 (화면 꺼짐·다른 탭)', whoOldVer: '다른 버전 — 업데이트가 필요해요', whoTitle: '함께 보는 사람', whoSleeping: '화면 꺼짐 — 방에 그대로 있고, 화면이 켜지면 돌아와요', whoReconnecting: '다시 연결하는 중…',
851
862
  shieldTitle: '연결됨', shieldText: '눌러서 이 탭의 동기화 재생을 활성화하세요.', shieldButton: '동기화 시작 ▶️',
852
863
  menuCinema: '시네마 모드 켜기/끄기', menuSubtitles: 'AI 자막 시작/중지', menuShowButton: '이 사이트에서 NexusSync 버튼 표시/숨기기'
853
864
  }
@@ -1167,14 +1178,15 @@
1167
1178
  .nxu-cinema-root.nxu-ambient-stage { top: var(--nxu-stage-y, 0px) !important; bottom: auto !important; left: var(--nxu-stage-x, 0px) !important; right: auto !important;
1168
1179
  width: calc(100vw - 2 * var(--nxu-stage-x, 0px)) !important; height: calc(100vh - 2 * var(--nxu-stage-y, 0px)) !important; height: calc(100dvh - 2 * var(--nxu-stage-y, 0px)) !important;
1169
1180
  box-shadow: 0 16px 48px rgba(0,0,0,0.5) !important; }
1170
- .nxu-fit-cover video.nxu-cinema-video, video.nxu-cinema-root.nxu-fit-cover { object-fit: cover !important; }
1171
- .nxu-fit-fill video.nxu-cinema-video, video.nxu-cinema-root.nxu-fit-fill { object-fit: fill !important; }
1181
+ .nxu-fit-cover video.nxu-cinema-video, video.nxu-cinema-root.nxu-fit-cover, video.nxu-cinema-video.nxu-fit-cover { object-fit: cover !important; }
1182
+ .nxu-fit-fill video.nxu-cinema-video, video.nxu-cinema-root.nxu-fit-fill, video.nxu-cinema-video.nxu-fit-fill { object-fit: fill !important; }
1172
1183
  .nxu-site-ui-off :is([class*="control" i], [class*="ctrl" i], [class*="toolbar" i], [class*="progress" i], [class*="seek" i], [class*="big-play" i], [class*="bigplay" i],
1173
1184
  [class*="play-button" i], [class*="playbutton" i], [class*="play-btn" i], [class*="spinner" i], [class*="loading" i], [class*="chrome" i], [class*="gradient" i], [class*="overlay" i],
1174
1185
  [class*="mask" i], [class*="volume" i], [class*="settings" i], [class*="menu" i], [class*="tooltip" i], [class*="watermark" i], .jw-display, .xgplayer-start, .fp-ui, .art-layers, .art-notice):not(video):not(.nxu-cinema-fill):not(.nxu-keep):not([class*="caption" i]):not([class*="subtitle" i]):not([class*="text-track" i]):not([class*="cue" i]):not([class*="sub-" i]):not([class*="danmaku" i]) {
1175
1186
  visibility: hidden !important; pointer-events: none !important; transition: none !important; animation: none !important; }
1176
1187
  .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
1188
  .nxu-site-ui-off .nxu-site-hide { visibility: hidden !important; pointer-events: none !important; transition: none !important; animation: none !important; }
1189
+ .nxu-site-ui-off .nxu-dsub-src, .nxu-site-ui-off .nxu-dsub-src * { visibility: hidden !important; }
1178
1190
  .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
1191
  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
1192
  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; }
@@ -1197,6 +1209,23 @@
1197
1209
  } catch (_) { }
1198
1210
  }
1199
1211
  function ensureCinemaStyles(doc = document) { ensurePageStyle(doc, 'nxu-cinema-style', CINEMA_CSS); }
1212
+ // Players built from web components keep the <video> inside a shadow root (famelack's
1213
+ // <hlsjs-video>, media-chrome, many live-TV sites): page styles never reach it, so the
1214
+ // cinema styles go into every shadow root on the way from the video to the page.
1215
+ function parentAcross(n) { return n.parentElement || (n.parentNode && n.parentNode.host) || null; }
1216
+ function ensureCinemaStylesIn(node) {
1217
+ const r = node?.getRootNode?.();
1218
+ if (!r || r.nodeType !== 11 || !r.host) return;
1219
+ try {
1220
+ const old = r.querySelector('style[data-nxu-cinema]');
1221
+ if (old && old.dataset.nxuCinema === NXU_RANK) return;
1222
+ old?.remove();
1223
+ const style = (node.ownerDocument || document).createElement('style');
1224
+ style.dataset.nxuCinema = NXU_RANK;
1225
+ style.textContent = CINEMA_CSS;
1226
+ r.appendChild(style);
1227
+ } catch (_) { }
1228
+ }
1200
1229
 
1201
1230
  const PLAYER_CLASS_HINTS = ['html5-video-player', 'video-js', 'jwplayer', 'plyr', 'artplayer', 'dplayer', 'xgplayer', 'shaka-video-container',
1202
1231
  'vjs-fluid', 'mejs__container', 'flowplayer', 'clappr', 'bitmovinplayer-container', 'video-player', 'player-container', 'video-container'];
@@ -1213,26 +1242,26 @@
1213
1242
  try { vr = video.getBoundingClientRect(); } catch (_) { return video; }
1214
1243
  let root = video;
1215
1244
  if (vr.width < 40 || vr.height < 30) {
1216
- let node = video.parentElement;
1245
+ let node = parentAcross(video);
1217
1246
  while (node && node !== doc.body) {
1218
1247
  if (PLAYER_CLASS_HINTS.some(c => node.classList?.contains(c))) root = node;
1219
- node = node.parentElement;
1248
+ node = parentAcross(node);
1220
1249
  }
1221
1250
  return root;
1222
1251
  }
1223
1252
  const maxW = vr.width * 1.12 + 24;
1224
1253
  const maxH = vr.height * 1.3 + 90;
1225
- let node = video.parentElement;
1254
+ let node = parentAcross(video);
1226
1255
  while (node && node !== doc.body && node !== doc.documentElement) {
1227
1256
  let r;
1228
1257
  try { r = node.getBoundingClientRect(); } catch (_) { break; }
1229
1258
  if (r.width > maxW || r.height > maxH) break;
1230
1259
  try {
1231
1260
  const cs = view.getComputedStyle(node);
1232
- if (cs.display === 'contents') { node = node.parentElement; continue; }
1261
+ if (cs.display === 'contents' || node.tagName === 'SLOT') { node = parentAcross(node); continue; }
1233
1262
  } catch (_) { }
1234
1263
  root = node;
1235
- node = node.parentElement;
1264
+ node = parentAcross(node);
1236
1265
  }
1237
1266
  return root;
1238
1267
  },
@@ -1240,8 +1269,10 @@
1240
1269
  _decorate(root, video) {
1241
1270
  const doc = root.ownerDocument;
1242
1271
  ensureCinemaStyles(doc);
1272
+ ensureCinemaStylesIn(root);
1243
1273
  const ancestors = [];
1244
- for (let n = root.parentElement; n; n = n.parentElement) {
1274
+ for (let n = parentAcross(root); n; n = parentAcross(n)) {
1275
+ ensureCinemaStylesIn(n);
1245
1276
  if (!n.classList.contains('nxu-cinema-ancestor')) {
1246
1277
  n.classList.add('nxu-cinema-ancestor');
1247
1278
  ancestors.push(n);
@@ -1249,7 +1280,10 @@
1249
1280
  }
1250
1281
  const fills = [];
1251
1282
  if (video && video !== root) {
1252
- for (let n = video.parentElement; n && n !== root; n = n.parentElement) {
1283
+ ensureCinemaStylesIn(video);
1284
+ for (let n = parentAcross(video); n && n !== root; n = parentAcross(n)) {
1285
+ ensureCinemaStylesIn(n);
1286
+ if (n.tagName === 'SLOT') continue;
1253
1287
  n.classList.add('nxu-cinema-fill');
1254
1288
  fills.push(n);
1255
1289
  }
@@ -1264,7 +1298,7 @@
1264
1298
  if (!link) return;
1265
1299
  try {
1266
1300
  link.root.classList.remove('nxu-cinema-root');
1267
- link.video?.classList.remove('nxu-cinema-video');
1301
+ link.video?.classList.remove('nxu-cinema-video', 'nxu-fit-cover', 'nxu-fit-fill');
1268
1302
  link.fills.forEach(n => n.classList.remove('nxu-cinema-fill'));
1269
1303
  link.ancestors.forEach(n => n.classList.remove('nxu-cinema-ancestor'));
1270
1304
  link.doc.documentElement.classList.remove('nxu-cinema-lock');
@@ -1420,6 +1454,9 @@
1420
1454
  const fit = this.fitMode();
1421
1455
  root.classList.toggle('nxu-fit-cover', fit === 'cover');
1422
1456
  root.classList.toggle('nxu-fit-fill', fit === 'fill');
1457
+ // A video in a shadow root is not a descendant the page's selector can see: mark it too.
1458
+ const v = this.applied?.video || STATE.video;
1459
+ if (v && v.getRootNode?.() !== root.getRootNode?.()) { v.classList.toggle('nxu-fit-cover', fit === 'cover'); v.classList.toggle('nxu-fit-fill', fit === 'fill'); }
1423
1460
  },
1424
1461
  // Cinema controls: hide the site's player UI (and native video controls); site
1425
1462
  // controls: show them again and wake them with a mouse move so they appear at once.
@@ -1460,6 +1497,7 @@
1460
1497
  };
1461
1498
  if (!hide || !root || !video || root === video) { undo(); return; }
1462
1499
  const run = () => {
1500
+ const textLayers = [];
1463
1501
  const chain = new Set();
1464
1502
  for (let n = video; n && n !== root; n = n.parentElement) chain.add(n);
1465
1503
  const hidden = [];
@@ -1474,13 +1512,14 @@
1474
1512
  const interactive = child.matches(CTRL) || !!child.querySelector(CTRL);
1475
1513
  const text = (child.textContent || '').trim();
1476
1514
  // Text without any control: most likely the site's own subtitles.
1477
- if (!interactive && text) continue;
1515
+ if (!interactive && text) { textLayers.push(child); continue; }
1478
1516
  child.classList.add('nxu-site-hide');
1479
1517
  hidden.push(child);
1480
1518
  }
1481
1519
  }
1482
1520
  (this._hidden || []).forEach(n => { if (!hidden.includes(n)) n.classList.remove('nxu-site-hide'); });
1483
1521
  this._hidden = hidden;
1522
+ this._textLayers = textLayers;
1484
1523
  };
1485
1524
  run();
1486
1525
  if (!this._hideObs || this._hideObsRoot !== root) {
@@ -2379,10 +2418,23 @@
2379
2418
  return /iPad|iPhone|iPod/.test(ua) || (navigator.platform === 'MacIntel' && Number(navigator.maxTouchPoints) > 1);
2380
2419
  },
2381
2420
  _isAndroid() { return /Android/i.test(navigator.userAgent || ''); },
2421
+ // Can the speech engine listen to a given audio track (the video's sound)? Browsers
2422
+ // without it silently ignore the track and listen to the microphone instead — with
2423
+ // headphones that hears nothing at all. Asked once: an engine that knows the argument
2424
+ // refuses a non-track value with a TypeError; one that does not ignores it (and would
2425
+ // start listening, so it is stopped at once).
2382
2426
  _supportsTrackInput() {
2383
- const ua = navigator.userAgent || '';
2384
- const desktopSafari = /Safari\//.test(ua) && !/Chrome|Chromium|CriOS|Edg|OPR|FxiOS|Android/.test(ua);
2385
- return !(this._isAppleMobile() || desktopSafari);
2427
+ if (this._trackInputOk !== undefined) return this._trackInputOk;
2428
+ if (this._isAppleMobile()) return (this._trackInputOk = false);
2429
+ const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
2430
+ if (!SR) return (this._trackInputOk = false);
2431
+ let ok = false;
2432
+ try {
2433
+ const probe = new SR();
2434
+ try { probe.start({}); try { probe.abort(); } catch (_) { } } catch (err) { ok = err?.name === 'TypeError' && /MediaStreamTrack/i.test(err.message || ''); }
2435
+ } catch (_) { }
2436
+ logDebug('AI Sub: speech engine ' + (ok ? 'can' : 'cannot') + ' listen to the video sound directly.', ok ? 'info' : 'warn');
2437
+ return (this._trackInputOk = ok);
2386
2438
  },
2387
2439
 
2388
2440
  // ── text helpers
@@ -2747,6 +2799,7 @@
2747
2799
  }
2748
2800
  } catch (_) { }
2749
2801
  },
2802
+ _diag: { sound: 0, results: 0, err: '' },
2750
2803
  _createRecognizer() {
2751
2804
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
2752
2805
  const r = new SR();
@@ -2779,10 +2832,10 @@
2779
2832
  this._appleRestoreTimer = setTimeout(() => this._setAppleSession('playback'), 220);
2780
2833
  }
2781
2834
  };
2782
- r.onsoundstart = () => { if (alive()) { this._touch(); this._soundHeard = true; } };
2835
+ r.onsoundstart = () => { if (alive()) { this._touch(); this._soundHeard = true; this._diag.sound++; } };
2783
2836
  r.onspeechstart = () => { if (alive()) this._touch(); };
2784
- r.onresult = (event) => { if (alive()) this._onResult(event); };
2785
- r.onerror = (event) => { if (alive()) this._onError(event); };
2837
+ r.onresult = (event) => { if (alive()) { this._diag.results++; this._onResult(event); } };
2838
+ r.onerror = (event) => { if (alive()) { this._diag.err = event?.error || '?'; this._onError(event); } };
2786
2839
  r.onend = () => { if (alive()) this._onEnd(); };
2787
2840
  this.recognizer = r;
2788
2841
  },
@@ -2811,6 +2864,10 @@
2811
2864
  this._sessionStartedAt = Date.now();
2812
2865
  this._setAppleSession('play-and-record');
2813
2866
  const track = !this._trackDisabled && this._supportsTrackInput() ? this._liveTrack() : null;
2867
+ if (!track && this.audioMode === 'media' && this.captureMode !== 'ios-mic' && !this._cloud && !this._toldNoTrack) {
2868
+ this._toldNoTrack = true;
2869
+ if (!this._supportsTrackInput()) { this._issue = this._issue || 'notrack'; showToast(t('subNoTrackInput')); }
2870
+ }
2814
2871
  try {
2815
2872
  if (track) this.recognizer.start(track);
2816
2873
  else this.recognizer.start();
@@ -2881,7 +2938,7 @@
2881
2938
  this._scheduleRestart('track-fallback', 150, true);
2882
2939
  }
2883
2940
  // 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';
2941
+ if (this._useWebSpeech && !this._issue && this._soundMs > 15000 && (this._lastResultAt || 0) < (this._startedAt || 0)) this._issue = 'noresult';
2885
2942
  this._updateListenChip();
2886
2943
  updateAIBtnUX();
2887
2944
  },
@@ -2966,22 +3023,22 @@
2966
3023
  chip.classList.toggle('warn', silent);
2967
3024
  chip.classList.toggle('warn', silent || !!this._issue);
2968
3025
  if (this._issue) chip.classList.remove('hide');
2969
- chip.querySelector('.sub-listen-text').textContent = this._issue === 'noresult' ? t('subIssueNoResult') : this._issue === 'net' ? t('subIssueNet') : silent ? t('subVideoSilent') : this.webMediaStream && !this._micMixed ? t('subHearVideo') : t('subHearMic');
3026
+ chip.querySelector('.sub-listen-text').textContent = this._issue === 'notrack' ? t('subIssueNoTrack') : this._issue === 'noresult' ? t('subIssueNoResult') : this._issue === 'net' ? t('subIssueNet') : silent ? t('subVideoSilent') : this.webMediaStream && !this._micMixed ? t('subHearVideo') : t('subHearMic');
2970
3027
  const level = Math.max(this._levels.media || 0, this._levels.mic || 0);
2971
3028
  chip.querySelector('.sub-listen-meter i').style.width = Math.min(100, Math.round(level * 400)) + '%';
2972
3029
  chip.querySelector('.sub-listen-btn').style.display = offer ? '' : 'none';
2973
3030
  let alt = chip.querySelector('.sub-listen-alt');
2974
- const wantAlt = this._issue === 'noresult';
3031
+ const wantAlt = this._issue === 'noresult' || this._issue === 'notrack';
2975
3032
  if (wantAlt && !alt) {
2976
3033
  alt = createEl('button', 'sub-listen-btn sub-listen-alt', '', { type: 'button' });
2977
3034
  alt.addEventListener('click', (e) => {
2978
3035
  e.stopPropagation();
2979
- if (this.audioMode === 'media') { STORE.set('nxu_audio_mode', 'mic'); this.restart('no words from the video sound'); }
3036
+ if (this.audioMode === 'media' && this._issue !== 'notrack') { STORE.set('nxu_audio_mode', 'mic'); this.restart('no words from the video sound'); }
2980
3037
  else { const m = shadow?.getElementById('trans-modal'); if (m) { openPanel(m); const d = m.querySelector('.ai-advanced'); if (d) d.open = true; } }
2981
3038
  });
2982
3039
  chip.appendChild(alt);
2983
3040
  }
2984
- if (alt) { alt.style.display = wantAlt ? '' : 'none'; alt.textContent = this.audioMode === 'media' ? t('subTryMic') : t('subTryKey'); }
3041
+ if (alt) { alt.style.display = wantAlt ? '' : 'none'; alt.textContent = this.audioMode === 'media' && this._issue !== 'notrack' ? t('subTryMic') : t('subTryKey'); }
2985
3042
  },
2986
3043
  _preparePlaybackMic() {
2987
3044
  const track = this.mediaStream?.getAudioTracks?.()[0];
@@ -3152,10 +3209,26 @@
3152
3209
  switch (error) {
3153
3210
  case 'aborted':
3154
3211
  return;
3155
- case 'not-allowed':
3156
- logDebug('AI Sub: microphone permission denied.', 'error');
3157
- this.stop(t('subMicDenied'));
3212
+ case 'not-allowed': {
3213
+ // Fed from a captured track, try once more with the engine's own input
3214
+ // (some browsers refuse a track); then say exactly why it cannot listen.
3215
+ if (this._recognitionInput === 'track' && !this._trackDisabled) {
3216
+ this._trackDisabled = true;
3217
+ logDebug('AI Sub: the speech engine refused the captured audio, trying its own input.', 'warn');
3218
+ this._destroyRecognizer(); this._createRecognizer(); this._scheduleRestart('track-refused', 200, true);
3219
+ return;
3220
+ }
3221
+ const policy = this._micBlockedByPolicy();
3222
+ logDebug('AI Sub: speech recognition not allowed' + (policy ? ' (blocked by this site)' : ''), 'error');
3223
+ const cloudKey = AI.key('openai') || AI.key('groq');
3224
+ this.stop(t(policy ? (cloudKey ? 'subSiteBlocksSpeechKey' : 'subSiteBlocksSpeech') : 'subMicDenied'));
3225
+ // With a key, cloud recognition does not need the browser's speech engine.
3226
+ if (policy && cloudKey && STORE.get('nxu_asr_provider', 'browser') === 'browser') {
3227
+ STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai');
3228
+ setTimeout(() => this.start().catch(() => { }), 400);
3229
+ }
3158
3230
  return;
3231
+ }
3159
3232
  case 'service-not-allowed':
3160
3233
  if (this.recognizer?.processLocally) {
3161
3234
  this._localSpeechReady = false;
@@ -3183,6 +3256,19 @@
3183
3256
  case 'network': {
3184
3257
  this._networkErrors++;
3185
3258
  this._issue = this._networkErrors >= 2 ? 'net' : '';
3259
+ // Not one word yet and the service keeps refusing: this browser has no
3260
+ // working speech service (some Chromium browsers and apps ship without
3261
+ // one). Say so plainly instead of retrying for minutes.
3262
+ if (this._networkErrors >= 4 && !this._diag.results && navigator.onLine !== false) {
3263
+ const cloudKey = AI.key('openai') || AI.key('groq');
3264
+ logDebug('AI Sub: the browser speech service is unreachable here.', 'error');
3265
+ this.stop(t(cloudKey ? 'subNoServiceKey' : 'subNoService'));
3266
+ if (cloudKey && STORE.get('nxu_asr_provider', 'browser') === 'browser') {
3267
+ STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai');
3268
+ setTimeout(() => this.start().catch(() => { }), 400);
3269
+ }
3270
+ return;
3271
+ }
3186
3272
  if (this._networkErrors >= 12) { this.stop(t('subNetworkFailed')); return; }
3187
3273
  if (navigator.onLine === false) { this._waitOnline = true; return; }
3188
3274
  this._networkRetryMs = Math.min(15000, Math.max(800, (this._networkRetryMs || 600) * 1.7));
@@ -3771,6 +3857,8 @@
3771
3857
  if (this._useWebSpeech) await this._prepareLocalSpeech(SR).catch(() => { });
3772
3858
  if (token !== this._startToken) return;
3773
3859
  this.state = 'running';
3860
+ this._diag = { sound: 0, results: 0, err: '' };
3861
+ this._toldNoTrack = false;
3774
3862
  this._startedAt = Date.now();
3775
3863
  this._soundMs = 0;
3776
3864
  this.active = true;
@@ -3788,6 +3876,27 @@
3788
3876
  logDebug(`AI Sub started (${this.captureMode}, ${this._recognitionLanguage()} → ${this.outLang}, recognition: ${this._cloud ? AI.asrModel() : this._sttProvider}${this._cloud && this._useWebSpeech ? ' + live preview' : ''}, translation: ${AI.translateProvider()}).`, 'success');
3789
3877
  },
3790
3878
  // Cloud recognition returned a finished utterance (already in speaking order).
3879
+ // Everything needed to tell why AI subtitles stay empty, as plain text the user can paste.
3880
+ async diagReport() {
3881
+ const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
3882
+ const v = STATE.video;
3883
+ let local = '-';
3884
+ try { if (SR && typeof SR.available === 'function') local = await withTimeout(SR.available({ langs: [this._recognitionLanguage()], processLocally: true }), 1500); } catch (_) { local = '?'; }
3885
+ const lines = [
3886
+ 'NexusSync ' + NXU_VERSION + ' · AI subtitle report',
3887
+ 'browser: ' + navigator.userAgent,
3888
+ 'page: ' + location.hostname + (window.isSecureContext ? ' (https)' : ' (NOT secure)'),
3889
+ 'speech API: ' + (SR ? 'yes' : 'NO') + ' · hears video sound directly: ' + (SR ? (this._supportsTrackInput() ? 'yes' : 'NO') : '-') + ' · on-device (' + this._recognitionLanguage() + '): ' + local,
3890
+ 'microphone blocked by site: ' + (this._micBlockedByPolicy() ? 'YES' : 'no') + ' · permission: ' + (await this._micPermissionState()),
3891
+ 'recognition: ' + (this._cloud ? 'cloud ' + AI.asrModel() : (this._useWebSpeech ? this._sttProvider || 'web-speech' : '-')) + ' · state: ' + this.state,
3892
+ 'wanted sound: ' + (this.audioMode || this._audioMode()) + ' · capturing: ' + (this.captureMode || '-') + ' · engine input: ' + (this._recognitionInput || '-') + (this._trackDisabled ? ' (track refused)' : '') + (this._micMixed ? ' · mic mixed in' : ''),
3893
+ 'video: ' + (v ? (v.paused ? 'paused' : 'playing') + (v.muted ? ', muted' : '') + ', volume ' + Math.round((v.volume || 0) * 100) + '%' : 'none') + ' · video sound peak: ' + (this._mediaPeak || 0).toFixed(4),
3894
+ 'levels: video ' + Math.round((this._levels?.media || 0) * 400) + ' · mic ' + Math.round((this._levels?.mic || 0) * 400),
3895
+ 'engine events: sound ' + this._diag.sound + ' · results ' + this._diag.results + ' · last error ' + (this._diag.err || '-') + ' · network errors ' + (this._networkErrors || 0),
3896
+ 'issue: ' + (this._issue || '-')
3897
+ ];
3898
+ return lines.join('\n');
3899
+ },
3791
3900
  onCloudTranscript(text, reason, meta) {
3792
3901
  if (!this.active) return;
3793
3902
  const clean = this._normalize(text);
@@ -3940,7 +4049,9 @@
3940
4049
  const engine = T._cloud ? AI.asrModel() + (T._useWebSpeech ? ' + live' : '') : (T._sttProvider === 'web-speech-local' ? t('engineLocal') : t('engineOnline'));
3941
4050
  const tx = T._providerStatus ? ` · ${t('translation')}: ${T._providerStatus}` : '';
3942
4051
  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}`;
4052
+ // What the speech engine reports (helps tell "no sound" from "no words").
4053
+ const dg = T._useWebSpeech ? ` · 🔎 ${T._diag.sound}/${T._diag.results}${T._diag.err ? ' · ⚠ ' + T._diag.err : ''}` : '';
4054
+ status.textContent = `● ${t('subListening')} · ${lang} → ${T._label(T.outLang)} · ${input} · ${engine}${tx}${level}${dg}`;
3944
4055
  }
3945
4056
  }
3946
4057
  }
@@ -5180,6 +5291,7 @@
5180
5291
  if (uid && typeof d.sess === 'string' && cur && typeof cur.sess === 'string' && cur.sess !== d.sess) break;
5181
5292
  if (uid && uid !== STATE.userId) {
5182
5293
  const name = participantName(uid);
5294
+ PRESENCE.left.add(uid);
5183
5295
  PRESENCE.seen.delete(uid);
5184
5296
  PRESENCE.refresh();
5185
5297
  showToast(t('peerLeft', { name }));
@@ -5240,12 +5352,12 @@
5240
5352
  if (ydoc && Array.isArray(d.data)) d.data.forEach(u => { try { Y.applyUpdate(ydoc, new Uint8Array(u), 'remote'); } catch (_) { } });
5241
5353
  break;
5242
5354
  case 'yjs_sync_request':
5243
- if (ydoc) sendFirebaseCmd('yjs_update', { data: Array.from(Y.encodeStateAsUpdate(ydoc)) }, 'nexus_rooms');
5355
+ if (ydoc) HEAL.pushFull('asked');
5244
5356
  break;
5245
5357
  case 'reaction':
5246
5358
  onRemoteReaction(d);
5247
5359
  break;
5248
- case 'nudge': case 'pointer': case 'countdown': case 'typing': case 'ink': case 'cover': case 'goto': case 'tune':
5360
+ case 'nudge': case 'pointer': case 'countdown': case 'typing': case 'ink': case 'cover': case 'goto': case 'tune': case 'avatar':
5249
5361
  SOCIAL.receive(p.t, d);
5250
5362
  break;
5251
5363
  }
@@ -5256,6 +5368,40 @@
5256
5368
  if (!RTC.sendData('yjs_sync_request', {})) sendFirebaseCmd('yjs_sync_request', {}, 'nexus_rooms');
5257
5369
  }
5258
5370
 
5371
+ // Room-state healing. An update sent just as a phone went to sleep can be lost; the
5372
+ // others then hold that device's later updates aside forever (they build on the lost
5373
+ // one), so its presence, play/pause and seeks stopped arriving while plain messages
5374
+ // (reactions) still did. Every device now resends its whole state after waking, and
5375
+ // anyone who notices missing pieces (or hears from someone it cannot see) asks for it.
5376
+ const HEAL = {
5377
+ _askAt: 0, _pushAt: 0,
5378
+ pushFull(reason) {
5379
+ if (!ydoc || !SOCIAL.live() || Date.now() - this._pushAt < 4000) return;
5380
+ this._pushAt = Date.now();
5381
+ const full = { data: Array.from(Y.encodeStateAsUpdate(ydoc)) };
5382
+ sendFirebaseCmd('yjs_update', full, 'nexus_rooms');
5383
+ if (STATE.connectionMode === 'WEBRTC_P2P') RTC.sendData('yjs_update', full);
5384
+ logDebug('Room state resent (' + reason + ').', 'info');
5385
+ },
5386
+ ask(reason) {
5387
+ if (!ydoc || !SOCIAL.live() || Date.now() - this._askAt < 8000) return;
5388
+ this._askAt = Date.now();
5389
+ requestRoomState();
5390
+ logDebug('Asked the room for its full state (' + reason + ').', 'info');
5391
+ },
5392
+ check() {
5393
+ if (!ydoc || !STATE.handshakeVerified) return;
5394
+ const st = ydoc.store;
5395
+ if (st && (st.pendingStructs || st.pendingDs)) this.ask('missing updates');
5396
+ },
5397
+ // A message from someone who is not in the list: their state did not reach us.
5398
+ heard(uid) {
5399
+ if (!uid || uid === STATE.userId || !STATE.handshakeVerified) return;
5400
+ if (!STATE.presenceMap?.[uid]) { this.ask('message from an unlisted device'); this.pushFull('peer unseen'); }
5401
+ }
5402
+ };
5403
+ if (IS_TOP) setInterval(() => { try { HEAL.check(); } catch (_) { } }, 10000);
5404
+
5259
5405
  // Sends room authority to the player inside a cross-origin frame.
5260
5406
  function sendStateToFrame(state, frame = STATE.cinemaIframe) {
5261
5407
  if (!frame || !state) return;
@@ -5270,7 +5416,7 @@
5270
5416
  rate,
5271
5417
  eventId: state.eventId,
5272
5418
  action: state.action,
5273
- startIn: state.play && wait > 40 ? Math.min(wait, 3000) : 0
5419
+ startIn: state.play && wait > 40 ? Math.min(wait, 10000) : 0
5274
5420
  });
5275
5421
  }
5276
5422
 
@@ -5371,7 +5517,7 @@
5371
5517
  const now = Date.now();
5372
5518
  // Freshness uses the time *we* received an update, not the sender's clock: phones and
5373
5519
  // 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); });
5520
+ 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
5521
  PRESENCE.refresh();
5376
5522
  // Someone on an older NexusSync: play/pause/seek from mixed versions do not line up
5377
5523
  // as well (older builds let heartbeats override other devices) — say so once.
@@ -5445,7 +5591,11 @@
5445
5591
  return;
5446
5592
  }
5447
5593
  }
5594
+ // A synchronized start (countdown, shared resume) is waiting: a heartbeat arriving
5595
+ // meanwhile must not cancel it (that left everyone paused after the countdown).
5596
+ if (STATE._scheduledPlay && action === 'heartbeat' && Date.now() < (STATE._scheduledPlayAt || 0) + 500) return;
5448
5597
  clearTimeout(STATE._scheduledPlay);
5598
+ STATE._scheduledPlay = null;
5449
5599
  STATE.remoteLockUntil = Date.now() + 100;
5450
5600
  STATE._remoteApplying = true;
5451
5601
  if (play) {
@@ -5454,13 +5604,21 @@
5454
5604
  if (wait > 40) {
5455
5605
  // Synchronized start: every device begins at the same shared instant.
5456
5606
  if (Math.abs(video.currentTime - time) > 0.25) remoteSeek(video, time);
5607
+ // This hold-and-wait pause is ours: when its event arrives late it must not be
5608
+ // taken for someone pausing (that stopped the room right after a countdown).
5609
+ video._nxuOwnPauseUntil = Date.now() + Math.min(wait, 10000) + 500;
5610
+ video._nxuOwnPauseSince = Date.now();
5457
5611
  if (!video.paused) { try { video.pause(); } catch (_) { } }
5458
5612
  RATE.apply(video, base);
5613
+ STATE._scheduledPlayAt = Date.now() + Math.min(wait, 10000);
5459
5614
  STATE._scheduledPlay = setTimeout(() => {
5615
+ STATE._scheduledPlay = null;
5460
5616
  STATE._remoteApplying = true;
5461
5617
  MEDIA_SAFE.play(video);
5462
5618
  setTimeout(() => { STATE._remoteApplying = false; }, 120);
5463
- }, Math.min(wait, 3000));
5619
+ // Some players refuse or swallow the first play(): check once more.
5620
+ setTimeout(() => { const r = _getVideoState(); if (r && r.play && video.paused && STATE.video === video) MEDIA_SAFE.play(video); }, 900);
5621
+ }, Math.min(wait, 10000));
5464
5622
  setTimeout(() => { STATE._remoteApplying = false; }, 80);
5465
5623
  return;
5466
5624
  }
@@ -5643,9 +5801,10 @@
5643
5801
  if (res) { this._frameWait.delete(data.rid); res(data); }
5644
5802
  },
5645
5803
  async _mySnap() {
5646
- if (STATE.video) return { img: this.snapshot(), t: STATE.video.currentTime };
5804
+ const playing = !(currentMediaInfo()?.paused ?? true);
5805
+ if (STATE.video) return { img: this.snapshot(), t: STATE.video.currentTime, playing, at: Date.now() };
5647
5806
  const d = await this._askFrame('snap');
5648
- return d ? { img: d.img || null, t: d.t } : null;
5807
+ return d ? { img: d.img || null, t: d.t, playing, at: Date.now() } : { img: null, t: this.mediaTime(), playing, at: Date.now() };
5649
5808
  },
5650
5809
  async _myEnv() {
5651
5810
  if (STATE.video) { this.arm(true); return this._envelope(); }
@@ -5664,7 +5823,7 @@
5664
5823
  this._peekUntil = Date.now() + 45000;
5665
5824
  this._startPeek();
5666
5825
  } 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() };
5826
+ 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
5827
  this.paint();
5669
5828
  } else if (op === 'mark' && Number.isFinite(d.t)) {
5670
5829
  this._marks.set(d.uid, { t: d.t, off: Number(d.off) || 0, name: who.name, color: who.color });
@@ -5693,7 +5852,7 @@
5693
5852
  const loop = async () => {
5694
5853
  if (Date.now() > this._peekUntil || !SOCIAL.live()) { this._peekTimer = null; return; }
5695
5854
  const s = await this._mySnap();
5696
- SOCIAL.send('tune', { op: 'snap', img: s ? s.img : null, t: s ? s.t : 0, off: this.offset() });
5855
+ SOCIAL.send('tune', { op: 'snap', img: s ? s.img : null, t: s ? s.t : 0, playing: !!(s && s.playing), off: this.offset() });
5697
5856
  this._peekTimer = setTimeout(loop, 1200);
5698
5857
  };
5699
5858
  this._peekTimer = setTimeout(loop, 50);
@@ -5778,16 +5937,16 @@
5778
5937
  const sd = Math.sqrt(fin.reduce((s, x) => s + (x - mean) ** 2, 0) / Math.max(1, fin.length)) || 1;
5779
5938
  return { d: best.d, score: best.score, second, z: (best.score - mean) / sd };
5780
5939
  },
5781
- async auto() {
5782
- if (!PRESENCE.others().length) { this._autoMsg = t('tuneNoPeer'); this.paint(); return; }
5783
- this._autoMsg = t('tuneAsking'); this.paint();
5940
+ async auto({ silent = false } = {}) {
5941
+ if (!PRESENCE.others().length) { if (!silent) { this._autoMsg = t('tuneNoPeer'); this.paint(); } return null; }
5942
+ if (!silent) { this._autoMsg = t('tuneAsking'); this.paint(); }
5784
5943
  const mine = await this._myEnv();
5785
5944
  const theirs = await new Promise((resolve) => {
5786
5945
  this._autoWait = resolve;
5787
5946
  SOCIAL.send('tune', { op: 'envreq' });
5788
5947
  setTimeout(() => { if (this._autoWait === resolve) { this._autoWait = null; resolve(null); } }, 9000);
5789
5948
  });
5790
- if (!mine || !theirs) { this._autoMsg = t('tuneAutoNeed'); this.paint(); return; }
5949
+ if (!mine || !theirs) { if (!silent) { this._autoMsg = t('tuneAutoNeed'); this.paint(); } return null; }
5791
5950
  let res = null;
5792
5951
  for (const luma of [false, true]) {
5793
5952
  const a = this._series(mine, luma), b = this._series(theirs.env, luma);
@@ -5796,14 +5955,80 @@
5796
5955
  if (Number.isFinite(r.score) && (!res || r.z > res.z)) res = r;
5797
5956
  }
5798
5957
  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; }
5958
+ if (!res || !(res.score > 0.3) || !(res.z >= 4)) { if (!silent) { this._autoMsg = t('tuneAutoNone'); this._autoFound = null; this.paint(); } return null; }
5800
5959
  // d: my content at time x = theirs at x − d. With both following the room, my
5801
5960
  // offset must be theirs + d.
5802
5961
  const want = Math.round((theirs.off + res.d) * 10) / 10;
5803
5962
  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);
5963
+ if (silent) return { want, sure, score: res.score, z: res.z };
5804
5964
  this._autoFound = want;
5805
5965
  this._autoMsg = t('tuneAutoFound', { s: this.fmt(want), c: sure });
5806
5966
  this.paint();
5967
+ return { want, sure, score: res.score, z: res.z };
5968
+ },
5969
+
5970
+ // ── same source or a different version? (decided from each device's media length)
5971
+ mediaSig() {
5972
+ const info = currentMediaInfo();
5973
+ if (!info) return null;
5974
+ if (info.live) return { d: -1 };
5975
+ return Number.isFinite(info.duration) && info.duration > 0 ? { d: Math.round(info.duration * 10) / 10 } : null;
5976
+ },
5977
+ source() {
5978
+ const mine = this.mediaSig();
5979
+ const others = PRESENCE.others().map(uid => STATE.presenceMap[uid]?.md).filter(m => m && Number.isFinite(m.d));
5980
+ if (!mine || !others.length) return { kind: 'unknown' };
5981
+ if (mine.d < 0 || others.some(m => m.d < 0)) return { kind: 'same' }; // live: one timeline
5982
+ const diffs = others.map(m => mine.d - m.d);
5983
+ const big = diffs.reduce((a, b) => (Math.abs(b) > Math.abs(a) ? b : a), 0);
5984
+ return Math.abs(big) < 1.5 ? { kind: 'same' } : { kind: 'different', diff: Math.round(big * 10) / 10 };
5985
+ },
5986
+ // Only one device shifts its timing: the one with the longer version (extra intro), or
5987
+ // with equal length the lowest id.
5988
+ _adjuster() {
5989
+ const mine = this.mediaSig();
5990
+ if (!mine) return false;
5991
+ const others = PRESENCE.others().map(uid => [uid, STATE.presenceMap[uid]?.md]).filter(([, m]) => m && Number.isFinite(m.d) && m.d > 0);
5992
+ return others.every(([uid, m]) => mine.d > m.d + 1.5 || (Math.abs(mine.d - m.d) <= 1.5 && STATE.userId < uid));
5993
+ },
5994
+ // Runs every few seconds in a room: same source → no shift (the room's own fine sync
5995
+ // does the frame-level work); different versions → find the shift by itself.
5996
+ _watchStart: 0, _tries: 0, _lastKind: '',
5997
+ async autoTick() {
5998
+ if (!IS_TOP || !STATE.handshakeVerified || STATE.isReadOnly || this._autoBusy) return;
5999
+ const src = this.source();
6000
+ if (src.kind !== this._lastKind) { this._lastKind = src.kind; this._tries = 0; this.paint(); }
6001
+ if (src.kind === 'same') {
6002
+ if (this.offset()) { this.set(0, { quiet: true }); showToast(t('tuneSameReset')); }
6003
+ return;
6004
+ }
6005
+ if (src.kind !== 'different' || this.offset() || this._autoDone === location.href || !this._adjuster()) return;
6006
+ const info = currentMediaInfo();
6007
+ if (!info || info.paused) return;
6008
+ const env = this._rec;
6009
+ if (STATE.video && (!env || env.ts.length < 450)) return; // ~45 s of history first
6010
+ if (this._tries >= 5) {
6011
+ 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() }); }
6012
+ return;
6013
+ }
6014
+ if (Date.now() - (this._lastTry || 0) < 30000) return;
6015
+ this._lastTry = Date.now();
6016
+ this._tries++;
6017
+ this._autoBusy = true;
6018
+ try {
6019
+ const r = await this.auto({ silent: true });
6020
+ // A very clear match is used at once; a fair one only when two tries agree.
6021
+ const prev = this._prevAuto;
6022
+ this._prevAuto = r;
6023
+ const clear = r && r.score > 0.45 && r.z >= 7;
6024
+ const agreed = r && prev && r.z >= 5 && prev.z >= 5 && Math.abs(r.want - prev.want) < 0.5;
6025
+ if ((clear || agreed) && Math.abs(r.want) <= this.LIMIT) {
6026
+ this._autoDone = location.href;
6027
+ const before = this.offset();
6028
+ this.set(r.want, { quiet: true });
6029
+ 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; } });
6030
+ }
6031
+ } catch (_) { } finally { this._autoBusy = false; }
5807
6032
  },
5808
6033
 
5809
6034
  // ── panel
@@ -5830,16 +6055,36 @@
5830
6055
  if (!panel || panel.style.display !== 'flex') return;
5831
6056
  const off = this.offset();
5832
6057
  const q = s => panel.querySelector(s);
6058
+ const src = this.source();
6059
+ q('.tune-src').textContent = src.kind === 'same' ? t('tuneSrcSame') : src.kind === 'different' ? t('tuneSrcDiff', { s: this.fmt(src.diff) }) : t('tuneSrcUnknown');
6060
+ q('.tune-src').dataset.kind = src.kind;
6061
+ panel.querySelector('.tune-body').classList.toggle('same', src.kind === 'same');
5833
6062
  q('.tune-off-val').textContent = this.fmt(off);
5834
6063
  q('.tune-off-desc').textContent = !off ? t('tuneOffsetZero') : t(off > 0 ? 'tuneAhead' : 'tuneBehind', { s: Math.abs(off).toFixed(1) + 's' });
6064
+ // A protected or cross-site picture cannot be copied (the browser forbids reading
6065
+ // it): instead of a black box the card shows that device's position in large type,
6066
+ // so the two can still be compared by time.
5835
6067
  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'; }
6068
+ const img = box.querySelector('img'), cap = box.querySelector('.tune-cap'), ph = box.querySelector('.tune-ph');
6069
+ const hasImg = !!(data && data.img);
6070
+ if (hasImg) { img.src = data.img; img.style.visibility = 'visible'; }
5838
6071
  else img.style.visibility = 'hidden';
5839
- cap.textContent = label + (data ? ' · ' + formatTime(data.t || 0) : '') + (data && !data.img ? ' · ' + t('tuneNoPicture') : !data && waiting ? ' · ' + t('tuneWaiting') : '');
6072
+ ph.style.display = hasImg ? 'none' : '';
6073
+ const age = data ? Math.max(0, (Date.now() - (data.at || Date.now())) / 1000) : 0;
6074
+ ph.querySelector('.tune-ph-time').textContent = data ? formatTime((data.t || 0) + (data.playing ? age : 0)) : '··:··';
6075
+ ph.querySelector('.tune-ph-note').textContent = !data ? (waiting ? t('tuneWaiting') : '') : t('tuneNoPicture');
6076
+ cap.textContent = label + (data ? ' · ' + formatTime(data.t || 0) : '');
5840
6077
  };
5841
- pic(q('.tune-pic.mine'), this._mine, t('tuneMine'), false);
6078
+ pic(q('.tune-pic.mine'), this._mine ? { ...this._mine, at: this._mine.at || Date.now() } : null, t('tuneMine'), false);
5842
6079
  const p = this._peer && Date.now() - this._peer.at < 8000 ? this._peer : null;
6080
+ // Time comparison (works for protected pictures too).
6081
+ const diffEl = q('.tune-diff');
6082
+ if (p && this._mine) {
6083
+ const mineNow = (this._mine.t || 0) + (this._mine.playing ? (Date.now() - (this._mine.at || Date.now())) / 1000 : 0);
6084
+ const theirNow = (p.t || 0) + (p.playing ? (Date.now() - p.at) / 1000 : 0);
6085
+ const d = Math.round((mineNow - theirNow) * 10) / 10;
6086
+ diffEl.textContent = Math.abs(d) < 0.3 ? t('tuneDiffSame') : t(d > 0 ? 'tuneDiffAhead' : 'tuneDiffBehind', { s: Math.abs(d).toFixed(1) + 's', name: p.name });
6087
+ } else diffEl.textContent = '';
5843
6088
  pic(q('.tune-pic.theirs'), p, p ? p.name : (PRESENCE.others().length ? participantName(PRESENCE.others()[0]) : '—'), !!PRESENCE.others().length);
5844
6089
  const theirs = [...this._marks.values()].pop();
5845
6090
  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 +6108,17 @@
5863
6108
  nudges.appendChild(b);
5864
6109
  });
5865
6110
  const tools = createEl('div', 'tune-tools');
5866
- const resync = createEl('button', 'btn', '🔄 ' + t('tuneResync'), { type: 'button' });
6111
+ const resync = createEl('button', 'btn tune-keep', '🔄 ' + t('tuneResync'), { type: 'button' });
5867
6112
  resync.onclick = () => uiElements.btnSyncStatus?.click();
5868
6113
  const reset = createEl('button', 'btn subtle', '↺ ' + t('tuneReset'), { type: 'button' });
5869
6114
  reset.onclick = () => this.set(0);
5870
- tools.append(resync, reset);
6115
+ tools.append(reset);
5871
6116
  const pics = createEl('div', 'tune-pics');
5872
6117
  ['mine', 'theirs'].forEach(k => {
5873
6118
  const box = createEl('div', 'tune-pic ' + k);
5874
- box.append(createEl('img', '', '', { alt: '' }), createEl('div', 'tune-cap'));
6119
+ const ph = createEl('div', 'tune-ph');
6120
+ ph.append(createEl('div', 'tune-ph-time', '··:··'), createEl('div', 'tune-ph-note'));
6121
+ box.append(createEl('img', '', '', { alt: '' }), ph, createEl('div', 'tune-cap'));
5875
6122
  pics.appendChild(box);
5876
6123
  });
5877
6124
  const markBtn = createEl('button', 'btn', t('tuneMarkBtn'), { type: 'button' });
@@ -5883,12 +6130,14 @@
5883
6130
  const autoApply = createEl('button', 'btn primary tune-auto-apply', t('tuneApply'), { type: 'button' });
5884
6131
  autoApply.onclick = () => { if (this._autoFound != null) this.set(this._autoFound); };
5885
6132
  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,
6133
+ // Version tools (offset, same scene, automatic) only matter for different versions.
6134
+ const ver = createEl('div', 'tune-ver');
6135
+ ver.append(
6136
+ h(t('tuneOffset')), offRow, nudges, reset, createEl('div', 'trans-help', t('tuneHelp')),
5889
6137
  h(t('tuneMark')), createEl('div', 'trans-help', t('tuneMarkHint')), markBtn, createEl('div', 'tune-marks trans-help'), markApply,
5890
6138
  h(t('tuneAuto')), createEl('div', 'trans-help', t('tuneAutoHint')), autoBtn, createEl('div', 'tune-auto-msg trans-help'), autoApply
5891
6139
  );
6140
+ body.append(createEl('div', 'tune-src'), resync, h(t('tuneCompare')), pics, createEl('div', 'tune-diff'), ver);
5892
6141
  return body;
5893
6142
  }
5894
6143
  };
@@ -5981,8 +6230,10 @@
5981
6230
  // Sync timing keeps a short history of what was played while in a room (on a computer
5982
6231
  // all the time; on phones only once the timing panel was opened, to save battery).
5983
6232
  if (IS_TOP) setInterval(() => {
6233
+ try { TUNE.autoTick(); } catch (_) { }
5984
6234
  try {
5985
- const want = STATE.handshakeVerified && (!IS_TOUCH || TUNE._armedByUser) && !!(STATE.video || STATE.cinemaIframe);
6235
+ // Different versions need the history; same source does not.
6236
+ const want = STATE.handshakeVerified && (!IS_TOUCH || TUNE._armedByUser || TUNE.source().kind === 'different') && !!(STATE.video || STATE.cinemaIframe);
5986
6237
  if (want && !TUNE._armed) { TUNE._armed = true; TUNE.arm(true); }
5987
6238
  else if (!want && TUNE._armed) { TUNE._armed = false; TUNE.arm(false); }
5988
6239
  else if (want && STATE.video && TUNE._rec && TUNE._rec.v !== STATE.video) TUNE.arm(true);
@@ -6267,12 +6518,19 @@
6267
6518
  const PRESENCE = {
6268
6519
  seen: new Map(),
6269
6520
  STALE_MS: 25000,
6521
+ // A device that went quiet (screen off, app in the background) stays in the room as
6522
+ // "sleeping" until it says goodbye or has been silent this long; it comes back by itself.
6523
+ LONG_MS: 30 * 60 * 1000,
6524
+ left: new Set(),
6270
6525
  refresh() {
6271
6526
  const now = Date.now();
6272
6527
  STATE.presenceMap = {};
6528
+ STATE.sleepingMap = {};
6273
6529
  if (yPresence) yPresence.forEach((val, uid) => {
6274
6530
  if (!val) return;
6275
- if (uid === STATE.userId || now - (this.seen.get(uid) || 0) < this.STALE_MS) STATE.presenceMap[uid] = val;
6531
+ const age = now - (this.seen.get(uid) || 0);
6532
+ if (uid === STATE.userId || age < this.STALE_MS) STATE.presenceMap[uid] = val;
6533
+ else if (this.seen.has(uid) && age < this.LONG_MS && !this.left.has(uid)) STATE.sleepingMap[uid] = val;
6276
6534
  });
6277
6535
  if (STATE.role !== 'IDLE' && !STATE.presenceMap[STATE.userId]) STATE.presenceMap[STATE.userId] = { nick: STATE.nickname || '', color: STATE.color, viewer: !!STATE.isViewer };
6278
6536
  updatePresenceUI();
@@ -6446,17 +6704,20 @@
6446
6704
  // small mark for "watching only", "away" (screen off / other tab) and an outdated version.
6447
6705
  function roomRoster() {
6448
6706
  const safeColor = c => (/^#[0-9a-f]{3,8}$/i.test(String(c || '')) ? c : '#7c4dff');
6449
- const list = Object.entries(STATE.presenceMap || {}).map(([uid, p]) => {
6707
+ const entries = [...Object.entries(STATE.presenceMap || {}), ...Object.entries(STATE.sleepingMap || {}).map(([u, p]) => [u, { ...p, _sleep: true }])];
6708
+ const list = entries.map(([uid, p]) => {
6450
6709
  const self = uid === STATE.userId;
6451
6710
  return {
6452
6711
  uid, self,
6453
6712
  name: self ? (STATE.nickname || t('you')) : (p?.nick || 'ID:' + String(uid).slice(0, 3)),
6454
6713
  color: safeColor(self ? STATE.color : p?.color),
6455
6714
  viewer: self ? !!STATE.isViewer : !!p?.viewer,
6456
- av: safeEmoji(self ? PROFILE.avatar() : p?.av),
6457
- st: String((self ? PROFILE.status() : p?.st) || '').slice(0, 40),
6715
+ av: safeAvatar(self ? PROFILE.avatar() : p?.av),
6716
+ img: AVATAR_IMG.get(uid),
6717
+ st: '',
6458
6718
  muted: !self && SAFETY.muted.has(uid),
6459
- away: !self && !!p?.hid,
6719
+ away: !self && (!!p?.hid || !!p?._sleep),
6720
+ sleeping: !self && !!p?._sleep,
6460
6721
  oldVer: !self && !!(p?.v && p.v !== NXU_VERSION)
6461
6722
  };
6462
6723
  });
@@ -6465,23 +6726,27 @@
6465
6726
  }
6466
6727
  function renderRoster(box, max = 4) {
6467
6728
  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(';');
6729
+ const issue = STATE.handshakeVerified && STATE.connectionMode !== 'WEBRTC_P2P' && typeof relayAlive === 'function' && !relayAlive();
6730
+ 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
6731
  if (box._rosterSig === sig) return list;
6470
6732
  box._rosterSig = sig;
6471
6733
  box.replaceChildren();
6734
+ // This device lost the room's channel: say so plainly (it reconnects by itself).
6735
+ if (issue) box.appendChild(createEl('span', 'nx-who warn', '⚠️ ' + t('whoReconnecting')));
6472
6736
  list.slice(0, max).forEach(m => {
6473
6737
  const chip = createEl('span', 'nx-who' + (m.away ? ' away' : '') + (m.self ? ' me' : ''));
6474
6738
  const dot = createEl('i', 'nx-who-dot');
6475
6739
  dot.style.background = m.color;
6476
- chip.append(dot);
6477
- if (m.av) chip.append(createEl('span', 'nx-who-av', m.av));
6740
+ if (m.img) { const im = createEl('img', 'nx-who-img', '', { alt: '' }); im.src = m.img; im.style.borderColor = m.color; chip.append(im); }
6741
+ else chip.append(dot);
6742
+ if (m.av && !m.img) chip.append(createEl('span', 'nx-who-av', m.av));
6478
6743
  chip.append(createEl('span', 'nx-who-name', m.name + (m.self && STATE.nickname ? ' ' + t('meTag') : '')));
6479
6744
  if (m.muted) chip.append(createEl('span', 'nx-who-tag', '🔇'));
6480
6745
  if (m.st && max > 4) chip.append(createEl('span', 'nx-who-st', m.st));
6481
6746
  if (m.viewer) chip.append(createEl('span', 'nx-who-tag', '👀'));
6482
6747
  if (m.away) chip.append(createEl('span', 'nx-who-tag', '💤'));
6483
6748
  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(' · ');
6749
+ 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
6750
  box.appendChild(chip);
6486
6751
  });
6487
6752
  if (list.length > max) box.appendChild(createEl('span', 'nx-who more', '+' + (list.length - max)));
@@ -6612,130 +6877,9 @@
6612
6877
  }
6613
6878
  }
6614
6879
 
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
6880
  function addBookmark(label = '') {
6736
6881
  const info = currentMediaInfo();
6737
6882
  if (!info) { showToast(t('noVideo')); return; }
6738
- try { LIBRARY.add(info); } catch (_) { }
6739
6883
  const bm = { time: info.time || 0, label, color: STATE.color, userId: STATE.userId, ts: Date.now() };
6740
6884
  if (ydoc && yBookmarks && STATE.handshakeVerified) yBookmarks.push([bm]);
6741
6885
  else { STATE.bookmarks.push(bm); renderBookmarkPins(); }
@@ -7066,6 +7210,8 @@
7066
7210
  const margin = 12, w = getW(), h = getH();
7067
7211
  const rect = localBox(panel);
7068
7212
  const rw = Math.min(rect.width, w - margin * 2), rh = Math.min(rect.height, h - margin * 2);
7213
+ if (panel.style.width && rect.width > rw) panel.style.width = Math.max(260, rw) + 'px';
7214
+ if (panel.style.height && rect.height > rh) panel.style.height = Math.max(200, rh) + 'px';
7069
7215
  panel.style.transform = 'none';
7070
7216
  panel.style.left = Math.max(margin, Math.min(rect.left, w - rw - margin)) + 'px';
7071
7217
  panel.style.top = Math.max(margin, Math.min(rect.top, h - rh - margin)) + 'px';
@@ -7077,6 +7223,7 @@
7077
7223
  panel.style.display = 'flex';
7078
7224
  panel.style.opacity = '1';
7079
7225
  panel.style.pointerEvents = 'auto';
7226
+ try { AUTO_CINEMA._hideCard(); } catch (_) { } // the "which player" card would cover the window
7080
7227
  PANEL_SIZE.apply(panel);
7081
7228
  if (panel.dataset.userMoved === 'true') requestAnimationFrame(() => clampPanelToViewport(panel));
7082
7229
  else centerPanel(panel);
@@ -7285,7 +7432,19 @@
7285
7432
  return select;
7286
7433
  }
7287
7434
 
7288
- // ⚙️ Settings: profile, my reactions, playback, what reaches me from others, advanced.
7435
+ // ⚙️ Settings: profile, my reactions, playback, tools. Every list is a grid of the same
7436
+ // number of cells per row (8), and every on/off choice is the same switch.
7437
+ function switchRow(btn, label, get, set) {
7438
+ btn.className = 'btn nx-sw';
7439
+ btn.setAttribute('role', 'switch');
7440
+ const text = createEl('span', 'nx-sw-label', label);
7441
+ const knob = createEl('i', 'nx-sw-track');
7442
+ btn.replaceChildren(text, knob);
7443
+ btn.paint = () => { const on = !!get(); btn.classList.toggle('active', on); btn.setAttribute('aria-checked', String(on)); };
7444
+ btn.onclick = (ev) => { ev.stopPropagation(); triggerHaptic(); set(!get()); btn.paint(); };
7445
+ btn.paint();
7446
+ return btn;
7447
+ }
7289
7448
  function buildSettingsPanel(parts) {
7290
7449
  const body = createEl('div', 'manual-body settings-body nx-settings');
7291
7450
  const section = (icon, title) => {
@@ -7294,80 +7453,74 @@
7294
7453
  body.appendChild(sec);
7295
7454
  return sec;
7296
7455
  };
7297
- const toggle = (label, get, set) => {
7298
- const row = createEl('label', 'trans-row nx-set-row');
7299
- const box = createEl('input', 'trans-check', '', { type: 'checkbox' });
7300
- box.checked = !!get();
7301
- box.addEventListener('change', () => set(!!box.checked));
7302
- row.append(createEl('span', '', label), box);
7303
- return row;
7456
+ const emojiInput = (ph, onEmoji) => {
7457
+ const inp = createEl('input', 'nx-compose-input nx-emoji-input', '', { type: 'text', maxlength: '16', placeholder: ph, autocomplete: 'off', enterkeyhint: 'done' });
7458
+ inp.addEventListener('input', () => { const em = safeEmoji(inp.value); if (em && onEmoji(em)) inp.value = ''; });
7459
+ inp.addEventListener('keydown', (ev) => ev.stopPropagation());
7460
+ return inp;
7304
7461
  };
7305
- // Profile
7462
+ const grid = (list, cls, onPick) => {
7463
+ const g = createEl('div', 'nx-grid8');
7464
+ list.forEach(em => {
7465
+ const b = createEl('button', 'nx-cell ' + cls, em, { type: 'button' });
7466
+ b.dataset.em = em;
7467
+ b.onclick = (ev) => { ev.stopPropagation(); onPick(em, b); };
7468
+ g.appendChild(b);
7469
+ });
7470
+ return g;
7471
+ };
7472
+ // Profile: name, colour, device delay, avatar (pick one, or type any emoji)
7306
7473
  const prof = section('👤', t('setProfile'));
7307
7474
  prof.open = true;
7308
7475
  prof.appendChild(PROFILE.editor());
7309
- const avRow = createEl('div', 'nx-av-row');
7310
- const paintAv = () => avRow.querySelectorAll('.nx-av').forEach(b => b.classList.toggle('on', b.dataset.av === PROFILE.avatar()));
7311
- ['', ...PROFILE.AVATARS].forEach(a => {
7312
- const b = createEl('button', 'nx-av', a || '∅', { type: 'button', 'aria-label': a || 'none' });
7313
- b.dataset.av = a;
7314
- b.onclick = (ev) => { ev.stopPropagation(); PROFILE.setAvatar(a); paintAv(); };
7315
- avRow.appendChild(b);
7316
- });
7476
+ const avSlot = createEl('button', 'nx-cell nx-av-slot on', '', { type: 'button', 'aria-label': t('setAvatar') });
7477
+ const avGrid = grid(PROFILE.AVATARS, 'nx-av', (em) => { PROFILE.setAvatar(em); paintAv(); });
7478
+ const paintAv = () => {
7479
+ const a = PROFILE.avatar();
7480
+ avSlot.textContent = a || (STATE.nickname || '?').slice(0, 1).toUpperCase();
7481
+ avSlot.classList.toggle('empty', !a);
7482
+ avGrid.querySelectorAll('.nx-av').forEach(b => b.classList.toggle('on', b.dataset.em === a));
7483
+ };
7484
+ const avInput = emojiInput(t('setAvatarPh'), (em) => { PROFILE.setAvatar(em); paintAv(); return true; });
7485
+ const avReset = createEl('button', 'btn subtle', '↺ ' + t('setAvatarReset'), { type: 'button' });
7486
+ avReset.onclick = (ev) => { ev.stopPropagation(); PROFILE.setAvatar(''); paintAv(); };
7487
+ const avHead = createEl('div', 'nx-pick-head');
7488
+ avHead.append(avSlot, avInput);
7317
7489
  paintAv();
7318
- const status = createEl('input', 'nx-compose-input nx-status-input', '', { type: 'text', maxlength: '40', placeholder: t('setStatusPh'), autocomplete: 'off' });
7319
- status.value = PROFILE.status();
7320
- status.addEventListener('input', () => PROFILE.setStatus(status.value));
7321
- prof.append(createEl('div', 'field-label', t('setAvatar')), avRow, createEl('div', 'field-label', t('setStatus')), status);
7322
- // My reactions
7490
+ prof.append(createEl('div', 'field-label', t('setAvatar')), avHead, avGrid, avReset);
7491
+ // My reactions: slots, then the palette or any emoji
7323
7492
  const reac = section('😀', t('setReactions'));
7324
- const slots = createEl('div', 'nx-react-slots');
7493
+ const slots = createEl('div', 'nx-grid8 nx-react-slots');
7325
7494
  let pick = 0;
7326
- const PALETTE = ['❤️', '🔥', '👏', '🤣', '😱', '😍', '🥺', '🤯', '👀', '💀', '🙏', '👍', '🎉', '💯', '😴', '🤔', '🍿', '😂', '😭', '😡', '💦', '🍪', '☕', '😘'];
7327
7495
  const paintSlots = () => {
7328
7496
  slots.replaceChildren(...REACTIONS.list().map((em, i) => {
7329
- const b = createEl('button', 'nx-react-slot' + (i === pick ? ' on' : ''), em, { type: 'button' });
7497
+ const b = createEl('button', 'nx-cell nx-react-slot' + (i === pick ? ' on' : ''), em, { type: 'button' });
7330
7498
  b.onclick = (ev) => { ev.stopPropagation(); pick = i; paintSlots(); };
7331
7499
  return b;
7332
7500
  }));
7333
7501
  };
7334
- const pal = createEl('div', 'nx-react-pal');
7335
- PALETTE.forEach(em => {
7336
- 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(); } };
7338
- pal.appendChild(b);
7339
- });
7340
- 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(); } });
7502
+ const putEmoji = (em) => { if (!REACTIONS.set(pick, em)) return false; pick = (pick + 1) % REACTIONS.list().length; paintSlots(); return true; };
7503
+ const pal = grid(REACTIONS.PALETTE, 'nx-react-pick', (em) => putEmoji(em));
7504
+ const custom = emojiInput(t('setEmojiPh'), putEmoji);
7505
+ const addSlot = createEl('button', 'btn subtle', t('setSlotAdd'), { type: 'button' });
7506
+ addSlot.onclick = (ev) => { ev.stopPropagation(); const i = REACTIONS.add(); if (i >= 0) pick = i; paintSlots(); };
7507
+ const delSlot = createEl('button', 'btn subtle', t('setSlotRemove'), { type: 'button' });
7508
+ delSlot.onclick = (ev) => { ev.stopPropagation(); if (REACTIONS.remove(pick)) pick = Math.min(pick, REACTIONS.list().length - 1); paintSlots(); };
7342
7509
  const resetBtn = createEl('button', 'btn subtle', '↺ ' + t('setReactionsReset'), { type: 'button' });
7343
- resetBtn.onclick = () => { REACTIONS.reset(); pick = 0; paintSlots(); };
7510
+ resetBtn.onclick = (ev) => { ev.stopPropagation(); REACTIONS.reset(); pick = 0; paintSlots(); };
7511
+ const slotRow = createEl('div', 'nx-btn-row nx-slot-row');
7512
+ slotRow.append(addSlot, delSlot, resetBtn);
7344
7513
  paintSlots();
7345
- reac.append(slots, createEl('div', 'trans-help', t('setReactionsHint')), pal, custom, resetBtn);
7346
- // Playback
7514
+ reac.append(slots, slotRow, createEl('div', 'trans-help', t('setReactionsHint')), pal, custom);
7515
+ // Playback: the same switch for every on/off choice
7347
7516
  const play = section('🎬', t('setPlayback'));
7348
- play.append(parts.autoCinema, parts.adGuard, toggle(t('setAutoNext'), () => NEXT_EP.enabled(), on => STORE.set('nxu_auto_next', on)));
7349
- // Watching together: what reaches me, and from whom
7350
- const tog = section('🛡️', t('setTogether'));
7351
- [['react', 'setRecvReact'], ['nudge', 'setRecvNudge'], ['ink', 'setRecvInk'], ['chat', 'setRecvChat'], ['ping', 'setRecvPing']].forEach(([k, label]) => tog.appendChild(toggle(t(label), () => SAFETY.receive(k), on => SAFETY.set(k, on))));
7352
- const people = createEl('div', 'nx-people');
7353
- const paintPeople = () => {
7354
- const others = roomRoster().filter(m => !m.self);
7355
- if (!others.length) { people.replaceChildren(createEl('div', 'trans-help', t('setNobody'))); return; }
7356
- people.replaceChildren(...others.map(m => {
7357
- const row = createEl('div', 'nx-person');
7358
- const dot = createEl('i', 'nx-who-dot'); dot.style.background = m.color;
7359
- const b = createEl('button', 'btn subtle', SAFETY.muted.has(m.uid) ? '👁 ' + t('setUnmute') : '🔇 ' + t('setMute'), { type: 'button' });
7360
- b.onclick = (ev) => { ev.stopPropagation(); SAFETY.toggleMute(m.uid); paintPeople(); updatePresenceUI(); };
7361
- row.append(dot, createEl('span', 'nx-person-name', (m.av ? m.av + ' ' : '') + m.name), b);
7362
- return row;
7363
- }));
7364
- };
7365
- tog.addEventListener('toggle', () => { if (tog.open) paintPeople(); });
7366
- tog.append(createEl('div', 'field-label', t('setPeople')), people, createEl('div', 'trans-help', t('setMutedHint')));
7367
- // Advanced
7517
+ const autoNext = switchRow(createEl('button', '', '', { type: 'button' }), '⏭ ' + t('setAutoNext'), () => NEXT_EP.enabled(), on => STORE.set('nxu_auto_next', on));
7518
+ play.append(parts.autoCinema, parts.adGuard, autoNext);
7519
+ // Tools and this site
7368
7520
  const adv = section('🔧', t('setAdvanced'));
7369
- adv.append(parts.subLog, parts.debug, parts.idleRow, parts.hideSite);
7370
- body.refreshPeople = paintPeople;
7521
+ const tools = createEl('div', 'nx-btn-row nx-tools');
7522
+ tools.append(parts.chatLog, parts.subLog, parts.debug);
7523
+ adv.append(tools, parts.idleRow, parts.hideSite, createEl('div', 'trans-help', t('setHideFabHelp')), createEl('div', 'nx-set-ver', 'NexusSync v' + NXU_VERSION));
7371
7524
  return body;
7372
7525
  }
7373
7526
 
@@ -7468,6 +7621,17 @@
7468
7621
  const opacityVal = createEl('span', 'range-val');
7469
7622
  opacityRow.append(createEl('span', '', t('subOpacity')), opacitySlider, opacityVal);
7470
7623
 
7624
+ const diagBtn = createEl('button', 'btn subtle', '🔬 ' + t('subDiagCopy'), { type: 'button', id: 'nxu-ai-diag' });
7625
+ diagBtn.onclick = async (ev) => {
7626
+ ev.stopPropagation();
7627
+ const text = await TRANSLATOR.diagReport();
7628
+ logDebug(text, 'info');
7629
+ let ok = false;
7630
+ try { await navigator.clipboard.writeText(text); ok = true; } catch (_) {
7631
+ try { if (typeof GM_setClipboard === 'function') { GM_setClipboard(text); ok = true; } } catch (_) { }
7632
+ }
7633
+ showToast(ok ? t('subDiagCopied') : t('subDiagInDebug'));
7634
+ };
7471
7635
  const details = createEl('details', 'ai-advanced');
7472
7636
  const advanced = createEl('div', 'ai-advanced-body');
7473
7637
  const offlineBtn = createEl('button', 'btn subtle', '⬇️ ' + t('offlineDownload'));
@@ -7487,6 +7651,7 @@
7487
7651
  details,
7488
7652
  createEl('div', 'ai-status', t('subStatusIdle'), { id: 'nxu-ai-status' }),
7489
7653
  createEl('button', 'btn primary', '🎙️ ' + t('subStart'), { id: 'stt-toggle' }),
7654
+ diagBtn,
7490
7655
  createEl('div', 'trans-help center', t('hotkeyHelp'))
7491
7656
  );
7492
7657
 
@@ -7607,15 +7772,17 @@
7607
7772
  .presence-pill.open .nx-who { max-width:none; }
7608
7773
  .nx-who.me { background:rgba(255,255,255,0.18); }
7609
7774
  .nx-who.away { opacity:0.55; }
7775
+ .nx-who.warn { background:rgba(255,170,0,0.28); }
7610
7776
  .nx-who.more { padding:2px 7px; }
7611
7777
  .nx-who-dot { flex:none; width:8px; height:8px; border-radius:50%; box-shadow:0 0 5px currentColor; }
7612
7778
  .nx-who-name { overflow:hidden; text-overflow:ellipsis; }
7613
7779
  .nx-who-tag { font-size:10px; }
7614
7780
  .nx-who-av { font-size:12px; line-height:1; }
7781
+ .nx-who-img { width:16px; height:16px; border-radius:50%; object-fit:cover; border:1.5px solid; flex:none; }
7615
7782
  .nx-who-st { font-weight:500; opacity:0.7; margin-left:4px; overflow:hidden; text-overflow:ellipsis; }
7616
7783
  .nx-talk-avatar.emoji { background:rgba(255,255,255,0.12) !important; font-size:16px; }
7617
- .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);
7618
- transition:opacity 0.25s ease, transform 0.25s ease; box-shadow:0 10px 30px rgba(0,0,0,0.35); backdrop-filter:blur(4px); -webkit-backdrop-filter:blur(4px); z-index:90; overflow-y:auto; text-shadow:0 1px 2px rgba(0,0,0,0.8); overflow-x:hidden; width:clamp(150px, 40vw, 190px); width:clamp(150px, 40cqw, 190px); }
7784
+ .dock { position:absolute; max-height:calc(100cqh - 24px); 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);
7785
+ transition:opacity 0.25s ease, transform 0.25s ease; box-shadow:0 10px 30px rgba(0,0,0,0.35); backdrop-filter:blur(4px); -webkit-backdrop-filter:blur(4px); z-index:90; overflow-y:auto; text-shadow:0 1px 2px rgba(0,0,0,0.8); overflow-x:hidden; width:clamp(150px, 40vw, 190px); width:clamp(160px, 22cqw, 240px); }
7619
7786
  .dock.open { opacity:1; pointer-events:auto; border-color:rgba(0,230,118,0.3); }
7620
7787
  .btn { background:rgba(255,255,255,0.06); color:var(--txt); border:1px solid transparent; padding:9px 12px; border-radius:9px; cursor:pointer; display:flex; align-items:center; justify-content:center; gap:8px;
7621
7788
  font-weight:600; font-size:13px; transition:background-color 0.2s, border-color 0.2s; touch-action:manipulation; width:100%; text-align:center; }
@@ -7628,11 +7795,15 @@
7628
7795
  .btn:disabled { opacity:0.5; cursor:wait; }
7629
7796
  .window-frame { position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); background:var(--glass-strong); backdrop-filter:blur(16px); -webkit-backdrop-filter:blur(16px); border-radius:16px; display:none; flex-direction:column;
7630
7797
  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
- width:min(420px, calc(100vw - 24px)); width:min(420px, calc(100cqw - 24px)); max-height:calc(100vh - 24px); max-height:calc(100cqh - 24px); }
7632
- #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; }
7798
+ width:min(420px, calc(100vw - 24px)); width:min(max(340px, 34cqw), 560px, calc(100cqw - 24px)); max-height:calc(100vh - 24px); max-height:calc(100cqh - 24px); }
7799
+ /* Windows follow the screen: wider on big screens, never past the edges on small ones. */
7800
+ #chat-panel, #sub-log-panel, #debug-panel { height:min(520px, calc(100vh - 24px)); height:min(max(360px, 66cqh), 760px, calc(100cqh - 24px)); }
7801
+ /* The window stays put and its body scrolls, so the resize grip stays in the corner
7802
+ (it used to scroll away with long content, e.g. every Settings section open). */
7803
+ #manual-modal, #trans-modal, #settings-modal, #tune-panel, #os-panel { overflow:hidden; }
7804
+ #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
7805
  /* 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); }
7806
+ #manual-modal, #trans-modal, #settings-modal, #tune-panel, #os-panel, #debug-panel, #chat-panel, #sub-log-panel { background:rgba(16,20,26,0.96); }
7636
7807
  .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
7808
  .header-controls { display:flex; gap:10px; align-items:center; }
7638
7809
  .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 +7857,8 @@
7686
7857
  /* NexusSync subtitles: soft plate, generous line height, clear of the controls. */
7687
7858
  .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
7859
  .nx-xsub.on { opacity:1; }
7860
+ .nx-xsub-line.l1 { color:#ffe98a; }
7861
+ .nx-xsub-line.l2 { color:#9be7ff; font-size:calc(clamp(13px, 2.2cqw, 28px) * var(--xs)); }
7689
7862
  .nexus-container.cinema-nexus:not(.chrome-idle) .nx-xsub { bottom:calc(104px + env(safe-area-inset-bottom, 0px)); }
7690
7863
  .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
7864
  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); }
@@ -7697,8 +7870,21 @@
7697
7870
  .cc-adj-val { min-width:46px; text-align:center; font-variant-numeric:tabular-nums; font-weight:700; }
7698
7871
  .cc-slider input { width:110px; accent-color:var(--cc-accent); }
7699
7872
  .cc-menu-note { font-size:11.5px; opacity:0.6; padding:4px 10px 6px; max-width:240px; }
7700
- .os-body { gap:8px; }
7873
+ .os-body { gap:8px; display:flex; flex-direction:column; }
7874
+ .os-body > * { flex:none; }
7875
+ /* The results take whatever room the window has (they used to be squeezed into a
7876
+ small box of their own inside the window, e.g. 120px on a phone in landscape). */
7877
+ #os-panel.has-results { height:min(760px, calc(100vh - 24px)); height:min(max(420px, 80cqh), 760px, calc(100cqh - 24px)); }
7878
+ #os-panel.has-results .os-results { flex:1 1 auto; max-height:none; min-height:96px; }
7879
+ #os-panel.has-results .os-hint { display:none; }
7880
+ /* Short screens (a phone in landscape): one scroll for the whole window, not a small inner box. */
7881
+ @media (max-height:560px) { #os-panel.has-results .os-results { flex:none; overflow:visible; } }
7701
7882
  .os-row { display:grid; grid-template-columns:1fr 1fr 1.4fr; gap:6px; }
7883
+ .os-tmdb { display:flex; flex-wrap:wrap; gap:5px; align-items:center; }
7884
+ .os-tmdb:empty { display:none; }
7885
+ .os-tmdb-label { font-size:10.5px; font-weight:800; opacity:0.6; letter-spacing:0.5px; }
7886
+ .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; }
7887
+ .os-chip.on { border-color:var(--accent); background:var(--glass-active); }
7702
7888
  .os-results { display:flex; flex-direction:column; gap:4px; max-height:min(46vh, 380px); overflow-y:auto; }
7703
7889
  .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
7890
  .os-item:hover { background:rgba(255,255,255,0.12); }
@@ -7706,6 +7892,12 @@
7706
7892
  .os-name { font-size:12.5px; font-weight:700; word-break:break-all; }
7707
7893
  .os-meta { font-size:11px; opacity:0.65; }
7708
7894
  .tune-body { gap:7px; }
7895
+ .tune-src { padding:8px 10px; border-radius:10px; font-size:12.5px; font-weight:700; background:rgba(255,255,255,0.08); }
7896
+ .tune-src[data-kind="same"] { background:rgba(0,230,118,0.16); }
7897
+ .tune-src[data-kind="different"] { background:rgba(255,202,40,0.18); }
7898
+ /* Same source: the room's own frame-level sync does it all; the version tools step back. */
7899
+ .tune-ver { display:flex; flex-direction:column; gap:7px; }
7900
+ .tune-body.same .tune-ver { display:none; }
7709
7901
  .tune-off { display:flex; align-items:baseline; gap:10px; }
7710
7902
  .tune-off-val { font-size:24px; font-weight:800; font-variant-numeric:tabular-nums; color:var(--accent); }
7711
7903
  .tune-off-desc { font-size:12px; opacity:0.75; }
@@ -7715,6 +7907,10 @@
7715
7907
  .tune-pics { display:grid; grid-template-columns:1fr 1fr; gap:6px; }
7716
7908
  .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
7909
  .tune-pic img { width:100%; height:100%; object-fit:cover; display:block; }
7910
+ .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; }
7911
+ .tune-ph-time { font-size:22px; font-weight:800; font-variant-numeric:tabular-nums; letter-spacing:0.5px; }
7912
+ .tune-ph-note { font-size:10.5px; opacity:0.65; line-height:1.3; }
7913
+ .tune-diff { font-size:12.5px; font-weight:700; text-align:center; min-height:16px; }
7718
7914
  .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
7915
  .nx-bm { gap:8px; }
7720
7916
  .nx-bm-list { display:flex; flex-direction:column; gap:5px; max-height:min(52vh, 420px); overflow-y:auto; }
@@ -7735,16 +7931,28 @@
7735
7931
  .nx-set-sec[open] > .nx-set-head::after { content:'▴'; }
7736
7932
  .nx-set-sec > :not(summary) { margin-top:6px; }
7737
7933
  .nx-set-row { display:flex; align-items:center; justify-content:space-between; gap:10px; font-size:12.5px; padding:4px 0; }
7738
- .nx-av-row, .nx-react-pal { display:flex; flex-wrap:wrap; gap:4px; }
7739
- .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
- .nx-av.on { border-color:var(--accent); background:var(--glass-active); }
7741
- .nx-react-slots { display:grid; grid-template-columns:repeat(8, 1fr); gap:4px; }
7742
- .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
- .nx-react-slot.on { border-color:var(--accent); box-shadow:0 0 0 2px rgba(0,230,118,0.35); }
7744
- .nx-people { display:flex; flex-direction:column; gap:4px; }
7745
- .nx-person { display:flex; align-items:center; gap:8px; font-size:12.5px; }
7746
- .nx-person .btn { width:auto; margin-left:auto; }
7747
- .nx-person-name { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
7934
+ /* Every list in Settings: one grid, eight equal cells per row, nothing wraps oddly. */
7935
+ .nx-grid8 { display:grid; grid-template-columns:repeat(8, minmax(0, 1fr)); gap:5px; }
7936
+ .nx-cell { aspect-ratio:1; min-width:0; width:100%; border-radius:10px; border:1px solid rgba(255,255,255,0.12); background:rgba(255,255,255,0.06); font-size:clamp(15px, 4.6cqw, 22px); line-height:1; cursor:pointer; padding:0; color:inherit; display:grid; place-items:center; }
7937
+ .nx-cell:hover { background:rgba(255,255,255,0.14); }
7938
+ .nx-cell.on { border-color:var(--accent); background:var(--glass-active); box-shadow:0 0 0 2px rgba(0,230,118,0.3); }
7939
+ .nx-pick-head { display:grid; grid-template-columns:calc((100% - 35px) / 8) 1fr; gap:5px; align-items:center; }
7940
+ .nx-av-slot { cursor:default; }
7941
+ .nx-av-slot.empty { font-weight:800; font-size:clamp(13px, 3.8cqw, 18px); opacity:0.8; }
7942
+ .nx-emoji-input { display:block; width:100%; box-sizing:border-box; padding:8px 14px; }
7943
+ .nx-btn-row { display:flex; gap:6px; }
7944
+ .nx-btn-row > .btn { flex:1 1 0; width:auto; min-width:0; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; padding-left:6px; padding-right:6px; }
7945
+ /* One switch for every on/off choice. */
7946
+ .btn.nx-sw { width:100%; justify-content:space-between; text-align:left; font-size:12.5px; font-weight:600; opacity:1; padding:9px 10px; background:rgba(255,255,255,0.04); }
7947
+ .btn.nx-sw.active { background:rgba(255,255,255,0.04) !important; border-color:transparent !important; }
7948
+ .nx-sw-label { flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
7949
+ .nx-sw-track { flex:none; position:relative; width:38px; height:22px; border-radius:11px; background:rgba(255,255,255,0.22); transition:background .18s; }
7950
+ .nx-sw-track::after { content:''; position:absolute; top:3px; left:3px; width:16px; height:16px; border-radius:50%; background:#fff; transition:transform .18s; box-shadow:0 1px 3px rgba(0,0,0,0.4); }
7951
+ .nx-sw.active .nx-sw-track { background:var(--accent); }
7952
+ .nx-sw.active .nx-sw-track::after { transform:translateX(16px); }
7953
+ .nx-set-sec > .nx-sw + .nx-sw { margin-top:4px; }
7954
+ .nx-set-ver { font-size:10.5px; opacity:0.45; text-align:right; }
7955
+ .nx-settings { container-type:inline-size; }
7748
7956
  .seg { display:flex; gap:6px; }
7749
7957
  .seg-btn { flex:1; min-height:38px; padding:8px 6px; border-radius:10px; border:1px solid rgba(255,255,255,0.16); background:rgba(255,255,255,0.06); color:inherit; font:inherit; font-size:13px; font-weight:700; cursor:pointer; }
7750
7958
  .seg-btn.on { background:rgba(124,77,255,0.38); border-color:rgba(160,130,255,0.95); }
@@ -7884,8 +8092,8 @@
7884
8092
  .nx-me-dot { background:var(--c, #69f0ae) !important; box-shadow:0 0 0 2px rgba(255,255,255,0.25), 0 0 10px var(--c, #69f0ae); }
7885
8093
  .nx-profile { display:flex; flex-direction:column; gap:7px; padding:6px 4px 2px; }
7886
8094
  .nx-profile-title { font-size:11.5px; font-weight:800; color:rgba(255,255,255,0.7); padding-left:4px; }
7887
- .nx-swatches { display:flex; flex-wrap:wrap; gap:7px; padding:0 2px; }
7888
- .nx-swatch { width:26px; height:26px; border-radius:50%; border:2px solid rgba(255,255,255,0.2); background:var(--c); cursor:pointer; padding:0; }
8095
+ .nx-swatches { display:grid; grid-template-columns:repeat(8, minmax(0, 1fr)); gap:5px; padding:0 2px; justify-items:center; }
8096
+ .nx-swatch { width:min(100%, 30px); aspect-ratio:1; height:auto; border-radius:50%; border:2px solid rgba(255,255,255,0.2); background:var(--c); cursor:pointer; padding:0; }
7889
8097
  .nx-swatch.on { border-color:#fff; box-shadow:0 0 0 2px var(--c), 0 0 12px var(--c); transform:scale(1.08); }
7890
8098
  .nx-swatch-custom { -webkit-appearance:none; appearance:none; background:conic-gradient(#ff5252, #ffd740, #69f0ae, #40c4ff, #7c4dff, #ff4fa3, #ff5252); overflow:hidden; }
7891
8099
  .nx-swatch-custom::-webkit-color-swatch-wrapper { padding:0; } .nx-swatch-custom::-webkit-color-swatch { border:none; opacity:0; }
@@ -8034,8 +8242,10 @@
8034
8242
  .cc-btn:hover { background:rgba(255,255,255,0.14); }
8035
8243
  .cc-btn:active { transform:scale(0.92); }
8036
8244
  .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); }
8245
+ /* On / off at a glance: an "on" button gets the accent colour, a tinted pill and a bar. */
8246
+ .cc-btn.on { color:var(--cc-accent); background:color-mix(in srgb, var(--cc-accent) 22%, transparent); }
8247
+ .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); }
8248
+ .cc-btn:not(.on) { opacity:0.92; }
8039
8249
  .cc-sub.on::after { display:none; }
8040
8250
  .cc-rate { min-width:46px; font-variant-numeric:tabular-nums; font-size:13px; }
8041
8251
  .cc-rate.on { color:#fff; background:rgba(0,230,118,0.22); }
@@ -8065,7 +8275,7 @@
8065
8275
  .cc-hover { position:absolute; bottom:26px; transform:translateX(-50%); background:rgba(12,14,18,0.9); color:#fff; font-size:12px; font-weight:700; font-variant-numeric:tabular-nums; padding:4px 8px; border-radius:6px; opacity:0; pointer-events:none; transition:opacity 0.15s; white-space:nowrap; box-shadow:0 2px 8px rgba(0,0,0,0.4); }
8066
8276
  .cc-hover.show { opacity:1; }
8067
8277
  .cc-hover small { display:block; font-weight:600; opacity:0.75; font-size:11px; max-width:180px; overflow:hidden; text-overflow:ellipsis; }
8068
- .cc-menu { position:absolute; bottom:calc(58px + env(safe-area-inset-bottom, 0px)); right:calc(14px + env(safe-area-inset-right, 0px)); z-index:80; min-width:150px; padding:6px; border-radius:12px; background:rgba(20,22,28,0.94); -webkit-backdrop-filter:blur(14px); backdrop-filter:blur(14px); box-shadow:0 10px 30px rgba(0,0,0,0.5); display:none; pointer-events:auto; }
8278
+ .cc-menu { position:absolute; bottom:calc(58px + env(safe-area-inset-bottom, 0px)); right:calc(14px + env(safe-area-inset-right, 0px)); z-index:80; min-width:150px; max-width:calc(100% - 28px); max-height:calc(100% - 140px - env(safe-area-inset-bottom, 0px)); overflow-y:auto; overscroll-behavior:contain; padding:6px; border-radius:12px; background:rgba(20,22,28,0.94); -webkit-backdrop-filter:blur(14px); backdrop-filter:blur(14px); box-shadow:0 10px 30px rgba(0,0,0,0.5); display:none; pointer-events:auto; }
8069
8279
  .cc-menu.open { display:block; animation:ccMenu 0.14s ease-out; }
8070
8280
  @keyframes ccMenu { from { opacity:0; transform:translateY(6px); } to { opacity:1; transform:none; } }
8071
8281
  .cc-menu-title { font-size:11px; font-weight:700; opacity:0.6; padding:4px 10px 6px; text-transform:uppercase; letter-spacing:0.5px; }
@@ -8192,13 +8402,8 @@
8192
8402
  const btnSyncStatus = mk('nxu-sync-status', '📡 ' + t('sync'));
8193
8403
  const btnInvite = mk('nxu-invite', '👥 ' + t('invite'), t('inviteTitle'));
8194
8404
  const btnCinema = mk('nxu-cinema', '🍿 ' + t('cinema'), t('cinemaTitle'));
8195
- const btnAutoCinema = mk('nxu-auto-cinema', '');
8196
- btnAutoCinema.classList.add('subtle');
8197
- const btnAdGuard = mk('nxu-ad-guard', '');
8198
- btnAdGuard.classList.add('subtle');
8199
- const paintAdGuard = () => { const on = AD_GUARD.enabled(); btnAdGuard.textContent = '🛡️ ' + t(on ? 'adGuardOn' : 'adGuardOff'); btnAdGuard.classList.toggle('active', on); };
8200
- paintAdGuard();
8201
- btnAdGuard.onclick = () => { STORE.set('nxu_ad_guard', !AD_GUARD.enabled()); paintAdGuard(); showToast('🛡️ ' + t(AD_GUARD.enabled() ? 'adGuardOn' : 'adGuardOff')); };
8405
+ const btnAutoCinema = switchRow(mk('nxu-auto-cinema', ''), '✨ ' + t('setAutoCinemaSw'), () => AUTO_CINEMA.enabled(), on => AUTO_CINEMA.setSite(on));
8406
+ const btnAdGuard = switchRow(mk('nxu-ad-guard', ''), '🛡️ ' + t('setAdGuardSw'), () => AD_GUARD.enabled(), on => { STORE.set('nxu_ad_guard', !!on); showToast('🛡️ ' + t(on ? 'adGuardOn' : 'adGuardOff')); });
8202
8407
  const btnPiP = mk('nxu-pip', '📺 PiP');
8203
8408
  const btnRate = mk('nxu-rate', '⏩ 1x', t('rateTitle'));
8204
8409
  // Talking happens in speech bubbles and quick ink now: the menu opens those directly
@@ -8208,16 +8413,18 @@
8208
8413
  const btnChat = mk('', '💬 ' + t('talkMenu'));
8209
8414
  const btnTranslate = mk('', '🌐 ' + t('aiSub'), t('aiSubTitle'));
8210
8415
  const btnSubLog = mk('', '📝 ' + t('subLog'));
8416
+ const btnChatLog = mk('nxu-chat-log', '💬 ' + t('chatLog'));
8211
8417
  const btnDebug = mk('', '🐛 ' + t('debug'));
8212
- const btnHideSite = createEl('button', 'btn subtle', '🙈 ' + t('hideOnSite'), { title: t('hideOnSiteTitle') });
8418
+ const btnHideSite = switchRow(createEl('button', '', '', { type: 'button', id: 'nxu-hide-site' }), '🙈 ' + t('setHideFab'), () => !!STORE.get('nxu_hide_fab_' + HOST, false), on => setFabHiddenOnSite(on));
8213
8419
  const btnSettings = mk('nxu-settings', '⚙️ ' + t('settings'));
8214
8420
  [btnLink, btnSyncStatus, btnInvite, btnCinema, btnPiP, btnRate, btnDraw, btnBookmark, btnChat].forEach(b => { b.style.display = 'none'; });
8215
8421
  btnSubLog.style.display = 'none';
8422
+ btnChatLog.style.display = 'none';
8216
8423
 
8217
8424
  // Chat panel
8218
8425
  const chatPanel = createEl('div', 'window-frame');
8219
8426
  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: '✖' }]);
8427
+ 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
8428
  const chatMessages = createEl('div');
8222
8429
  chatMessages.id = 'chat-messages';
8223
8430
  const nickRow = createEl('div', 'nick-row');
@@ -8246,7 +8453,9 @@
8246
8453
  quickRow.appendChild(chip);
8247
8454
  });
8248
8455
  const chatJumpBtn = createEl('button', 'jump-btn', '↓ ' + t('newMessages'));
8249
- chatPanel.append(chatHeader, nickRow, chatMessages, typingRow, quickRow, chatInputArea, chatJumpBtn);
8456
+ // The chat window is a history (like the subtitle log): reading, translating, saving.
8457
+ // Writing happens in the speech bubbles (💬 in the reaction bar, or Enter).
8458
+ chatPanel.append(chatHeader, chatMessages, typingRow, chatJumpBtn);
8250
8459
 
8251
8460
  // Subtitle history panel
8252
8461
  const subLogPanel = createEl('div', 'window-frame');
@@ -8297,13 +8506,13 @@
8297
8506
  const debugContent = createEl('div', 'debug-content');
8298
8507
  const debugJumpBtn = createEl('button', 'jump-btn', '↓ ' + t('latest'));
8299
8508
  debugJumpBtn.id = 'debug-jump-btn';
8300
- const idleRow = createEl('div', 'idle-row');
8301
- const idleSlider = createEl('input', '', '', { type: 'range', min: '3', max: '30', step: '1', style: 'flex:1;' });
8509
+ const idleRow = createEl('div', 'nx-latency nx-idle-row');
8510
+ const idleSlider = createEl('input', 'nx-latency-range', '', { type: 'range', min: '3', max: '30', step: '1' });
8302
8511
  const idleVal = createEl('span', '', '');
8303
8512
  idleSlider.value = CONFIG.idleTimeoutMs / 1000;
8304
8513
  idleVal.textContent = idleSlider.value + 's';
8305
8514
  idleSlider.addEventListener('input', () => { idleVal.textContent = idleSlider.value + 's'; STORE.set('nxu_idle_timeout', +idleSlider.value); });
8306
- idleRow.append(createEl('span', '', '⏱️ ' + t('uiHide')), idleSlider, idleVal, createEl('span', '', 'v' + NXU_VERSION, { style: 'margin-left:6px;opacity:0.6;' }));
8515
+ idleRow.append(createEl('span', 'nx-latency-label', '⏱️ ' + t('uiHide')), idleSlider, idleVal);
8307
8516
  debugPanel.append(debugHeader, debugContent, debugJumpBtn);
8308
8517
 
8309
8518
  // Sync timing (offset between different versions of a movie)
@@ -8320,18 +8529,12 @@
8320
8529
  const osHeader = createWindowHeader('💬 ' + t('osTitle'), [{ className: 'close-btn', text: '✖' }]);
8321
8530
  osPanel.append(osHeader, OPENSUBS.build());
8322
8531
 
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
8532
 
8330
8533
  // Settings (things that are set once live here, not in the menu)
8331
8534
  const settingsModal = createEl('div', 'window-frame');
8332
8535
  settingsModal.id = 'settings-modal';
8333
8536
  const settingsHeader = createWindowHeader('⚙️ ' + t('settings'), [{ className: 'close-btn', text: '✖' }]);
8334
- const settingsBody = buildSettingsPanel({ autoCinema: btnAutoCinema, adGuard: btnAdGuard, subLog: btnSubLog, debug: btnDebug, idleRow, hideSite: btnHideSite });
8537
+ const settingsBody = buildSettingsPanel({ autoCinema: btnAutoCinema, adGuard: btnAdGuard, subLog: btnSubLog, chatLog: btnChatLog, debug: btnDebug, idleRow, hideSite: btnHideSite });
8335
8538
  settingsModal.append(settingsHeader, settingsBody);
8336
8539
 
8337
8540
  const drawCanvas = createEl('canvas');
@@ -8343,9 +8546,9 @@
8343
8546
  // Sketching and chat live in the reaction bar (🖍️ 💬); the menu does not repeat them.
8344
8547
  // The menu keeps only what is used while watching; speed and PiP live in the cinema
8345
8548
  // controls, and everything that is set once lives in ⚙️ Settings.
8346
- dock.append(btnFindMedia, btnLink, btnInvite, btnTune, btnCinema, btnBookmark, btnTranslate, btnSettings);
8549
+ dock.append(btnFindMedia, btnLink, btnInvite, btnTune, btnCinema, btnTranslate, btnSettings);
8347
8550
  uiWrapper.append(dock, reactPill, fab);
8348
- nexusContainer.append(drawCanvas, uiWrapper, chatPanel, subLogPanel, manualModal, transModal, settingsModal, bmPanel, tunePanel, osPanel, toast, debugPanel);
8551
+ nexusContainer.append(drawCanvas, uiWrapper, chatPanel, subLogPanel, manualModal, transModal, settingsModal, tunePanel, osPanel, toast, debugPanel);
8349
8552
  shadow.appendChild(nexusContainer);
8350
8553
  promoteHost();
8351
8554
 
@@ -8355,7 +8558,7 @@
8355
8558
 
8356
8559
  uiElements = {
8357
8560
  uiWrapper, fab, reactPill, dock, btnFindMedia, btnLink, btnSyncStatus, btnTranslate, btnCinema, btnAutoCinema, btnPiP, btnRate, btnDraw, btnBookmark, btnChat, btnSubLog,
8358
- btnDebug, btnHideSite, btnSettings, settingsModal, btnTune, tunePanel, chatPanel, chatMessages, chatInput, chatJumpBtn, subLogPanel, subLogMessages,
8561
+ btnDebug, btnHideSite, btnChatLog, btnSettings, settingsModal, btnTune, tunePanel, chatPanel, chatMessages, chatInput, chatJumpBtn, subLogPanel, subLogMessages,
8359
8562
  subLogJumpBtn, drawCanvas, manualModal, transModal, toast, debugJumpBtn, syncBubble: null,
8360
8563
  pinError, guestInput, pinHint, pinDisplay, pinCopyBtn, hostBtn, connectBtn, btnInvite, typingRow, nickInput
8361
8564
  };
@@ -8365,9 +8568,9 @@
8365
8568
  attachJumpLogic(subLogMessages, subLogJumpBtn);
8366
8569
  attachJumpLogic(debugContent, debugJumpBtn);
8367
8570
  makeDraggable(uiWrapper, fab);
8368
- [[chatPanel, chatHeader], [subLogPanel, subLogHeader], [manualModal, manualHeader], [transModal, transHeader], [settingsModal, settingsHeader], [bmPanel, bmHeader], [tunePanel, tuneHeader], [osPanel, osHeader], [debugPanel, debugHeader]]
8571
+ [[chatPanel, chatHeader], [subLogPanel, subLogHeader], [manualModal, manualHeader], [transModal, transHeader], [settingsModal, settingsHeader], [tunePanel, tuneHeader], [osPanel, osHeader], [debugPanel, debugHeader]]
8369
8572
  .forEach(([panel, header]) => makePanelDraggable(panel, header));
8370
- [chatPanel, subLogPanel, debugPanel, transModal, settingsModal, bmPanel, tunePanel, osPanel].forEach(panel => PANEL_SIZE.attach(panel));
8573
+ [chatPanel, subLogPanel, debugPanel, transModal, settingsModal, tunePanel, osPanel].forEach(panel => PANEL_SIZE.attach(panel));
8371
8574
 
8372
8575
  shadow.querySelectorAll('.window-frame').forEach(panel => {
8373
8576
  const pinBtn = panel.querySelector('.pin-btn');
@@ -8385,6 +8588,23 @@
8385
8588
  chatMessages.querySelectorAll('.chat-msg:not(.mine) .chat-text').forEach(el => CHAT_TR.applyTo(el));
8386
8589
  };
8387
8590
  chatHeader.querySelector('.chat-close-btn').onclick = () => { STATE.chatActive = false; closePanel(chatPanel); btnChat.classList.remove('active'); };
8591
+ btnChatLog.onclick = () => { STATE.chatActive = true; openPanel(chatPanel); DOM_UTILS.forceScroll(chatMessages, chatJumpBtn); };
8592
+ chatHeader.querySelector('.chat-clear-btn').onclick = () => { chatMessages.replaceChildren(); showToast(t('chatCleared')); };
8593
+ chatHeader.querySelector('.chat-export-btn').onclick = () => {
8594
+ let text = 'NexusSync Chat\n==============\n\n';
8595
+ Array.from(chatMessages.children).forEach(row => {
8596
+ const who = row.querySelector('.chat-name')?.textContent || '';
8597
+ const at = row.querySelector('.chat-clock')?.textContent || '';
8598
+ const body = row.querySelector('.chat-text');
8599
+ text += `[${at}] ${who}: ${body?.dataset.orig || body?.textContent || ''}\n`;
8600
+ });
8601
+ const url = URL.createObjectURL(new Blob([text], { type: 'text/plain;charset=utf-8' }));
8602
+ const a = document.createElement('a');
8603
+ a.href = url;
8604
+ a.download = `NexusSync_Chat_${new Date().toISOString().replace(/[:T-]/g, '').slice(0, 14)}.txt`;
8605
+ document.body.appendChild(a); a.click(); a.remove();
8606
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
8607
+ };
8388
8608
  subLogHeader.querySelector('.btn-close-log').onclick = () => { STATE.subLogActive = false; closePanel(subLogPanel); btnSubLog.classList.remove('active'); };
8389
8609
  subLogHeader.querySelector('.btn-clear-log').onclick = () => { subLogMessages.replaceChildren(); showToast(t('logCleared')); };
8390
8610
  subLogHeader.querySelector('.btn-export-log').onclick = () => {
@@ -8594,7 +8814,6 @@
8594
8814
  };
8595
8815
 
8596
8816
  btnCinema.onclick = () => { triggerHaptic(); CINEMA.toggle(); };
8597
- btnAutoCinema.onclick = () => { triggerHaptic(); AUTO_CINEMA.setSite(!AUTO_CINEMA.enabled()); };
8598
8817
  btnPiP.onclick = async () => {
8599
8818
  let video = STATE.video;
8600
8819
  if (!video || video.readyState === 0) {
@@ -8616,10 +8835,7 @@
8616
8835
  if (uiElements.dock?.classList.contains('open')) toggleDock(false);
8617
8836
  INK.start();
8618
8837
  };
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);
8622
- btnHideSite.onclick = () => setFabHiddenOnSite(true);
8838
+ btnBookmark.onclick = () => addBookmark();
8623
8839
 
8624
8840
  setupCanvasLogic();
8625
8841
  resetIdleTimer(true);
@@ -8645,6 +8861,7 @@
8645
8861
  if (hidden) UI_GATE.forced = false;
8646
8862
  STORE.set('nxu_hide_fab_' + HOST, !!hidden);
8647
8863
  uiElements.uiWrapper?.classList.toggle('site-hidden', !!hidden);
8864
+ uiElements.btnHideSite?.paint?.();
8648
8865
  try { ROTATE._tick(); } catch (_) { }
8649
8866
  if (hidden) {
8650
8867
  toggleDock(false);
@@ -8733,7 +8950,7 @@
8733
8950
  const color = /^(#[0-9a-f]{3,8}|hsl\([\d., %]+\))$/i.test(msg.color || '') ? msg.color : '#69f0ae';
8734
8951
  const row = createEl('div', 'chat-msg' + (msg.sender === STATE.userId ? ' mine' : ''));
8735
8952
  row.style.borderLeft = `4px solid ${color}`;
8736
- const av = safeEmoji(msg.av);
8953
+ const av = safeAvatar(msg.av);
8737
8954
  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
8955
  name.style.color = color;
8739
8956
  row.appendChild(name);
@@ -8812,18 +9029,19 @@
8812
9029
  return first.length <= 16 && /\p{Extended_Pictographic}|\p{Regional_Indicator}/u.test(first) ? first : '';
8813
9030
  }
8814
9031
 
8815
- // What reaches this device from the others, and from whom: kinds of events can be turned
8816
- // off, a person can be muted for this room, and floods of reactions are thinned out.
9032
+ // An avatar: one emoji.
9033
+ function safeAvatar(s) { return safeEmoji(s); }
9034
+
9035
+ // Photo avatars were removed (1.6.0): older devices may still announce or send one; it is ignored.
9036
+ const AVATAR_IMG = { get() { return ''; }, mine() { }, onRemote() { } };
9037
+
9038
+ // Everything the others send (reactions, nudges, sketches, bubbles, pointers) always
9039
+ // reaches a connected device — those are the point of watching together. Only floods of
9040
+ // reactions are thinned out.
8817
9041
  const SAFETY = {
8818
- KINDS: ['react', 'nudge', 'ink', 'chat', 'ping'],
8819
9042
  muted: new Set(),
8820
- receive(kind) { return STORE.get('nxu_recv_' + kind, true) !== false; },
8821
- set(kind, on) { STORE.set('nxu_recv_' + kind, !!on); },
8822
- allows(uid, kind) {
8823
- if (uid && this.muted.has(uid)) return false;
8824
- return !kind || this.receive(kind);
8825
- },
8826
- toggleMute(uid) { if (this.muted.has(uid)) this.muted.delete(uid); else this.muted.add(uid); },
9043
+ receive() { return true; },
9044
+ allows() { return true; },
8827
9045
  _rate: new Map(),
8828
9046
  // More than 6 reactions a second from one person: the rest are not shown.
8829
9047
  flood(uid, max = 6) {
@@ -8839,10 +9057,13 @@
8839
9057
  // The eight reaction buttons: the user's own choice (any emoji), or the defaults.
8840
9058
  const REACTIONS = {
8841
9059
  DEFAULT: ['😂', '😭', '😡', '💦', '🍪', '☕', '😘', '🖕'],
9060
+ PALETTE: ['❤️', '🔥', '👏', '🤣', '😱', '😍', '🥺', '🤯', '👀', '💀', '🙏', '👍', '🎉', '💯', '😴', '🤔', '🍿', '😂', '😭', '😡', '💦', '🍪', '☕', '😘'],
9061
+ MAX: 16,
8842
9062
  list() {
8843
9063
  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);
9064
+ if (!Array.isArray(saved) || !saved.length) return this.DEFAULT.slice();
9065
+ const arr = saved.slice(0, this.MAX).map(safeEmoji);
9066
+ return arr.map((e, i) => e || this.DEFAULT[i % this.DEFAULT.length]);
8846
9067
  },
8847
9068
  set(i, emoji) {
8848
9069
  const list = this.list();
@@ -8853,6 +9074,23 @@
8853
9074
  this.apply();
8854
9075
  return true;
8855
9076
  },
9077
+ add() {
9078
+ const list = this.list();
9079
+ if (list.length >= this.MAX) return -1;
9080
+ const spare = ['❤️', '🔥', '👏', '😱', '👀', '🎉', '🤔', '💯'].find(x => !list.includes(x)) || '⭐';
9081
+ list.push(spare);
9082
+ STORE.set('nxu_reactions', list);
9083
+ this.apply();
9084
+ return list.length - 1;
9085
+ },
9086
+ remove(i) {
9087
+ const list = this.list();
9088
+ if (list.length <= 1 || i < 0 || i >= list.length) return false;
9089
+ list.splice(i, 1);
9090
+ STORE.set('nxu_reactions', list);
9091
+ this.apply();
9092
+ return true;
9093
+ },
8856
9094
  reset() { STORE.set('nxu_reactions', null); this.apply(); },
8857
9095
  apply() {
8858
9096
  CONFIG.emojis = this.list();
@@ -8869,7 +9107,7 @@
8869
9107
  };
8870
9108
 
8871
9109
  const PROFILE = {
8872
- SWATCHES: ['#69f0ae', '#40c4ff', '#7c4dff', '#ff4fa3', '#ff6e40', '#ffd740', '#b2ff59', '#18ffff', '#ea80fc', '#ff8a80'],
9110
+ SWATCHES: ['#69f0ae', '#40c4ff', '#7c4dff', '#ff4fa3', '#ff6e40', '#ffd740', '#ea80fc'],
8873
9111
  color() {
8874
9112
  const c = String(STORE.get('nxu_color', '') || '');
8875
9113
  return /^#[0-9a-f]{6}$/i.test(c) ? c : generateUserColor(STATE.userId);
@@ -8883,16 +9121,14 @@
8883
9121
  },
8884
9122
  // What this device announces in the room (presence): name, colour, avatar, status.
8885
9123
  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 };
8887
- },
8888
- AVATARS: ['🙂', '😎', '🦊', '🐱', '🐶', '🐼', '🐸', '🦄', '🐧', '🍿', '🎧', '🌙', '🔥', '🌸', '👾', '🤖'],
8889
- avatar() { return safeEmoji(STORE.get('nxu_avatar', '')); },
8890
- 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(); },
8892
- setStatus(s) {
8893
- STORE.set('nxu_status', String(s || '').replace(/\s+/g, ' ').slice(0, 40));
8894
- clearTimeout(this._st); this._st = setTimeout(() => { this.publish(); updatePresenceUI(); }, 600);
8895
- },
9124
+ return { ts: Date.now(), color: STATE.color, viewer: !!STATE.isViewer, nick: STATE.nickname || '', av: this.avatar(), md: TUNE.mediaSig(), v: NXU_VERSION, r: NXU_RANK, sess: NXU_SESSION, hid: !!document.hidden };
9125
+ },
9126
+ AVATARS: ['🙂', '😎', '🥳', '🤠', '👻', '👾', '🤖', '🎃', '🦊', '🐱', '🐶', '🐯', '🐵', '🐼', '🐸', '🐰', '🐻', '🐨', '🦁', '🐧', '🦄', '🐙', '🍿', '🎧'],
9127
+ avatar() { return safeAvatar(STORE.get('nxu_avatar', '')); },
9128
+ image() { return ''; },
9129
+ imageHash() { return ''; },
9130
+ status() { return ''; },
9131
+ setAvatar(a) { STORE.set('nxu_avatar', safeAvatar(a)); this.publish(); updatePresenceUI(); },
8896
9132
  setName(name) {
8897
9133
  STATE.nickname = String(name || '').trim().slice(0, 16);
8898
9134
  STORE.set('nxu_nickname', STATE.nickname);
@@ -9076,8 +9312,10 @@
9076
9312
  const text = String(msg.text).slice(0, 200);
9077
9313
  const card = createEl('button', 'nx-bubble nx-talk' + (mine ? ' mine' : ''), '', { type: 'button' });
9078
9314
  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());
9315
+ const av = safeAvatar(mine ? PROFILE.avatar() : (msg.av || STATE.presenceMap?.[msg.sender]?.av));
9316
+ const photo = AVATAR_IMG.get(mine ? STATE.userId : msg.sender);
9317
+ const avatar = createEl('span', 'nx-talk-avatar' + (av || photo ? ' emoji' : ''), photo ? '' : av || (Array.from(name.replace(/^ID:/, ''))[0] || '?').toUpperCase());
9318
+ if (photo) { avatar.style.backgroundImage = `url("${photo}")`; avatar.style.backgroundSize = 'cover'; }
9081
9319
  const body = createEl('span', 'nx-talk-body');
9082
9320
  body.append(createEl('span', 'nx-bubble-name', name), createEl('span', 'nx-bubble-text', text));
9083
9321
  card.append(avatar, body);
@@ -9542,54 +9780,13 @@
9542
9780
  restore() { const v = Number((STORE.get('nxu_bright', {}) || {})[HOST]); if (Number.isFinite(v) && v !== 1) this.set(v, { save: false }); }
9543
9781
  };
9544
9782
 
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
9783
  // ───────────────────────── Subtitles in cinema: the video's own tracks, a file, or
9588
9784
  // OpenSubtitles — drawn by NexusSync in one consistent style, with timing and size.
9589
9785
  const SUBS = {
9590
- cues: null, // [{ s, e, text }] for an external file
9591
- label: '',
9592
- track: null, // a TextTrack of the page's video
9786
+ // Up to three subtitle layers at once (e.g. Dutch + English + Korean for learning):
9787
+ // each is a track of the page's video or a loaded file, drawn in its own colour.
9788
+ layers: [], // { id, kind: 'track'|'cues', track?, cues?, label }
9789
+ MAX: 3,
9593
9790
  delay: 0,
9594
9791
  _box: null, _timer: 0, _last: '',
9595
9792
  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 +9795,8 @@
9598
9795
  if (!v || !v.textTracks) return [];
9599
9796
  return [...v.textTracks].filter(tr => tr.kind === 'subtitles' || tr.kind === 'captions');
9600
9797
  },
9601
- active() { return !!(this.cues || this.track); },
9798
+ active() { return this.layers.length > 0; },
9799
+ hasTrack(tr) { return this.layers.some(l => l.track === tr); },
9602
9800
  _ensureBox() {
9603
9801
  const c = getContainer();
9604
9802
  if (!c) return null;
@@ -9606,35 +9804,43 @@
9606
9804
  this._box.style.setProperty('--xs', String(this.size()));
9607
9805
  return this._box;
9608
9806
  },
9807
+ _drop(l) {
9808
+ if (l.track) { try { l.track.removeEventListener('cuechange', this._onCue); l.track.mode = 'disabled'; } catch (_) { } }
9809
+ },
9609
9810
  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 = '';
9811
+ this.layers.forEach(l => this._drop(l));
9812
+ this.layers = [];
9612
9813
  clearInterval(this._timer); this._timer = 0;
9613
9814
  this._render('');
9614
9815
  try { CUE_MIRROR.render(); } catch (_) { }
9615
9816
  },
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
9817
+ remove(id) {
9818
+ const l = this.layers.find(x => x.id === id);
9819
+ if (!l) return;
9820
+ this._drop(l);
9821
+ this.layers = this.layers.filter(x => x !== l);
9822
+ if (!this.layers.length) this.off(); else this.tick(true);
9823
+ },
9824
+ _add(layer) {
9825
+ while (this.layers.length >= this.MAX) { this._drop(this.layers[0]); this.layers.shift(); }
9826
+ layer.id = Math.random().toString(36).slice(2, 8);
9827
+ this.layers.push(layer);
9622
9828
  try { CUE_MIRROR.render(); } catch (_) { }
9623
- this._onCue = () => this.tick();
9624
- tr.addEventListener('cuechange', this._onCue);
9625
9829
  this._loop();
9626
- showToast(t('subLoaded', { name: this.label }));
9830
+ showToast(t('subLoaded', { name: layer.label }));
9627
9831
  },
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 }));
9832
+ // A track of the video: tapping it again takes it away.
9833
+ useTrack(tr) {
9834
+ const has = this.layers.find(l => l.track === tr);
9835
+ if (has) { this.remove(has.id); return; }
9836
+ this._onCue = this._onCue || (() => this.tick());
9837
+ tr.mode = 'hidden'; // cues still arrive, the browser does not draw them itself
9838
+ tr.addEventListener('cuechange', this._onCue);
9839
+ this._add({ kind: 'track', track: tr, label: tr.label || tr.language || t('subTrack') });
9635
9840
  },
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(); },
9841
+ useCues(cues, label) { this._add({ kind: 'cues', cues: cues.sort((a, b) => a.s - b.s), label }); },
9842
+ _loop() { clearInterval(this._timer); this._timer = setInterval(() => this.tick(), 150); this.tick(true); },
9843
+ setDelay(d) { this.delay = Math.round(Math.max(-120, Math.min(120, d)) * 10) / 10; this.tick(true); },
9638
9844
  _now() {
9639
9845
  const info = currentMediaInfo();
9640
9846
  if (!info) return null;
@@ -9645,28 +9851,37 @@
9645
9851
  }
9646
9852
  return tm;
9647
9853
  },
9648
- tick() {
9854
+ _textOf(l, at) {
9855
+ if (l.kind === 'cues') {
9856
+ let lo = 0, hi = l.cues.length - 1, idx = -1;
9857
+ while (lo <= hi) { const mid = (lo + hi) >> 1; if (l.cues[mid].s <= at) { idx = mid; lo = mid + 1; } else hi = mid - 1; }
9858
+ const parts = [];
9859
+ 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); }
9860
+ return this._clean(parts.join('\n'));
9861
+ }
9862
+ const list = l.track.cues ? [...l.track.cues] : [];
9863
+ const act = this.delay ? list.filter(c => c.startTime <= at && at < c.endTime) : [...(l.track.activeCues || [])];
9864
+ return this._clean(act.map(c => (c.text || '')).join('\n'));
9865
+ },
9866
+ tick(force = false) {
9649
9867
  if (!this.active()) return;
9650
9868
  const tm = this._now();
9651
9869
  if (tm == null) return;
9652
9870
  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));
9871
+ const groups = this.layers.map((l, i) => ({ i, text: this._textOf(l, at) }));
9872
+ const sig = groups.map(g => g.text).join('\u0001');
9873
+ if (!force && sig === this._last && this._box?.isConnected) return;
9874
+ this._last = sig;
9875
+ const any = groups.some(g => g.text);
9876
+ const box = any ? this._ensureBox() : this._box;
9877
+ if (!box) return;
9878
+ const kids = [];
9879
+ 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))); });
9880
+ box.replaceChildren(...kids);
9881
+ box.classList.toggle('on', any);
9668
9882
  },
9669
9883
  _clean(s) { return String(s || '').replace(/<[^>]+>/g, '').replace(/\{\\[^}]*\}/g, '').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').trim(); },
9884
+ // Plain text into the layer (the site's own subtitles, see DOM_SUBS).
9670
9885
  _render(text) {
9671
9886
  if (text === this._last && this._box?.isConnected) return;
9672
9887
  this._last = text;
@@ -9717,7 +9932,7 @@
9717
9932
  },
9718
9933
  // A gentle offer when cinema has nothing to read: once per page.
9719
9934
  maybeSuggest() {
9720
- if (!IS_TOP || !STATE.isCinema || this.active() || this._suggested === location.href) return;
9935
+ if (!IS_TOP || !STATE.isCinema || this.active() || DOM_SUBS._src || this._suggested === location.href) return;
9721
9936
  if (this.tracks().length || (CUE_MIRROR.box?.textContent || '').trim() || TRANSLATOR.active) return;
9722
9937
  const info = currentMediaInfo();
9723
9938
  if (!info || info.live || info.paused) return;
@@ -9732,6 +9947,61 @@
9732
9947
  }
9733
9948
  };
9734
9949
 
9950
+ // The site's own subtitles drawn as page text (a separate subtitle file the site renders
9951
+ // itself, not a track of the video). With the NexusSync controls the player box is
9952
+ // stretched to the screen, and those lines kept their old position — often below the
9953
+ // visible screen on phones. Text in the player that keeps changing is recognised as
9954
+ // subtitles, hidden in place and shown in NexusSync's subtitle layer instead, which
9955
+ // always stays inside the visible screen and above the controls.
9956
+ const DOM_SUBS = {
9957
+ _obs: null, _root: null, _cands: new Map(), _src: null, _timer: 0,
9958
+ SEL: '[class*="caption" i], [class*="subtitle" i], [class*="cue" i], [class*="text-track" i], [class*="subs" i], [id*="subtitle" i], [id*="caption" i]',
9959
+ sync() {
9960
+ const root = STATE.isCinema && CINEMA.nexusControls() && CINEMA.applied?.chain?.[0]?.root;
9961
+ const v = CINEMA.applied?.video;
9962
+ if (!root || !v || root === v || root.ownerDocument !== document) { this.stop(); return; }
9963
+ if (this._root === root) return;
9964
+ this.stop();
9965
+ this._root = root;
9966
+ this._obs = new MutationObserver(() => { if (!this._timer) this._timer = setTimeout(() => { this._timer = 0; this.scan(); }, 80); });
9967
+ this._obs.observe(root, { childList: true, subtree: true, characterData: true });
9968
+ this.scan();
9969
+ },
9970
+ stop() {
9971
+ this._obs?.disconnect(); this._obs = null; this._root = null;
9972
+ clearTimeout(this._timer); this._timer = 0;
9973
+ document.querySelectorAll('.nxu-dsub-src').forEach(n => n.classList.remove('nxu-dsub-src'));
9974
+ if (this._src && !SUBS.active()) SUBS._render('');
9975
+ this._src = null; this._cands.clear();
9976
+ },
9977
+ _text(el) { return String(el.innerText || el.textContent || '').replace(/[ \t]+/g, ' ').replace(/\n{2,}/g, '\n').trim().slice(0, 300); },
9978
+ scan() {
9979
+ const root = this._root;
9980
+ if (!root || !root.isConnected) { this.stop(); return; }
9981
+ if (this._src && this._src.isConnected) { this._show(); return; }
9982
+ const v = CINEMA.applied?.video;
9983
+ const cands = new Set();
9984
+ try { root.querySelectorAll(this.SEL).forEach(el => cands.add(el)); } catch (_) { }
9985
+ (CINEMA._textLayers || []).forEach(el => cands.add(el));
9986
+ const now = Date.now();
9987
+ for (const el of cands) {
9988
+ if (!el.isConnected || el.contains(v) || el.closest('.nxu-cue-mirror') || el.querySelector('button, input, svg, [role="slider"]')) continue;
9989
+ const txt = this._text(el);
9990
+ const c = this._cands.get(el) || { last: null, changes: [], };
9991
+ if (txt !== c.last) { if (c.last !== null) c.changes.push(now); c.last = txt; }
9992
+ c.changes = c.changes.filter(ts => now - ts < 30000);
9993
+ this._cands.set(el, c);
9994
+ // Two changes of its text within half a minute: subtitles, not a title.
9995
+ 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; }
9996
+ }
9997
+ },
9998
+ _show() {
9999
+ if (SUBS.active()) return; // the user picked other subtitles
10000
+ SUBS._render(this._text(this._src));
10001
+ }
10002
+ };
10003
+ setInterval(() => { try { DOM_SUBS.sync(); } catch (_) { } }, 1000);
10004
+
9735
10005
  // OpenSubtitles.org search (its public REST interface: no account needed).
9736
10006
  const OPENSUBS = {
9737
10007
  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 +10020,27 @@
9750
10020
  .replace(/[\[\](){}]/g, ' ').replace(/\b(19|20)\d{2}\b/g, ' ').replace(/\s+/g, ' ').trim();
9751
10021
  return { query: s, year, season, episode };
9752
10022
  },
10023
+ // OpenSubtitles knows films by their English titles; a Korean (or other) page title is
10024
+ // looked up on TMDB first, and its English titles are offered (the first one is used).
10025
+ async tmdb(query, year) {
10026
+ const url = 'https://www.themoviedb.org/search?query=' + encodeURIComponent(query) + '&language=en-US';
10027
+ const res = await httpRequest({ url, headers: { 'Accept-Language': 'en-US,en;q=0.9' }, timeout: 12000 });
10028
+ if (res.status !== 200) throw new Error('HTTP ' + res.status);
10029
+ const doc = new DOMParser().parseFromString(res.text || '', 'text/html');
10030
+ const out = [];
10031
+ doc.querySelectorAll('a[data-media-type] h2').forEach(h2 => {
10032
+ const a = h2.closest('a');
10033
+ const title = (h2.querySelector('span')?.textContent || h2.textContent || '').trim();
10034
+ if (!title || out.some(x => x.title === title)) return;
10035
+ const card = a.closest('[class*="media-card"]') || a.parentElement?.parentElement;
10036
+ const date = card?.querySelector('.release_date')?.textContent || '';
10037
+ const y = (date.match(/(19|20)\d{2}/) || [])[0] || '';
10038
+ out.push({ title, year: y, type: a.getAttribute('data-media-type') === 'tv' ? 'tv' : 'movie' });
10039
+ });
10040
+ // The page's year (if any) decides between same-named films.
10041
+ if (year) out.sort((p, q) => (q.year === year) - (p.year === year));
10042
+ return out.slice(0, 6);
10043
+ },
9753
10044
  async search({ query, season, episode, lang }) {
9754
10045
  const l3 = this.LANG3[lang] || 'eng';
9755
10046
  const parts = [];
@@ -9798,8 +10089,38 @@
9798
10089
  const q = panel.querySelector('.os-q'), se = panel.querySelector('.os-season'), ep = panel.querySelector('.os-episode'), lg = panel.querySelector('.os-lang');
9799
10090
  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
10091
  lg.value = this.LANG3[this.lang()] ? this.lang() : 'en';
10092
+ // Opened again after picking one: start at the top (it used to keep the old scroll
10093
+ // position past the end of a shorter list, which looked like an empty window).
10094
+ panel.scrollTop = 0;
10095
+ const body = panel.querySelector('.os-body'); if (body) body.scrollTop = 0;
10096
+ panel.querySelectorAll('.os-item.busy').forEach(b => b.classList.remove('busy'));
9801
10097
  openPanel(panel);
9802
- if (q.value && !panel.querySelector('.os-item')) this.run(panel);
10098
+ if (q.value && !panel.querySelector('.os-item')) this.prepare(panel, g);
10099
+ },
10100
+ // Non-Latin titles: English title from TMDB first, offered as one-tap choices.
10101
+ async prepare(panel, g) {
10102
+ const q = panel.querySelector('.os-q'), chips = panel.querySelector('.os-tmdb');
10103
+ chips.replaceChildren();
10104
+ if (/[^\u0000-\u024f\s\d\p{P}]/u.test(q.value)) {
10105
+ chips.append(createEl('span', 'trans-help', t('osTmdbLooking')));
10106
+ try {
10107
+ let list = await this.tmdb(q.value, g?.year || '');
10108
+ // Nothing for the whole title: try the part before a colon ("Title: Subtitle").
10109
+ if (!list.length && /[::]/.test(q.value)) list = await this.tmdb(q.value.split(/[::]/)[0].trim(), g?.year || '');
10110
+ chips.replaceChildren();
10111
+ if (list.length) {
10112
+ chips.append(createEl('span', 'os-tmdb-label', 'TMDB'));
10113
+ list.forEach((m, i) => {
10114
+ const b = createEl('button', 'os-chip' + (i === 0 ? ' on' : ''), m.title + (m.year ? ' (' + m.year + ')' : ''), { type: 'button' });
10115
+ b.onclick = () => { chips.querySelectorAll('.os-chip').forEach(c => c.classList.toggle('on', c === b)); q.value = m.title; this.run(panel); };
10116
+ chips.appendChild(b);
10117
+ });
10118
+ q.dataset.original = q.value;
10119
+ q.value = list[0].title;
10120
+ } else chips.append(createEl('span', 'trans-help', t('osTmdbNone')));
10121
+ } catch (err) { chips.replaceChildren(); logDebug('TMDB lookup failed: ' + (err.message || err), 'warn'); }
10122
+ }
10123
+ this.run(panel);
9803
10124
  },
9804
10125
  async run(panel) {
9805
10126
  const q = panel.querySelector('.os-q').value.trim();
@@ -9808,9 +10129,13 @@
9808
10129
  const lang = panel.querySelector('.os-lang').value;
9809
10130
  STORE.set('nxu_os_lang', lang);
9810
10131
  out.replaceChildren(createEl('div', 'trans-help', t('osSearching')));
10132
+ const win = panel.closest('#os-panel') || panel;
9811
10133
  try {
9812
10134
  const list = await this.search({ query: q, season: +panel.querySelector('.os-season').value || 0, episode: +panel.querySelector('.os-episode').value || 0, lang });
9813
- if (!list.length) { out.replaceChildren(createEl('div', 'trans-help', t('osNone'))); return; }
10135
+ if (!list.length) { win.classList.remove('has-results'); out.replaceChildren(createEl('div', 'trans-help', t('osNone'))); return; }
10136
+ win.classList.add('has-results');
10137
+ requestAnimationFrame(() => clampPanelToViewport(win));
10138
+ out.scrollTop = 0;
9814
10139
  out.replaceChildren(...list.map(item => {
9815
10140
  const b = createEl('button', 'os-item', '', { type: 'button' });
9816
10141
  b.append(createEl('span', 'os-name', String(item.MovieReleaseName || item.SubFileName || item.MovieName || '').slice(0, 140)),
@@ -9844,7 +10169,8 @@
9844
10169
  const out = createEl('div', 'os-results');
9845
10170
  go.onclick = () => this.run(body);
9846
10171
  [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')));
10172
+ const tm = createEl('div', 'os-tmdb');
10173
+ body.append(q, tm, row, go, out, createEl('div', 'trans-help os-hint', t('osHint')));
9848
10174
  return body;
9849
10175
  }
9850
10176
  };
@@ -9881,23 +10207,31 @@
9881
10207
  const r = v.getBoundingClientRect();
9882
10208
  if (r.width < 240 || r.height < 135) return;
9883
10209
  const seen = new Set();
10210
+ // "Holds the video" across shadow roots (players often keep the <video> inside one:
10211
+ // a plain contains() said no, and a whole page section got hidden — black screen).
10212
+ const holds = (el) => { for (let n = v; n; n = n.parentNode || n.host) { if (n === el) return true; } return false; };
10213
+ const area = r.width * r.height;
9884
10214
  for (const fx of [0.15, 0.5, 0.85]) for (const fy of [0.15, 0.5, 0.85]) {
9885
10215
  const x = r.left + r.width * fx, y = r.top + r.height * fy;
9886
10216
  if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) continue;
9887
10217
  let stack;
9888
10218
  try { stack = document.elementsFromPoint(x, y); } catch (_) { continue; }
9889
10219
  for (const el of stack) {
9890
- if (el === v || el.contains(v)) break; // reached the picture
10220
+ if (el === v || holds(el)) break; // reached the picture
9891
10221
  if (seen.has(el) || this.hidden.has(el) || el.closest('#nxu-host') || el.id === 'nxu-host') continue;
9892
10222
  seen.add(el);
9893
10223
  // Climb to the whole overlay box (but never to something holding the video).
9894
10224
  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;
10225
+ while (box.parentElement && !holds(box.parentElement) && box.parentElement !== document.body) box = box.parentElement;
10226
+ if (this.hidden.has(box) || holds(box) || box.querySelector?.('video')) continue;
9897
10227
  const sig = `${box.id} ${typeof box.className === 'string' ? box.className : ''}`;
9898
10228
  if (this.RX_CONTROL.test(sig)) continue;
9899
10229
  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
10230
+ if (br.width * br.height > area * 0.92 && !box.querySelector?.('a[href], iframe')) continue; // likely the player's own click layer
10231
+ // Only boxes laid over the picture: never a page section much larger than
10232
+ // the video, never something in the normal flow of the page.
10233
+ if (br.width * br.height > area * 1.6) continue;
10234
+ try { if (getComputedStyle(box).position === 'static' && getComputedStyle(el).position === 'static') continue; } catch (_) { }
9901
10235
  if (!this._adLike(box) && !this._adLike(el)) continue;
9902
10236
  this.hide(box);
9903
10237
  }
@@ -9967,9 +10301,7 @@
9967
10301
  paintButton() {
9968
10302
  const b = uiElements.btnAutoCinema;
9969
10303
  if (!b) return;
9970
- const on = this.enabled();
9971
- b.textContent = '✨ ' + t(on ? 'autoCinemaBtnOn' : 'autoCinemaBtnOff');
9972
- b.classList.toggle('active', on);
10304
+ b.paint?.();
9973
10305
  },
9974
10306
  // One real video on the page, big enough, long enough — not a feed.
9975
10307
  _singleMedia() {
@@ -10064,13 +10396,11 @@
10064
10396
  };
10065
10397
  setInterval(() => {
10066
10398
  try { AUTO_CINEMA.tick(); } catch (_) { }
10067
- try { JUMP.tick(); } catch (_) { }
10068
10399
  try {
10069
10400
  if (STATE.isCinema) { SUBS._cinemaSince = SUBS._cinemaSince || Date.now(); if (Date.now() - SUBS._cinemaSince > 6000) SUBS.maybeSuggest(); }
10070
10401
  else SUBS._cinemaSince = 0;
10071
10402
  } catch (_) { }
10072
10403
  }, 1200);
10073
- try { JUMP.init(); } catch (_) { }
10074
10404
 
10075
10405
  // ───────────────────────── Next episode
10076
10406
  // On series pages (drama/anime sites) the page usually has a "next episode" link or
@@ -10381,7 +10711,7 @@
10381
10711
  _typing: new Map(),
10382
10712
  _connectedAt: 0,
10383
10713
  _lastCanvasBubble: 0,
10384
- TYPES: ['nudge', 'pointer', 'countdown', 'typing', 'ink', 'cover', 'goto', 'tune'],
10714
+ TYPES: ['nudge', 'pointer', 'countdown', 'typing', 'ink', 'cover', 'goto', 'tune', 'avatar'],
10385
10715
  live() { return STATE.handshakeVerified && !STATE.isReadOnly && STATE.role !== 'IDLE'; },
10386
10716
  send(type, data = {}) {
10387
10717
  if (!this.live()) return false;
@@ -10392,6 +10722,7 @@
10392
10722
  },
10393
10723
  receive(type, d) {
10394
10724
  if (!d || typeof d !== 'object' || d.uid === STATE.userId || !this.live()) return;
10725
+ if (type !== 'typing' && type !== 'avatar') try { HEAL.heard(d.uid); } catch (_) { }
10395
10726
  // Muted people and switched-off kinds (the cover, countdowns and "go together"
10396
10727
  // always come through: they keep everyone watching the same thing).
10397
10728
  const kind = { nudge: 'nudge', ink: 'ink', pointer: 'ping', typing: 'chat' }[type];
@@ -10411,6 +10742,7 @@
10411
10742
  else if (type === 'cover') COVER.onRemote(who, d);
10412
10743
  else if (type === 'goto') TRAVEL.onRemote(who, d);
10413
10744
  else if (type === 'tune') TUNE.onRemote(who, d);
10745
+ else if (type === 'avatar') AVATAR_IMG.onRemote(d);
10414
10746
  },
10415
10747
  // Fresh events only: the history a newcomer downloads must not pop up as notifications.
10416
10748
  isFresh(ts) {
@@ -10616,8 +10948,6 @@
10616
10948
  // Remote chat message → bubble (unless the chat is already open).
10617
10949
  onChat(msg) {
10618
10950
  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
10951
  TALK.say(msg);
10622
10952
  },
10623
10953
  // Remote drawing → shown on screen right away (view only) + bubble to join in.
@@ -10855,7 +11185,7 @@
10855
11185
  const PRESS_COLORS = { '😂': '#ffd54f', '😭': '#82b1ff', '😡': '#ff5252', '💦': '#4fc3f7', '🍪': '#d7a86e', '☕': '#bcaaa4', '😘': '#ff6fae', '🖕': '#ffb74d' };
10856
11186
  function pressFx(btn, emoji) {
10857
11187
  if (!btn) return;
10858
- btn.style.setProperty('--pop', PRESS_COLORS[emoji] || '#69f0ae');
11188
+ btn.style.setProperty('--pop', '#69f0ae');
10859
11189
  btn.classList.remove('pop');
10860
11190
  void btn.offsetWidth;
10861
11191
  btn.classList.add('pop');
@@ -10946,7 +11276,9 @@
10946
11276
  const sway = (Math.random() < 0.5 ? -1 : 1) * (10 + Math.random() * 14);
10947
11277
  const d = 1700 + Math.random() * 500;
10948
11278
  const base = { duration: d, delay };
10949
- const kind = { '❤️': 'heart', '💗': 'heart', '😂': 'laugh', '😭': 'cry', '😡': 'angry', '💦': 'splash', '🍪': 'munch', '☕': 'steam', '😘': 'kiss', '🖕': 'flip', '🫣': 'peek', '🌰': 'toss', '🚽': 'flush' }[e] || 'float';
11279
+ // Every reaction moves the same way now that anyone can pick any emoji (only the
11280
+ // nudge's 💗 keeps its heartbeat).
11281
+ const kind = e === '💗' ? 'heart' : 'float';
10950
11282
  if (this.reduced()) { this._run(el, [{ opacity: 0 }, { opacity: 1, offset: 0.2 }, { opacity: 0, transform: `translateY(${-R * 0.4}px)` }], base); return; }
10951
11283
  switch (kind) {
10952
11284
  case 'heart':
@@ -11208,6 +11540,7 @@
11208
11540
  function onRemoteReaction(d) {
11209
11541
  if (!d || typeof d.emoji !== 'string' || d.emoji.length > 8) return;
11210
11542
  const uid = typeof d.uid === 'string' ? d.uid.slice(0, 40) : 'peer';
11543
+ try { HEAL.heard(uid); } catch (_) { }
11211
11544
  if (!SAFETY.allows(uid, 'react') || SAFETY.flood(uid)) return;
11212
11545
  const color = typeof d.color === 'string' && /^(#[0-9a-f]{3,8}|hsl\([\d., %]+\))$/i.test(d.color) ? d.color : '#82b1ff';
11213
11546
  const name = (typeof d.nick === 'string' && d.nick.trim().slice(0, 16)) || participantName(uid);
@@ -11319,7 +11652,6 @@
11319
11652
  case 'seekBy': MEDIA_SAFE.seek(v, Math.max(0, v.currentTime + value)); break;
11320
11653
  case 'volume': v.volume = Math.max(0, Math.min(1, value)); v.muted = value === 0; break;
11321
11654
  case 'mute': v.muted = !v.muted; break;
11322
- case 'boost': BOOST.set(value); break;
11323
11655
  }
11324
11656
  }
11325
11657
 
@@ -11846,13 +12178,16 @@
11846
12178
  if (!open) return;
11847
12179
  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
12180
  const tracks = SUBS.tracks();
12181
+ const nothing = !SUBS.active() && !TRANSLATOR.active && !DOM_SUBS._src;
11849
12182
  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)));
12183
+ item(t('xsubOff'), nothing, () => { SUBS.off(); if (TRANSLATOR.active) TRANSLATOR.stop(t('subOff')); this.toggleSubMenu(false); })];
12184
+ // Several can be on at once (up to three): tap to add, tap again to take away.
12185
+ tracks.forEach((tr, i) => kids.push(item('🎞 ' + (tr.label || tr.language || t('subTrack') + ' ' + (i + 1)), SUBS.hasTrack(tr), () => { SUBS.useTrack(tr); this.toggleSubMenu(true); })));
12186
+ SUBS.layers.filter(l => l.kind === 'cues').forEach(l => kids.push(item('💬 ' + l.label, true, () => { SUBS.remove(l.id); this.toggleSubMenu(true); })));
12187
+ if (SUBS.layers.length > 1) kids.push(createEl('div', 'cc-menu-note', t('subMulti')));
11853
12188
  kids.push(item(t('subSearch'), false, () => { this.toggleSubMenu(false); OPENSUBS.open(); }));
11854
12189
  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(); }));
12190
+ kids.push(item(t('subAi'), !!TRANSLATOR.active, () => { this.toggleSubMenu(false); TRANSLATOR.toggle(); }));
11856
12191
  if (SUBS.active()) {
11857
12192
  const d = createEl('div', 'cc-menu-adjust');
11858
12193
  const val = createEl('span', 'cc-adj-val', (SUBS.delay > 0 ? '+' : '') + SUBS.delay.toFixed(1) + 's');
@@ -11888,11 +12223,22 @@
11888
12223
  return { row, r, out };
11889
12224
  };
11890
12225
  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));
12226
+ const b = slider('☀️ ' + t('viewBright'), 30, 200, BRIGHTNESS.level, pct, v => { BRIGHTNESS.set(v); this.update(); });
11893
12227
  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);
12228
+ reset.onclick = (ev) => { ev.stopPropagation(); BRIGHTNESS.set(1); b.r.value = '100'; b.out.textContent = '100%'; this.update(); };
12229
+ const kids = [createEl('div', 'cc-menu-title', t('viewMenu')), b.row, reset];
12230
+ // Several soundtracks in the file (dubbed / original / commentary): pick one.
12231
+ const at = STATE.video?.audioTracks;
12232
+ if (at && at.length > 1) {
12233
+ kids.push(createEl('div', 'cc-menu-title', t('viewAudio')));
12234
+ for (let i = 0; i < at.length; i++) {
12235
+ const tr = at[i];
12236
+ const btn = createEl('button', tr.enabled ? 'sel' : '', '🔊 ' + (tr.label || tr.language || t('viewAudio') + ' ' + (i + 1)), { type: 'button', role: 'menuitemradio' });
12237
+ btn.onclick = (ev) => { ev.stopPropagation(); for (let j = 0; j < at.length; j++) at[j].enabled = j === i; this.toggleViewMenu(true); };
12238
+ kids.push(btn);
12239
+ }
12240
+ }
12241
+ menu.replaceChildren(...kids);
11896
12242
  resetIdleTimer(true);
11897
12243
  },
11898
12244
 
@@ -12023,7 +12369,11 @@
12023
12369
  const rate = +info.rate.toFixed(2);
12024
12370
  e.rateBtn.textContent = `${rate}x`;
12025
12371
  e.rateBtn.classList.toggle('on', Math.abs(rate - 1) > 0.01);
12026
- e.subBtn.classList.toggle('on', TRANSLATOR.state !== 'idle');
12372
+ e.subBtn.classList.toggle('on', TRANSLATOR.state !== 'idle' || SUBS.active());
12373
+ e.viewBtn?.classList.toggle('on', Math.abs(BRIGHTNESS.level - 1) > 0.01);
12374
+ e.pipBtn.classList.toggle('on', !!document.pictureInPictureElement);
12375
+ e.fsBtn.classList.toggle('on', fullscreenActive());
12376
+ [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
12377
  const canStyle = info.kind === 'video' || !!STATE.cinemaIframe;
12028
12378
  e.ambientBtn.classList.toggle('on', CINEMA.ambientEnabled());
12029
12379
  e.ambientBtn.style.display = canStyle ? '' : 'none';
@@ -12199,7 +12549,13 @@
12199
12549
  }
12200
12550
  stopPauseEnforcement();
12201
12551
  }
12202
- if (e.type === 'play' || e.type === 'pause' || e.type === 'seeked') clearTimeout(STATE._scheduledPlay);
12552
+ // The hold before a shared start (countdown) is ours. The tap that started the
12553
+ // countdown is still a "recent gesture" when the hold's pause event arrives, which
12554
+ // used to cancel the start and send a pause to everyone (intermittently, depending
12555
+ // on how late the event came). Only a tap made after the hold began counts.
12556
+ const freshTap = (STATE._lastUserGestureTs || 0) > (video._nxuOwnPauseSince || 0) + 30;
12557
+ if ((e.type === 'pause' || e.type === 'seeked') && Date.now() < (video._nxuOwnPauseUntil || 0) && !freshTap) return;
12558
+ if ((e.type === 'play' || e.type === 'pause' || e.type === 'seeked') && gesture && (freshTap || !STATE._scheduledPlay)) { clearTimeout(STATE._scheduledPlay); STATE._scheduledPlay = null; }
12203
12559
  const isPause = e.type === 'pause';
12204
12560
  if (isPause && document.hidden) return;
12205
12561
  // A click or key that slipped through the NexusSync UI to the site's player.
@@ -12675,9 +13031,12 @@
12675
13031
  // Events this command causes are tagged so they are not sent back as decisions.
12676
13032
  // A heartbeat usually changes nothing, so it only tags when it actually seeks or
12677
13033
  // 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; };
13034
+ const mark = (kinds, ms = 700) => { video._nxuRemoteEventId = data.eventId || null; video._nxuRemoteUntil = Date.now() + ms; video._nxuRemoteKinds = kinds; };
13035
+ // A shared start is waiting (countdown): heartbeats meanwhile must not cancel it.
13036
+ if (heartbeat && video._nxuStartTimer && Date.now() < (video._nxuStartAt || 0) + 500) return;
12679
13037
  if (!heartbeat) mark(data.cmd === 'play' ? 'play seeked ratechange' : data.cmd === 'rate' ? 'ratechange' : 'pause seeked ratechange');
12680
13038
  clearTimeout(video._nxuStartTimer);
13039
+ video._nxuStartTimer = null;
12681
13040
  if (data.cmd === 'rate') {
12682
13041
  RATE.apply(video, rate);
12683
13042
  return;
@@ -12690,15 +13049,22 @@
12690
13049
  const changes = !heartbeat || video.paused || Math.abs(hbDrift) > CONFIG.hardSyncTolerance;
12691
13050
  if (changes) STATE._remoteApplying = true;
12692
13051
  if (data.startIn > 40) {
12693
- // Synchronized start shared with the other devices.
13052
+ // Synchronized start shared with the other devices. The hold's own pause
13053
+ // and seek are tagged as caused by the room for the whole wait (they used
13054
+ // to go back up as someone pausing, which stopped the countdown).
13055
+ const waitMs = Math.min(data.startIn, 10000);
13056
+ mark('pause play seeked ratechange', waitMs + 1500);
12694
13057
  if (!video.paused) { try { video.pause(); } catch (_) { } }
12695
13058
  if (Number.isFinite(data.time) && Math.abs(video.currentTime - data.time) > 0.25) MEDIA_SAFE.seek(video, data.time);
12696
13059
  RATE.apply(video, rate);
13060
+ video._nxuStartAt = Date.now() + waitMs;
12697
13061
  video._nxuStartTimer = setTimeout(() => {
13062
+ video._nxuStartTimer = null;
12698
13063
  STATE._remoteApplying = true;
12699
13064
  MEDIA_SAFE.play(video);
12700
13065
  setTimeout(() => { STATE._remoteApplying = false; }, 150);
12701
- }, Math.min(data.startIn, 3000));
13066
+ setTimeout(() => { if (video.paused) MEDIA_SAFE.play(video); }, 900);
13067
+ }, waitMs);
12702
13068
  setTimeout(() => { STATE._remoteApplying = false; }, 150);
12703
13069
  return;
12704
13070
  }
@@ -12908,8 +13274,8 @@
12908
13274
  if (uiElements.btnRate) uiElements.btnRate.style.display = hasMedia ? '' : 'none';
12909
13275
  updateRateButton();
12910
13276
  if (uiElements.btnCinema) uiElements.btnCinema.style.display = hasMedia || STATE.isCinema ? '' : 'none';
12911
- 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
13277
+ if (uiElements.btnAutoCinema) AUTO_CINEMA.paintButton();
13278
+ if (uiElements.btnBookmark) uiElements.btnBookmark.style.display = 'none';
12913
13279
  if (uiElements.btnFindMedia) uiElements.btnFindMedia.style.display = hasMedia ? 'none' : '';
12914
13280
  if (uiElements.btnLink) uiElements.btnLink.style.display = hasMedia || connected ? '' : 'none';
12915
13281
  updateDockMenuState();
@@ -12922,6 +13288,7 @@
12922
13288
  const showSubLog = connected || TRANSLATOR.active || hasHistory;
12923
13289
  ['btnSyncStatus', 'btnDraw', 'btnChat', 'btnInvite', 'btnTune'].forEach(key => { if (uiElements[key]) uiElements[key].style.display = show; });
12924
13290
  if (uiElements.btnSubLog) uiElements.btnSubLog.style.display = showSubLog ? '' : 'none';
13291
+ if (uiElements.btnChatLog) uiElements.btnChatLog.style.display = connected || uiElements.chatMessages?.childElementCount ? '' : 'none';
12925
13292
  if (!connected) {
12926
13293
  if (STATE.chatActive) {
12927
13294
  STATE.chatActive = false;
@@ -12961,6 +13328,11 @@
12961
13328
  if (STATE.handshakeVerified) {
12962
13329
  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
13330
  sendFirebaseCmd('heartbeat', { ts: Date.now() }, 'nexus_rooms');
13331
+ // What this device sent while falling asleep may have been lost: resend everything,
13332
+ // and fetch what the others did meanwhile.
13333
+ HEAL._pushAt = 0; HEAL._askAt = 0;
13334
+ HEAL.pushFull('woke up');
13335
+ HEAL.ask('woke up');
12964
13336
  syncServerClock();
12965
13337
  if (RTC.isHost && STATE.connectionMode === 'HTTP_RELAY') RTC.init();
12966
13338
  }