Repository navigation
Expand file tree
/
Copy pathcode-sample.js
More file actions
120 lines (100 loc) · 2.79 KB
/
Copy pathcode-sample.js
File metadata and controls
120 lines (100 loc) · 2.79 KB
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
import {LitElement, html, css} from 'https://unpkg.com/@polymer/lit-element@latest/lit-element.js?module';
class CodeSample extends LitElement {
static get styles() {
return [css`
:host {
display: block;
margin-bottom: 40px;
box-sizing: border-box;
}
main {
border: 1px solid #e0e0e0;
}
pre {
margin: 30px 0 0;
display: block;
}
header {
margin: 20px 0;
}
h3 {
font-weight: normal;
font-size: 25px;
margin-bottom: 0px;
}
h4 {
font-weight: normal;
font-size: 17px;
}
.preview {
padding: 40px 20px 10px;
}
code.html {
padding: 20px;
}
.hljs-tag {
line-break: anywhere;
}
`];
}
static get properties() {
return {
title: { type: String },
description: { type: String }
}
}
getCode() {
const html = _.escape(this.innerHTML);
const lines = html.split('\n');
const firstCodeLine = lines.findIndex(value => value.length > 0);
if (firstCodeLine < 0) {
return html;
}
let whiteSpaceToRemove = '';
const whiteSpaceCharacters = lines[firstCodeLine].search(/\S/);
for (let i = 0; i < whiteSpaceCharacters; i++) {
whiteSpaceToRemove += ' ';
}
const newHtml = lines
.map(line => line.replace(whiteSpaceToRemove, ''))
.map(line => {
const escapedArrays = [...line.matchAll(/(\=\"\[)(&quot;.*?&quot;)(\]")/g)];
escapedArrays.forEach(match => {
const [original, start, middle, end] = match;
let newStart = _.unescape(start).replace('"', "'");
let newMiddle = _.unescape(middle);
let newEnd = _.unescape(end).replace('"', "'");
const newString = newStart + newMiddle + newEnd;
line = line.replace(original, newString);
});
return line;
})
.map(line => {
return line.replace('=""', '');
})
.join('\n');
const titleComment = _.escape(`<!-- Code for "${this.title}" example -->`);
return titleComment + newHtml;
}
firstUpdated() {
const codeElement = this.shadowRoot.querySelector('pre code');
codeElement.innerHTML = this.getCode();
hljs.highlightBlock(codeElement);
}
render() {
return html`
<header>
<h3>${this.title}</h3>
<h4>${this.description}</h4>
</header>
<main>
<div class="preview">
<slot></slot>
</div>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.9.1/styles/default.min.css">
<pre><code class="html"></code></pre>
</main>
`;
}
}
customElements.define('code-sample', CodeSample);