|
64 | 64 | function createHeaderButton() { |
65 | 65 | const a = document.createElement("a"); |
66 | 66 | a.href = "https://godbolt.org/"; |
67 | | - a.className = "md-header__button md-icon online-compile-header-button"; |
| 67 | + a.className = "md-button online-compile-header-button"; |
68 | 68 | a.title = "在线编译(打开 Compiler Explorer)"; |
69 | 69 | a.setAttribute("aria-label", a.title); |
70 | | - a.innerHTML = |
71 | | - '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true">' + |
72 | | - '<path d="M10 17l6-5-6-5v10ZM19 19H5V5h14v14Zm0-16H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2Z"/>' + |
73 | | - "</svg>"; |
| 70 | + a.textContent = "在线编译"; |
74 | 71 |
|
75 | 72 | a.addEventListener("click", (e) => { |
76 | 73 | e.preventDefault(); |
|
81 | 78 | } |
82 | 79 |
|
83 | 80 | function ensureHeaderButton() { |
84 | | - const headerInner = |
85 | | - document.querySelector(".md-header__inner") || |
86 | | - document.querySelector("header.md-header") || |
87 | | - document.body; |
| 81 | + const header = document.querySelector("header.md-header") || document.querySelector(".md-header"); |
| 82 | + if (!(header instanceof HTMLElement)) return; |
88 | 83 |
|
89 | | - if (!(headerInner instanceof HTMLElement)) return; |
90 | | - if (headerInner.querySelector(".online-compile-header-button")) return; |
| 84 | + const search = header.querySelector(".md-search"); |
| 85 | + const target = |
| 86 | + (search && search.parentElement instanceof HTMLElement ? search.parentElement : null) || |
| 87 | + header.querySelector(".md-header__inner") || |
| 88 | + header; |
91 | 89 |
|
92 | | - headerInner.appendChild(createHeaderButton()); |
| 90 | + if (!(target instanceof HTMLElement)) return; |
| 91 | + if (target.querySelector(".online-compile-header-button")) return; |
| 92 | + |
| 93 | + const btn = createHeaderButton(); |
| 94 | + if (search && search instanceof HTMLElement) { |
| 95 | + target.insertBefore(btn, search); |
| 96 | + } else { |
| 97 | + target.appendChild(btn); |
| 98 | + } |
93 | 99 | } |
94 | 100 |
|
95 | 101 | function onReady(fn) { |
|
100 | 106 | } |
101 | 107 | } |
102 | 108 |
|
103 | | - onReady(() => { |
| 109 | + function init() { |
104 | 110 | ensureHeaderButton(); |
| 111 | + } |
105 | 112 |
|
106 | | - const observer = new MutationObserver(() => ensureHeaderButton()); |
107 | | - observer.observe(document.body, { childList: true, subtree: true }); |
| 113 | + onReady(() => { |
| 114 | + const doc$ = window.document$; |
| 115 | + if (doc$ && typeof doc$.subscribe === "function") { |
| 116 | + doc$.subscribe(() => init()); |
| 117 | + } else { |
| 118 | + init(); |
| 119 | + const observer = new MutationObserver(() => init()); |
| 120 | + observer.observe(document.body, { childList: true, subtree: true }); |
| 121 | + } |
108 | 122 | }); |
109 | 123 | })(); |
0 commit comments