Skip to content

Commit 0f08a7f

Browse files
committed
(#440) Dynamic code block functionality
This allows for the dynamic code block component in choco-astro to listen for values entered into input for code block components and replace custom variables placed in the code block on a page.
1 parent 9ff68ec commit 0f08a7f

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

js/docs.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@ import './src/scrollspy.js';
1313
import './src/ts/tab-multiples.ts';
1414
import './src/ts/tables.ts';
1515
import './src/theme-toggle.js';
16+
import './src/code-block.js';

js/src/code-block.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { copyCodeBlocks } from './util/functions';
2+
3+
document.addEventListener('DOMContentLoaded', () => {
4+
const containsCodeBlockReplace = document.querySelectorAll('.contains-code-block-replace');
5+
const codeBlockValueInputs = document.querySelectorAll('.code-block-value-input');
6+
7+
codeBlockValueInputs.forEach(el => {
8+
9+
const inputVariable = el.name;
10+
const defaultValue = el.getAttribute('data-default-value');
11+
for (const codeBlock of containsCodeBlockReplace) {
12+
codeBlock.innerHTML = codeBlock.innerHTML.replaceAll(inputVariable, `<span class="${inputVariable}">${defaultValue}</span>`);
13+
}
14+
15+
const replaceCodeVariableInCodeBlock = () => {
16+
const codeReplaceVariables = document.querySelectorAll(`.${inputVariable}`);
17+
18+
if (el.value) {
19+
for (const variable of codeReplaceVariables ) {
20+
variable.innerHTML = el.value;
21+
}
22+
} else {
23+
for (const variable of codeReplaceVariables ) {
24+
variable.innerHTML = defaultValue;
25+
}
26+
}
27+
};
28+
29+
replaceCodeVariableInCodeBlock();
30+
31+
el.addEventListener('keyup', () => {
32+
replaceCodeVariableInCodeBlock();
33+
});
34+
});
35+
copyCodeBlocks();
36+
});

0 commit comments

Comments
 (0)