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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
|
/* eslint-disable no-undef */
/**
*
* @param {StyleSheetList} styleSheets
*/
const ForeignHtmlRenderer = function (styleSheets) {
/**
*
* @param {String} binStr
*/
const binaryStringToBase64 = binStr =>
new Promise(resolve => {
const reader = new FileReader();
reader.readAsDataURL(binStr);
reader.onloadend = function () {
resolve(reader.result);
};
});
function prepend(extension) {
return window.location.origin + extension;
}
function CorsProxy(url) {
return prepend('/corsproxy/') + encodeURIComponent(url);
}
/**
*
* @param {String} url
* @returns {Promise}
*/
const getResourceAsBase64 = (webUrl, inurl) =>
new Promise(resolve => {
const xhr = new XMLHttpRequest();
// const url = inurl.startsWith("/") && !inurl.startsWith("//") ? webUrl + inurl : inurl;
// const url = CorsProxy(inurl.startsWith("/") && !inurl.startsWith("//") ? webUrl + inurl : inurl);// inurl.startsWith("http") ? CorsProxy(inurl) : inurl;
let url = inurl;
if (inurl.startsWith('/static')) {
url = new URL(webUrl).origin + inurl;
} else if (inurl.startsWith('/') && !inurl.startsWith('//')) {
url = CorsProxy(new URL(webUrl).origin + inurl);
} else if (!inurl.startsWith('http') && !inurl.startsWith('//')) {
url = CorsProxy(`${webUrl}/${inurl}`);
} else if (inurl.startsWith('https') && !inurl.startsWith(window.location.origin)) {
url = CorsProxy(inurl);
}
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onreadystatechange = async function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const resBase64 = await binaryStringToBase64(xhr.response);
resolve({
resourceUrl: inurl,
resourceBase64: resBase64,
});
} else if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(`COULDN'T FIND: ${inurl.startsWith('/') ? webUrl + inurl : inurl}`);
resolve({
resourceUrl: '',
resourceBase64: inurl,
});
}
};
xhr.send(null);
});
/**
*
* @param {String[]} urls
* @returns {Promise}
*/
const getMultipleResourcesAsBase64 = (webUrl, urls) => {
const promises = [];
for (let i = 0; webUrl && i < urls.length; i += 1) {
promises.push(getResourceAsBase64(webUrl, urls[i]));
}
return Promise.all(promises);
};
/**
*
* @param {String} str
* @param {Number} startIndex
* @param {String} prefixToken
* @param {String[]} suffixTokens
*
* @returns {String|null}
*/
const parseValue = function (str, startIndex, prefixToken, suffixTokens) {
const idx = str.indexOf(prefixToken, startIndex);
if (idx === -1) {
return null;
}
let val = '';
for (let i = idx + prefixToken.length; i < str.length; i += 1) {
if (suffixTokens.indexOf(str[i]) !== -1) {
break;
}
val += str[i];
}
return {
foundAtIndex: idx,
value: val,
};
};
/**
*
* @param {String} str
* @returns {String}
*/
const removeQuotes = function (str) {
return str.replace(/["']/g, '');
};
/**
*
* @param {String} cssRuleStr
* @returns {String[]}
*/
const getUrlsFromCssString = function (cssRuleStr, selector = 'url(', delimiters = [')'], mustEndWithQuote = false) {
const urlsFound = [];
let searchStartIndex = 0;
// eslint-disable-next-line no-constant-condition
while (true) {
const url = parseValue(cssRuleStr, searchStartIndex, selector, delimiters);
if (url === null) {
break;
}
searchStartIndex = url.foundAtIndex + url.value.length + 1;
if (!mustEndWithQuote || url.value[url.value.length - 1] === '"') {
const unquoted = removeQuotes(url.value);
if (unquoted /* || (!unquoted.startsWith('http')&& !unquoted.startsWith("/") ) */ && unquoted !== 'http://' && unquoted !== 'https://') {
if (unquoted) urlsFound.push(unquoted);
}
}
}
return urlsFound;
};
/**
* Extracts font-face URLs from CSS rules
* @param {String} cssRuleStr
* @returns {String[]}
*/
const getFontFaceUrlsFromCss = function (cssRuleStr) {
const fontFaceUrls = [];
// Find @font-face blocks
const fontFaceBlocks = cssRuleStr.match(/@font-face\s*{[^}]*}/g) || [];
fontFaceBlocks.forEach(block => {
// Extract URLs from src properties
const urls = block.match(/src\s*:\s*[^;]*/g) || [];
urls.forEach(srcDeclaration => {
// Find all url() references in the src declaration
const fontUrls = getUrlsFromCssString(srcDeclaration);
fontFaceUrls.push(...fontUrls);
});
});
return fontFaceUrls;
};
/**
*
* @param {String} html
* @returns {String[]}
*/
const getImageUrlsFromFromHtml = function (html) {
return getUrlsFromCssString(html, 'src=', [' ', '>', '\t'], true);
};
const escapeRegExp = function (string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
};
/**
* Create a fallback font-face rule for handling CORS errors
* @returns {String}
*/
const createFallbackFontFaceRules = function () {
return `
@font-face {
font-family: 'CORS-fallback-serif';
src: local('Times New Roman'), local('Georgia'), serif;
}
@font-face {
font-family: 'CORS-fallback-sans';
src: local('Arial'), local('Helvetica'), sans-serif;
}
/* Add fallback font handling */
[data-font-error] {
font-family: 'CORS-fallback-sans', sans-serif !important;
}
[data-font-error="serif"] {
font-family: 'CORS-fallback-serif', serif !important;
}
`;
};
/**
* Clean up and optimize CSS for better rendering
* @param {String} cssStyles
* @returns {String}
*/
const optimizeCssForRendering = function (cssStyles) {
// Add fallback font-face rules
const enhanced = cssStyles + createFallbackFontFaceRules();
// Replace problematic font-face declarations with proxied versions
let optimized = enhanced.replace(/(url\(['"]?)(https?:\/\/[^)'"]+)(['"]?\))/gi, (match, prefix, url, suffix) => {
// If it's a font file, proxy it
if (url.match(/\.(woff2?|ttf|eot|otf)(\?.*)?$/i)) {
return `${prefix}${CorsProxy(url)}${suffix}`;
}
return match;
});
// Add error handling for fonts
optimized += `
/* Suppress font CORS errors in console */
@supports (font-display: swap) {
@font-face {
font-display: swap !important;
}
}
`;
return optimized;
};
/**
*
* @param {String} contentHtml
* @param {Number} width
* @param {Number} height
*
* @returns {Promise<String>}
*/
const buildSvgDataUri = (webUrl, inputContentHtml, width, height, scroll, xoff) => {
/* !! The problems !!
* 1. CORS (not really an issue, expect perhaps for images, as this is a general security consideration to begin with)
* 2. Platform won't wait for external assets to load (fonts, images, etc.)
*/
// copy styles
let cssStyles = '';
const urlsFoundInCss = [];
const fontUrlsInCss = [];
for (let i = 0; i < styleSheets.length; i += 1) {
try {
const rules = styleSheets[i].cssRules;
for (let j = 0; j < rules.length; j += 1) {
const cssRuleStr = rules[j].cssText;
urlsFoundInCss.push(...getUrlsFromCssString(cssRuleStr));
fontUrlsInCss.push(...getFontFaceUrlsFromCss(cssRuleStr));
cssStyles += cssRuleStr;
}
} catch (e) {
/* empty */
}
}
// Optimize and enhance CSS
cssStyles = optimizeCssForRendering(cssStyles);
// const fetchedResourcesFromStylesheets = await getMultipleResourcesAsBase64(webUrl, urlsFoundInCss);
// for (let i = 0; i < fetchedResourcesFromStylesheets.length; i++) {
// const r = fetchedResourcesFromStylesheets[i];
// if (r.resourceUrl) {
// cssStyles = cssStyles.replace(new RegExp(escapeRegExp(r.resourceUrl), "g"), r.resourceBase64);
// }
// }
let contentHtml = inputContentHtml
.replace(/<source[^>]*>/g, '') // <picture> tags have a <source> which has a srcset field of image refs. instead of converting each, just use the default <img> of the picture
.replace(/noscript/g, 'div')
.replace(/<div class="mediaset"><\/div>/g, '') // when scripting isn't available (ie, rendering web pages here), <noscript> tags should become <div>'s. But for Brown CS, there's a layout problem if you leave the empty <mediaset> tag
.replace(/<link[^>]*>/g, '') // don't need to keep any linked style sheets because we've already processed all style sheets above
.replace(/srcset="([^ "]*)[^"]*"/g, 'src="$1"'); // instead of converting each item in the srcset to a data url, just convert the first one and use that
// Add script to handle font loading errors
contentHtml += `
<script>
// Handle font loading errors with fallbacks
document.addEventListener('DOMContentLoaded', function() {
// Mark elements with font issues
document.querySelectorAll('*').forEach(function(el) {
const style = window.getComputedStyle(el);
const fontFamily = style.getPropertyValue('font-family');
if (fontFamily && !fontFamily.includes('serif') && !fontFamily.includes('sans')) {
el.setAttribute('data-font-error', 'sans');
} else if (fontFamily && fontFamily.includes('serif')) {
el.setAttribute('data-font-error', 'serif');
}
});
});
</script>
`;
const urlsFoundInHtml = getImageUrlsFromFromHtml(contentHtml).filter(url => !url.startsWith('data:'));
return getMultipleResourcesAsBase64(webUrl, urlsFoundInHtml).then(fetchedResources => {
for (let i = 0; i < fetchedResources.length; i += 1) {
const r = fetchedResources[i];
if (r.resourceUrl) {
contentHtml = contentHtml.replace(new RegExp(escapeRegExp(r.resourceUrl), 'g'), r.resourceBase64);
}
}
const styleElem = document.createElement('style');
styleElem.innerHTML =
'#mw-sidebar-checkbox ~ .vector-main-menu-container { display: none !important; } ' + // hack to prevent wikipedia menu from appearing
cssStyles.replace('>', '>').replace('<', '<');
const styleElemString = new XMLSerializer().serializeToString(styleElem).replace(/>/g, '>').replace(/</g, '<');
// create DOM element string that encapsulates styles + content
const contentRootElem = document.createElement('body');
contentRootElem.style.zIndex = '1111';
// contentRootElem.style.transform = "scale(0.08)"
contentRootElem.innerHTML = styleElemString + contentHtml;
contentRootElem.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
// document.body.appendChild(contentRootElem);
const contentRootElemString = new XMLSerializer().serializeToString(contentRootElem);
// build SVG string
const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='${width}' height='${height}'>
<foreignObject x='${-xoff}' y='${-scroll}' width='${xoff + width}' height='${scroll + height}'>
${contentRootElemString}
</foreignObject>
</svg>`;
// convert SVG to data-uri
return `data:image/svg+xml;base64,${window.btoa(unescape(encodeURIComponent(svg)))}`;
});
};
/**
* @param {String} html
* @param {Number} width
* @param {Number} height
*
* @return {Promise<Image>}
*/
this.renderToImage = (webUrl, html, width, height, scroll, xoff) =>
new Promise(resolve => {
console.log(`BUILDING SVG for: ${webUrl}`);
buildSvgDataUri(webUrl, html, width, height, scroll, xoff).then(uri => {
const img = new Image();
img.src = uri;
img.onload = () => {
console.log(`IMAGE SVG created: ${webUrl}`);
resolve(img);
};
});
});
/**
* @param {String} html
* @param {Number} width
* @param {Number} height
*
* @return {Promise<Image>}
*/
this.renderToCanvas = (webUrl, html, width, height, scroll, xoff, oversample) =>
this.renderToImage(webUrl, html, width, height, scroll, xoff).then(img => {
const canvas = document.createElement('canvas');
canvas.width = img.width * oversample;
canvas.height = img.height * oversample;
const canvasCtx = canvas.getContext('2d');
canvasCtx.drawImage(img, 0, 0, img.width * oversample, img.height * oversample);
return canvas;
});
/**
* @param {String} html
* @param {Number} width
* @param {Number} height
*
* @return {Promise<String>}
*/
this.renderToBase64Png = (webUrl, html, width, height, scroll, xoff, oversample) =>
this.renderToCanvas(webUrl, html, width, height, scroll, xoff, oversample) //
.then(canvas => canvas.toDataURL('image/png'));
};
export function CreateImage(webUrl, styleSheets, html, width, height, scroll, xoff = 0, oversample = 1) {
return new ForeignHtmlRenderer(styleSheets).renderToBase64Png(
webUrl,
html
.replace(/docView-hack/g, 'documentView-hack')
.replace(/\n/g, '')
.replace(/<script((?!\/script).)*<\/script>/g, ''),
width,
height,
scroll,
xoff,
oversample
);
}
const ClipboardUtils = new (function () {
const permissions = {
'image/bmp': true,
'image/gif': true,
'image/png': true,
'image/jpeg': true,
'image/tiff': true,
};
function getType(types) {
for (let j = 0; j < types.length; j += 1) {
const type = types[j];
if (permissions[type]) {
return type;
}
}
return null;
}
function getItem(items) {
for (let i = 0; i < items.length; i += 1) {
const item = items[i];
if (item) {
const type = getType(item.types);
if (type) {
return item.getType(type);
}
}
}
return null;
}
function loadFile(file, callback) {
if (window.FileReader) {
const reader = new FileReader();
reader.onload = function () {
callback(reader.result, null);
};
reader.onerror = function () {
callback(null, 'Incorrect file.');
};
reader.readAsDataURL(file);
} else {
callback(null, 'File api is not supported.');
}
}
this.readImage = function (callback) {
if (navigator.clipboard) {
const promise = navigator.clipboard.read();
promise
.then(items => {
const promise2 = getItem(items);
if (promise2 == null) {
callback(null, null);
return;
}
promise2
.then(result => {
loadFile(result, callback);
})
.catch(() => {
callback(null, 'Reading clipboard error.');
});
})
.catch(() => {
callback(null, 'Reading clipboard error.');
});
} else {
callback(null, 'Clipboard is not supported.');
}
};
})();
export function pasteImageBitmap(callback) {
return ClipboardUtils.readImage(callback);
}
|