ldc-loue/resources/ts/components/bo/WordCounterComponent.vue
2022-07-04 10:17:34 +00:00

124 lines
2.6 KiB
Vue

<template>
<div class="wordCounter">
<span class="words"
><u>{{ __("Mots") }}</u
>&nbsp;:&nbsp;<b>{{ _words }}</b></span
>
<span class="chars"
><u>{{ __("Caractères") }}</u
>&nbsp;:&nbsp;<b>{{ _chars }}</b></span
>
</div>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import trans from "../../modules/trans";
export default defineComponent({
mixins: [trans],
mounted() {
const json = String(this.$attrs.json ?? "{}"),
data = JSON.parse(json);
this._id = String(this.id);
if (data.id) {
this._id = data.id;
}
},
props: {
id: {
type: String,
default: null,
},
},
data(): {
_id: string;
_words: number;
_chars: number;
_input: HTMLInputElement | HTMLTextAreaElement | null;
} {
return {
_id: "",
_words: 0,
_chars: 0,
_input: null,
};
},
watch: {
id() {
this._id = this.id;
},
_id() {
if (!this._id) {
return;
}
this.$nextTick(() => {
const input = document.getElementById(this._id);
if (
!input ||
!(input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement)
) {
throw new Error(`${this._id} is not a input or textarea`);
}
this._input = input;
});
},
_input() {
if (
!this._input ||
!(
this._input instanceof HTMLInputElement ||
this._input instanceof HTMLTextAreaElement
)
) {
throw new Error(`${this._id} is not a input or textarea`);
}
this._input.addEventListener("input", (e) => {
const el = e.target;
if (
!el ||
!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement)
) {
throw new Error(`${this._id} is not a input or textarea`);
}
this.updateValues(el.value);
});
this.updateValues(this._input.value);
},
},
methods: {
updateValues(string: string) {
let chars, words;
[words, chars] = this.calculateValues(string);
this._words = words;
this._chars = chars;
},
calculateValues(string: string) {
const arr = string.split(" ");
return [arr.filter((word) => word !== "").length, string.length];
},
},
});
</script>
<style lang="scss">
.wordCounter {
display: inline-block;
color: initial;
border: 1px solid rgb(196, 196, 196);
border-bottom: 0;
background-color: #fafafa;
position: relative;
width: 100%;
.words {
position: relative;
left: 2rem;
}
.chars {
position: absolute;
left: 9rem;
}
}
</style>