|
1 | 1 | <script lang="ts">
|
2 |
| - import { isDesktop } from "$lib/utils/isDesktop"; |
| 2 | + import { browser } from "$app/environment"; |
3 | 3 | import { createEventDispatcher, onMount } from "svelte";
|
4 | 4 |
|
5 | 5 | export let value = "";
|
|
13 | 13 |
|
14 | 14 | const dispatch = createEventDispatcher<{ submit: void }>();
|
15 | 15 |
|
| 16 | + function isVirtualKeyboard(): boolean { |
| 17 | + if (!browser) return false; |
| 18 | +
|
| 19 | + // Check for touch capability |
| 20 | + if (navigator.maxTouchPoints > 0) return true; |
| 21 | +
|
| 22 | + // Check for touch events |
| 23 | + if ("ontouchstart" in window) return true; |
| 24 | +
|
| 25 | + // Fallback to user agent string check |
| 26 | + const userAgent = navigator.userAgent.toLowerCase(); |
| 27 | +
|
| 28 | + return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(userAgent); |
| 29 | + } |
| 30 | +
|
16 | 31 | $: minHeight = `${1 + minRows * 1.5}em`;
|
17 | 32 | $: maxHeight = maxRows ? `${1 + maxRows * 1.5}em` : `auto`;
|
18 | 33 |
|
19 | 34 | function handleKeydown(event: KeyboardEvent) {
|
20 |
| - // submit on enter |
21 | 35 | if (event.key === "Enter" && !event.shiftKey && !isCompositionOn) {
|
22 | 36 | event.preventDefault();
|
23 |
| - // blur to close keyboard on mobile |
24 |
| - textareaElement.blur(); |
25 |
| - // refocus so that user on desktop can start typing without needing to reclick on textarea |
26 |
| - if (isDesktop(window)) { |
27 |
| - textareaElement.focus(); |
| 37 | + if (isVirtualKeyboard()) { |
| 38 | + // Insert a newline at the cursor position |
| 39 | + const start = textareaElement.selectionStart; |
| 40 | + const end = textareaElement.selectionEnd; |
| 41 | + value = value.substring(0, start) + "\n" + value.substring(end); |
| 42 | + textareaElement.selectionStart = textareaElement.selectionEnd = start + 1; |
| 43 | + } else { |
| 44 | + dispatch("submit"); |
28 | 45 | }
|
29 |
| - dispatch("submit"); // use a custom event instead of `event.target.form.requestSubmit()` as it does not work on Safari 14 |
30 | 46 | }
|
31 | 47 | }
|
32 | 48 |
|
33 | 49 | onMount(() => {
|
34 |
| - if (isDesktop(window)) { |
| 50 | + if (!isVirtualKeyboard()) { |
35 | 51 | textareaElement.focus();
|
36 | 52 | }
|
37 | 53 | });
|
|
44 | 60 | style="min-height: {minHeight}; max-height: {maxHeight}">{(value || " ") + "\n"}</pre>
|
45 | 61 |
|
46 | 62 | <textarea
|
47 |
| - enterkeyhint="send" |
| 63 | + enterkeyhint={!isVirtualKeyboard() ? "enter" : "send"} |
48 | 64 | tabindex="0"
|
49 | 65 | rows="1"
|
50 | 66 | class="scrollbar-custom absolute top-0 m-0 h-full w-full resize-none scroll-p-3 overflow-x-hidden overflow-y-scroll border-0 bg-transparent p-3 outline-none focus:ring-0 focus-visible:ring-0"
|
|
0 commit comments