# Prompt Input

Kotak tulis chat AI. Kolom tumbuh saat mengetik, berkas terlampir sebagai chip, Enter mengirim, Shift+Enter baris baru, tombol kirim berubah jadi stop.

- Kategori: MarkasUI
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/prompt-input.json
- CLI: `npx markasui@latest add prompt-input`

## Kapan dipakai

Kotak pesan asisten AI, chatbot, atau chat dukungan tempat orang menulis prompt dan melampirkan berkas.

- Set loading selama jawaban mengalir dan hentikan permintaan di onStop
- Jaga daftar model tetap pendek, dua sampai empat pilihan
- Letakkan di bawah percakapan, di bawah log ChatMessage
- Terjemahkan semua prop label bila halaman tidak berbahasa Inggris

## Kode

### Blade

Simpan di `resources/views/components/markas/prompt-input.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'value' => '',
    'loading' => false,
    'maxLength' => null,
    'maxHeight' => 200,
    'attachments' => true,
    'accept' => null,
    'models' => [],
    'model' => null,
    'placeholderLabel' => 'Ask anything',
    'inputLabel' => 'Message',
    'sendLabel' => 'Send',
    'stopLabel' => 'Stop',
    'attachLabel' => 'Attach files',
    'removeLabel' => 'Remove {name}',
    'modelLabel' => 'Model',
])

@php
    $root = 'grid gap-1 rounded-2xl border border-line bg-surface p-2 transition-colors duration-150 ease-out has-[textarea:focus-visible]:border-primary-line has-[textarea:focus-visible]:outline-2 has-[textarea:focus-visible]:outline-offset-2 has-[textarea:focus-visible]:outline-primary motion-reduce:transition-none';
    $chips = 'flex flex-wrap gap-1.5 px-1 pt-1';
    $chip = 'inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border border-line bg-subtle pr-1 pl-2 text-xs font-medium text-ink';
    $chipName = 'max-w-40 truncate';
    $chipRemove = 'grid size-5 shrink-0 place-items-center rounded text-muted transition-colors duration-150 ease-out hover:bg-line hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary motion-reduce:transition-none';
    $field = 'block min-h-10 w-full resize-none overflow-y-auto bg-transparent px-2 py-2 text-sm leading-6 text-ink outline-none field-sizing-content placeholder:text-faint';
    $bar = 'flex items-center gap-1';
    $iconButton = 'inline-flex size-8 shrink-0 items-center justify-center rounded-full text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none';
    $select = 'h-8 max-w-40 cursor-pointer truncate rounded-full bg-transparent px-2.5 text-xs font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none';
    $counter = 'ml-auto px-1.5 text-xs text-muted tabular-nums data-[state=limit]:text-danger';
    $send = 'group grid size-8 shrink-0 place-items-center rounded-full bg-primary text-on-primary transition-[background-color,opacity,scale] duration-150 ease-out hover:bg-primary-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-90 disabled:pointer-events-none disabled:opacity-30 motion-reduce:transition-none';
    $sendIcon = 'col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-50 group-data-[state=stop]:opacity-0 motion-reduce:transition-none';
    $stopIcon = 'col-start-1 row-start-1 size-3 scale-50 rounded-xs bg-current opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-100 group-data-[state=stop]:opacity-100 motion-reduce:transition-none';
    $icon = 'size-4';
    $smallIcon = 'size-3';

    $options = array_map(fn ($option) => is_array($option) ? $option : ['value' => $option, 'label' => $option], $models);
    $canSend = trim((string) $value) !== '' && ! $loading;
    $atLimit = $maxLength !== null && mb_strlen((string) $value) >= $maxLength;
@endphp

{{-- Enter or the send button dispatches send with { text, files }. While loading the button dispatches stop instead; it turns into submit during that click, so the click is prevented. --}}
<form
    x-data="{
        text: @js((string) $value),
        files: [],
        loading: @js((bool) $loading),
        max: @js($maxLength),
        get canSend() {
            return this.text.trim() !== '' && ! this.loading;
        },
        {{-- Browsers without field-sizing grow the textarea by hand. --}}
        grow() {
            const el = this.$refs.field;
            if (window.CSS?.supports?.('field-sizing', 'content')) return;
            el.style.height = 'auto';
            el.style.height = `${el.scrollHeight}px`;
        },
        submit() {
            if (! this.canSend) return;
            this.$dispatch('send', { text: this.text, files: this.files });
            this.text = '';
            this.files = [];
        },
        enter(event) {
            if (event.shiftKey || event.isComposing) return;
            event.preventDefault();
            this.$root.requestSubmit();
        },
        pick(event) {
            this.files = [...this.files, ...event.target.files];
            event.target.value = '';
        },
        remove(index) {
            this.files = this.files.filter((_, i) => i !== index);
            this.$refs.field.focus();
        },
    }"
    x-effect="text; $nextTick(() => grow())"
    x-on:submit.prevent="submit()"
    {{ $attributes->class([$root]) }}
>
    <template x-if="files.length > 0">
        <ul class="{{ $chips }}">
            <template x-for="(file, index) in files" x-bind:key="`${file.name}-${index}`">
                <li class="{{ $chip }}">
                    <span class="{{ $chipName }}" x-text="file.name"></span>
                    <button type="button" x-bind:aria-label="@js($removeLabel).replace('{name}', file.name)" x-on:click="remove(index)" class="{{ $chipRemove }}">
                        <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="{{ $smallIcon }}"><path d="M18 6 6 18M6 6l12 12" /></svg>
                    </button>
                </li>
            </template>
        </ul>
    </template>
    <textarea
        x-ref="field"
        x-model="text"
        rows="1"
        @if ($maxLength !== null) maxlength="{{ $maxLength }}" @endif
        aria-label="{{ $inputLabel }}"
        placeholder="{{ $placeholderLabel }}"
        style="max-height: {{ (int) $maxHeight }}px"
        x-on:keydown.enter="enter($event)"
        class="{{ $field }}"
    >{{ $value }}</textarea>
    <div class="{{ $bar }}">
        @if ($attachments)
            <button type="button" aria-label="{{ $attachLabel }}" x-on:click="$refs.files.click()" class="{{ $iconButton }}">
                <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="{{ $icon }}"><path d="m21 11-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6L15 7.6" /></svg>
            </button>
            <input x-ref="files" type="file" multiple hidden tabindex="-1" @if ($accept) accept="{{ $accept }}" @endif x-on:change="pick($event)" />
        @endif
        @if (count($options) > 0)
            <select aria-label="{{ $modelLabel }}" class="{{ $select }}">
                @foreach ($options as $option)
                    <option value="{{ $option['value'] }}" @selected($option['value'] === $model)>{{ $option['label'] }}</option>
                @endforeach
            </select>
        @endif
        {{ $__laravel_slots['actions'] ?? '' }}
        <span
            data-state="{{ $atLimit ? 'limit' : 'ok' }}"
            x-bind:data-state="max !== null && text.length >= max ? 'limit' : 'ok'"
            @if ($maxLength !== null) x-text="`${text.length}/${max}`" @endif
            class="{{ $counter }}"
        >{{ $maxLength !== null ? mb_strlen((string) $value).'/'.$maxLength : '' }}</span>
        <button
            type="{{ $loading ? 'button' : 'submit' }}"
            aria-label="{{ $loading ? $stopLabel : $sendLabel }}"
            data-state="{{ $loading ? 'stop' : 'send' }}"
            @disabled(! $canSend && ! $loading)
            x-bind:type="loading ? 'button' : 'submit'"
            x-bind:aria-label="loading ? @js($stopLabel) : @js($sendLabel)"
            x-bind:data-state="loading ? 'stop' : 'send'"
            x-bind:disabled="! loading && ! canSend"
            x-on:click="if (loading) { $event.preventDefault(); $dispatch('stop'); }"
            class="{{ $send }}"
        >
            <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="{{ $sendIcon }}"><path d="M12 19V5M6 11l6-6 6 6" /></svg>
            <span aria-hidden="true" class="{{ $stopIcon }}"></span>
        </button>
    </div>
</form>
```

