From 1b005ec0b4fb45b0b96cbb3270627de569f51b0e Mon Sep 17 00:00:00 2001 From: Jason Johnston Date: Sat, 23 May 2020 21:23:51 -0600 Subject: [PATCH] fix(troika-3d-text): #46 fix error on script load when `document` not 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. --- packages/troika-3d-text/src/TextBuilder.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/troika-3d-text/src/TextBuilder.js b/packages/troika-3d-text/src/TextBuilder.js index 9cc9643c..340b1439 100644 --- a/packages/troika-3d-text/src/TextBuilder.js +++ b/packages/troika-3d-text/src/TextBuilder.js @@ -14,7 +14,6 @@ const CONFIG = { sdfGlyphSize: 64, textureWidth: 2048 } -const linkEl = document.createElement('a') //for resolving relative URLs to absolute let hasRequested = false /** @@ -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 @@ -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',