Last active
September 19, 2020 04:00
-
-
Save ca0v/c35d6a4ad49ff1be6c27f00af7701ad2 to your computer and use it in GitHub Desktop.
Svelte After Several Hours
This file contains hidden or 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> | |
const chars = "hello world".split("").map((v, i) => ({ v, i })); | |
$: src = chars.map((v) => v.v).join(""); | |
function deleteHandler(e) { | |
switch (e.e.code) { | |
case "ArrowLeft": { | |
const targetIndex = (chars.length + e.i - 1) % chars.length; | |
chars[e.i].v = chars[targetIndex].v; | |
chars[targetIndex].v = e.v; | |
chars = chars; | |
focus(targetIndex); | |
break; | |
} | |
case "ArrowRight": { | |
const targetIndex = (chars.length + e.i + 1) % chars.length; | |
chars[e.i].v = chars[targetIndex].v; | |
chars[targetIndex].v = e.v; | |
chars = chars; | |
focus(targetIndex); | |
break; | |
} | |
case "Backspace": | |
case "Delete": | |
chars.splice(e.i, 1); | |
chars = chars; | |
break; | |
case "Insert": | |
chars.splice(e.i, 0, { v: "." }); | |
chars.forEach((c, i) => (c.i = i)); | |
chars = chars; | |
break; | |
default: | |
if (1 !== e.e.key.length) return; | |
chars[e.i].v = e.e.key; | |
break; | |
} | |
} | |
function focus(index) { | |
document.querySelector(`#input_${index}`)?.focus(); | |
} | |
function selectText(e) { | |
e.srcElement.select(); | |
} | |
</script> | |
<style> | |
input.char { | |
width: 2em; | |
border: 1px solid white; | |
} | |
</style> | |
<h1>{src}</h1> | |
<div> | |
{#each chars as item (item.i)} | |
<input | |
id="input_{item.i}" | |
class="char" | |
maxlength="1" | |
type="text" | |
bind:value={item.v} | |
on:focus={selectText} | |
on:keydown={(e) => deleteHandler({ e, ...item })} /> | |
{/each} | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment