Created
September 28, 2024 02:34
-
-
Save KTibow/553c2bd74f19f3f747d2be786581a615 to your computer and use it in GitHub Desktop.
(pared down) version of a list item component that both drag/drops and can be edited, with the caret matching up
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
import { createEventDispatcher } from "svelte"; | |
export let text: string; | |
let editing = false; | |
let lastClickX = 0; | |
let lastClickY = 0; | |
const applyCaret = (node: HTMLInputElement) => { | |
const offset = (document as any).caretPositionFromPoint(lastClickX, lastClickY).offset; | |
node.focus(); | |
node.setSelectionRange(offset, offset); | |
}; | |
const dispatch = createEventDispatcher(); | |
</script> | |
<li> | |
{#if editing} | |
<input | |
type="text" | |
bind:value={text} | |
use:applyCaret | |
on:blur={() => { | |
dispatch("save"); | |
editing = false; | |
}} | |
on:keydown={(e) => { | |
if (e.key == "Enter" || e.key == "Escape") { | |
e.currentTarget.blur(); | |
} | |
}} | |
/> | |
{:else} | |
<span | |
tabindex="0" | |
role="button" | |
on:click={(e) => { | |
editing = true; | |
lastClickX = e.clientX; | |
lastClickY = e.clientY; | |
}} | |
on:keydown|stopPropagation={(e) => { | |
if (e.key == "Enter" || e.key == " ") { | |
e.preventDefault(); | |
editing = true; | |
lastClickX = 0; | |
lastClickY = 0; | |
} | |
}} | |
> | |
{text} | |
</span> | |
{/if} | |
</li> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment