forked from langchain-ai/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlanguage-toggle.js
More file actions
265 lines (229 loc) · 8.35 KB
/
Copy pathlanguage-toggle.js
File metadata and controls
265 lines (229 loc) · 8.35 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
/**
* Language Toggle Script
*
* Enables smart navigation when switching between Python and TypeScript docs.
* When a reader picks the other language from the dropdown, this redirects them
* to the equivalent page (preserving the section hash) instead of the default
* overview/landing page for that language.
*
* Why this is needed:
* - Both language options in the switcher link to the same, language-agnostic
* landing page (e.g. /build-overview), so the target language cannot be read
* from the destination URL. It is read from the clicked item's label instead.
* - Switching languages can trigger a full page reload, so the intended switch
* is persisted in sessionStorage to survive the navigation.
*
* Mintlify auto-injects every .js file in the repo as custom JS, so this runs on
* every page without needing a <script> tag in docs.json. The dropdown items
* render as `<p class="nav-dropdown-item-title">Python</p>` inside
* `nav-dropdown-item-*` containers.
*/
(function () {
"use strict";
const LANGUAGE_PREFIX_PAIRS = [
{
python: "/oss/python/",
javascript: "/oss/javascript/",
},
{
python: "/langsmith/python/",
javascript: "/langsmith/javascript/",
},
];
// Language-agnostic Build tabs still live under the Python/TypeScript
// dropdowns (so they appear in Build), but must not show the switcher.
const HIDE_LANGUAGE_DROPDOWN_PREFIXES = ["/oss/openwiki"];
// Toggled on <html>; paired with a CSS rule that hides .nav-dropdown-trigger.
const HIDE_LANGUAGE_DROPDOWN_CLASS = "hide-language-dropdown";
// sessionStorage key holding a pending language switch (survives a reload).
const PENDING_KEY = "lc-language-toggle-pending";
// A pending switch older than this (ms) is ignored, so a stored record can
// never trigger a stray redirect on some later, unrelated navigation.
const PENDING_TTL_MS = 8000;
function shouldHideLanguageDropdown(path) {
return HIDE_LANGUAGE_DROPDOWN_PREFIXES.some(
(prefix) => path === prefix || path.startsWith(prefix + "/"),
);
}
function syncLanguageDropdownVisibility() {
document.documentElement.classList.toggle(
HIDE_LANGUAGE_DROPDOWN_CLASS,
shouldHideLanguageDropdown(location.pathname),
);
}
/**
* Detect which language a path belongs to.
* Returns "python", "javascript", or null.
*/
function getPathLanguage(path) {
for (const prefixes of LANGUAGE_PREFIX_PAIRS) {
if (path.startsWith(prefixes.python)) return "python";
if (path.startsWith(prefixes.javascript)) return "javascript";
}
return null;
}
/**
* Convert a path from one language to another.
* e.g., getEquivalentPath("/oss/python/foo", "javascript") → "/oss/javascript/foo"
*/
function getEquivalentPath(sourcePath, targetLang) {
const sourceLang = targetLang === "python" ? "javascript" : "python";
for (const prefixes of LANGUAGE_PREFIX_PAIRS) {
const sourcePrefix = prefixes[sourceLang];
if (sourcePath.startsWith(sourcePrefix)) {
return (
prefixes[targetLang] + sourcePath.substring(sourcePrefix.length)
);
}
}
return null;
}
/**
* Map a dropdown item label to a language, or null if it is not a language
* item. The docs use "Python" and "TypeScript" as the dropdown labels.
*/
function labelToLanguage(text) {
const label = (text || "").trim().toLowerCase();
if (label === "python") return "python";
if (label === "typescript" || label === "javascript") return "javascript";
return null;
}
/**
* Given the clicked element, find the language a dropdown item would switch
* to, tolerating clicks on the item's icon, text container, or title.
*/
function clickTargetLanguage(startEl) {
for (let node = startEl, depth = 0; node && depth < 5; node = node.parentElement, depth++) {
if (!node.classList) continue;
let titleEl = null;
if (node.classList.contains("nav-dropdown-item-title")) {
titleEl = node;
} else if (node.querySelector) {
titleEl = node.querySelector(".nav-dropdown-item-title");
}
if (titleEl) {
return labelToLanguage(titleEl.textContent);
}
}
return null;
}
function readPending() {
try {
return sessionStorage.getItem(PENDING_KEY);
} catch (e) {
// sessionStorage can throw in private-mode Safari; degrade gracefully.
return null;
}
}
function writePending(value) {
try {
sessionStorage.setItem(PENDING_KEY, value);
} catch (e) {
/* ignore */
}
}
function clearPending() {
try {
sessionStorage.removeItem(PENDING_KEY);
} catch (e) {
/* ignore */
}
}
/**
* If a fresh language switch is pending, redirect to the equivalent of the
* page it started from, in the newly selected language. Consumed once.
* Returns true if a redirect was triggered.
*/
function applyPendingSwitch() {
const raw = readPending();
if (!raw) return false;
// Consume once: a switch is acted on at most a single time.
clearPending();
let pending;
try {
pending = JSON.parse(raw);
} catch (e) {
return false;
}
if (
!pending ||
!pending.src ||
!pending.lang ||
typeof pending.ts !== "number" ||
Date.now() - pending.ts > PENDING_TTL_MS
) {
return false;
}
// Split the source into path and hash.
const hashIndex = pending.src.indexOf("#");
const srcPath = hashIndex === -1 ? pending.src : pending.src.slice(0, hashIndex);
const srcHash = hashIndex === -1 ? "" : pending.src.slice(hashIndex);
const srcLang = getPathLanguage(srcPath);
// A shared, language-agnostic source page (e.g. /build-overview) has no
// per-language equivalent to preserve.
if (!srcLang || srcLang === pending.lang) return false;
const equivalent = getEquivalentPath(srcPath, pending.lang);
if (!equivalent || equivalent === location.pathname) return false;
location.replace(equivalent + srcHash);
return true;
}
// Handle a language dropdown click the instant it happens, before Mintlify
// navigates (the destination URL does not encode the target language, and the
// navigation may be a full page reload).
document.addEventListener(
"click",
function (e) {
const targetLang = e.target && clickTargetLanguage(e.target);
if (!targetLang) return;
// Record the intended switch as a fallback: this survives a full page
// reload and is applied on the next load if the fast path below does not
// run (e.g. the source is the shared, language-agnostic landing page).
writePending(
JSON.stringify({
src: location.pathname + location.hash,
lang: targetLang,
ts: Date.now(),
}),
);
// Fast path: if the current page has a resolvable equivalent, go straight
// there and skip the intermediate landing-page load (avoids a visible
// flash). The capture-phase listener runs before Mintlify's own click
// handler, so suppressing propagation prevents its navigation.
const srcLang = getPathLanguage(location.pathname);
if (srcLang && srcLang !== targetLang) {
const equivalent = getEquivalentPath(location.pathname, targetLang);
if (equivalent && equivalent !== location.pathname) {
e.preventDefault();
e.stopImmediatePropagation();
location.assign(equivalent + location.hash);
}
}
},
true,
);
// Watch for URL changes from Mintlify's client-side routing.
let lastPath = location.pathname;
function onPathChange() {
if (location.pathname !== lastPath) {
lastPath = location.pathname;
applyPendingSwitch();
}
syncLanguageDropdownVisibility();
}
window.addEventListener("popstate", onPathChange);
window.addEventListener("hashchange", onPathChange);
// Intercept History API calls used by client-side routing.
const originalPushState = history.pushState;
const originalReplaceState = history.replaceState;
history.pushState = function () {
originalPushState.apply(this, arguments);
onPathChange();
};
history.replaceState = function () {
originalReplaceState.apply(this, arguments);
onPathChange();
};
// Handle the full-page-reload case: apply any pending switch on initial load.
applyPendingSwitch();
syncLanguageDropdownVisibility();
})();