-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathindex.js
97 lines (85 loc) · 2.59 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
97
import JSZip from 'jszip';
import FileSaver from 'file-saver';
export default (editor, opts = {}) => {
let pfx = editor.getConfig('stylePrefix');
let btnExp = document.createElement('button');
let commandName = 'gjs-export-zip';
let config = {
addExportBtn: 1,
btnLabel: 'Export to ZIP',
filenamePfx: 'grapesjs_template',
filename: null,
root: {
css: {
'style.css': ed => ed.getCss(),
},
'index.html': ed =>
`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./css/style.css">
</head>
<body>${ed.getHtml()}</body>
<html>`,
},
isBinary: null,
...opts,
};
btnExp.innerHTML = config.btnLabel;
btnExp.className = `${pfx}btn-prim`;
// Add command
editor.Commands.add(commandName, {
createFile(zip, name, content) {
const opts = {};
const ext = name.split('.')[1];
const isBinary = config.isBinary ?
config.isBinary(content, name) :
!(ext && ['html', 'css'].indexOf(ext) >= 0) &&
!/^[\x00-\x7F]*$/.test(content);
if (isBinary) {
opts.binary = true;
}
editor.log(['Create file', { name, content, opts }],
{ ns: 'plugin-export' });
zip.file(name, content, opts);
},
async createDirectory(zip, root) {
root = typeof root === 'function' ? await root(editor) : root;
for (const name in root) {
if (root.hasOwnProperty(name)) {
let content = root[name];
content = typeof content === 'function' ? await content(editor) : content;
const typeOf = typeof content;
if (typeOf === 'string') {
this.createFile(zip, name, content);
} else if (typeOf === 'object') {
const dirRoot = zip.folder(name);
await this.createDirectory(dirRoot, content);
}
}
}
},
run(editor) {
const zip = new JSZip();
this.createDirectory(zip, config.root).then(() => {
zip.generateAsync({ type: 'blob' })
.then(content => {
const filenameFn = config.filename;
let filename = filenameFn ?
filenameFn(editor) : `${config.filenamePfx}_${Date.now()}.zip`;
FileSaver.saveAs(content, filename);
});
});
}
});
// Add button inside export dialog
if (config.addExportBtn) {
editor.on('run:export-template', () => {
editor.Modal.getContentEl().appendChild(btnExp);
btnExp.onclick = () => {
editor.runCommand(commandName);
};
});
}
};