Skip to content

Prompt input ​

The message box of an AI chat: a growing textarea, file attachments, a model choice, suggestions and a send button that turns into stop.

Installation ​

bash
npx bootcn add prompt-input
bash
pnpm dlx bootcn add prompt-input
bash
yarn dlx bootcn add prompt-input
bash
bunx --bun bootcn add prompt-input

The CLI also installs the design tokens and these components: none. It prints the <link> and <script> tags to add to your layout.

Usage ​

Send the prompt to your server with fetch and show the reply in a Conversation:

js
document.addEventListener('bootcn:prompt-input:submit', async (event) => {
  event.preventDefault(); // handled here, no page load
  const form = event.target;
  Bootcn.promptInput.setBusy(form, true);
  const response = await fetch('/chat.php', { method: 'POST', body: event.detail.data });
  // ...append the reply...
  Bootcn.promptInput.setBusy(form, false);
});

For a page without JavaScript handling, give the form action, method="post" and enctype="multipart/form-data"; PHP receives $_POST['message'], $_POST['model'] and $_FILES['files'].

JavaScript API ​

  • data-bootcn-prompt-input on the <form>, with data-bootcn-prompt-textarea, data-bootcn-prompt-submit, and optionally data-bootcn-prompt-file (a native file input), data-bootcn-prompt-attachments (the list) and data-bootcn-prompt-status (a live region).
  • Enter sends, Shift + Enter adds a line; the textarea grows up to 12rem. The send button is disabled while there is no text and no file.
  • Attachments: choose files or drop them on the box. Each one is listed with its size and a remove button; the file input's FileList is kept in step, so a normal form post sends exactly the files shown.
  • Event bootcn:prompt-input:submit (bubbles, cancelable), detail: { text, files, data } (data is a FormData). A form without an action attribute is handled in JavaScript only and is cleared after the event. With an action, it posts normally (enctype="multipart/form-data") unless a listener calls event.preventDefault().
  • Bootcn.promptInput.setBusy(form, true) turns the send button into a stop button, which emits bootcn:prompt-input:stop.
  • Suggestion buttons (data-bootcn-prompt-suggestion) fill the textarea and emit bootcn:prompt-input:suggestion (detail.text).
  • clear(form), refresh(form), files(form), init() / destroy().

Accessibility ​

  • The textarea has a (visually hidden) label and a visible hint describing Enter and Shift + Enter.
  • The attach button is a native file input with a label, so it works with the keyboard and screen readers; attachments are a labelled list, each with a named remove button, and focus moves to the next one after a removal.
  • Attaching and removing files is announced in a live region.
  • The send button is named "Send", or "Stop" while busy.

Dependencies ​

  • Bootstrap 5.3+ CSS.
  • themes/tokens/tokens.css.

Source ​

The exact files the CLI installs (prompt-input@1.0.0). View on GitHub · Report an issue

