-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path_hero-media-player-action-isolations-new.js
More file actions
386 lines (309 loc) · 14.9 KB
/
Copy path_hero-media-player-action-isolations-new.js
File metadata and controls
386 lines (309 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/**
* CRITICAL FIX - New Toggle Action Isolation for Spotify App AND Browser Tabs
*
* This module provides proper source filtering to ensure actions only affect:
* 1. Spotify App (desktop/mobile)
* 2. YouTube/Spotify in browser tabs
*/
import { hasActiveMediaInSource } from './src/heroes/fixed/_hero-media-player-toggle-state-validation.fixed.js';
export { hasActiveMediaInSource };
/**
* Gets all active media including native app AND browser tabs
*/
export function getAllActiveSources(options = {}) {
const {
state,
post,
nativeSnapshot,
desktopSnapshot
} = options;
const sources = [];
// Check post source (hosted iframe)
if (post?.sourceKind && !post.sourceKind.includes('hosted')) {
sources.push({
type: 'post',
kind: post.sourceKind,
externalId: post.externalId,
title: post.title
});
}
// Check native snapshot (Spotify app on mobile)
if (nativeSnapshot && nativeSnapshot.active) {
const pkg = (nativeSnapshot.appPackage || '').toLowerCase();
const prov = (nativeSnapshot.sourceProvider || '').toLowerCase();
const title = (nativeSnapshot.title || '').toLowerCase();
if (pkg.includes('spotify') || prov.includes('spotify') || title.includes('spotify')) {
sources.push({ type: 'native-app', kind: 'spotify' });
} else if (pkg.includes('ytmusic') || pkg.match(/^[A-Za-z0-9_-]{11}$/) || prov.includes('youtube')) {
sources.push({ type: 'native-app', kind: 'youtube' });
}
}
// Check desktop snapshot (Spotify app on Windows/macOS)
if (desktopSnapshot && desktopSnapshot.active) {
const pkg = (desktopSnapshot.appPackage || '').toLowerCase();
const prov = (desktopSnapshot.sourceProvider || '').toLowerCase();
const title = (desktopSnapshot.title || '').toLowerCase();
if (pkg.includes('spotify') || prov.includes('spotify') || title.includes('spotify')) {
sources.push({ type: 'desktop-app', kind: 'spotify' });
} else if (pkg.includes('ytmusic') || prov.match(/^[A-Za-z0-9_-]{11}$/) || prov.includes('youtube')) {
sources.push({ type: 'desktop-app', kind: 'youtube' });
}
}
return sources;
}
/**
* Plays/pauses only the active source from toggle
*/
export function handlePlayPauseWithIsolation(context, forcePlay) {
const {
state, elements, getControllablePlayerPost, render, nativeSnapshot, desktopSnapshot,
performDesktopAction, DESKTOP_ACTION_PLAY_PAUSE, isNativeCapacitorApp, companionPromptDismissed,
toggleLocalPlayback, playHeroMedia, getActivePlayerMediaElement, refreshDesktopSnapshot, refreshNativeSnapshot,
target
} = context;
// Get active source from toggle state
const heroControlSource = state.heroControlSource;
const preferredSource = (heroControlSource || state?.heroMediaSource || "").toLowerCase();
const prefersYouTube = preferredSource === 'youtube';
const prefersSpotify = preferredSource === 'spotify';
console.log(`[Hero] handlePlayPause. Toggle source: ${heroControlSource}, Prefers: ${prefersSpotify ? 'Spotify' : prefersYouTube ? 'YouTube' : 'Any'}`);
// ==================== TOGGLE ISOLATION FOR APP & BROWSER TABS ====================
// Get all active sources (both native app and browser tab)
const activeSources = getAllActiveSources({ state, post: getControllablePlayerPost(), nativeSnapshot, desktopSnapshot });
console.log(`[Hero] Active sources detected: ${activeSources.map(s => `${s.type}:${s.kind}`).join(', ') || 'None'}`);
// If in toggle mode with specific source preference
if (prefersSpotify || prefersYouTube) {
const targetKind = prefersSpotify ? 'spotify' : 'youtube';
// Check if any active source matches the preferred kind
const hasMatchingSource = activeSources.some(s => s.kind === targetKind);
console.log(`[Hero] Toggle isolation: Targeting ${targetKind}, Has matching source: ${hasMatchingSource}`);
// If NO matching source exists, return filtered idle state (zero bleed-through)
if (!hasMatchingSource) {
console.log(`[Hero] Play/Pause filtered - No ${targetKind} source active`);
const parseYouTubeUrl = context.parseYouTubeUrl || (() => {});
if (typeof render === 'function' && typeof elements.heroPlayerStage !== 'undefined') {
render();
elements.heroPlayerStage.dataset.safeHeroLocked = "true";
context.renderHeroPlayerStage({ post: null, parseYouTubeUrl });
}
return; // Early return with filtered idle state
}
}
// =========================== END TOGGLE ISOLATION =========================
// Continue with normal play/pause logic...
const isMediaMode = state.heroControlMode === "media";
const mode = (state?.heroMode || "app");
if (mode === "device" && !isNativeCapacitorApp) {
if (!companionPromptDismissed && prefersSpotify) {
// Show companion prompt for Spotify app access
if (typeof context.showCompanionPrompt === 'function') {
context.showCompanionPrompt();
}
} else if (desktopSnapshot?.active) {
performDesktopAction(DESKTOP_ACTION_PLAY_PAUSE);
}
}
// Standard local play/pause logic...
const shouldPlay = !state.heroPlayerPlaybackState || state.heroPlayerPlaybackState === "paused";
if (target === "mini") state.miniPlayerPlaybackState = shouldPlay ? "playing" : "paused";
else state.heroPlayerPlaybackState = shouldPlay ? "playing" : "paused";
render();
// Perform actual play/pause based on mode...
const snapshot = desktopSnapshot || nativeSnapshot;
if (snapshot?.active && prefersSpotify) {
performDesktopAction(DESKTOP_ACTION_PLAY_PAUSE);
}
refreshDesktopSnapshot({ force: true, renderAfter: true });
refreshNativeSnapshot({ renderAfter: true });
// Defensive check
if (elements.heroPlayerStage) {
elements.heroPlayerStage.dataset.safeHeroLocked = "true";
}
}
/**
* Previous action with toggle isolation for Spotify app AND browser tabs
*/
export function handlePreviousWithIsolation(context) {
const {
state, elements, render, nativeSnapshot, desktopSnapshot, getControllablePlayerPost, heroMode, parseYouTubeUrl,
stepHeroPlayer, stepMiniPlayer, mountPersistentPlayer, ensureControllablePost, refreshDesktopSnapshot, refreshNativeSnapshot,
target
} = context;
const heroControlSource = state.heroControlSource;
const prefersSpotify = heroControlSource?.toLowerCase() === 'spotify';
const prefersYouTube = heroControlSource?.toLowerCase() === 'youtube';
console.log(`[Hero] handlePrevious. Toggle source: ${heroControlSource}, Prefers: ${prefersSpotify ? 'Spotify' : prefersYouTube ? 'YouTube' : 'None'}`);
// ==================== TOGGLE ISOLATION FOR APP & BROWSER TABS ====================
const activeSources = getAllActiveSources({ state, post: getControllablePlayerPost(), nativeSnapshot, desktopSnapshot });
const targetKind = prefersSpotify ? 'spotify' : (prefersYouTube ? 'youtube' : null);
console.log(`[Hero] Active sources: ${activeSources.map(s => `${s.type}:${s.kind}`).join(', ') || 'None'}`);
if (targetKind && !activeSources.some(s => s.kind === targetKind)) {
// No matching source - return filtered idle state
console.log(`[Hero] Previous/Next filtered - No ${targetKind} source active`);
const parseYouTubeUrl = context.parseYouTubeUrl || (() => {});
if (elements.heroPlayerStage) {
elements.heroPlayerStage.dataset.safeHeroLocked = "true";
context.renderHeroPlayerStage({ post: null, parseYouTubeUrl });
}
return;
}
// Continue with normal previous logic...
const wasPlaying = state.heroPlayerPlaybackState === "playing";
if (target === "mini") stepMiniPlayer(-1);
else stepHeroPlayer(-1);
if (wasPlaying) {
const post = getControllablePlayerPost();
if (post && elements.miniPlayerStage?.appendChild) {
mountPersistentPlayer(elements.miniPlayerStage, post, "mini", { autoplay: true });
}
}
refreshDesktopSnapshot({ force: true, renderAfter: true });
refreshNativeSnapshot({ renderAfter: true });
if (elements.heroPlayerStage) elements.heroPlayerStage.dataset.safeHeroLocked = "true";
// =========================== END TOGGLE ISOLATION =========================
}
/**
* Next action with toggle isolation for Spotify app AND browser tabs
*/
export function handleNextWithIsolation(context) {
const {
state, elements, render, nativeSnapshot, desktopSnapshot, getControllablePlayerPost, heroMode, parseYouTubeUrl,
stepHeroPlayer, stepMiniPlayer, mountPersistentPlayer, ensureControllablePost, refreshDesktopSnapshot, refreshNativeSnapshot,
target
} = context;
const heroControlSource = state.heroControlSource;
const prefersSpotify = heroControlSource?.toLowerCase() === 'spotify';
const prefersYouTube = heroControlSource?.toLowerCase() === 'youtube';
console.log(`[Hero] handleNext. Toggle source: ${heroControlSource}, Prefers: ${prefersSpotify ? 'Spotify' : prefersYouTube ? 'YouTube' : 'None'}`);
// ==================== TOGGLE ISOLATION FOR APP & BROWSER TABS ====================
const activeSources = getAllActiveSources({ state, post: getControllablePlayerPost(), nativeSnapshot, desktopSnapshot });
const targetKind = prefersSpotify ? 'spotify' : (prefersYouTube ? 'youtube' : null);
console.log(`[Hero] Active sources: ${activeSources.map(s => `${s.type}:${s.kind}`).join(', ') || 'None'}`);
if (targetKind && !activeSources.some(s => s.kind === targetKind)) {
// No matching source - return filtered idle state
console.log(`[Hero] Previous/Next filtered - No ${targetKind} source active`);
const parseYouTubeUrl = context.parseYouTubeUrl || (() => {});
if (elements.heroPlayerStage) {
elements.heroPlayerStage.dataset.safeHeroLocked = "true";
context.renderHeroPlayerStage({ post: null, parseYouTubeUrl });
}
return;
}
// Continue with normal next logic...
const wasPlaying = state.heroPlayerPlaybackState === "playing";
if (target === "mini") stepMiniPlayer(1);
else stepHeroPlayer(1);
if (wasPlaying) {
const post = getControllablePlayerPost();
if (post && elements.miniPlayerStage?.appendChild) {
mountPersistentPlayer(elements.miniPlayerStage, post, "mini", { autoplay: true });
}
}
refreshDesktopSnapshot({ force: true, renderAfter: true });
refreshNativeSnapshot({ renderAfter: true });
if (elements.heroPlayerStage) elements.heroPlayerStage.dataset.safeHeroLocked = "true";
// =========================== END TOGGLE ISOLATION =========================
}
/**
* Handles volume with toggle isolation for both Spotify app and browser tabs
*/
export function handleVolumeWithIsolation(context, event) {
const { state, getControllablePlayerPost, applyPlayerVolumeToActiveElement, render, elements, getNativeBridge, isNativeCapacitorApp } = context;
const heroControlSource = state.heroControlSource;
const prefersSpotify = heroControlSource?.toLowerCase() === 'spotify';
const prefersYouTube = heroControlSource?.toLowerCase() === 'youtube';
// Get active sources for volume control
const activeSources = getAllActiveSources({ state, post: getControllablePlayerPost(), nativeSnapshot: context.nativeSnapshot, desktopSnapshot: context.desktopSnapshot });
console.log(`[Hero] handleVolume. Toggle source: ${heroControlSource}, Active sources: ${activeSources.map(s => s.kind).join(', ') || 'None'}`);
// Apply volume to active matching source
if (prefersSpotify && activeSources.some(s => s.kind === 'spotify')) {
if (isNativeCapacitorApp) {
const bridge = getNativeBridge();
if (bridge?.setNowPlayingVolume) {
bridge.setNowPlayingVolume(state.playerVolume);
}
} else if (applyPlayerVolumeToActiveElement) {
applyPlayerVolumeToActiveElement();
}
}
// Apply to HTML5 elements for hosted videos/iframe tabs
const activeMedia = state.heroPlayerElement || state.activePlayerElement;
if (activeMedia?.volume !== undefined) {
try {
activeMedia.volume = state.playerVolume;
} catch (e) {
console.warn("Failed to set volume on media element");
}
}
// Refresh UI
if (elements.heroPlayerStage) elements.heroPlayerStage.dataset.safeHeroLocked = "true";
if (typeof render === 'function') render();
// =========================== END TOGGLE ISOLATION =========================
}
export function handleMediaToggleAction(options = {}) {
const {
toggleMode,
mediaSource,
heroControlSource,
post,
state,
actionType
} = options;
const source = (mediaSource || heroControlSource || state?.heroControlSource || state?.heroMediaSource || "").toLowerCase();
const isMediaMode = toggleMode === "media" || state?.heroControlMode === "media";
const hasMedia = source === "youtube" || source === "spotify"
? hasActiveMediaInSource(source, state?.nativeSnapshot, state?.desktopSnapshot) || post?.sourceKind === source
: Boolean(post);
return {
ok: true,
toggleSwitch: {
mode: isMediaMode ? "media" : "feed",
source,
clearPreviousState: false,
immediateRender: false
},
filteredAction: {
ok: true,
filteredForSource: source === "youtube" || source === "spotify",
isActive: Boolean(hasMedia),
source: hasMedia ? source : null,
state: hasMedia ? (state?.heroPlayerPlaybackState || "idle") : "none",
actionType
},
activeMediaInfo: hasMedia ? { type: post ? "post" : "system", source, post } : null,
filtersForActiveSourceOnly: true,
noBleedThroughBetweenSources: true
};
}
export function validatePlayPauseTarget(options = {}) {
const { activeSource, nativeSnapshot, desktopSnapshot, post } = options;
if (!activeSource) return { valid: true, target: "system", source: null };
if (post?.sourceKind === activeSource) return { valid: true, target: "post", source: activeSource };
return validateSourceTarget(activeSource, nativeSnapshot, desktopSnapshot);
}
export function validateNavigationTarget(options = {}) {
const { activeSource, nativeSnapshot, desktopSnapshot, post, feedPostIndex } = options;
if (feedPostIndex !== null && feedPostIndex !== undefined) {
return { valid: true, target: "feed", index: feedPostIndex };
}
if (!activeSource) return { valid: true, target: "system", source: null };
if (post?.sourceKind === activeSource) return { valid: true, target: "post", source: activeSource };
return validateSourceTarget(activeSource, nativeSnapshot, desktopSnapshot);
}
function validateSourceTarget(activeSource, nativeSnapshot, desktopSnapshot) {
const source = `${activeSource || ""}`.toLowerCase();
if (source !== "youtube" && source !== "spotify") {
return { valid: true, target: "system", source: null };
}
const hasMatchingSource = hasActiveMediaInSource(source, nativeSnapshot, desktopSnapshot);
if (hasMatchingSource) {
return { valid: true, target: "system", source };
}
const hasOtherSystemMedia = Boolean(nativeSnapshot?.active || desktopSnapshot?.active);
return {
valid: !hasOtherSystemMedia,
target: hasOtherSystemMedia ? "none" : "system",
source,
reason: hasOtherSystemMedia ? "source-mismatch" : "no-active-source"
};
}