refactor: simplify auto header insertion logic (#2578)

This commit is contained in:
Luffy 2025-08-02 15:15:36 +08:00 committed by GitHub
parent c9301b0c9d
commit b468bcd677
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 12 additions and 6 deletions

View File

@ -72,7 +72,9 @@ window.$docsify = {
- Type: `Boolean`
- Default: `false`
If `loadSidebar` and `autoHeader` are both enabled, for each link in `_sidebar.md`, prepend a header to the page before converting it to HTML. See [#78](https://github.com/docsifyjs/docsify/issues/78).
If `loadSidebar` and `autoHeader` are both enabled, for each link in `_sidebar.md`, prepend a header to the page before converting it to HTML — but only if the page does not already contain an H1 heading.
For more details, see [#78](https://github.com/docsifyjs/docsify/issues/78).
```js
window.$docsify = {

View File

@ -342,11 +342,15 @@ export function Render(Base) {
if (autoHeader && activeEl) {
const main = dom.getNode('#main');
const firstNode = main.children[0];
if (firstNode && firstNode.tagName !== 'H1') {
const h1 = this.compiler.header(activeEl.innerText, 1);
const wrapper = dom.create('div', h1);
dom.before(main, wrapper.children[0]);
const hasH1 = main.querySelector('h1');
if (!hasH1) {
const h1HTML = this.compiler.header(activeEl.innerText, 1);
const h1Node = dom.create('div', h1HTML).firstElementChild;
if (h1Node) {
dom.before(main, h1Node);
}
}
}
}