html
<form class="bootcn-prompt-input" data-bootcn-prompt-input>
  <div class="bootcn-prompt-suggestions" role="group" aria-label="Suggestions">
    <button type="button" class="bootcn-prompt-suggestion" data-bootcn-prompt-suggestion>
      Write a sign-up form
    </button>
    <button type="button" class="bootcn-prompt-suggestion" data-bootcn-prompt-suggestion>
      Explain dark mode
    </button>
    <button type="button" class="bootcn-prompt-suggestion" data-bootcn-prompt-suggestion>
      Build a pricing table
    </button>
  </div>
  <div class="bootcn-prompt-input__box">
    <ul
      class="bootcn-prompt-input__attachments"
      aria-label="Attachments"
      data-bootcn-prompt-attachments
      hidden
    ></ul>
    <label class="visually-hidden" for="bootcn-prompt-message">Message</label>
    <textarea
      class="bootcn-prompt-input__textarea"
      id="bootcn-prompt-message"
      name="message"
      rows="1"
      placeholder="Ask anything…"
      aria-describedby="bootcn-prompt-hint"
      data-bootcn-prompt-textarea
    ></textarea>
    <div class="bootcn-prompt-input__toolbar">
      <input
        class="bootcn-prompt-input__file"
        type="file"
        id="bootcn-prompt-files"
        name="files[]"
        multiple
        data-bootcn-prompt-file
      />
      <label class="bootcn-prompt-input__tool" for="bootcn-prompt-files">
        <svg
          class="bootcn-icon"
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
          focusable="false"
        >
          <path
            d="m21 11-8.6 8.6a5 5 0 0 1-7.1-7.1l8.6-8.6a3.3 3.3 0 0 1 4.7 4.7l-8.6 8.6a1.7 1.7 0 0 1-2.4-2.4L16 7.4"
          />
        </svg>
        <span class="visually-hidden">Attach files</span>
      </label>
      <select class="form-select bootcn-prompt-input__model" name="model" aria-label="Model">
        <option value="fast">Fast</option>
        <option value="balanced" selected>Balanced</option>
        <option value="deep">Deep thinking</option>
      </select>
      <button
        type="submit"
        class="bootcn-prompt-input__submit"
        aria-label="Send"
        data-bootcn-prompt-submit
      >
        <svg
          class="bootcn-icon bootcn-prompt-input__send-icon"
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
          focusable="false"
        >
          <path d="m5 12 7-7 7 7" />
          <path d="M12 19V5" />
        </svg>
        <svg
          class="bootcn-icon bootcn-prompt-input__stop-icon"
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          aria-hidden="true"
          focusable="false"
        >
          <rect x="6" y="6" width="12" height="12" rx="1.5" fill="currentColor" />
        </svg>
      </button>
    </div>
  </div>
  <p class="bootcn-prompt-input__hint" id="bootcn-prompt-hint">
    Enter to send, Shift + Enter for a new line.
  </p>
  <p class="visually-hidden" role="status" data-bootcn-prompt-status></p>
</form>
css
.bootcn-prompt-input {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  width: 42rem;
  max-width: 100%;
}

