erstellt EditableItem mit frontend-error-handling eingefügt caselist, crimelist

This commit is contained in:
2025-06-26 18:40:09 +02:00
parent f8234c0488
commit f87b106ad2
5 changed files with 196 additions and 213 deletions

View File

@@ -0,0 +1,123 @@
<script lang="ts">
import Edit from '$lib/icons/Edit.svelte';
import Trash from '$lib/icons/Trash.svelte';
import { createEventDispatcher } from 'svelte';
import { validateInput } from '$lib/helper/error-utils';
interface ListItem {
name: string;
token?: string;
// add other properties as needed
}
export let value: string = '';
export let variant: '' | 'casename' | 'crimename' = ''; // casename | crimename
export let existings: ListItem[];
export let id: number;
export let editable: boolean = true;
export let editing: boolean;
console.log('Debug editing', editing);
const existingNames = existings.map((item) => item.name);
const dispatch = createEventDispatcher<{
editSart: {};
save: {};
delete: {};
cancel: void;
}>();
let internalValue = value;
let oldValue = value;
let showWarning = false;
let duplicate = false;
let errors: string[] = [];
let errorText = '';
$: errors = validateInput(oldValue, internalValue, { minLength: 3, existingNames });
function startEdit() {
oldValue = value;
internalValue = value;
editing = true;
dispatch('editSart', { id, value, variant, editing });
}
function cancelEdit() {
internalValue = oldValue;
editing = false;
showWarning = false;
console.log('Abgebrochen');
dispatch('cancel');
}
function saveEdit(ev?: MouseEvent | KeyboardEvent) {
ev?.preventDefault();
ev?.stopPropagation();
const name = internalValue.trim();
if (errors.length !== 0) {
showWarning = true;
console.log('Abgebrochen', errors);
return;
}
if (!name) {
showWarning = true;
console.log('Abgebrochen', showWarning);
return;
}
if (existingNames.includes(name) && name !== oldValue.trim()) {
showWarning = true;
console.log('Abgebrochen', showWarning);
return;
}
editing = false;
showWarning = false;
duplicate = false;
dispatch('save', { newValue: internalValue, oldValue, variant });
}
function deleteItem() {
dispatch('delete', { value, variant });
}
function handleKey(e: KeyboardEvent) {
if (e.key === 'Enter') saveEdit(e);
if (e.key === 'Escape') cancelEdit();
}
</script>
<div class="" {...$$restProps}>
<div class="flex gap-x-2">
{#if editing}
<input
bind:value={internalValue}
on:keydown={handleKey}
on:blur|preventDefault|stopPropagation={cancelEdit}
class=""
class:bg-red-200={(showWarning && editing) || errors.length !== 0}
/>
{:else}
<span>{value}</span>
{#if !editing && editable}
<button on:click|preventDefault|stopPropagation={startEdit}>
<Edit />
</button>
<button on:click|preventDefault={deleteItem}>
<Trash />
</button>
{/if}
{/if}
</div>
{#if editing && errors}
<p class="text-red-600 text-sm mt-1 font-medium">{errors[0]}</p>
{/if}
</div>