From 8f9ddb5f621019db3e41eef9490f96f0318a85d9 Mon Sep 17 00:00:00 2001 From: Linda Paiste Date: Sun, 25 Jun 2023 14:11:20 -0500 Subject: [PATCH] Support dynamic paths in `loadImage`. --- client/modules/Preview/EmbedFrame.jsx | 8 +++++++ client/utils/previewEntry.js | 32 +++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/client/modules/Preview/EmbedFrame.jsx b/client/modules/Preview/EmbedFrame.jsx index 43f229fa2d..fbd4847082 100644 --- a/client/modules/Preview/EmbedFrame.jsx +++ b/client/modules/Preview/EmbedFrame.jsx @@ -254,6 +254,14 @@ function injectLocalFiles(files, htmlFile, options) { previewScripts.setAttribute('crossorigin', ''); sketchDoc.head.appendChild(previewScripts); + const fileData = sketchDoc.createElement('script'); + fileData.innerHTML = ` + window.files = ${JSON.stringify( + files.filter((file) => file.url || file.fileType === 'folder') + )}; + `; + sketchDoc.head.prepend(fileData); + const sketchDocString = `\n${sketchDoc.documentElement.outerHTML}`; scriptOffs = getAllScriptOffsets(sketchDocString); const consoleErrorsScript = sketchDoc.createElement('script'); diff --git a/client/utils/previewEntry.js b/client/utils/previewEntry.js index 2dfa2a239b..c19226bf26 100644 --- a/client/utils/previewEntry.js +++ b/client/utils/previewEntry.js @@ -1,6 +1,8 @@ import loopProtect from 'loop-protect'; import { Hook, Decode, Encode } from 'console-feed'; import StackTrace from 'stacktrace-js'; +import { resolvePathToFile } from '../../server/utils/filePath'; +import { EXTERNAL_LINK_REGEX } from '../../server/utils/fileUtils'; import evaluateExpression from './evaluateExpression'; // should postMessage user the dispatcher? does the parent window need to @@ -178,3 +180,33 @@ if (_report) { _report.apply(window.p5, [newMessage, method, color]); }; } + +const __patchedMethods = {}; + +function applyPatching(methodName) { + __patchedMethods[methodName] = window.p5.prototype[methodName]; + if (__patchedMethods[methodName]) { + window.p5.prototype[methodName] = function patched(path, ...args) { + let resolvedPath = path; + if (!EXTERNAL_LINK_REGEX.test(path)) { + const file = resolvePathToFile(path, window.files); + if (file && file.url) { + resolvedPath = file.url; + } + } + return __patchedMethods[methodName].apply(this, [resolvedPath, ...args]); + }; + } +} + +[ + 'loadImage', + 'loadModel', + 'loadJSON', + 'loadStrings', + 'loadTable', + 'loadXML', + 'loadBytes', + 'loadFont', + 'loadShader' +].forEach(applyPatching);