```blade
<x-markas.prompt-input
    :models="['Markas Pro', 'Markas Mini']"
    model="Markas Pro"
    :max-length="2000"
    placeholder-label="Tanya apa saja"
    input-label="Pesan"
    send-label="Kirim"
    stop-label="Hentikan"
    attach-label="Lampirkan berkas"
    remove-label="Hapus {name}"
    x-on:send="tanya($event.detail.text, $event.detail.files); loading = true"
    x-on:stop="batal(); loading = false"
/>
```

### React

Simpan di `src/components/markas/PromptInput.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

import {
  useEffect,
  useRef,
  useState,
  type ComponentProps,
  type FormEvent,
  type KeyboardEvent,
  type MouseEvent,
  type ReactNode,
} from "react";

const root =
  "grid gap-1 rounded-2xl border border-line bg-surface p-2 transition-colors duration-150 ease-out has-[textarea:focus-visible]:border-primary-line has-[textarea:focus-visible]:outline-2 has-[textarea:focus-visible]:outline-offset-2 has-[textarea:focus-visible]:outline-primary motion-reduce:transition-none";
const chips = "flex flex-wrap gap-1.5 px-1 pt-1";
const chip =
  "inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border border-line bg-subtle pr-1 pl-2 text-xs font-medium text-ink";
const chipName = "max-w-40 truncate";
const chipRemove =
  "grid size-5 shrink-0 place-items-center rounded text-muted transition-colors duration-150 ease-out hover:bg-line hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary motion-reduce:transition-none";
const field =
  "block min-h-10 w-full resize-none overflow-y-auto bg-transparent px-2 py-2 text-sm leading-6 text-ink outline-none field-sizing-content placeholder:text-faint";
const bar = "flex items-center gap-1";
const iconButton =
  "inline-flex size-8 shrink-0 items-center justify-center rounded-full text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const select =
  "h-8 max-w-40 cursor-pointer truncate rounded-full bg-transparent px-2.5 text-xs font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const counter =
  "ml-auto px-1.5 text-xs text-muted tabular-nums data-[state=limit]:text-danger";
const send =
  "group grid size-8 shrink-0 place-items-center rounded-full bg-primary text-on-primary transition-[background-color,opacity,scale] duration-150 ease-out hover:bg-primary-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-90 disabled:pointer-events-none disabled:opacity-30 motion-reduce:transition-none";
const sendIcon =
  "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-50 group-data-[state=stop]:opacity-0 motion-reduce:transition-none";
const stopIcon =
  "col-start-1 row-start-1 size-3 scale-50 rounded-xs bg-current opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-100 group-data-[state=stop]:opacity-100 motion-reduce:transition-none";
const icon = "size-4";
const smallIcon = "size-3";

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

/** Browsers without field-sizing grow the textarea by hand. */
function grow(el: HTMLTextAreaElement | null) {
  if (!el || globalThis.CSS?.supports?.("field-sizing", "content")) return;
  el.style.height = "auto";
  el.style.height = `${el.scrollHeight}px`;
}

const Svg = ({ d, className }: { d: string; className: string }) => (
  <svg
    aria-hidden="true"
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="1.5"
    strokeLinecap="round"
    strokeLinejoin="round"
    className={className}
  >
    <path d={d} />
  </svg>
);

export type PromptInputValue = { text: string; files: File[] };
export type PromptInputModel = string | { value: string; label: string };

export type PromptInputProps = Omit<
  ComponentProps<"form">,
  "onSubmit" | "defaultValue"
> & {
  value?: string;
  defaultValue?: string;
  onValueChange?: (text: string) => void;
  /** Fires on the send button or Enter with the text and attached files. */
  onSend?: (value: PromptInputValue) => void;
  /** Fires when the stop button is pressed while loading. */
  onStop?: () => void;
  /** Turns the send button into a stop button. */
  loading?: boolean;
  /** Character limit. Shows a counter next to the send button. */
  maxLength?: number;
  /** Tallest the field grows before it scrolls, in px. */
  maxHeight?: number;
  /** Shows the attach button. */
  attachments?: boolean;
  accept?: string;
  /** Options of the small model picker on the left. */
  models?: PromptInputModel[];
  model?: string;
  onModelChange?: (model: string) => void;
  /** Extra tools on the left of the action row. */
  actions?: ReactNode;
  placeholderLabel?: string;
  inputLabel?: string;
  sendLabel?: string;
  stopLabel?: string;
  attachLabel?: string;
  /** Name of each remove button. Accepts {name}. */
  removeLabel?: string;
  modelLabel?: string;
};

export function PromptInput({
  value,
  defaultValue = "",
  onValueChange,
  onSend,
  onStop,
  loading = false,
  maxLength,
  maxHeight = 200,
  attachments = true,
  accept,
  models = [],
  model,
  onModelChange,
  actions,
  placeholderLabel = "Ask anything",
  inputLabel = "Message",
  sendLabel = "Send",
  stopLabel = "Stop",
  attachLabel = "Attach files",
  removeLabel = "Remove {name}",
  modelLabel = "Model",
  className,
  ...props
}: PromptInputProps) {
  const [inner, setInner] = useState(defaultValue);
  const [files, setFiles] = useState<File[]>([]);
  const fieldRef = useRef<HTMLTextAreaElement>(null);
  const fileRef = useRef<HTMLInputElement>(null);
  const text = value ?? inner;
  const canSend = text.trim() !== "" && !loading;

  useEffect(() => grow(fieldRef.current), [text]);

  const setText = (next: string) => {
    setInner(next);
    onValueChange?.(next);
  };
  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!canSend) return;
    onSend?.({ text, files });
    setText("");
    setFiles([]);
  };
  const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
    if (
      event.key !== "Enter" ||
      event.shiftKey ||
      event.nativeEvent.isComposing
    )
      return;
    event.preventDefault();
    event.currentTarget.form?.requestSubmit();
  };
  /** The button turns into submit during this click, so keep it from sending. */
  const stop = (event: MouseEvent<HTMLButtonElement>) => {
    event.preventDefault();
    onStop?.();
  };
  const remove = (index: number) => {
    setFiles((list) => list.filter((_, i) => i !== index));
    fieldRef.current?.focus();
  };

  return (
    <form onSubmit={handleSubmit} className={cx(root, className)} {...props}>
      {files.length > 0 && (
        <ul className={chips}>
          {files.map((file, index) => (
            <li key={`${file.name}-${index}`} className={chip}>
              <span className={chipName}>{file.name}</span>
              <button
                type="button"
                aria-label={removeLabel.replace("{name}", file.name)}
                className={chipRemove}
                onClick={() => remove(index)}
              >
                <Svg d="M18 6 6 18M6 6l12 12" className={smallIcon} />
              </button>
            </li>
          ))}
        </ul>
      )}
      <textarea
        ref={fieldRef}
        rows={1}
        value={text}
        maxLength={maxLength}
        aria-label={inputLabel}
        placeholder={placeholderLabel}
        style={{ maxHeight }}
        className={field}
        onChange={(event) => setText(event.target.value)}
        onKeyDown={handleKeyDown}
      />
      <div className={bar}>
        {attachments && (
          <>
            <button
              type="button"
              aria-label={attachLabel}
              className={iconButton}
              onClick={() => fileRef.current?.click()}
            >
              <Svg
                d="m21 11-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6L15 7.6"
                className={icon}
              />
            </button>
            <input
              ref={fileRef}
              type="file"
              multiple
              hidden
              tabIndex={-1}
              accept={accept}
              onChange={(event) => {
                const picked = Array.from(event.target.files ?? []);
                setFiles((list) => [...list, ...picked]);
                event.target.value = "";
              }}
            />
          </>
        )}
        {models.length > 0 && (
          <select
            aria-label={modelLabel}
            defaultValue={model}
            className={select}
            onChange={(event) => onModelChange?.(event.target.value)}
          >
            {models.map((option) => {
              const item =
                typeof option === "string"
                  ? { value: option, label: option }
                  : option;
              return (
                <option key={item.value} value={item.value}>
                  {item.label}
                </option>
              );
            })}
          </select>
        )}
        {actions}
        <span
          data-state={
            maxLength !== undefined && text.length >= maxLength ? "limit" : "ok"
          }
          className={counter}
        >
          {maxLength !== undefined ? `${text.length}/${maxLength}` : ""}
        </span>
        <button
          type={loading ? "button" : "submit"}
          aria-label={loading ? stopLabel : sendLabel}
          data-state={loading ? "stop" : "send"}
          disabled={!loading && !canSend}
          className={send}
          onClick={loading ? stop : undefined}
        >
          <Svg d="M12 19V5M6 11l6-6 6 6" className={sendIcon} />
          <span aria-hidden="true" className={stopIcon} />
        </button>
      </div>
    </form>
  );
}
```

