Skip to content

Commit

Permalink
fix(troika-3d-text): #46 fix error on script load when document not…
Browse files Browse the repository at this point in the history
… present

This makes the link element creation lazy, and falls back to a no-op when there
is no browser DOM available, e.g. in React server-side rendering, so that just
loading the script does not throw an error.
  • Loading branch information
lojjic committed May 24, 2020
1 parent 8f4d50d commit 1b005ec
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions packages/troika-3d-text/src/TextBuilder.js
Expand Up @@ -14,7 +14,6 @@ const CONFIG = {
sdfGlyphSize: 64,
textureWidth: 2048
}
const linkEl = document.createElement('a') //for resolving relative URLs to absolute
let hasRequested = false

/**
Expand Down Expand Up @@ -109,8 +108,7 @@ function getTextRenderInfo(args, callback) {

// Apply default font here to avoid a 'null' atlas, and convert relative
// URLs to absolute so they can be resolved in the worker
linkEl.href = args.font || CONFIG.defaultFontURL
args.font = linkEl.href
args.font = toAbsoluteURL(args.font || CONFIG.defaultFontURL)

// Normalize text to a string
args.text = '' + args.text
Expand Down Expand Up @@ -220,6 +218,16 @@ function assign(toObj, fromObj) {
return toObj
}

// Utility for making URLs absolute
let linkEl
function toAbsoluteURL(path) {
if (!linkEl) {
linkEl = typeof document === 'undefined' ? {} : document.createElement('a')
}
linkEl.href = path
return linkEl.href
}


const fontProcessorWorkerModule = defineWorkerModule({
name: 'FontProcessor',
Expand Down

0 comments on commit 1b005ec

Please sign in to comment.