forked from frappe/builder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditableSpan.vue
More file actions
92 lines (84 loc) · 1.9 KB
/
EditableSpan.vue
File metadata and controls
92 lines (84 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<template>
<div
ref="editableRef"
:contenteditable="editMode"
@dblclick="handleDoubleClick"
@blur="handleBlur"
@keydown="handleKeydown">
<slot></slot>
</div>
</template>
<script lang="ts" setup>
import { nextTick, ref, watch } from "vue";
import { toast } from "vue-sonner";
const props = withDefaults(
defineProps<{
modelValue?: string;
editable?: boolean;
onChange?: (value: string) => Promise<void>;
}>(),
{
modelValue: "",
editable: false,
},
);
const editMode = ref(false);
const editableRef = ref<HTMLElement>();
function handleDoubleClick() {
editMode.value = true;
}
function handleBlur() {
editMode.value = false;
const text = editableRef.value?.innerText.trim() ?? "";
if (text === props.modelValue) return;
if (!text) {
editableRef.value!.innerText = props.modelValue;
return;
}
if (props.onChange) {
props.onChange(text).catch((e) => {
let error_message = e.exc.split("\n").slice(-2)[0];
if (error_message.includes("Duplicate") || error_message.includes("select another name")) {
error_message = "Name already exists";
}
toast.error("Failed to rename", {
description: error_message,
});
editableRef.value!.innerText = props.modelValue;
});
}
}
function handleKeydown(e: KeyboardEvent) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
editableRef.value?.blur();
}
if (e.key === "Escape") {
e.preventDefault();
editableRef.value?.blur();
}
}
watch(
() => editMode.value,
(value) => {
nextTick(() => {
if (value && editableRef.value) {
editableRef.value?.focus();
const range = document.createRange();
range.selectNodeContents(editableRef.value);
range.collapse(false);
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
}
});
},
);
watch(
() => props.editable,
(value) => {
editMode.value = value;
},
{ immediate: true },
);
</script>