Skip to content

Commit c427df7

Browse files
Yuuno, Hibikijoeyklee
authored andcommitted
Support p5 preload with ml5 functions (#288)
* support p5 preload with ml5 functions * make withPreload object clean
1 parent f75bc83 commit c427df7

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

src/index.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,14 @@ import styleTransfer from './StyleTransfer/';
1616
import charRNN from './CharRNN/';
1717
import pix2pix from './Pix2pix/';
1818
import SketchRNN from './SketchRNN';
19+
import preloadRegister from './utils/p5PreloadHelper';
1920
import { version } from '../package.json';
2021

21-
module.exports = {
22+
const withPreload = {
2223
imageClassifier,
24+
};
25+
26+
module.exports = Object.assign({}, preloadRegister(withPreload), {
2327
KNNClassifier,
2428
featureExtractor,
2529
pitchDetection,
@@ -33,4 +37,4 @@ module.exports = {
3337
...imageUtils,
3438
tf,
3539
version,
36-
};
40+
});

src/utils/p5PreloadHelper.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Copyright (c) 2019 ml5
2+
//
3+
// This software is released under the MIT License.
4+
// https://opensource.org/licenses/MIT
5+
6+
7+
/**
8+
* a list to store all functions to hook p5 preload
9+
* @param {obj} object or prototype to wrap with
10+
* @returns obj
11+
*/
12+
export default function registerPreload(obj) {
13+
if (typeof window === 'undefined') return obj;
14+
if (typeof window.p5 === 'undefined') return obj;
15+
if (typeof window.p5.prototype === 'undefined') return obj;
16+
if (typeof window.p5.prototype.registerPreloadMethod === 'undefined') return obj;
17+
18+
const preloadFn = obj;
19+
Object.keys(obj).forEach((key) => {
20+
const fn = obj[key];
21+
22+
preloadFn[key] = function preloads(...args) {
23+
return fn.apply(obj, [...args, function doingPreloads() {
24+
const targetPreloadFn = '_decrementPreload';
25+
if (window[targetPreloadFn]) return window[targetPreloadFn]();
26+
return null;
27+
}]);
28+
};
29+
window.p5.prototype.registerPreloadMethod(`${key}`, obj);
30+
});
31+
32+
return obj;
33+
}

0 commit comments

Comments
 (0)