lite hjälpfunktioner för text och en textruta att skriva i

This commit is contained in:
botvid johansson 2025-02-05 14:37:16 +01:00
parent f49bd5d1ca
commit 2ae2227a4d
3 changed files with 112 additions and 2 deletions

33
src/lib/textarea/main.ts Normal file
View File

@ -0,0 +1,33 @@
export const insertText = (textarea, text) => {
const start = textarea.selectionStart;
const end = textarea.selectionStart + text.length;
textarea.setRangeText(text, start, end, "end");
};
export const insertExpandedPhrase = (textarea, expander, len, text) => {
const start = textarea.selectionStart - len;
const end = textarea.selectionStart;
textarea.setRangeText(text.concat(expander), start, end, "end");
};
const findIndexOfCurrentWord = (textarea) => {
const currentValue = textarea.value;
const cursorPos = textarea.selectionStart;
let startIndex = cursorPos - 1;
while (
startIndex >= 0 &&
/\p{Letter}|\p{Number}/u.test(currentValue[startIndex])
) {
console.log(currentValue[startIndex]);
startIndex--;
}
return startIndex;
};
export const getCurrentWord = (textarea) => {
const currentValue = textarea.value;
const cursorPos = textarea.selectionStart;
const startIndex = findIndexOfCurrentWord(textarea);
return currentValue.substring(startIndex + 1, cursorPos);
};

View File

@ -1,2 +1,7 @@
<h1>Welcome to SvelteKit</h1> <script lang="ts">
<p>Visit <a href="https://svelte.dev/docs/kit">svelte.dev/docs/kit</a> to read the documentation</p> import Textarea from './textarea.svelte';
</script>
<div class="h-full w-full" role="application">
<Textarea />
</div>

View File

@ -0,0 +1,72 @@
<script lang="ts">
import { onMount } from 'svelte';
import { browser } from '$app/environment';
import { getCurrentWord, insertExpandedPhrase, insertText } from '$lib/textarea/main';
let state = {
capitalizeNext: true,
currentWord: ''
};
let textarea;
let text = '';
onMount(() => {
if (browser) {
let t = document.getElementById('doc');
if (t != null) {
textarea = t;
setTimeout(() => {
textarea.focus();
console.log('focus the textarae');
}, 25);
}
}
});
const change = () => {
if (textarea != null) {
if (textarea.value.length == 0) {
state.capitalizeNext = true;
}
}
};
const input = (e) => {
if (e.inputType == 'insertText') {
const key = e.data || '';
if (e.data == null) return;
if (state.capitalizeNext) {
insertText(textarea, key.toUpperCase());
state.capitalizeNext = false;
e.preventDefault();
}
//expand(e);
}
if (e.inputType == 'insertText') {
}
};
/* const hotkeyHandler = (e: KeyboardEvent) => {
if (e.key == 'F4') {
state.textarea.value = '';
}
};
*/
</script>
<div class="docContainer" role="application" id="docContainer">
<textarea id="doc" rows="4" on:keyup={change} on:beforeinput={input} bind:value={text}></textarea>
</div>
<style lang="postcss">
.docContainer {
width: 100%;
}
.docContainer textarea {
width: 100%;
color: black;
padding: 0.3em;
resize: none;
font-size: 2em;
}
</style>