Repository navigation
Expand file tree
/
Copy pathlanguage-selector.js
More file actions
540 lines (457 loc) · 16.6 KB
/
Copy pathlanguage-selector.js
File metadata and controls
540 lines (457 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
// Language switcher for Stagehand docs
// Handles: 1) Sidebar language dropdown selection 2) Code block language syncing
//
// v3 ONLY — v4 switches languages with native <Tabs>. Mintlify injects every
// root-level .js on every page, and the version switcher moves between v3 and v4
// client-side, so a single guard at load would be wrong in both directions. Each
// entry point checks isV3Page() instead. No DOM test environment here; verify by
// hand in `mint dev` after changing this.
(function () {
// ============================================
// CONFIGURATION
// ============================================
const DROPDOWN_LANGUAGES = ["TypeScript", "Python", "Java", "Go", "Ruby"];
const LANGUAGE_MAP = {
TypeScript: "Javascript",
Python: "Python",
Java: "Java",
Go: "Go",
Ruby: "Ruby",
};
const CODE_BLOCK_LANGUAGES = ["Javascript", "Python", "Go", "Java", "Ruby", "cURL", "PHP"];
const SDK_PATH_MAP = {
Python: "python",
Java: "java",
Go: "go",
Ruby: "ruby",
};
const NAVIGATION_MAP = {
TypeScript: "/v3/first-steps/introduction",
Python: "/v3/sdk/python",
Java: "/v3/sdk/java",
Go: "/v3/sdk/go",
Ruby: "/v3/sdk/ruby",
};
let currentSelectedLanguage = "TypeScript";
let isSelecting = false;
const isV3Page = () => window.location.pathname.startsWith("/v3");
// Drop everything this script owns: the body classes it sets and any in-flight
// code-block selection. Runs whenever we find ourselves off v3.
function resetState() {
isSelecting = false;
document.body.classList.remove("stagehand-selecting", "stagehand-hide-version-switcher");
}
// ============================================
// UTILITIES
// ============================================
// Run callback on next frame (immediate visual update)
const onNextFrame = (fn) => requestAnimationFrame(() => requestAnimationFrame(fn));
const dropdownStyle = document.createElement("style");
dropdownStyle.id = "stagehand-language-style";
dropdownStyle.textContent = `
/* Hide dropdown during programmatic selection */
.stagehand-selecting [role="menu"],
.stagehand-selecting [role="listbox"] {
opacity: 0 !important;
pointer-events: none !important;
transition: none !important;
}
/* Hide version switcher when non-TypeScript language is selected */
.stagehand-hide-version-switcher .stagehand-version-switcher {
display: none !important;
}
/* Hide SDK reference items that don't match the selected language */
li[id^="/v3/sdk/"].stagehand-sdk-hidden {
display: none !important;
}
`;
document.head.appendChild(dropdownStyle);
// ============================================
// SDK REFERENCE FILTERING
// ============================================
function updateSDKReferenceVisibility() {
// Get the SDK path for the current language
const currentSDKPath = SDK_PATH_MAP[currentSelectedLanguage];
// Find all SDK reference items in the sidebar
const sdkItems = document.querySelectorAll('li[id^="/v3/sdk/"]');
sdkItems.forEach((item) => {
const itemId = item.getAttribute("id") || "";
// Extract the language from the id (e.g., "/v3/sdk/python" -> "python")
const itemLang = itemId.split("/").pop();
if (currentSelectedLanguage === "TypeScript") {
// For TypeScript, hide all SDK references (they don't apply)
item.classList.add("stagehand-sdk-hidden");
} else if (currentSDKPath && itemLang === currentSDKPath) {
// Show the SDK that matches the current language
item.classList.remove("stagehand-sdk-hidden");
} else {
// Hide SDKs that don't match
item.classList.add("stagehand-sdk-hidden");
}
});
}
// ============================================
// VERSION SWITCHER VISIBILITY
// ============================================
function getVersionSwitcher() {
// Find the version switcher button (contains "v3" or "v2" and has chevron-down)
const buttons = document.querySelectorAll("button");
for (const btn of buttons) {
const text = (btn.textContent || "").trim().toLowerCase();
// Check if it's a version button (v2, v3, etc.) with chevron icon
if (/^v\d+$/.test(text) && btn.querySelector(".lucide-chevron-down")) {
return btn;
}
}
return null;
}
function updateVersionSwitcherVisibility() {
const versionSwitcher = getVersionSwitcher();
if (versionSwitcher) {
// Mark the version switcher so we can target it with CSS
versionSwitcher.classList.add("stagehand-version-switcher");
// Show version switcher only for TypeScript
if (currentSelectedLanguage === "TypeScript") {
document.body.classList.remove("stagehand-hide-version-switcher");
} else {
document.body.classList.add("stagehand-hide-version-switcher");
}
}
}
// ============================================
// SIDEBAR DROPDOWN FUNCTIONS
// ============================================
function getDropdownButton() {
const buttons = document.querySelectorAll("button");
for (const btn of buttons) {
const text = (btn.textContent || "").trim();
if (DROPDOWN_LANGUAGES.includes(text)) {
return btn;
}
}
return null;
}
function getDropdownMenu() {
return document.querySelector('menu[role="menu"], [role="menu"]');
}
function updateButtonText(newText) {
const button = getDropdownButton();
if (!button) return;
const paragraph = button.querySelector("p");
if (paragraph) {
paragraph.textContent = newText;
}
}
function updateDropdownCheckIndicator() {
const menu = getDropdownMenu();
if (!menu) return;
const menuItems = menu.querySelectorAll('a, [role="menuitem"]');
const checkIconsMap = new Map();
let anyCheckIcon = null;
for (const item of menuItems) {
const text = (item.textContent || "").trim();
const checkIcon = item.querySelector(
'.lucide-check, [class*="lucide-check"], svg[class*="check"]',
);
for (const lang of DROPDOWN_LANGUAGES) {
if (text.includes(lang)) {
checkIconsMap.set(lang, { item, checkIcon });
if (checkIcon) {
anyCheckIcon = checkIcon;
}
break;
}
}
}
for (const [lang, { item, checkIcon }] of checkIconsMap) {
const shouldBeSelected = lang === currentSelectedLanguage;
if (checkIcon) {
checkIcon.style.opacity = shouldBeSelected ? "1" : "0";
checkIcon.style.visibility = shouldBeSelected ? "visible" : "hidden";
} else if (shouldBeSelected && anyCheckIcon) {
const clonedCheck = anyCheckIcon.cloneNode(true);
clonedCheck.style.opacity = "1";
clonedCheck.style.visibility = "visible";
const targetSpan = item.querySelector("span:last-child") || item;
if (targetSpan.querySelector('.lucide-check, [class*="lucide-check"]') === null) {
targetSpan.appendChild(clonedCheck);
}
}
}
}
// ============================================
// CODE BLOCK LANGUAGE SELECTOR FUNCTIONS
// ============================================
function simulateClick(element) {
if (!element) return;
const rect = element.getBoundingClientRect();
const x = rect.left + rect.width / 2;
const y = rect.top + rect.height / 2;
["pointerdown", "mousedown", "pointerup", "mouseup", "click"].forEach((eventType) => {
const EventClass = eventType.startsWith("pointer") ? PointerEvent : MouseEvent;
element.dispatchEvent(
new EventClass(eventType, {
view: window,
bubbles: true,
cancelable: true,
clientX: x,
clientY: y,
button: 0,
buttons: 1,
isPrimary: true,
pointerType: "mouse",
}),
);
});
}
function getCodeBlockLanguageDropdown() {
const paragraphs = document.querySelectorAll("p");
for (const p of paragraphs) {
const text = (p.textContent || "").trim();
if (CODE_BLOCK_LANGUAGES.includes(text)) {
const parentDiv = p.closest("div");
if (parentDiv && parentDiv.querySelector(".lucide-chevrons-up-down")) {
return { element: parentDiv, language: text };
}
}
}
return null;
}
function waitForCodeBlockMenuAndSelect(targetLanguage, attempts = 0) {
// A client-side navigation can land on v4 while this frame was already
// scheduled. Bail before touching the DOM so a v3 selection never clicks a
// v4 control.
if (!isV3Page()) {
resetState();
return;
}
if (attempts > 30) {
document.body.classList.remove("stagehand-selecting");
document.body.click();
isSelecting = false;
return;
}
const menuItems = document.querySelectorAll('[role="menuitem"], [role="option"]');
if (menuItems.length === 0) {
requestAnimationFrame(() => waitForCodeBlockMenuAndSelect(targetLanguage, attempts + 1));
return;
}
for (const item of menuItems) {
const text = (item.textContent || "").trim();
if (text === targetLanguage) {
simulateClick(item);
onNextFrame(() => {
document.body.classList.remove("stagehand-selecting");
isSelecting = false;
});
return;
}
}
requestAnimationFrame(() => waitForCodeBlockMenuAndSelect(targetLanguage, attempts + 1));
}
function selectCodeBlockLanguage(targetLanguage) {
// Guarded at the source: this is what sets `stagehand-selecting`, whose CSS
// blanks out every [role="menu"] on the page.
if (!isV3Page()) return;
if (isSelecting) return;
const current = getCodeBlockLanguageDropdown();
if (!current) return;
if (current.language === targetLanguage) return;
isSelecting = true;
document.body.classList.add("stagehand-selecting");
simulateClick(current.element);
requestAnimationFrame(() => waitForCodeBlockMenuAndSelect(targetLanguage));
}
function syncCodeBlockLanguage() {
const codeBlockLang = LANGUAGE_MAP[currentSelectedLanguage];
if (codeBlockLang) {
selectCodeBlockLanguage(codeBlockLang);
}
}
// ============================================
// EVENT HANDLERS & OBSERVERS
// ============================================
function setupDropdownMenuObserver() {
const menuObserver = new MutationObserver(() => {
if (!isV3Page()) return;
const menu = getDropdownMenu();
if (menu) {
updateDropdownCheckIndicator();
onNextFrame(updateDropdownCheckIndicator);
}
});
menuObserver.observe(document.body, {
subtree: true,
childList: true,
});
}
function setupMenuClickHandler() {
document.addEventListener(
"click",
(e) => {
if (!isV3Page()) return;
const target = e.target;
// Check if we clicked on a sidebar dropdown menu item
const menuItem = target.closest('[role="menu"] a, menu a');
if (!menuItem) return;
const text = (menuItem.textContent || "").trim();
// Check if it's one of our language options
for (const lang of DROPDOWN_LANGUAGES) {
if (text.includes(lang)) {
currentSelectedLanguage = lang;
// Update the check indicator immediately
updateDropdownCheckIndicator();
// Update version switcher visibility
updateVersionSwitcherVisibility();
// Update SDK reference visibility
updateSDKReferenceVisibility();
// Store in sessionStorage
try {
sessionStorage.setItem("stagehand-selected-language", lang);
} catch (err) {
// Ignore storage errors
}
// Navigate to the corresponding SDK page
const targetPath = NAVIGATION_MAP[lang];
const normalizedPathname = window.location.pathname.replace(/\/$/, "");
if (targetPath && !normalizedPathname.endsWith(targetPath)) {
e.preventDefault();
e.stopPropagation();
window.location.href = targetPath;
return;
}
// Update button text after menu closes
onNextFrame(() => updateButtonText(lang));
// Sync the code block language selector
onNextFrame(syncCodeBlockLanguage);
break;
}
}
},
true,
);
}
function restoreLanguageSelection() {
if (!isV3Page()) return;
try {
const stored = sessionStorage.getItem("stagehand-selected-language");
if (stored && DROPDOWN_LANGUAGES.includes(stored)) {
currentSelectedLanguage = stored;
updateButtonText(stored);
updateVersionSwitcherVisibility();
updateSDKReferenceVisibility();
onNextFrame(syncCodeBlockLanguage);
}
} catch (err) {
// Ignore storage errors
}
// Always update visibility on restore
onNextFrame(() => {
updateVersionSwitcherVisibility();
updateSDKReferenceVisibility();
});
}
function setupPageChangeObserver() {
let sdkUpdatePending = false;
const observer = new MutationObserver(() => {
if (!isV3Page()) return;
// Check if button needs updating
const button = getDropdownButton();
if (button) {
const currentText = (button.textContent || "").trim();
if (
currentText !== currentSelectedLanguage &&
DROPDOWN_LANGUAGES.includes(currentSelectedLanguage)
) {
updateButtonText(currentSelectedLanguage);
}
}
// Re-check version switcher visibility (DOM might have re-rendered)
const versionSwitcher = getVersionSwitcher();
if (versionSwitcher && !versionSwitcher.classList.contains("stagehand-version-switcher")) {
updateVersionSwitcherVisibility();
}
// Check for SDK reference items that need to be hidden (debounced via rAF)
const sdkItems = document.querySelectorAll(
'li[id^="/v3/sdk/"]:not(.stagehand-sdk-processed)',
);
if (sdkItems.length > 0 && !sdkUpdatePending) {
sdkUpdatePending = true;
onNextFrame(() => {
updateSDKReferenceVisibility();
document.querySelectorAll('li[id^="/v3/sdk/"]').forEach((item) => {
item.classList.add("stagehand-sdk-processed");
});
sdkUpdatePending = false;
});
}
});
observer.observe(document.body, {
subtree: true,
childList: true,
});
}
// Watch for code block dropdowns appearing and sync them
function setupCodeBlockObserver() {
let lastCodeBlockDropdown = null;
const observer = new MutationObserver(() => {
if (!isV3Page()) return;
const dropdown = getCodeBlockLanguageDropdown();
if (dropdown && dropdown.element !== lastCodeBlockDropdown) {
lastCodeBlockDropdown = dropdown.element;
// New code block dropdown appeared, sync it
const targetLang = LANGUAGE_MAP[currentSelectedLanguage];
if (targetLang && dropdown.language !== targetLang) {
onNextFrame(() => selectCodeBlockLanguage(targetLang));
}
}
});
observer.observe(document.body, {
subtree: true,
childList: true,
});
}
// ============================================
// INITIALIZATION
// ============================================
function init() {
// Listeners are always attached because a reader can reach v3 by client-side
// navigation; each one checks isV3Page() before touching the DOM.
setupMenuClickHandler();
setupDropdownMenuObserver();
setupPageChangeObserver();
setupCodeBlockObserver();
applyForCurrentPage();
}
function applyForCurrentPage() {
if (!isV3Page()) {
resetState();
return;
}
restoreLanguageSelection();
updateVersionSwitcherVisibility();
updateSDKReferenceVisibility();
}
// Initialize on page load
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
// Re-run when URL changes (SPA navigation)
let lastUrl = location.href;
const urlObserver = new MutationObserver(() => {
if (location.href !== lastUrl) {
lastUrl = location.href;
// Remove processed class so SDK items get re-evaluated
document.querySelectorAll('li[id^="/v3/sdk/"].stagehand-sdk-processed').forEach((item) => {
item.classList.remove("stagehand-sdk-processed");
});
onNextFrame(() => {
applyForCurrentPage();
syncCodeBlockLanguage();
});
}
});
urlObserver.observe(document.body, { subtree: true, childList: true });
})();