|
| 1 | +<script setup lang="ts"> |
| 2 | +const props = defineProps<{ |
| 3 | + modelValue: object | string |
| 4 | +}>() |
| 5 | +
|
| 6 | +const emit = defineEmits<{ |
| 7 | + 'update:modelValue': [value: object | string] |
| 8 | +}>() |
| 9 | +
|
| 10 | +const content_text = ref('') |
| 11 | +const error_message = ref('') |
| 12 | +
|
| 13 | +watchEffect(() => { |
| 14 | + if (typeof props.modelValue === 'string') { |
| 15 | + content_text.value = props.modelValue |
| 16 | + } |
| 17 | + else { |
| 18 | + content_text.value = JSON.stringify(props.modelValue, null, '\t') |
| 19 | + } |
| 20 | +}) |
| 21 | +
|
| 22 | +function handleInput(event: Event) { |
| 23 | + const target = event.target as HTMLTextAreaElement |
| 24 | + content_text.value = target.value |
| 25 | + validateAndEmit(target.value) |
| 26 | +} |
| 27 | +
|
| 28 | +function validateAndEmit(raw: string) { |
| 29 | + try { |
| 30 | + const parsed = JSON.parse(raw) |
| 31 | + error_message.value = '' |
| 32 | + emit('update:modelValue', parsed) |
| 33 | + } |
| 34 | + catch (err) { |
| 35 | + error_message.value = err instanceof Error ? err.message : 'Invalid JSON' |
| 36 | + } |
| 37 | +} |
| 38 | +
|
| 39 | +function formatJson() { |
| 40 | + try { |
| 41 | + const parsed = JSON.parse(content_text.value) |
| 42 | + content_text.value = JSON.stringify(parsed, null, '\t') |
| 43 | + error_message.value = '' |
| 44 | + emit('update:modelValue', parsed) |
| 45 | + } |
| 46 | + catch (err) { |
| 47 | + error_message.value = err instanceof Error ? err.message : 'Invalid JSON' |
| 48 | + } |
| 49 | +} |
| 50 | +</script> |
| 51 | + |
| 52 | +<template> |
| 53 | + <div class="flex flex-col h-full"> |
| 54 | + <div class="flex items-center justify-between gap-2 p-2 border-b border-default"> |
| 55 | + <span |
| 56 | + v-if="error_message" |
| 57 | + class="text-xs text-red-500 truncate" |
| 58 | + > |
| 59 | + {{ error_message }} |
| 60 | + </span> |
| 61 | + <span v-else /> |
| 62 | + <UButton |
| 63 | + icon="lucide:align-left" |
| 64 | + label="Format" |
| 65 | + color="neutral" |
| 66 | + variant="ghost" |
| 67 | + size="xs" |
| 68 | + @click="formatJson" |
| 69 | + /> |
| 70 | + </div> |
| 71 | + |
| 72 | + <div class="flex-1 overflow-auto"> |
| 73 | + <textarea |
| 74 | + :value="content_text" |
| 75 | + class="w-full h-full p-4 font-mono text-sm bg-transparent resize-none focus:outline-none" |
| 76 | + spellcheck="false" |
| 77 | + @input="handleInput" |
| 78 | + /> |
| 79 | + </div> |
| 80 | + </div> |
| 81 | +</template> |
0 commit comments