Skip to content

Commit b6cb6e7

Browse files
authored
Merge pull request #2259 from lindapaiste/feature/dynamic-paths
Fix #212: Support dynamic paths in `loadImage`
2 parents 3799b6b + 28ff489 commit b6cb6e7

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

client/modules/Preview/EmbedFrame.jsx

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,14 @@ function injectLocalFiles(files, htmlFile, options) {
254254
previewScripts.setAttribute('crossorigin', '');
255255
sketchDoc.head.appendChild(previewScripts);
256256

257+
const fileData = sketchDoc.createElement('script');
258+
fileData.innerHTML = `
259+
window.files = ${JSON.stringify(
260+
files.filter((file) => file.url || file.fileType === 'folder')
261+
)};
262+
`;
263+
sketchDoc.head.prepend(fileData);
264+
257265
const sketchDocString = `<!DOCTYPE HTML>\n${sketchDoc.documentElement.outerHTML}`;
258266
scriptOffs = getAllScriptOffsets(sketchDocString);
259267
const consoleErrorsScript = sketchDoc.createElement('script');

client/utils/previewEntry.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import loopProtect from 'loop-protect';
22
import { Hook, Decode, Encode } from 'console-feed';
33
import StackTrace from 'stacktrace-js';
4+
import { resolvePathToFile } from '../../server/utils/filePath';
5+
import { EXTERNAL_LINK_REGEX } from '../../server/utils/fileUtils';
46
import evaluateExpression from './evaluateExpression';
57

68
// should postMessage user the dispatcher? does the parent window need to
@@ -178,3 +180,33 @@ if (_report) {
178180
_report.apply(window.p5, [newMessage, method, color]);
179181
};
180182
}
183+
184+
const __patchedMethods = {};
185+
186+
function applyPatching(methodName) {
187+
__patchedMethods[methodName] = window.p5.prototype[methodName];
188+
if (__patchedMethods[methodName]) {
189+
window.p5.prototype[methodName] = function patched(path, ...args) {
190+
let resolvedPath = path;
191+
if (!EXTERNAL_LINK_REGEX.test(path)) {
192+
const file = resolvePathToFile(path, window.files);
193+
if (file && file.url) {
194+
resolvedPath = file.url;
195+
}
196+
}
197+
return __patchedMethods[methodName].apply(this, [resolvedPath, ...args]);
198+
};
199+
}
200+
}
201+
202+
[
203+
'loadImage',
204+
'loadModel',
205+
'loadJSON',
206+
'loadStrings',
207+
'loadTable',
208+
'loadXML',
209+
'loadBytes',
210+
'loadFont',
211+
'loadShader'
212+
].forEach(applyPatching);

0 commit comments

Comments
 (0)