/
index.js
96 lines (77 loc) · 2.47 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import grapesjs from 'grapesjs';
export default grapesjs.plugins.add('gjs-plugin-filestack', (editor, opts = {}) => {
let c = opts;
let config = editor.getConfig();
let pfx = config.stylePrefix || '';
let btnEl;
let defaults = {
// Filestack's API key
key: '',
// Custom button element which triggers Filestack modal
btnEl: '',
// Text for the button in case the custom one is not provided
btnText: 'Add images',
// Filestack's options
filestackOpts: {
accept: 'image/*',
maxFiles: 10
},
// On complete upload callback
// blobs - Array of Objects, eg. [{url:'...', filename: 'name.jpeg', ...}]
// assets - Array of inserted assets
// for debug: console.log(JSON.stringify(blobs));
onComplete: (blobs, assets) => {},
};
// Load defaults
for (let name in defaults) {
if (!(name in c))
c[name] = defaults[name];
}
if(!filestack) {
throw new Error('Filestack instance not found');
}
if(!c.key){
throw new Error("Filestack's API key not found");
}
const fsClient = filestack.init(c.key);
// When the Asset Manager modal is opened
editor.on('run:open-assets', () => {
const modal = editor.Modal;
const modalBody = modal.getContentEl();
const uploader = modalBody.querySelector('.' + pfx + 'am-file-uploader');
const assetsHeader = modalBody.querySelector('.' + pfx + 'am-assets-header');
const assetsBody = modalBody.querySelector('.' + pfx + 'am-assets-cont');
uploader && (uploader.style.display = 'none');
assetsHeader && (assetsHeader.style.display = 'none');
assetsBody.style.width = '100%';
// Instance button if not yet exists
if(!btnEl) {
btnEl = c.btnEl;
if(!btnEl) {
btnEl = document.createElement('button');
btnEl.className = pfx + 'btn-prim ' + pfx + 'btn-filestack';
btnEl.innerHTML = c.btnText;
}
btnEl.onclick = () => {
fsClient.pick(c.filestackOpts).then((objs) => {
const blob = objs.filesUploaded;
const blobs = blob instanceof Array ? blob : [blob];
let assets = addAssets(blobs);
c.onComplete(blobs, assets);
});
};
}
assetsBody.insertBefore(btnEl, assetsHeader);
});
/**
* Add new assets to the editor
* @param {Array} files
*/
const addAssets = (files) => {
const urls = files.map((file) => {
file.src = file.url;
return file;
});
return editor.AssetManager.add(urls);
};
});