```tsx
import { PromptInput } from "@/components/markas/PromptInput";

<PromptInput
  models={["Markas Pro", "Markas Mini"]}
  maxLength={2000}
  loading={loading}
  placeholderLabel="Tanya apa saja"
  inputLabel="Pesan"
  sendLabel="Kirim"
  stopLabel="Hentikan"
  attachLabel="Lampirkan berkas"
  removeLabel="Hapus {name}"
  onSend={({ text, files }) => tanya(text, files)}
  onStop={batal}
/>;
```

### Vue

Simpan di `src/components/markas/PromptInput.vue`. Tanpa dependensi tambahan.

```vue
<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";

export type PromptInputValue = { text: string; files: File[] };
export type PromptInputModel = string | { value: string; label: string };

const props = withDefaults(
  defineProps<{
    /** Turns the send button into a stop button. */
    loading?: boolean;
    /** Character limit. Shows a counter next to the send button. */
    maxLength?: number;
    /** Tallest the field grows before it scrolls, in px. */
    maxHeight?: number;
    /** Shows the attach button. */
    attachments?: boolean;
    accept?: string;
    /** Options of the small model picker on the left. */
    models?: PromptInputModel[];
    placeholderLabel?: string;
    inputLabel?: string;
    sendLabel?: string;
    stopLabel?: string;
    attachLabel?: string;
    /** Name of each remove button. Accepts {name}. */
    removeLabel?: string;
    modelLabel?: string;
  }>(),
  {
    loading: false,
    maxLength: undefined,
    maxHeight: 200,
    attachments: true,
    accept: undefined,
    models: () => [],
    placeholderLabel: "Ask anything",
    inputLabel: "Message",
    sendLabel: "Send",
    stopLabel: "Stop",
    attachLabel: "Attach files",
    removeLabel: "Remove {name}",
    modelLabel: "Model",
  },
);
const text = defineModel<string>({ default: "" });
const model = defineModel<string>("model");
const emit = defineEmits<{ send: [value: PromptInputValue]; stop: [] }>();

const root =
  "grid gap-1 rounded-2xl border border-line bg-surface p-2 transition-colors duration-150 ease-out has-[textarea:focus-visible]:border-primary-line has-[textarea:focus-visible]:outline-2 has-[textarea:focus-visible]:outline-offset-2 has-[textarea:focus-visible]:outline-primary motion-reduce:transition-none";
const chips = "flex flex-wrap gap-1.5 px-1 pt-1";
const chip =
  "inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border border-line bg-subtle pr-1 pl-2 text-xs font-medium text-ink";
const chipName = "max-w-40 truncate";
const chipRemove =
  "grid size-5 shrink-0 place-items-center rounded text-muted transition-colors duration-150 ease-out hover:bg-line hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary motion-reduce:transition-none";
const field =
  "block min-h-10 w-full resize-none overflow-y-auto bg-transparent px-2 py-2 text-sm leading-6 text-ink outline-none field-sizing-content placeholder:text-faint";
const bar = "flex items-center gap-1";
const iconButton =
  "inline-flex size-8 shrink-0 items-center justify-center rounded-full text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const select =
  "h-8 max-w-40 cursor-pointer truncate rounded-full bg-transparent px-2.5 text-xs font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const counter =
  "ml-auto px-1.5 text-xs text-muted tabular-nums data-[state=limit]:text-danger";
const send =
  "group grid size-8 shrink-0 place-items-center rounded-full bg-primary text-on-primary transition-[background-color,opacity,scale] duration-150 ease-out hover:bg-primary-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-90 disabled:pointer-events-none disabled:opacity-30 motion-reduce:transition-none";
const sendIcon =
  "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-50 group-data-[state=stop]:opacity-0 motion-reduce:transition-none";
const stopIcon =
  "col-start-1 row-start-1 size-3 scale-50 rounded-xs bg-current opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-100 group-data-[state=stop]:opacity-100 motion-reduce:transition-none";
const icon = "size-4";
const smallIcon = "size-3";

const files = ref<File[]>([]);
const fieldEl = ref<HTMLTextAreaElement>();
const fileEl = ref<HTMLInputElement>();
const canSend = computed(() => text.value.trim() !== "" && !props.loading);
const options = computed(() =>
  props.models.map((option) =>
    typeof option === "string" ? { value: option, label: option } : option,
  ),
);
const atLimit = computed(
  () => props.maxLength !== undefined && text.value.length >= props.maxLength,
);

/** Browsers without field-sizing grow the textarea by hand. */
function grow(el?: HTMLTextAreaElement) {
  if (!el || globalThis.CSS?.supports?.("field-sizing", "content")) return;
  el.style.height = "auto";
  el.style.height = `${el.scrollHeight}px`;
}
watch(text, () => nextTick(() => grow(fieldEl.value)));

function onSubmit() {
  if (!canSend.value) return;
  emit("send", { text: text.value, files: files.value });
  text.value = "";
  files.value = [];
}
function onKeydown(event: KeyboardEvent) {
  if (event.key !== "Enter" || event.shiftKey || event.isComposing) return;
  event.preventDefault();
  (event.target as HTMLTextAreaElement).form?.requestSubmit();
}
function onPick(event: Event) {
  const input = event.target as HTMLInputElement;
  files.value = [...files.value, ...Array.from(input.files ?? [])];
  input.value = "";
}
function remove(index: number) {
  files.value = files.value.filter((_, i) => i !== index);
  fieldEl.value?.focus();
}
/** The button turns into submit during this click, so keep it from sending. */
function onSendClick(event: MouseEvent) {
  if (!props.loading) return;
  event.preventDefault();
  emit("stop");
}
</script>

<template>
  <form :class="root" @submit.prevent="onSubmit">
    <ul v-if="files.length > 0" :class="chips">
      <li
        v-for="(file, index) in files"
        :key="`${file.name}-${index}`"
        :class="chip"
      >
        <span :class="chipName">{{ file.name }}</span>
        <button
          type="button"
          :aria-label="props.removeLabel.replace('{name}', file.name)"
          :class="chipRemove"
          @click="remove(index)"
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            :class="smallIcon"
          >
            <path d="M18 6 6 18M6 6l12 12" />
          </svg>
        </button>
      </li>
    </ul>
    <textarea
      ref="fieldEl"
      v-model="text"
      rows="1"
      :maxlength="props.maxLength"
      :aria-label="props.inputLabel"
      :placeholder="props.placeholderLabel"
      :style="{ maxHeight: `${props.maxHeight}px` }"
      :class="field"
      @keydown="onKeydown"
    />
    <div :class="bar">
      <template v-if="props.attachments">
        <button
          type="button"
          :aria-label="props.attachLabel"
          :class="iconButton"
          @click="fileEl?.click()"
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            :class="icon"
          >
            <path
              d="m21 11-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6L15 7.6"
            />
          </svg>
        </button>
        <input
          ref="fileEl"
          type="file"
          multiple
          hidden
          tabindex="-1"
          :accept="props.accept"
          @change="onPick"
        />
      </template>
      <select
        v-if="options.length > 0"
        v-model="model"
        :aria-label="props.modelLabel"
        :class="select"
      >
        <option v-for="item in options" :key="item.value" :value="item.value">
          {{ item.label }}
        </option>
      </select>
      <slot name="actions" />
      <span :data-state="atLimit ? 'limit' : 'ok'" :class="counter">{{
        props.maxLength !== undefined ? `${text.length}/${props.maxLength}` : ""
      }}</span>
      <button
        :type="props.loading ? 'button' : 'submit'"
        :aria-label="props.loading ? props.stopLabel : props.sendLabel"
        :data-state="props.loading ? 'stop' : 'send'"
        :disabled="!props.loading && !canSend"
        :class="send"
        @click="onSendClick"
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          :class="sendIcon"
        >
          <path d="M12 19V5M6 11l6-6 6 6" />
        </svg>
        <span aria-hidden="true" :class="stopIcon" />
      </button>
    </div>
  </form>
</template>
```

