-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdeeplink.js
More file actions
433 lines (414 loc) · 18.2 KB
/
Copy pathdeeplink.js
File metadata and controls
433 lines (414 loc) · 18.2 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
/* deeplink.js — shared deep-link helper for the swagger-*-model/index.html viewers.
*
* Hash format: #spec=<module-name>&op=<operationId>
* - spec=<module-name> → which OpenAPI spec to load (existing behavior)
* - op=<operationId> → optional; expand & scroll to that operation row
*
* Public API (window.__DeepLink):
* parseHash() → { spec?, op?, ver? }
* setSpec(name) → updates hash to #spec=<name> (drops op)
* setSpecOp(name, op) → updates hash to #spec=<name>&op=<op>
* tryExpandOp(opId) → expands a Swagger UI operation row by id (idempotent)
*
* Behavior added at load:
* - MutationObserver on #swagger-ui auto-expands an `op=` target when Swagger
* UI finishes rendering.
* - Click delegate on `.opblock-summary` updates the hash to include the
* clicked op's operationId so users can copy a deep link.
*
* NOTE: viewer scripts must call __DeepLink.setSpec() instead of writing
* window.location.hash directly so the op= param is preserved when present.
*/
(function () {
'use strict';
function parseHash() {
var raw = (window.location.hash || '').replace(/^#/, '');
if (!raw) return {};
var out = {};
var segs = raw.split('&');
for (var i = 0; i < segs.length; i++) {
var seg = segs[i];
var eq = seg.indexOf('=');
if (eq <= 0) continue;
var k = seg.substring(0, eq);
var v = seg.substring(eq + 1);
try { v = decodeURIComponent(v); } catch (_) { /* keep raw */ }
out[k] = v;
}
return out;
}
function buildHash(params) {
var keys = ['ver', 'spec', 'op']; // stable order
var parts = [];
for (var i = 0; i < keys.length; i++) {
var k = keys[i];
var v = params[k];
if (v == null || v === '') continue;
parts.push(k + '=' + encodeURIComponent(v));
}
// any extra params not in the canonical list
for (var k2 in params) {
if (keys.indexOf(k2) !== -1) continue;
if (!Object.prototype.hasOwnProperty.call(params, k2)) continue;
var v2 = params[k2];
if (v2 == null || v2 === '') continue;
parts.push(k2 + '=' + encodeURIComponent(v2));
}
return parts.length ? '#' + parts.join('&') : '';
}
function writeHash(newHash) {
if (window.location.hash === newHash) return;
if (window.history && typeof window.history.replaceState === 'function') {
// replaceState avoids triggering a hashchange event (which would
// re-enter checkHash and reload the spec).
window.history.replaceState(null, '', newHash || window.location.pathname + window.location.search);
} else {
window.location.hash = newHash;
}
}
function setSpec(name) {
if (!name) return;
// Changing spec drops op (operations are spec-scoped).
var cur = parseHash();
var next = { spec: name };
if (cur.ver) next.ver = cur.ver;
writeHash(buildHash(next));
}
function setSpecOp(name, op, skipAutoExpand) {
if (!name) return;
var cur = parseHash();
var next = { spec: name, op: op || undefined };
if (cur.ver) next.ver = cur.ver;
writeHash(buildHash(next));
// writeHash uses history.replaceState, which does NOT fire a
// 'hashchange' event. Without this, a tree-leaf click that loads a
// new spec would never start the observer that scrolls/expands the
// target op. Kick it explicitly so the op pops into view as soon as
// Swagger UI finishes rendering it.
//
// skipAutoExpand is set when the hash update originates from the user
// physically clicking an .opblock-summary: Swagger UI's own handler
// will toggle that operation, so kicking tryExpandOp here too would
// fire a SECOND, competing toggle on the same click (expand, then the
// native handler collapses it) — the "needs a second click" bug.
if (op && !skipAutoExpand) {
try { attachAutoExpand(); } catch (_) { /* DOM not ready */ }
}
}
/** Find the Swagger UI .opblock element for the given operationId. */
function findOpElement(opId) {
if (!opId) return null;
var ui = document.getElementById('swagger-ui');
if (!ui) return null;
// Preferred: search the operationId span text directly when present.
var spans = ui.querySelectorAll('.opblock .opblock-summary-operation-id');
for (var i = 0; i < spans.length; i++) {
if ((spans[i].textContent || '').trim() === opId) {
return spans[i].closest('.opblock');
}
}
// Tag-prefix path: id format is "operations-<tag>-<operationId>", and
// for our generators tag === spec name from the hash.
var cur = parseHash();
var nodes = ui.querySelectorAll('div.opblock[id^="operations-"]');
if (cur.spec) {
var wantTail = cur.spec + '-' + opId;
for (var j = 0; j < nodes.length; j++) {
var rest = nodes[j].id.substring('operations-'.length);
if (rest === wantTail) return nodes[j];
}
}
// Fallback: id-suffix heuristic.
for (var k = 0; k < nodes.length; k++) {
var n = nodes[k];
var r2 = n.id.substring('operations-'.length);
if (r2 === opId || (r2.length > opId.length + 1
&& r2.substring(r2.length - opId.length - 1) === ('-' + opId))) {
return n;
}
}
return null;
}
function tryExpandOp(opId) {
var el = findOpElement(opId);
if (!el) return false;
// Swagger UI v5 wires the expand toggle onto the inner <button>
// .opblock-summary-control. Clicking the outer .opblock-summary
// <div> does NOT fire the handler. Prefer the control, fall back
// to the summary if the control isn't there (older themes).
var control = el.querySelector('.opblock-summary-control')
|| el.querySelector('.opblock-summary');
var alreadyOpen = el.classList.contains('is-open');
if (control && !alreadyOpen && el.getAttribute('data-deeplink-expanded') !== '1') {
el.setAttribute('data-deeplink-expanded', '1');
try { control.click(); } catch (_) { /* ignore */ }
}
try { el.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch (_) { /* old browser */ }
return true;
}
function extractOpIdFromBlock(opblock) {
if (!opblock) return null;
// Preferred: Swagger UI v5 sometimes renders the operationId inside a
// span with class .opblock-summary-operation-id — its textContent is
// the verbatim operationId.
var idSpan = opblock.querySelector('.opblock-summary-operation-id');
if (idSpan && idSpan.textContent) {
var v = idSpan.textContent.trim();
if (v) return v;
}
if (!opblock.id) return null;
var rest = opblock.id.indexOf('operations-') === 0
? opblock.id.substring('operations-'.length)
: opblock.id;
// Our generators always emit OpenAPI `tags: [<module-name>]` matching
// the loaded spec name. So if a current spec is set, strip it as the
// tag prefix to recover the operationId verbatim (operationIds may
// contain hyphens, colons, slashes, etc.).
var cur = parseHash();
if (cur.spec && rest.indexOf(cur.spec + '-') === 0) {
return rest.substring(cur.spec.length + 1);
}
// Fallback: last-hyphen heuristic.
var idx = rest.lastIndexOf('-');
if (idx === -1) return rest;
return rest.substring(idx + 1);
}
function attachAutoExpand() {
var ui = document.getElementById('swagger-ui');
if (!ui) return;
var pending = parseHash().op;
if (!pending) return;
// Try right away in case Swagger UI already rendered.
if (tryExpandOp(pending)) return;
// Otherwise observe DOM mutations until the row appears.
var attempts = 0;
var observer = new MutationObserver(function () {
attempts++;
if (tryExpandOp(pending)) {
observer.disconnect();
} else if (attempts > 2000) {
observer.disconnect();
}
});
observer.observe(ui, { childList: true, subtree: true });
}
function attachClickCapture() {
// Capture-phase listeners fire before any inline onclick handlers and
// before the browser's default <a href="#"> navigation.
document.addEventListener('click', function (e) {
var target = e.target;
if (!target || !target.closest) return;
// (1) Sidebar module links use href="#" with onclick that should
// return false. In some environments (programmatic click, certain
// event timings) the default action still fires and pushes "#"
// into history, wiping our hash. Suppress that default here.
var sidebar = target.closest('#moduleList a, .module-list a');
if (sidebar && (sidebar.getAttribute('href') === '#' ||
sidebar.getAttribute('href') === '')) {
e.preventDefault();
// do NOT stopPropagation — onclick="loadSpec(...)" still runs
}
// (2) Update hash when user clicks an opblock summary so the URL
// bar always reflects the currently-open operation.
var summary = target.closest('.opblock-summary');
if (!summary) return;
var opblock = summary.closest('.opblock');
var opId = extractOpIdFromBlock(opblock);
if (!opId) return;
var cur = parseHash();
if (!cur.spec) return;
// setSpecOp uses replaceState — does not trigger another reload.
// Pass skipAutoExpand=true: this is a physical click on the
// opblock, so Swagger UI will toggle it natively; kicking our own
// tryExpandOp here would double-toggle and leave it collapsed
// (the "needs a second click to expand" defect).
setSpecOp(cur.spec, opId, true);
}, true); // capture phase so we run before Swagger UI's own handlers
}
// Re-run auto-expand whenever the hash changes (e.g. user pastes a new
// deep link). Spec changes are still handled by the viewer's checkHash().
window.addEventListener('hashchange', function () {
attachAutoExpand();
});
// Defensive guard: if Swagger UI (or anything else) tries to push/replace
// a hash that drops our spec= param, merge it back in.
(function guardHistory() {
function preserveSpec(url) {
// url may be null/undefined (means "current URL") — leave alone.
if (url == null) return url;
try {
var u = new URL(url, window.location.href);
var cur = parseHash();
if (!cur.spec) return url;
// parse incoming hash
var newRaw = (u.hash || '').replace(/^#/, '');
var hasSpec = /(^|&)spec=/.test(newRaw);
if (hasSpec) return url;
// Re-attach our spec (and op if present) so it isn't lost.
var keep = { spec: cur.spec };
if (cur.op) keep.op = cur.op;
if (cur.ver) keep.ver = cur.ver;
// If the incoming hash is empty or just "#", just use ours.
if (!newRaw) {
u.hash = buildHash(keep);
return u.pathname + u.search + u.hash;
}
// Otherwise prepend our params.
u.hash = buildHash(keep) + '&' + newRaw;
return u.pathname + u.search + u.hash;
} catch (_) {
return url;
}
}
var origPush = history.pushState;
var origRepl = history.replaceState;
history.pushState = function (s, t, u) {
return origPush.call(this, s, t, preserveSpec(u));
};
history.replaceState = function (s, t, u) {
return origRepl.call(this, s, t, preserveSpec(u));
};
})();
// ----------------------------------------------------------------
// Scroll memory
// ----------------------------------------------------------------
// The viewer is effectively an SPA — switching spec via the sidebar
// keeps the page mounted and only repaints #swagger-ui. The browser's
// native scroll restoration does not fire for hash-only navigations,
// so the back/forward buttons return the user to the right spec but
// always at the top of the page.
//
// We persist scrollY per-hash in sessionStorage (per-tab, survives
// back/forward, drops on tab close). On hashchange we wait for the
// spec content to actually render (via a MutationObserver on the
// Swagger UI container), then restore scrollY — but only when the
// hash does NOT carry an op= target, since op-targeted scrolls take
// precedence and would fight with us.
var SCROLL_KEY_PREFIX = 'iosxe-scroll:';
var scrollSaveTimer = null;
function _scrollKey() {
return SCROLL_KEY_PREFIX + (window.location.hash || '');
}
function _saveScroll() {
try { sessionStorage.setItem(_scrollKey(), String(window.scrollY)); } catch (_) {}
}
function _debouncedSaveScroll() {
if (scrollSaveTimer) clearTimeout(scrollSaveTimer);
scrollSaveTimer = setTimeout(_saveScroll, 200);
}
function _readSavedScroll() {
try {
var v = sessionStorage.getItem(_scrollKey());
if (v == null) return null;
var y = parseInt(v, 10);
return isNaN(y) ? null : y;
} catch (_) { return null; }
}
function _restoreScrollWhenReady() {
var p = parseHash();
if (p.op) return; // op= owns the scroll target
var y = _readSavedScroll();
if (!y) return;
var ui = document.getElementById('swagger-ui');
if (!ui) {
// Try once after the next tick in case the page hasn't wired
// up #swagger-ui yet.
setTimeout(_restoreScrollWhenReady, 100);
return;
}
var attempts = 0;
function attempt() {
attempts++;
// Only scroll once the document is tall enough — otherwise we
// clamp to the bottom and lose position when content arrives.
var maxY = (document.documentElement.scrollHeight || 0) - window.innerHeight;
if (maxY >= y - 4) {
try { window.scrollTo(0, y); } catch (_) { /* ignore */ }
return;
}
if (attempts > 60) return; // ~6s budget
setTimeout(attempt, 100);
}
attempt();
}
function attachScrollMemory() {
// Save on user scroll (debounced so we don't thrash sessionStorage).
window.addEventListener('scroll', _debouncedSaveScroll, { passive: true });
// Save before unload to capture the final position.
window.addEventListener('beforeunload', _saveScroll);
// Restore after a hashchange (spec switch via sidebar / back-forward).
window.addEventListener('hashchange', function () {
// Wait a tick so the viewer's own checkHash() can kick off the
// spec load — then poll until the new content is tall enough.
setTimeout(_restoreScrollWhenReady, 50);
});
// Initial restore on first paint.
setTimeout(_restoreScrollWhenReady, 200);
}
// Initial wiring after DOM ready.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', function () {
attachClickCapture();
attachAutoExpand();
attachScrollMemory();
});
} else {
attachClickCapture();
attachAutoExpand();
attachScrollMemory();
}
/**
* Copy the current viewer URL (including #spec=...&op=...&ver=...) to
* the clipboard. The URL is always in sync with what the user is looking
* at because (a) the sidebar updates the spec hash on every click and
* (b) attachClickCapture() above appends the op when an operation row
* is clicked.
*
* Pass the button element to get a brief "Copied!" confirmation. Falls
* back to a hidden <textarea> + execCommand for browsers without the
* async Clipboard API (Safari < 13.1, file:// origins).
*/
function copyShareLink(btn) {
var url = window.location.href;
function flash(label) {
if (!btn) return;
var orig = btn.textContent;
btn.textContent = label;
// 3 s gives the user enough time to see the confirmation
// without re-reading the button caption while their mouse
// is still over it (a 1.5 s flash was easy to miss on the
// viewer pages that had a busy header).
setTimeout(function () { btn.textContent = orig; }, 3000);
}
function fallback() {
try {
var ta = document.createElement('textarea');
ta.value = url;
ta.setAttribute('readonly', '');
ta.style.position = 'absolute';
ta.style.left = '-9999px';
document.body.appendChild(ta);
ta.select();
var ok = document.execCommand('copy');
document.body.removeChild(ta);
flash(ok ? 'Copied!' : 'Copy failed');
} catch (_) { flash('Copy failed'); }
}
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url).then(
function () { flash('Copied!'); },
function () { fallback(); }
);
} else {
fallback();
}
}
window.__DeepLink = {
parseHash: parseHash,
buildHash: buildHash,
setSpec: setSpec,
setSpecOp: setSpecOp,
tryExpandOp: tryExpandOp,
copyShareLink: copyShareLink
};
})();