Skip to content

Commit

Permalink
fix: string and colorize JSON when JSON component clicked, not mounted
Browse files Browse the repository at this point in the history
  • Loading branch information
jacob-8 committed Mar 19, 2024
1 parent 0fb19b7 commit 43863f1
Showing 1 changed file with 25 additions and 40 deletions.
65 changes: 25 additions & 40 deletions src/lib/data/JSON.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,55 +2,40 @@
import Button from '../ui/Button.svelte';
import ShowHide from '../functions/ShowHide.svelte';
export let obj: Record<string, any>;
$: json = JSON.stringify(obj, null, 2)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
function (match) {
var color = 'darkorange'; // number'
if (/^"/.test(match)) {
if (/:$/.test(match)) {
color = 'red'; // key
} else {
color = 'green'; // string
function string_and_colorize(obj: Record<string, any>): string {
return JSON.stringify(obj, null, 2)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
(match) => {
var color = 'darkorange'; // number'
if (/^"/.test(match)) {
if (/:$/.test(match))
color = 'red'; // key
else
color = 'green'; // string
} else if (/true|false/.test(match)) {
color = 'blue'; // boolean
} else if (/null/.test(match)) {
color = 'magenta'; // null
}
} else if (/true|false/.test(match)) {
color = 'blue'; // boolean
} else if (/null/.test(match)) {
color = 'magenta'; // null
return `<span style="color:${color}">${match}</span>`;
}
return '<span style="color:' + color + '">' + match + '</span>';
}
);
);
}
</script>

<ShowHide let:show let:toggle>
<Button onclick={toggle} form="simple" color="black">
<span class="i-fa-solid-code" />
</Button>
{#if show}
<div class="fullscreen">
<button type="button" class="px-3 py-2 bg-gray-100 text-gray-700" on:click={toggle}
>Hide</button
>
<pre style="white-space:pre-wrap; font-size: 12px;">
{@html json}
</pre>
<div class="fixed inset-0 bg-white z-100 overflow-y-auto">
<button type="button" class="px-3 py-2 bg-gray-100 text-gray-700" on:click={toggle}>Hide</button>
<pre class="whitespace-pre-wrap text-xs">{@html string_and_colorize(obj)}</pre>
</div>
{/if}
</ShowHide>

<style>
.fullscreen {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
background: white;
z-index: 100;
overflow-y: auto;
}
</style>

0 comments on commit 43863f1

Please sign in to comment.