```vue
<script setup lang="ts">
import PromptInput from "@/components/markas/PromptInput.vue";
</script>

<template>
  <PromptInput
    :models="['Markas Pro', 'Markas Mini']"
    :max-length="2000"
    :loading="loading"
    placeholder-label="Tanya apa saja"
    input-label="Pesan"
    send-label="Kirim"
    stop-label="Hentikan"
    attach-label="Lampirkan berkas"
    remove-label="Hapus {name}"
    @send="({ text, files }) => tanya(text, files)"
    @stop="batal"
  />
</template>
```

### Svelte

Simpan di `src/lib/components/markas/PromptInput.svelte`. Tanpa dependensi tambahan.

```svelte
<script lang="ts" module>
  export type PromptInputValue = { text: string; files: File[] };
  export type PromptInputModel = string | { value: string; label: string };
</script>

<script lang="ts">
  import type { Snippet } from "svelte";
  import type { HTMLFormAttributes } from "svelte/elements";

  const root =
    "grid gap-1 rounded-2xl border border-line bg-surface p-2 transition-colors duration-150 ease-out has-[textarea:focus-visible]:border-primary-line has-[textarea:focus-visible]:outline-2 has-[textarea:focus-visible]:outline-offset-2 has-[textarea:focus-visible]:outline-primary motion-reduce:transition-none";
  const chips = "flex flex-wrap gap-1.5 px-1 pt-1";
  const chip =
    "inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border border-line bg-subtle pr-1 pl-2 text-xs font-medium text-ink";
  const chipName = "max-w-40 truncate";
  const chipRemove =
    "grid size-5 shrink-0 place-items-center rounded text-muted transition-colors duration-150 ease-out hover:bg-line hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary motion-reduce:transition-none";
  const field =
    "block min-h-10 w-full resize-none overflow-y-auto bg-transparent px-2 py-2 text-sm leading-6 text-ink outline-none field-sizing-content placeholder:text-faint";
  const bar = "flex items-center gap-1";
  const iconButton =
    "inline-flex size-8 shrink-0 items-center justify-center rounded-full text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
  const select =
    "h-8 max-w-40 cursor-pointer truncate rounded-full bg-transparent px-2.5 text-xs font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
  const counter =
    "ml-auto px-1.5 text-xs text-muted tabular-nums data-[state=limit]:text-danger";
  const send =
    "group grid size-8 shrink-0 place-items-center rounded-full bg-primary text-on-primary transition-[background-color,opacity,scale] duration-150 ease-out hover:bg-primary-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-90 disabled:pointer-events-none disabled:opacity-30 motion-reduce:transition-none";
  const sendIcon =
    "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-50 group-data-[state=stop]:opacity-0 motion-reduce:transition-none";
  const stopIcon =
    "col-start-1 row-start-1 size-3 scale-50 rounded-xs bg-current opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-100 group-data-[state=stop]:opacity-100 motion-reduce:transition-none";
  const icon = "size-4";
  const smallIcon = "size-3";

  /** Browsers without field-sizing grow the textarea by hand. */
  function grow(el: HTMLTextAreaElement | undefined) {
    if (!el || globalThis.CSS?.supports?.("field-sizing", "content")) return;
    el.style.height = "auto";
    el.style.height = `${el.scrollHeight}px`;
  }

  type Props = Omit<HTMLFormAttributes, "onsubmit"> & {
    /** Text in the field, bindable with bind:value. */
    value?: string;
    /** Fires on the send button or Enter with the text and attached files. */
    onSend?: (value: PromptInputValue) => void;
    /** Fires when the stop button is pressed while loading. */
    onStop?: () => void;
    /** Turns the send button into a stop button. */
    loading?: boolean;
    /** Character limit. Shows a counter next to the send button. */
    maxLength?: number;
    /** Tallest the field grows before it scrolls, in px. */
    maxHeight?: number;
    /** Shows the attach button. */
    attachments?: boolean;
    accept?: string;
    /** Options of the small model picker on the left. */
    models?: PromptInputModel[];
    /** Picked model, bindable with bind:model. */
    model?: string;
    /** Extra tools on the left of the action row. */
    actions?: Snippet;
    placeholderLabel?: string;
    inputLabel?: string;
    sendLabel?: string;
    stopLabel?: string;
    attachLabel?: string;
    /** Name of each remove button. Accepts {name}. */
    removeLabel?: string;
    modelLabel?: string;
  };

  let {
    value = $bindable(""),
    onSend,
    onStop,
    loading = false,
    maxLength,
    maxHeight = 200,
    attachments = true,
    accept,
    models = [],
    model = $bindable(),
    actions,
    placeholderLabel = "Ask anything",
    inputLabel = "Message",
    sendLabel = "Send",
    stopLabel = "Stop",
    attachLabel = "Attach files",
    removeLabel = "Remove {name}",
    modelLabel = "Model",
    class: className,
    ...rest
  }: Props = $props();

  let files = $state<File[]>([]);
  let fieldEl = $state<HTMLTextAreaElement>();
  let fileEl = $state<HTMLInputElement>();
  const canSend = $derived(value.trim() !== "" && !loading);
  const options = $derived(
    models.map((option) =>
      typeof option === "string" ? { value: option, label: option } : option,
    ),
  );
  const atLimit = $derived(
    maxLength !== undefined && value.length >= maxLength,
  );

  $effect(() => {
    void value;
    grow(fieldEl);
  });

  function onsubmit(event: SubmitEvent) {
    event.preventDefault();
    if (!canSend) return;
    onSend?.({ text: value, files });
    value = "";
    files = [];
  }

  function onkeydown(
    event: KeyboardEvent & { currentTarget: EventTarget & HTMLTextAreaElement },
  ) {
    if (event.key !== "Enter" || event.shiftKey || event.isComposing) return;
    event.preventDefault();
    event.currentTarget.form?.requestSubmit();
  }

  function onpick(
    event: Event & { currentTarget: EventTarget & HTMLInputElement },
  ) {
    const input = event.currentTarget;
    files = [...files, ...Array.from(input.files ?? [])];
    input.value = "";
  }

  function remove(index: number) {
    files = files.filter((_, i) => i !== index);
    fieldEl?.focus();
  }

  /** The button turns into submit during this click, so keep it from sending. */
  function onSendClick(event: MouseEvent) {
    if (!loading) return;
    event.preventDefault();
    onStop?.();
  }
</script>

<form {onsubmit} class={[root, className]} {...rest}>
  {#if files.length > 0}
    <ul class={chips}>
      {#each files as file, index (`${file.name}-${index}`)}
        <li class={chip}>
          <span class={chipName}>{file.name}</span>
          <button
            type="button"
            aria-label={removeLabel.replace("{name}", file.name)}
            class={chipRemove}
            onclick={() => remove(index)}
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              class={smallIcon}
            >
              <path d="M18 6 6 18M6 6l12 12" />
            </svg>
          </button>
        </li>
      {/each}
    </ul>
  {/if}
  <textarea
    bind:this={fieldEl}
    bind:value
    rows="1"
    maxlength={maxLength}
    aria-label={inputLabel}
    placeholder={placeholderLabel}
    style:max-height={`${maxHeight}px`}
    class={field}
    {onkeydown}></textarea>
  <div class={bar}>
    {#if attachments}
      <button
        type="button"
        aria-label={attachLabel}
        class={iconButton}
        onclick={() => fileEl?.click()}
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          class={icon}
        >
          <path
            d="m21 11-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6L15 7.6"
          />
        </svg>
      </button>
      <input
        bind:this={fileEl}
        type="file"
        multiple
        hidden
        tabindex="-1"
        {accept}
        onchange={onpick}
      />
    {/if}
    {#if options.length > 0}
      <select bind:value={model} aria-label={modelLabel} class={select}>
        {#each options as item (item.value)}
          <option value={item.value}>{item.label}</option>
        {/each}
      </select>
    {/if}
    {@render actions?.()}
    <span data-state={atLimit ? "limit" : "ok"} class={counter}
      >{maxLength !== undefined ? `${value.length}/${maxLength}` : ""}</span
    >
    <button
      type={loading ? "button" : "submit"}
      aria-label={loading ? stopLabel : sendLabel}
      data-state={loading ? "stop" : "send"}
      disabled={!loading && !canSend}
      class={send}
      onclick={onSendClick}
    >
      <svg
        aria-hidden="true"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        class={sendIcon}
      >
        <path d="M12 19V5M6 11l6-6 6 6" />
      </svg>
      <span aria-hidden="true" class={stopIcon}></span>
    </button>
  </div>
</form>
```

