Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add a server render util #347

Merged
merged 3 commits into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/js/build-html.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
export default function (options) {
var forEach = [].forEach
var some = [].some
var body = document.body
// if (typeof window === 'undefined') return
var body = typeof window !== 'undefined' && document.body
var tocElement
var currentlyHighlighting = true
var SPACE_CHAR = ' '
Expand Down
1 change: 1 addition & 0 deletions src/js/scroll-smooth/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export default function initSmoothScrolling (options) {

var duration = options.duration
var offset = options.offset
if (typeof window === 'undefined' || typeof location === 'undefined') return

var pageUrl = location.hash
? stripHash(location.href)
Expand Down
29 changes: 29 additions & 0 deletions src/js/server-render.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import * as tocbot from './index-esm.js'
import { JSDOM } from 'jsdom'

export function htmlTemplate (content){
return `
<html>
<body>
<div class="js-toc-content">
${content}
</div>
<div class="js-toc">
</div>
</body>
</html>
`
}

export function serverRender (content) {
const html = htmlTemplate(content)
const { window, location } = new JSDOM(html)
global.window = window
global.document = window.document
global.location = location

// Init and get HTML content.
tocbot.init()
const toc = window.document.body.querySelector('.js-toc')
return toc && toc.innerHTML
}