opnform/resources/js/components/common/EditableDiv.vue

73 lines
2.0 KiB
Vue
Raw Normal View History

2022-09-20 19:59:52 +00:00
<template>
2023-10-16 10:54:51 +00:00
<div ref="parentRef"
2022-09-20 19:59:52 +00:00
tabindex="0"
:class="{
'hover:bg-gray-100 dark:hover:bg-gray-800 rounded px-2 cursor-pointer': !editing
2023-10-16 10:54:51 +00:00
}"
2022-09-20 19:59:52 +00:00
class="relative"
2023-10-16 10:54:51 +00:00
:style="{ height: editing ? divHeight + 'px' : 'auto' }"
2022-09-20 19:59:52 +00:00
@focus="startEditing"
>
<slot v-if="!editing" :content="content">
<label class="cursor-pointer truncate w-full">
{{ content }}
</label>
</slot>
<div v-if="editing" class="absolute inset-0 border-2 transition-colors"
2023-10-16 10:54:51 +00:00
:class="{ 'border-transparent': !editing, 'border-blue-500': editing }"
>
<input ref="editInputRef" v-model="content"
2022-09-20 19:59:52 +00:00
class="absolute inset-0 focus:outline-none bg-white transition-colors"
2023-10-16 10:54:51 +00:00
:class="[{'bg-blue-50': editing}, contentClass]" @blur="editing = false" @keyup.enter="editing = false"
2022-09-20 19:59:52 +00:00
@input="handleInput"
>
</div>
</div>
</template>
2023-10-16 10:54:51 +00:00
<script setup>
import { ref, onMounted, watch, nextTick, defineProps, defineEmits } from 'vue'
const props = defineProps({
modelValue: { type: String, required: true },
textAlign: { type: String, default: 'left' },
contentClass: { type: String, default: '' }
})
const emit = defineEmits()
const content = ref(props.modelValue)
const editing = ref(false)
const divHeight = ref(0)
const parentRef = ref(null) // Ref for parent element
const editInputRef = ref(null) // Ref for edit input element
const startEditing = () => {
if (parentRef.value) {
divHeight.value = parentRef.value.offsetHeight
editing.value = true
nextTick(() => {
if (editInputRef.value) {
editInputRef.value.focus()
}
})
2022-09-20 19:59:52 +00:00
}
}
2023-10-16 10:54:51 +00:00
const handleInput = () => {
emit('update:modelValue', content.value)
}
// Watch for changes in props.modelValue and update the local content
watch(() => props.modelValue, (newValue) => {
content.value = newValue
})
// Wait until the component is mounted to set the initial divHeight
onMounted(() => {
if (parentRef.value) {
divHeight.value = parentRef.value.offsetHeight
}
})
2022-09-20 19:59:52 +00:00
</script>