```svelte
<script lang="ts">
  import PromptInput from "$lib/components/markas/PromptInput.svelte";

  let text = $state("");
  let loading = $state(false);
</script>

<PromptInput
  bind:value={text}
  {loading}
  models={["Markas Pro", "Markas Mini"]}
  model="Markas Pro"
  onSend={({ text, files }) => (loading = true)}
  onStop={() => (loading = false)}
/>
```

### Astro

Simpan di `src/components/markas/PromptInput.astro`. Tanpa dependensi tambahan.

```astro
---
import type { HTMLAttributes } from "astro/types";

const root =
  "grid gap-1 rounded-2xl border border-line bg-surface p-2 transition-colors duration-150 ease-out has-[textarea:focus-visible]:border-primary-line has-[textarea:focus-visible]:outline-2 has-[textarea:focus-visible]:outline-offset-2 has-[textarea:focus-visible]:outline-primary motion-reduce:transition-none";
const chips = "flex flex-wrap gap-1.5 px-1 pt-1";
const chip =
  "inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border border-line bg-subtle pr-1 pl-2 text-xs font-medium text-ink";
const chipName = "max-w-40 truncate";
const chipRemove =
  "grid size-5 shrink-0 place-items-center rounded text-muted transition-colors duration-150 ease-out hover:bg-line hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary motion-reduce:transition-none";
const field =
  "block min-h-10 w-full resize-none overflow-y-auto bg-transparent px-2 py-2 text-sm leading-6 text-ink outline-none field-sizing-content placeholder:text-faint";
const bar = "flex items-center gap-1";
const iconButton =
  "inline-flex size-8 shrink-0 items-center justify-center rounded-full text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const select =
  "h-8 max-w-40 cursor-pointer truncate rounded-full bg-transparent px-2.5 text-xs font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const counter =
  "ml-auto px-1.5 text-xs text-muted tabular-nums data-[state=limit]:text-danger";
const send =
  "group grid size-8 shrink-0 place-items-center rounded-full bg-primary text-on-primary transition-[background-color,opacity,scale] duration-150 ease-out hover:bg-primary-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-90 disabled:pointer-events-none disabled:opacity-30 motion-reduce:transition-none";
const sendIcon =
  "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-50 group-data-[state=stop]:opacity-0 motion-reduce:transition-none";
const stopIcon =
  "col-start-1 row-start-1 size-3 scale-50 rounded-xs bg-current opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-100 group-data-[state=stop]:opacity-100 motion-reduce:transition-none";
const icon = "size-4";
const smallIcon = "size-3";

export type PromptInputModel = string | { value: string; label: string };

type Props = HTMLAttributes<"form"> & {
  /** Starting text. */
  value?: string;
  /** Turns the send button into a stop button. Toggle it later with the loading attribute on markas-prompt-input. */
  loading?: boolean;
  /** Character limit. Shows a counter next to the send button. */
  maxLength?: number;
  /** Tallest the field grows before it scrolls, in px. */
  maxHeight?: number;
  /** Shows the attach button. */
  attachments?: boolean;
  accept?: string;
  /** Options of the small model picker on the left. */
  models?: PromptInputModel[];
  model?: string;
  placeholderLabel?: string;
  inputLabel?: string;
  sendLabel?: string;
  stopLabel?: string;
  attachLabel?: string;
  /** Name of each remove button. Accepts {name}. */
  removeLabel?: string;
  modelLabel?: string;
};

const {
  value = "",
  loading = false,
  maxLength,
  maxHeight = 200,
  attachments = true,
  accept,
  models = [],
  model,
  placeholderLabel = "Ask anything",
  inputLabel = "Message",
  sendLabel = "Send",
  stopLabel = "Stop",
  attachLabel = "Attach files",
  removeLabel = "Remove {name}",
  modelLabel = "Model",
  class: className,
  ...rest
} = Astro.props;

const options = models.map((option) =>
  typeof option === "string" ? { value: option, label: option } : option,
);
const canSend = value.trim() !== "" && !loading;
const atLimit = maxLength !== undefined && value.length >= maxLength;
---

<markas-prompt-input
  class="contents"
  loading={loading ? "" : undefined}
  data-send-label={sendLabel}
  data-stop-label={stopLabel}
  data-remove-label={removeLabel}
>
  <form class:list={[root, className]} {...rest}>
    <ul class={chips} hidden>
      <template>
        <li class={chip}>
          <span class={chipName}></span>
          <button type="button" class={chipRemove}>
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              class={smallIcon}
            >
              <path d="M18 6 6 18M6 6l12 12"></path>
            </svg>
          </button>
        </li>
      </template>
    </ul>
    <textarea
      rows="1"
      maxlength={maxLength}
      aria-label={inputLabel}
      placeholder={placeholderLabel}
      style={`max-height: ${Number(maxHeight)}px`}
      class={field}>{value}</textarea>
    <div class={bar}>
      {
        attachments && (
          <>
            <button
              type="button"
              aria-label={attachLabel}
              class={iconButton}
              data-markas-attach
            >
              <svg
                aria-hidden="true"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                stroke-width="1.5"
                stroke-linecap="round"
                stroke-linejoin="round"
                class={icon}
              >
                <path d="m21 11-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6L15 7.6"></path>
              </svg>
            </button>
            <input type="file" multiple hidden tabindex="-1" accept={accept} />
          </>
        )
      }
      {
        options.length > 0 && (
          <select aria-label={modelLabel} class={select}>
            {options.map((item) => (
              <option value={item.value} selected={item.value === model}>
                {item.label}
              </option>
            ))}
          </select>
        )
      }
      <slot name="actions" />
      <span
        data-state={atLimit ? "limit" : "ok"}
        data-max={maxLength}
        class={counter}>{maxLength !== undefined ? `${value.length}/${maxLength}` : ""}</span>
      <button
        type={loading ? "button" : "submit"}
        aria-label={loading ? stopLabel : sendLabel}
        data-state={loading ? "stop" : "send"}
        disabled={!loading && !canSend}
        class={send}
        data-markas-send
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          class={sendIcon}
        >
          <path d="M12 19V5M6 11l6-6 6 6"></path>
        </svg>
        <span aria-hidden="true" class={stopIcon}></span>
      </button>
    </div>
  </form>
</markas-prompt-input>

<script>
  /** Browsers without field-sizing grow the textarea by hand. */
  function grow(el: HTMLTextAreaElement) {
    if (globalThis.CSS?.supports?.("field-sizing", "content")) return;
    el.style.height = "auto";
    el.style.height = `${el.scrollHeight}px`;
  }

  /**
   * Enter or the send button dispatches send with { text, files }. While loading the button
   * dispatches stop instead; it turns into submit during that click, so the click is prevented.
   * Set or remove the loading attribute to switch between the two.
   */
  class PromptInput extends HTMLElement {
    static observedAttributes = ["loading"];
    #files: File[] = [];
    #controller?: AbortController;

    get #form() {
      return this.querySelector("form");
    }

    get #field() {
      return this.querySelector("textarea");
    }

    get #loading() {
      return this.hasAttribute("loading");
    }

    connectedCallback() {
      const form = this.#form;
      const field = this.#field;
      if (!form || !field) return;
      this.#controller = new AbortController();
      const { signal } = this.#controller;
      field.addEventListener("input", () => this.#sync(), { signal });
      field.addEventListener(
        "keydown",
        (event) => {
          if (event.key !== "Enter" || event.shiftKey || event.isComposing)
            return;
          event.preventDefault();
          form.requestSubmit();
        },
        { signal },
      );
      form.addEventListener("submit", (event) => this.#submit(event), {
        signal,
      });
      form.addEventListener("click", (event) => this.#click(event), {
        signal,
      });
      form.addEventListener(
        "change",
        (event) => {
          const input = event.target;
          if (!(input instanceof HTMLInputElement) || input.type !== "file")
            return;
          this.#files = [...this.#files, ...Array.from(input.files ?? [])];
          input.value = "";
          this.#renderFiles();
        },
        { signal },
      );
      this.#sync();
    }

    disconnectedCallback() {
      this.#controller?.abort();
    }

    attributeChangedCallback() {
      this.#sync();
    }

    #submit(event: SubmitEvent) {
      event.preventDefault();
      const field = this.#field;
      if (!field || field.value.trim() === "" || this.#loading) return;
      this.dispatchEvent(
        new CustomEvent("send", {
          detail: { text: field.value, files: this.#files },
          bubbles: true,
        }),
      );
      field.value = "";
      this.#files = [];
      this.#renderFiles();
      this.#sync();
    }

    #click(event: MouseEvent) {
      const target = event.target as Element;
      if (target.closest("[data-markas-attach]")) {
        this.querySelector<HTMLInputElement>("input[type=file]")?.click();
        return;
      }
      const remove = target.closest<HTMLElement>("[data-index]");
      if (remove) {
        const index = Number(remove.dataset.index);
        this.#files = this.#files.filter((_, i) => i !== index);
        this.#renderFiles();
        this.#field?.focus();
        return;
      }
      if (target.closest("[data-markas-send]") && this.#loading) {
        event.preventDefault();
        this.dispatchEvent(new CustomEvent("stop", { bubbles: true }));
      }
    }

    #renderFiles() {
      const list = this.querySelector("ul");
      const template = list?.querySelector("template");
      if (!list || !template) return;
      for (const item of list.querySelectorAll("li")) item.remove();
      this.#files.forEach((file, index) => {
        const item = template.content.firstElementChild!.cloneNode(
          true,
        ) as HTMLElement;
        item.querySelector("span")!.textContent = file.name;
        const button = item.querySelector("button")!;
        button.dataset.index = String(index);
        button.setAttribute(
          "aria-label",
          (this.dataset.removeLabel ?? "").replace("{name}", file.name),
        );
        list.append(item);
      });
      list.hidden = this.#files.length === 0;
    }

    /** Update the counter and the send button from the text and the loading attribute. */
    #sync() {
      const field = this.#field;
      const button = this.querySelector<HTMLButtonElement>("[data-markas-send]");
      if (!field || !button) return;
      const loading = this.#loading;
      const text = field.value;
      button.type = loading ? "button" : "submit";
      button.setAttribute(
        "aria-label",
        (loading ? this.dataset.stopLabel : this.dataset.sendLabel) ?? "",
      );
      button.dataset.state = loading ? "stop" : "send";
      button.disabled = !loading && text.trim() === "";
      const counter = this.querySelector<HTMLElement>("[data-max]");
      if (counter) {
        const max = Number(counter.dataset.max);
        counter.textContent = `${text.length}/${max}`;
        counter.dataset.state = text.length >= max ? "limit" : "ok";
      }
      grow(field);
    }
  }

  if (!customElements.get("markas-prompt-input"))
    customElements.define("markas-prompt-input", PromptInput);
</script>
```