.bootcn-prompt-suggestions {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.bootcn-prompt-suggestion {
  padding: 0.375rem 0.875rem;
  border: var(--bootcn-border-width) solid var(--bootcn-border-color);
  border-radius: 9999px;
  background-color: var(--bootcn-background);
  color: var(--bootcn-foreground);
  font-size: 0.8125rem;
}

.bootcn-prompt-suggestion:hover {
  background-color: var(--bootcn-accent);
}

.bootcn-prompt-suggestion:focus-visible {
  outline: 0;
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-prompt-input__box {
  display: flex;
  flex-direction: column;
  border: var(--bootcn-border-width) solid var(--bootcn-input);
  border-radius: var(--bootcn-radius-xl);
  background-color: var(--bootcn-background);
  box-shadow: var(--bootcn-shadow-sm);
  transition:
    border-color var(--bootcn-transition-duration) var(--bootcn-transition-timing),
    box-shadow var(--bootcn-transition-duration) var(--bootcn-transition-timing);
}

.bootcn-prompt-input__box:focus-within {
  border-color: var(--bootcn-ring);
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-prompt-input__box.is-dragging {
  border-style: dashed;
  border-color: var(--bootcn-ring);
  background-color: var(--bootcn-muted);
}

.bootcn-prompt-input__textarea {
  display: block;
  width: 100%;
  min-height: 3rem;
  max-height: 12rem;
  padding: 0.875rem 1rem 0.25rem;
  overflow-y: auto;
  border: 0;
  background: transparent;
  color: var(--bootcn-foreground);
  font-size: 0.9375rem;
  line-height: 1.5;
  resize: none;
  outline: 0;
}

.bootcn-prompt-input__textarea::placeholder {
  color: var(--bootcn-muted-foreground);
}

.bootcn-prompt-input__toolbar {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  padding: 0.5rem;
}

/* The file input stays focusable; its label is the visible button. */
.bootcn-prompt-input__file {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}

.bootcn-prompt-input__tool {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  border-radius: var(--bootcn-radius);
  color: var(--bootcn-muted-foreground);
  cursor: pointer;
}

.bootcn-prompt-input__tool:hover {
  background-color: var(--bootcn-accent);
  color: var(--bootcn-foreground);
}

.bootcn-prompt-input__file:focus-visible + .bootcn-prompt-input__tool {
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-prompt-input__model {
  width: auto;
  height: 2rem;
  padding: 0 2rem 0 0.625rem;
  border-color: transparent;
  background-color: transparent;
  background-position: right 0.5rem center;
  color: var(--bootcn-muted-foreground);
  font-size: 0.8125rem;
  font-weight: 500;
}

.bootcn-prompt-input__model:hover {
  background-color: var(--bootcn-accent);
  color: var(--bootcn-foreground);
}

.bootcn-prompt-input__model:focus {
  border-color: transparent;
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-prompt-input__submit {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 2rem;
  height: 2rem;
  margin-left: auto;
  border: 0;
  border-radius: 9999px;
  background-color: var(--bootcn-primary);
  color: var(--bootcn-primary-foreground);
}

.bootcn-prompt-input__submit:hover {
  opacity: 0.9;
}

.bootcn-prompt-input__submit:focus-visible {
  outline: 0;
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-prompt-input__submit:disabled {
  opacity: 0.5;
}

.bootcn-prompt-input__stop-icon,
.bootcn-prompt-input.is-busy .bootcn-prompt-input__send-icon {
  display: none;
}

.bootcn-prompt-input.is-busy .bootcn-prompt-input__stop-icon {
  display: inline-block;
}

.bootcn-prompt-input__hint {
  margin: 0;
  color: var(--bootcn-muted-foreground);
  font-size: 0.75rem;
  text-align: center;
}

/* Attachments */
.bootcn-prompt-input__attachments {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin: 0;
  padding: 0.75rem 0.75rem 0;
  list-style: none;
}

.bootcn-prompt-input__attachments[hidden] {
  display: none;
}

.bootcn-prompt-attachment {
  display: inline-flex;
  align-items: center;
  gap: 0.5rem;
  max-width: 16rem;
  padding: 0.25rem 0.25rem 0.25rem 0.625rem;
  border: var(--bootcn-border-width) solid var(--bootcn-border-color);
  border-radius: var(--bootcn-radius);
  background-color: var(--bootcn-muted);
  font-size: 0.8125rem;
}

.bootcn-prompt-attachment__name {
  overflow: hidden;
  font-weight: 500;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.bootcn-prompt-attachment__size {
  flex: none;
  color: var(--bootcn-muted-foreground);
}

.bootcn-prompt-attachment__remove {
  display: inline-flex;
  flex: none;
  align-items: center;
  justify-content: center;
  width: 1.5rem;
  height: 1.5rem;
  border: 0;
  border-radius: var(--bootcn-radius-sm);
  background: transparent;
  color: var(--bootcn-muted-foreground);
}

.bootcn-prompt-attachment__remove:hover {
  background-color: var(--bootcn-accent);
  color: var(--bootcn-foreground);
}

.bootcn-prompt-attachment__remove:focus-visible {
  outline: 0;
  box-shadow: var(--bootcn-focus-ring);
}

.bootcn-prompt-attachment__remove .bootcn-icon {
  width: 0.875rem;
  height: 0.875rem;
}

@media (prefers-reduced-motion: reduce) {
  .bootcn-prompt-input__box {
    transition: none;
  }
}
js
(function () {
  'use strict';

  const ns = (window.Bootcn = window.Bootcn || {});
  if (ns.promptInput) return; // already loaded: idempotent

  const ROOT = '[data-bootcn-prompt-input]';
  const REMOVE_ICON =
    '<svg class="bootcn-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" ' +
    'stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ' +
    'aria-hidden="true" focusable="false"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
  const attached = new WeakMap(); // form -> File[]
  let listening = false;

  function parts(form) {
    return {
      textarea: form.querySelector('[data-bootcn-prompt-textarea]'),
      file: form.querySelector('[data-bootcn-prompt-file]'),
      list: form.querySelector('[data-bootcn-prompt-attachments]'),
      submit: form.querySelector('[data-bootcn-prompt-submit]'),
      status: form.querySelector('[data-bootcn-prompt-status]'),
    };
  }

  function filesOf(form) {
    if (!attached.has(form)) attached.set(form, []);
    return attached.get(form);
  }

  function announce(form, text) {
    const region = parts(form).status;
    if (!region) return;
    region.textContent = '';
    setTimeout(function () {
      region.textContent = text;
    }, 50);
  }

  function formatSize(bytes) {
    if (bytes < 1024) return bytes + ' B';
    if (bytes < 1024 * 1024) return Math.round(bytes / 1024) + ' KB';
    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
  }

  function resize(textarea) {
    if (!textarea) return;
    textarea.style.height = 'auto';
    textarea.style.height = textarea.scrollHeight + 'px';
  }

  function isBusy(form) {
    return form.classList.contains('is-busy');
  }

  function sync(form) {
    const p = parts(form);
    if (!p.submit || isBusy(form)) return;
    const empty = !(p.textarea && p.textarea.value.trim()) && filesOf(form).length === 0;
    p.submit.disabled = empty;
  }

  // Keeps the file input's FileList equal to the attachment list, so a
  // normal form post sends exactly the files shown.
  function syncInput(form) {
    const input = parts(form).file;
    if (!input || typeof DataTransfer === 'undefined') return;
    try {
      const transfer = new DataTransfer();
      filesOf(form).forEach(function (file) {
        transfer.items.add(file);
      });
      input.files = transfer.files;
    } catch {
      // Older browsers: the list is still shown; the input keeps its own files.
    }
  }

  function render(form) {
    const p = parts(form);
    if (!p.list) return;
    p.list.replaceChildren();
    filesOf(form).forEach(function (file, index) {
      const item = document.createElement('li');
      item.className = 'bootcn-prompt-attachment';
      const name = document.createElement('span');
      name.className = 'bootcn-prompt-attachment__name';
      name.textContent = file.name;
      const size = document.createElement('span');
      size.className = 'bootcn-prompt-attachment__size';
      size.textContent = formatSize(file.size);
      const remove = document.createElement('button');
      remove.type = 'button';
      remove.className = 'bootcn-prompt-attachment__remove';
      remove.setAttribute('aria-label', 'Remove ' + file.name);
      remove.setAttribute('data-bootcn-prompt-remove', String(index));
      remove.innerHTML = REMOVE_ICON;
      item.append(name, size, remove);
      p.list.appendChild(item);
    });
    p.list.hidden = filesOf(form).length === 0;
    syncInput(form);
    sync(form);
  }

  function addFiles(form, fileList) {
    const files = filesOf(form);
    const added = [];
    Array.from(fileList || []).forEach(function (file) {
      const duplicate = files.some(function (other) {
        return (
          other.name === file.name &&
          other.size === file.size &&
          other.lastModified === file.lastModified
        );
      });
      if (!duplicate) {
        files.push(file);
        added.push(file.name);
      }
    });
    render(form);
    if (added.length === 1) announce(form, added[0] + ' attached.');
    else if (added.length > 1) announce(form, added.length + ' files attached.');
  }

  function removeFile(form, index) {
    const files = filesOf(form);
    const file = files[index];
    if (!file) return;
    files.splice(index, 1);
    render(form);
    const buttons = form.querySelectorAll('[data-bootcn-prompt-remove]');
    const next = buttons[index] || buttons[index - 1];
    if (next) next.focus();
    else if (parts(form).file) parts(form).file.focus();
    announce(form, file.name + ' removed.');
  }

  function clear(form) {
    const p = parts(form);
    if (p.textarea) {
      p.textarea.value = '';
      resize(p.textarea);
    }
    attached.set(form, []);
    render(form);
  }

  function setBusy(form, busy) {
    const p = parts(form);
    form.classList.toggle('is-busy', busy);
    if (p.submit) {
      p.submit.setAttribute('aria-label', busy ? 'Stop' : 'Send');
      p.submit.type = busy ? 'button' : 'submit';
      if (busy) p.submit.disabled = false;
    }
    sync(form);
  }

  function onInput(event) {
    const textarea = event.target;
    if (!textarea.matches || !textarea.matches('[data-bootcn-prompt-textarea]')) return;
    const form = textarea.closest(ROOT);
    if (!form) return;
    resize(textarea);
    sync(form);
  }

  function onKeydown(event) {
    const textarea = event.target;
    if (!textarea.matches || !textarea.matches('[data-bootcn-prompt-textarea]')) return;
    if (event.key !== 'Enter' || event.shiftKey || event.isComposing) return;
    const form = textarea.closest(ROOT);
    if (!form) return;
    event.preventDefault();
    const submit = parts(form).submit;
    if (!isBusy(form) && submit && !submit.disabled) form.requestSubmit(submit);
  }

  function onChange(event) {
    const input = event.target;
    if (!input.matches || !input.matches('[data-bootcn-prompt-file]')) return;
    const form = input.closest(ROOT);
    if (form) addFiles(form, input.files);
  }

  function onClick(event) {
    const target = event.target.closest && event.target.closest(ROOT + ' button');
    if (!target) return;
    const form = target.closest(ROOT);
    if (target.hasAttribute('data-bootcn-prompt-remove')) {
      removeFile(form, Number(target.getAttribute('data-bootcn-prompt-remove')));
    } else if (target.hasAttribute('data-bootcn-prompt-suggestion')) {
      const textarea = parts(form).textarea;
      if (!textarea) return;
      textarea.value = target.textContent.trim();
      resize(textarea);
      sync(form);
      textarea.focus();
      textarea.setSelectionRange(textarea.value.length, textarea.value.length);
      form.dispatchEvent(
        new CustomEvent('bootcn:prompt-input:suggestion', {
          bubbles: true,
          detail: { text: textarea.value },
        }),
      );
    } else if (target.hasAttribute('data-bootcn-prompt-submit') && isBusy(form)) {
      form.dispatchEvent(new CustomEvent('bootcn:prompt-input:stop', { bubbles: true }));
    }
  }

  // A form without an action attribute is handled in JavaScript only.
  // With an action, it posts normally unless a listener of
  // bootcn:prompt-input:submit calls preventDefault().
  function onSubmit(event) {
    const form = event.target;
    if (!form.matches || !form.matches(ROOT)) return;
    const p = parts(form);
    const text = p.textarea ? p.textarea.value.trim() : '';
    const files = filesOf(form).slice();
    if (isBusy(form) || (!text && files.length === 0)) {
      event.preventDefault();
      return;
    }
    const custom = new CustomEvent('bootcn:prompt-input:submit', {
      bubbles: true,
      cancelable: true,
      detail: { text: text, files: files, data: new FormData(form) },
    });
    const handled = !form.dispatchEvent(custom);
    if (handled || !form.hasAttribute('action')) {
      event.preventDefault();
      clear(form);
      if (p.textarea) p.textarea.focus();
    }
  }

  function dropZone(event) {
    const box = event.target.closest && event.target.closest(ROOT + ' .bootcn-prompt-input__box');
    if (!box || !event.dataTransfer || !Array.from(event.dataTransfer.types).includes('Files')) {
      return null;
    }
    const form = box.closest(ROOT);
    return parts(form).file ? box : null;
  }

  function onDragOver(event) {
    const box = dropZone(event);
    if (!box) return;
    event.preventDefault();
    box.classList.add('is-dragging');
  }

  function onDragLeave(event) {
    const box = event.target.closest && event.target.closest(ROOT + ' .bootcn-prompt-input__box');
    if (box && !box.contains(event.relatedTarget)) box.classList.remove('is-dragging');
  }

  function onDrop(event) {
    const box = dropZone(event);
    if (!box) return;
    event.preventDefault();
    box.classList.remove('is-dragging');
    addFiles(box.closest(ROOT), event.dataTransfer.files);
  }

  function refresh(form) {
    resize(parts(form).textarea);
    sync(form);
  }

  const handlers = [
    ['input', onInput],
    ['keydown', onKeydown],
    ['change', onChange],
    ['click', onClick],
    ['submit', onSubmit],
    ['dragover', onDragOver],
    ['dragleave', onDragLeave],
    ['drop', onDrop],
  ];

  function init() {
    if (!listening) {
      handlers.forEach(function (pair) {
        document.addEventListener(pair[0], pair[1]);
      });
      listening = true;
    }
    document.querySelectorAll(ROOT).forEach(refresh);
  }

  function destroy() {
    if (!listening) return;
    handlers.forEach(function (pair) {
      document.removeEventListener(pair[0], pair[1]);
    });
    listening = false;
  }

  ns.promptInput = {
    init: init,
    destroy: destroy,
    setBusy: setBusy,
    clear: clear,
    refresh: refresh,
    files: function (form) {
      return filesOf(form).slice();
    },
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

Released under the MIT License. Not affiliated with Bootstrap or shadcn/ui.