Skip to content

Commit 35cd655

Browse files
committed
Play button for js code
1 parent 0f53771 commit 35cd655

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

web/src/js/hljs-run.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
export default class RunButtonPlugin {
2+
constructor() {
3+
this.playgroundUrl = '/playground.html';
4+
this.text = '<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">' +
5+
'<path stroke-linecap="round" stroke-linejoin="round" d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z" />' +
6+
'</svg>'
7+
}
8+
9+
'after:highlightElement'({ el, result, text }) {
10+
if (result.language !== 'js') return;
11+
if (el.parentElement.querySelector(".hljs-run-button")) return;
12+
const runButton = document.createElement("a");
13+
runButton.href = '#';
14+
runButton.innerHTML = this.text;
15+
runButton.classList.add("hljs-run-button");
16+
runButton.addEventListener('click', (event) => {
17+
event.preventDefault();
18+
const hash = encodeURIComponent(text);
19+
window.location.href = `.${this.playgroundUrl}?hash=${hash}`;
20+
});
21+
const wrapper = document.createElement("div");
22+
wrapper.classList.add('hljs-run');
23+
wrapper.appendChild(runButton);
24+
el.appendChild(wrapper);
25+
}
26+
}

web/src/js/main.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import javascript from 'highlight.js/lib/languages/javascript';
44
import typescript from 'highlight.js/lib/languages/typescript';
55
import json from 'highlight.js/lib/languages/json';
66
import bash from 'highlight.js/lib/languages/bash';
7+
import RunButtonPlugin from './hljs-run.js';
78

89
hljs.registerLanguage('js', javascript);
910
hljs.registerLanguage('ts', typescript);
@@ -54,5 +55,6 @@ document.addEventListener('DOMContentLoaded', function(_event) {
5455
this.parentElement.classList.remove('active');
5556
})
5657

58+
hljs.addPlugin(new RunButtonPlugin());
5759
hljs.highlightAll();
5860
});

web/src/scss/parts/code.scss

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
@use '../includes/variables' as *;
2+
@use '../includes/theme' as *;
23

34
.hljs {
45
display: block;
@@ -98,6 +99,7 @@
9899
}
99100

100101
code {
102+
position: relative;
101103
background: $selection;
102104
padding: 0 0.25rem;
103105
}
@@ -108,3 +110,17 @@ pre code {
108110
font-size: 0.85rem;
109111
line-height: 1.375rem;
110112
}
113+
114+
.hljs-run {
115+
position: absolute;
116+
top: 0.25rem;
117+
right: 0.25rem;
118+
width: 24px;
119+
height: 24px;
120+
121+
.hljs-run-button {
122+
display: block;
123+
width: 100%;
124+
height: 100%;
125+
}
126+
}

0 commit comments

Comments
 (0)