```astro
---
import PromptInput from "@/components/markas/PromptInput.astro";
---

<PromptInput models={["Markas Pro", "Markas Mini"]} model="Markas Pro" />

<script>
  const input = document.querySelector("markas-prompt-input");
  input?.addEventListener("send", () => input.toggleAttribute("loading", true));
  input?.addEventListener("stop", () => input.toggleAttribute("loading", false));
</script>
```

Script yang dibundel memancarkan `send` dengan `{ text, files }` dan `stop` di `markas-prompt-input`; pasang atau hapus atribut `loading`-nya untuk mengganti tombol.

### Angular

Simpan di `src/app/markas/prompt-input.component.ts`. Tanpa dependensi tambahan.

```ts
import {
  afterRenderEffect,
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  type ElementRef,
  input,
  model,
  numberAttribute,
  output,
  signal,
  viewChild,
} from "@angular/core";

const root =
  "grid gap-1 rounded-2xl border border-line bg-surface p-2 transition-colors duration-150 ease-out has-[textarea:focus-visible]:border-primary-line has-[textarea:focus-visible]:outline-2 has-[textarea:focus-visible]:outline-offset-2 has-[textarea:focus-visible]:outline-primary motion-reduce:transition-none";
const chips = "flex flex-wrap gap-1.5 px-1 pt-1";
const chip =
  "inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border border-line bg-subtle pr-1 pl-2 text-xs font-medium text-ink";
const chipName = "max-w-40 truncate";
const chipRemove =
  "grid size-5 shrink-0 place-items-center rounded text-muted transition-colors duration-150 ease-out hover:bg-line hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-primary motion-reduce:transition-none";
const field =
  "block min-h-10 w-full resize-none overflow-y-auto bg-transparent px-2 py-2 text-sm leading-6 text-ink outline-none field-sizing-content placeholder:text-faint";
const bar = "flex items-center gap-1";
const iconButton =
  "inline-flex size-8 shrink-0 items-center justify-center rounded-full text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const select =
  "h-8 max-w-40 cursor-pointer truncate rounded-full bg-transparent px-2.5 text-xs font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:transition-none";
const counter =
  "ml-auto px-1.5 text-xs text-muted tabular-nums data-[state=limit]:text-danger";
const send =
  "group grid size-8 shrink-0 place-items-center rounded-full bg-primary text-on-primary transition-[background-color,opacity,scale] duration-150 ease-out hover:bg-primary-strong focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:scale-90 disabled:pointer-events-none disabled:opacity-30 motion-reduce:transition-none";
const sendIcon =
  "col-start-1 row-start-1 size-4 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-50 group-data-[state=stop]:opacity-0 motion-reduce:transition-none";
const stopIcon =
  "col-start-1 row-start-1 size-3 scale-50 rounded-xs bg-current opacity-0 transition-[opacity,scale] duration-200 ease-out group-data-[state=stop]:scale-100 group-data-[state=stop]:opacity-100 motion-reduce:transition-none";
const icon = "size-4";
const smallIcon = "size-3";

/** Browsers without field-sizing grow the textarea by hand. */
function grow(el: HTMLTextAreaElement) {
  if (globalThis.CSS?.supports?.("field-sizing", "content")) return;
  el.style.height = "auto";
  el.style.height = `${el.scrollHeight}px`;
}

const toNumber = (value: unknown) =>
  value === undefined || value === null || value === ""
    ? undefined
    : numberAttribute(value);

export type PromptInputValue = { text: string; files: File[] };
export type PromptInputModel = string | { value: string; label: string };

/**
 * Supports [(value)] for the text and [(model)] for the picker. An element with the `actions`
 * attribute (an ng-container works) adds tools to the action row. The host stays out of layout;
 * the user's class lands on the form.
 */
@Component({
  selector: "markas-prompt-input",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents" },
  template: `
    <form [class]="classes()" (submit)="onSubmit($event)">
      @if (files().length > 0) {
        <ul [class]="chips">
          @for (file of files(); track $index) {
            <li [class]="chip">
              <span [class]="chipName">{{ file.name }}</span>
              <button
                type="button"
                [attr.aria-label]="removeName(file)"
                [class]="chipRemove"
                (click)="remove($index)"
              >
                <svg
                  aria-hidden="true"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  stroke-width="1.5"
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  [class]="smallIcon"
                >
                  <path d="M18 6 6 18M6 6l12 12" />
                </svg>
              </button>
            </li>
          }
        </ul>
      }
      <textarea
        #fieldEl
        rows="1"
        [value]="value()"
        [attr.maxlength]="maxLength() ?? null"
        [attr.aria-label]="inputLabel()"
        [attr.placeholder]="placeholderLabel()"
        [style.max-height.px]="maxHeight()"
        [class]="field"
        (input)="value.set(fieldEl.value)"
        (keydown)="onKeyDown($event)"
      ></textarea>
      <div [class]="bar">
        @if (attachments()) {
          <button
            type="button"
            [attr.aria-label]="attachLabel()"
            [class]="iconButton"
            (click)="fileEl.click()"
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              [class]="icon"
            >
              <path
                d="m21 11-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6L15 7.6"
              />
            </svg>
          </button>
          <input
            #fileEl
            type="file"
            multiple
            hidden
            tabindex="-1"
            [attr.accept]="accept() ?? null"
            (change)="onPick(fileEl)"
          />
        }
        @if (options().length > 0) {
          <select
            [attr.aria-label]="modelLabel()"
            [class]="select"
            (change)="model.set(selectEl.value)"
            #selectEl
          >
            @for (item of options(); track item.value) {
              <option [value]="item.value" [selected]="item.value === model()">
                {{ item.label }}
              </option>
            }
          </select>
        }
        <ng-content select="[actions]" />
        <span
          [attr.data-state]="atLimit() ? 'limit' : 'ok'"
          [class]="counter"
          >{{
            maxLength() !== undefined ? value().length + "/" + maxLength() : ""
          }}</span
        >
        <button
          [attr.type]="loading() ? 'button' : 'submit'"
          [attr.aria-label]="loading() ? stopLabel() : sendLabel()"
          [attr.data-state]="loading() ? 'stop' : 'send'"
          [disabled]="!loading() && !canSend()"
          [class]="sendClass"
          (click)="onSendClick($event)"
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            [class]="sendIcon"
          >
            <path d="M12 19V5M6 11l6-6 6 6" />
          </svg>
          <span aria-hidden="true" [class]="stopIcon"></span>
        </button>
      </div>
    </form>
  `,
})
export class PromptInput {
  /** Text in the field. */
  readonly value = model("");
  /** Turns the send button into a stop button. */
  readonly loading = input(false, { transform: booleanAttribute });
  /** Character limit. Shows a counter next to the send button. */
  readonly maxLength = input<number | undefined, unknown>(undefined, {
    transform: toNumber,
  });
  /** Tallest the field grows before it scrolls, in px. */
  readonly maxHeight = input(200, { transform: numberAttribute });
  /** Shows the attach button. */
  readonly attachments = input(true, { transform: booleanAttribute });
  readonly accept = input<string>();
  /** Options of the small model picker on the left. */
  readonly models = input<PromptInputModel[]>([]);
  /** Picked model. */
  readonly model = model<string>();
  readonly placeholderLabel = input("Ask anything");
  readonly inputLabel = input("Message");
  readonly sendLabel = input("Send");
  readonly stopLabel = input("Stop");
  readonly attachLabel = input("Attach files");
  /** Name of each remove button. Accepts {name}. */
  readonly removeLabel = input("Remove {name}");
  readonly modelLabel = input("Model");
  readonly userClass = input("", { alias: "class" });
  /** Fires on the send button or Enter with the text and attached files. */
  readonly send = output<PromptInputValue>();
  /** Fires when the stop button is pressed while loading. */
  readonly stop = output<void>();

  protected readonly chips = chips;
  protected readonly chip = chip;
  protected readonly chipName = chipName;
  protected readonly chipRemove = chipRemove;
  protected readonly field = field;
  protected readonly bar = bar;
  protected readonly iconButton = iconButton;
  protected readonly select = select;
  protected readonly counter = counter;
  protected readonly sendClass = send;
  protected readonly sendIcon = sendIcon;
  protected readonly stopIcon = stopIcon;
  protected readonly icon = icon;
  protected readonly smallIcon = smallIcon;

  protected readonly files = signal<File[]>([]);
  protected readonly classes = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
  protected readonly canSend = computed(
    () => this.value().trim() !== "" && !this.loading(),
  );
  protected readonly options = computed(() =>
    this.models().map((option) =>
      typeof option === "string" ? { value: option, label: option } : option,
    ),
  );
  protected readonly atLimit = computed(() => {
    const max = this.maxLength();
    return max !== undefined && this.value().length >= max;
  });
  private readonly fieldEl =
    viewChild.required<ElementRef<HTMLTextAreaElement>>("fieldEl");

  constructor() {
    afterRenderEffect(() => {
      this.value();
      grow(this.fieldEl().nativeElement);
    });
  }

  protected removeName(file: File) {
    return this.removeLabel().replace("{name}", file.name);
  }

  protected onSubmit(event: Event) {
    event.preventDefault();
    if (!this.canSend()) return;
    this.send.emit({ text: this.value(), files: this.files() });
    this.value.set("");
    this.files.set([]);
  }

  protected onKeyDown(event: KeyboardEvent) {
    if (event.key !== "Enter" || event.shiftKey || event.isComposing) return;
    event.preventDefault();
    (event.target as HTMLTextAreaElement).form?.requestSubmit();
  }

  protected onPick(input: HTMLInputElement) {
    this.files.update((list) => [...list, ...Array.from(input.files ?? [])]);
    input.value = "";
  }

  protected remove(index: number) {
    this.files.update((list) => list.filter((_, i) => i !== index));
    this.fieldEl().nativeElement.focus();
  }

  /** The button turns into submit during this click, so keep it from sending. */
  protected onSendClick(event: MouseEvent) {
    if (!this.loading()) return;
    event.preventDefault();
    this.stop.emit();
  }
}
```

