Skip to content

Instantly share code, notes, and snippets.

@KTibow
Created September 28, 2024 02:34
Show Gist options
  • Save KTibow/553c2bd74f19f3f747d2be786581a615 to your computer and use it in GitHub Desktop.
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
<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