-
Notifications
You must be signed in to change notification settings - Fork 10
/
script.js
207 lines (180 loc) · 6.38 KB
/
script.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
(function () {
/**
* Handle pasting of files
*
* @param {ClipboardEvent} e
*/
function handlePaste(e) {
if (!document.getElementById('wiki__text')) return; // only when editing
const items = (e.clipboardData || e.originalEvent.clipboardData).items;
// When running prosemirror, check for HTML paste first
if (typeof window.proseMirrorIsActive !== 'undefined' && window.proseMirrorIsActive === true) {
for (let index in items) {
const item = items[index];
if (item.kind === 'string' && item.type === 'text/html') {
e.preventDefault();
e.stopPropagation();
item.getAsString(async html => {
html = await processHTML(html);
const pm = window.Prosemirror.view;
const parser = window.Prosemirror.classes.DOMParser.fromSchema(pm.state.schema);
const nodes = parser.parse(html);
pm.dispatch(pm.state.tr.replaceSelectionWith(nodes));
}
);
return; // we found an HTML item, no need to continue
}
}
}
// if we're still here, handle files
for (let index in items) {
const item = items[index];
if (item.kind === 'file') {
const reader = new FileReader();
reader.onload = event => {
uploadData(event.target.result);
};
reader.readAsDataURL(item.getAsFile());
// we had at least one file, prevent default
e.preventDefault();
e.stopPropagation();
}
}
}
/**
* Creates and shows the progress dialog
*
* @returns {HTMLDivElement}
*/
function progressDialog() {
// create dialog
const offset = document.querySelectorAll('.plugin_imagepaste').length * 3;
const box = document.createElement('div');
box.className = 'plugin_imagepaste';
box.innerText = LANG.plugins.imgpaste.inprogress;
box.style.position = 'fixed';
box.style.top = offset + 'em';
box.style.left = '1em';
document.querySelector('.dokuwiki').append(box);
return box;
}
/**
* Processes the given HTML and downloads all images
*
* @param html
* @returns {Promise<HTMLDivElement>}
*/
async function processHTML(html) {
const box = progressDialog();
const div = document.createElement('div');
div.innerHTML = html;
const imgs = Array.from(div.querySelectorAll('img'));
await Promise.all(imgs.map(async img => {
if (!img.src.match(/^https?:\/\//i)) return; // skip non-external images
if (img.src.startsWith(DOKU_BASE)) return; // skip local images
try {
result = await downloadData(img.src);
img.src = result.url;
img.className = 'media';
img.dataset.relid = getRelativeID(result.id);
} catch (e) {
console.error(e);
}
}));
box.remove();
return div;
}
/**
* Tell the backend to download the given URL and return the new ID
*
* @param {string} imgUrl
* @returns {Promise<object>} The JSON response
*/
async function downloadData(imgUrl) {
const formData = new FormData();
formData.append('call', 'plugin_imgpaste');
formData.append('url', imgUrl);
formData.append('id', JSINFO.id);
const response = await fetch(
DOKU_BASE + 'lib/exe/ajax.php',
{
method: 'POST',
body: formData
}
);
if (!response.ok) {
throw new Error(response.statusText);
}
return await response.json();
}
/**
* Uploads the given dataURL to the server and displays a progress dialog
*
* @param {string} dataURL
*/
function uploadData(dataURL) {
const box = progressDialog();
// upload via AJAX
jQuery.ajax({
url: DOKU_BASE + 'lib/exe/ajax.php',
type: 'POST',
data: {
call: 'plugin_imgpaste',
data: dataURL,
id: JSINFO.id
},
// insert syntax and close dialog
success: function (data) {
box.classList.remove('info');
box.classList.add('success');
box.innerText = data.message;
setTimeout(() => {
box.remove();
}, 1000);
insertSyntax(data.id);
},
// display error and close dialog
error: function (xhr, status, error) {
box.classList.remove('info');
box.classList.add('error');
box.innerText = error;
setTimeout(() => {
box.remove();
}, 1000);
}
});
}
/**
* Create a link ID for the given ID, preferrably relative to the current page
*
* @param {string} id
* @returns {string}
*/
function getRelativeID(id) {
// TODO remove the "if" check after LinkWizard.createRelativeID() is available in stable (after Kaos)
if (typeof LinkWizard !== 'undefined' && typeof LinkWizard.createRelativeID === 'function') {
id = LinkWizard.createRelativeID(JSINFO.id, id);
} else {
id = ':' + id;
}
return id;
}
/**
* Inserts the given ID into the current editor
*
* @todo add support for other editors like CKEditor
* @param {string} id The newly uploaded file ID
*/
function insertSyntax(id) {
id = getRelativeID(id);
if (typeof window.proseMirrorIsActive !== 'undefined' && window.proseMirrorIsActive === true) {
const pm = window.Prosemirror.view;
const imageNode = pm.state.schema.nodes.image.create({id: id});
pm.dispatch(pm.state.tr.replaceSelectionWith(imageNode));
} else {
insertAtCarret('wiki__text', '{{' + id + '}}');
}
}
// main
window.addEventListener('paste', handlePaste, true);
})();