Skip to content

Commit 43863f1

Browse files
committed
fix: string and colorize JSON when JSON component clicked, not mounted
1 parent 0fb19b7 commit 43863f1

File tree

1 file changed

+25
-40
lines changed

1 file changed

+25
-40
lines changed

src/lib/data/JSON.svelte

Lines changed: 25 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,55 +2,40 @@
22
import Button from '../ui/Button.svelte';
33
import ShowHide from '../functions/ShowHide.svelte';
44
export let obj: Record<string, any>;
5-
$: json = JSON.stringify(obj, null, 2)
6-
.replace(/&/g, '&amp;')
7-
.replace(/</g, '&lt;')
8-
.replace(/>/g, '&gt;')
9-
.replace(
10-
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
11-
function (match) {
12-
var color = 'darkorange'; // number'
13-
if (/^"/.test(match)) {
14-
if (/:$/.test(match)) {
15-
color = 'red'; // key
16-
} else {
17-
color = 'green'; // string
5+
6+
function string_and_colorize(obj: Record<string, any>): string {
7+
return JSON.stringify(obj, null, 2)
8+
.replace(/&/g, '&amp;')
9+
.replace(/</g, '&lt;')
10+
.replace(/>/g, '&gt;')
11+
.replace(
12+
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
13+
(match) => {
14+
var color = 'darkorange'; // number'
15+
if (/^"/.test(match)) {
16+
if (/:$/.test(match))
17+
color = 'red'; // key
18+
else
19+
color = 'green'; // string
20+
} else if (/true|false/.test(match)) {
21+
color = 'blue'; // boolean
22+
} else if (/null/.test(match)) {
23+
color = 'magenta'; // null
1824
}
19-
} else if (/true|false/.test(match)) {
20-
color = 'blue'; // boolean
21-
} else if (/null/.test(match)) {
22-
color = 'magenta'; // null
25+
return `<span style="color:${color}">${match}</span>`;
2326
}
24-
return '<span style="color:' + color + '">' + match + '</span>';
25-
}
26-
);
27+
);
28+
}
2729
</script>
2830

2931
<ShowHide let:show let:toggle>
3032
<Button onclick={toggle} form="simple" color="black">
3133
<span class="i-fa-solid-code" />
3234
</Button>
3335
{#if show}
34-
<div class="fullscreen">
35-
<button type="button" class="px-3 py-2 bg-gray-100 text-gray-700" on:click={toggle}
36-
>Hide</button
37-
>
38-
<pre style="white-space:pre-wrap; font-size: 12px;">
39-
{@html json}
40-
</pre>
36+
<div class="fixed inset-0 bg-white z-100 overflow-y-auto">
37+
<button type="button" class="px-3 py-2 bg-gray-100 text-gray-700" on:click={toggle}>Hide</button>
38+
<pre class="whitespace-pre-wrap text-xs">{@html string_and_colorize(obj)}</pre>
4139
</div>
4240
{/if}
4341
</ShowHide>
44-
45-
<style>
46-
.fullscreen {
47-
position: fixed;
48-
top: 0;
49-
bottom: 0;
50-
right: 0;
51-
left: 0;
52-
background: white;
53-
z-index: 100;
54-
overflow-y: auto;
55-
}
56-
</style>

0 commit comments

Comments
 (0)