```ts
import { Component, signal } from "@angular/core";
import {
  PromptInput,
  type PromptInputValue,
} from "./markas/prompt-input.component";

@Component({
  selector: "app-chat",
  imports: [PromptInput],
  template: `
    <markas-prompt-input
      [(value)]="text"
      [loading]="loading()"
      [models]="['Markas Pro', 'Markas Mini']"
      model="Markas Pro"
      (send)="onSend($event)"
      (stop)="loading.set(false)"
    />
  `,
})
export class Chat {
  readonly text = signal("");
  readonly loading = signal(false);
  onSend(value: PromptInputValue) {
    this.loading.set(true);
  }
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `value / v-model` | `string` | "" | Teks di kolom. React juga menerima defaultValue dan onValueChange. Dikosongkan setelah mengirim. |
| `onSend / @send / x-on:send` | `(value: { text: string; files: File[] }) => void` | - | Dipicu oleh Enter atau tombol kirim saat ada teks. Blade mengirim event DOM send dengan { text, files } sebagai detail. |
| `onStop / @stop / x-on:stop` | `() => void` | - | Dipicu saat tombol stop ditekan ketika loading. |
| `loading` | `boolean` | false | Jawaban sedang dibuat. Tombol kirim menjadi tombol stop dan Enter tidak lagi mengirim. |
| `maxLength` | `number` | - | Batas karakter kolom. Menampilkan penghitung 12/500 yang memerah saat mencapai batas. |
| `maxHeight` | `number` | 200 | Tinggi maksimum kolom dalam px sebelum bisa digulir. |
| `attachments` | `boolean` | true | Menampilkan tombol lampiran. Berkas terpilih tampil sebagai chip dengan tombol hapus. |
| `accept` | `string` | - | Jenis berkas untuk input file tersembunyi, misalnya image/*,.pdf. |
| `models` | `(string \| { value: string; label: string })[]` | [] | Pilihan pemilih model native kecil di kiri baris aksi. Kosong menyembunyikannya. |
| `model / v-model:model` | `string` | - | Model terpilih. React melaporkan perubahan lewat onModelChange, Blade memicu event change native. |
| `actions` | `ReactNode / slot` | - | Alat tambahan setelah pemilih model, misalnya toggle pencarian atau penalaran. Blade dan Vue memakai slot actions. |
| `placeholderLabel` | `string` | Ask anything | Placeholder kolom. Default "Ask anything", isi misalnya "Tanya apa saja". |
| `inputLabel` | `string` | Message | Nama aksesibel kolom. Default "Message", isi misalnya "Pesan". |
| `sendLabel` | `string` | Send | Nama aksesibel tombol kirim. Default "Send", isi misalnya "Kirim". |
| `stopLabel` | `string` | Stop | Nama aksesibel tombol saat loading. Default "Stop", isi misalnya "Hentikan". |
| `attachLabel` | `string` | Attach files | Nama aksesibel tombol lampiran. Default "Attach files", isi misalnya "Lampirkan berkas". |
| `removeLabel` | `string` | Remove {name} | Nama aksesibel tombol hapus tiap chip. {name} diganti nama berkas. Default "Remove {name}". |
| `modelLabel` | `string` | Model | Nama aksesibel pemilih model. Default "Model". |
| `(send) / (stop)` | `output` | - | Khusus Angular. Output untuk kirim dan berhenti; teks mendukung [(value)] dan pemilih [(model)]. Svelte memakai onSend, onStop, bind:value, dan bind:model. Astro memancarkan send dan stop di markas-prompt-input dan mengikuti atribut loading-nya. |

## Aksesibilitas

- Kolom adalah textarea native bernama inputLabel dengan maxlength native. Seluruh kotak menampilkan cincin fokus saat kolom difokus.
- Enter mengirim dan Shift+Enter menyisipkan baris baru. Enter diabaikan selama IME sedang menyusun huruf.
- Tombol kirim nonaktif sampai ada teks. Saat loading tombol tetap aktif dan bernama stopLabel.
- Input file tersembunyi dan dibuka oleh tombol lampiran. Setiap chip punya tombol hapus yang menyebut nama berkas, dan menghapus memindahkan fokus kembali ke kolom.

## Catatan

- Kolom tumbuh mengikuti isi sampai maxHeight, lalu bisa digulir. Memakai CSS field-sizing dan mengukur manual di browser lama.
- Enter mengirim, Shift+Enter menambah baris. Teks dan berkas terlampir dikosongkan setelah mengirim.
- Tombol kirim hanya aktif saat ada teks. Saat loading tombol berubah menjadi stop dan memicu stop.
- Di Blade handler x-on berjalan di dalam komponen, jadi `loading = true` di x-on:send langsung mengganti tombol menjadi stop.
