File size: 4,966 Bytes
15c3607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
<script lang="ts">
	import { tick } from 'svelte';
	import { Plus, Trash2 } from '@lucide/svelte';
	import { Input } from '$lib/components/ui/input';
	import {
		autoResizeTextarea,
		sanitizeKeyValuePairKey,
		sanitizeKeyValuePairValue
	} from '$lib/utils';
	import { KEY_VALUE_PAIR_KEY_MAX_LENGTH, KEY_VALUE_PAIR_VALUE_MAX_LENGTH } from '$lib/constants';
	import type { KeyValuePair } from '$lib/types';

	interface Props {
		class?: string;
		pairs: KeyValuePair[];
		onPairsChange: (pairs: KeyValuePair[]) => void;
		keyPlaceholder?: string;
		valuePlaceholder?: string;
		addButtonLabel?: string;
		emptyMessage?: string;
		sectionLabel?: string;
		sectionLabelOptional?: boolean;
	}

	let {
		class: className = '',
		pairs,
		onPairsChange,
		keyPlaceholder = 'Key',
		valuePlaceholder = 'Value',
		addButtonLabel = 'Add',
		emptyMessage = 'No items configured.',
		sectionLabel,
		sectionLabelOptional = true
	}: Props = $props();

	// Pre-allocate the ref array so `bind:ref={keyInputRefs[index]}` never reads `undefined`
	// for in-range indices; the $effect below keeps it in sync when `pairs` grows.
	// svelte-ignore state_referenced_locally
	let keyInputRefs: (HTMLInputElement | null)[] = $state(pairs.map(() => null));

	async function addPair() {
		// Capture the target index before mutating so deletions earlier in the
		// list can't make keyInputRefs.length drift past the newly-appended row.
		const newIndex = pairs.length;
		onPairsChange([...pairs, { key: '', value: '' }]);
		await tick();
		keyInputRefs[newIndex]?.focus();
	}

	function removePair(index: number) {
		onPairsChange(pairs.filter((_, i) => i !== index));
	}

	function updatePairKey(index: number, rawKey: string) {
		const key = sanitizeKeyValuePairKey(rawKey);
		const newPairs = [...pairs];

		newPairs[index] = { ...newPairs[index], key };
		onPairsChange(newPairs);
	}

	function trimPairKey(index: number, key: string) {
		const trimmed = key.trim();
		if (trimmed === key) return;

		const newPairs = [...pairs];

		newPairs[index] = { ...newPairs[index], key: trimmed };
		onPairsChange(newPairs);
	}

	function updatePairValue(index: number, rawValue: string) {
		const value = sanitizeKeyValuePairValue(rawValue);
		const newPairs = [...pairs];

		newPairs[index] = { ...newPairs[index], value };
		onPairsChange(newPairs);
	}

	function trimPairValue(index: number, value: string) {
		const trimmed = value.trim();
		if (trimmed === value) return;

		const newPairs = [...pairs];

		newPairs[index] = { ...newPairs[index], value: trimmed };
		onPairsChange(newPairs);
	}

	// Keep keyInputRefs aligned with pairs length so bind:ref never sees `undefined`.
	// $effect.pre runs during traversal in tree order, before the {#each} block re-renders,
	// so newly-appended items always have a defined slot when their binding is set up.
	$effect.pre(() => {
		while (keyInputRefs.length < pairs.length) {
			keyInputRefs.push(null);
		}
	});
</script>

<div class={className}>
	<div class="mb-2 flex items-center justify-between">
		{#if sectionLabel}
			<span class="text-xs font-medium">
				{sectionLabel}
				{#if sectionLabelOptional}
					<span class="text-muted-foreground">(optional)</span>
				{/if}
			</span>
		{/if}

		<button
			type="button"
			class="inline-flex cursor-pointer items-center gap-1 rounded-md px-1.5 py-1 text-xs text-muted-foreground hover:bg-muted hover:text-foreground"
			onclick={addPair}
		>
			<Plus class="h-3 w-3" />
			{addButtonLabel}
		</button>
	</div>
	{#if pairs.length > 0}
		<div class="space-y-3">
			{#each pairs as pair, index (index)}
				<div class="flex items-start gap-2">
					<Input
						bind:ref={keyInputRefs[index]}
						type="text"
						placeholder={keyPlaceholder}
						value={pair.key}
						maxlength={KEY_VALUE_PAIR_KEY_MAX_LENGTH}
						oninput={(e) => updatePairKey(index, e.currentTarget.value)}
						onblur={(e) => trimPairKey(index, e.currentTarget.value)}
						class="flex-1"
					/>

					<textarea
						use:autoResizeTextarea
						placeholder={valuePlaceholder}
						value={pair.value}
						maxlength={KEY_VALUE_PAIR_VALUE_MAX_LENGTH}
						oninput={(e) => {
							updatePairValue(index, e.currentTarget.value);
							autoResizeTextarea(e.currentTarget);
						}}
						onblur={(e) => trimPairValue(index, e.currentTarget.value)}
						class="flex-1 resize-none rounded-md border border-input bg-transparent px-3 py-2 text-sm leading-5 placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none"
						rows="1"
					></textarea>

					<button
						type="button"
						class="mt-1.5 shrink-0 cursor-pointer rounded-md p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
						onclick={() => removePair(index)}
						aria-label="Remove item"
					>
						<Trash2 class="h-3.5 w-3.5" />
					</button>
				</div>
			{/each}
		</div>
	{:else}
		<p class="text-xs text-muted-foreground">{emptyMessage}</p>
	{/if}
</div>