Skip to content

Commit

Permalink
add a server render util (#347)
Browse files Browse the repository at this point in the history
* work on server render util

* add formatting

* remove example code
  • Loading branch information
tscanlin committed May 21, 2024
1 parent 0a279fa commit 8015c37
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
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
}

0 comments on commit 8015c37

Please sign in to comment.