UNPKG

2.62 kBJavaScriptView Raw
1// ___ _ __ _ __
2// / _ \ '__| '__|
3// | __/ | | |
4// \___|_| |_|
5
6const uncolor = require('uncolor');
7
8function contentChar(code) {
9 const model ='\\00000';
10 code = code.toString(16);
11 return model.slice(0, model.length - code.length) + code;
12}
13
14function cssContent(str) {
15 return `${uncolor(str)}`
16 .split('')
17 .map((char) => {
18 const code = char.charCodeAt();
19 // NB: it might be necessary to have ensure that the generated code is exactly 5 characters long
20 // return (code < 65 || code > 127) ? contentChar(code) : char;
21 return (code < 65 || code > 127) ? `\\00${code.toString(16)} ` : char;
22 })
23 .join('');
24}
25
26function errRule(message, bgcolor) {
27 return `
28 display: block;
29 box-sizing: border-box;
30 font-family: monospace;
31 font-size: 1.25em;
32 line-height: 1.25;
33 white-space: pre-wrap;
34 width: 100%;
35 min-height: 6em;
36 padding: 1em;
37 content: '${cssContent(message)}';
38 background-color: ${bgcolor};
39 background-image: url('data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 73"%3E %3Cg fill="%23959595" fill-rule="evenodd" transform="translate(-160 -54)"%3E %3Cpath d="M235.65625 82.15625H182.8125c-4.60813 0-8.34375 3.73562-8.34375 8.34375s3.73562 8.34375 8.34375 8.34375h52.84375V112.75h-11.125v13.90625H210.625V112.75h-13.90625v13.90625H182.8125V112.75c-12.28834 0-22.25-9.96166-22.25-22.25s9.96166-22.25 22.25-22.25V54.34375h13.90625V68.25H210.625V54.34375h13.90625V68.25h11.125v13.90625z"/%3E %3Ccircle cx="248.5" cy="119.5" r="7.5"/%3E %3C/g%3E %3C/svg%3E ');
40 background-repeat: no-repeat;
41 background-position: 2em 1em;
42 background-size: 5em;
43 padding-left: 9em;
44 `.replace(/\n/g,'');
45}
46
47function cssErr(message, bgcolor) {
48 return `html:before { ${errRule(message, bgcolor)} }`;
49}
50
51function htmlCssErr(message, bgcolor) {
52 return `
53 <!DOCTYPE html>
54 <html>
55 <head>
56 <meta charset="utf-8">
57 <meta name="viewport" content="width=device-width">
58 <title>Error</title>
59 <style>
60 html:before { ${errRule(message, bgcolor)} }
61 </style>
62 </head>
63 <body>
64 </body>
65 </html>
66 `;
67}
68
69function jsCssErr(message, bgcolor) {
70 const rule = errRule(message, bgcolor);
71 return `
72 var style = document.createElement('style');
73 style.appendChild(document.createTextNode(''));
74 document.head.appendChild(style);
75 if ("insertRule" in style.sheet) { style.sheet.insertRule("html:before {" + ${JSON.stringify(rule)} + "}", 0); }
76 else if ("addRule" in style.sheet) { style.sheet.addRule("html:before", ${JSON.stringify(rule)}, 0); }
77 `;
78}
79
80module.exports = {
81 cssErr,
82 jsCssErr,
83 htmlCssErr
84};