<script lang="ts">
  import Icon from "../layout/Icon.svelte";

  export let value: string[];
  export let exclaimMode = false;

  let nextTag = "";

  function onKey(ev: KeyboardEvent) {
    if ((ev.metaKey||ev.ctrlKey) && nextTag === "" && ev.key === "Backspace") {
      value = value.slice(0, -1);
    }

    if ((ev.metaKey||ev.ctrlKey) && nextTag !== "" && ev.key === "Enter") {
      value = [...value, nextTag];
      nextTag = "";
      ev.preventDefault();
    }
  }

  $: while (nextTag.includes(",")) {
    const newTags = nextTag.split(",").map(t => t.trim());
    value = [...value, ...newTags.slice(0, -1)];
    nextTag = newTags[newTags.length - 1];
  }

  $: value = (value||[]).filter((e, i) => !value.slice(0, i).includes(e));

  $: if (exclaimMode) {
    value = (value||[]).filter((e, i) => (
      e.startsWith("!")
        ? !value.slice(i+1).includes(e.slice(1))
        : !value.slice(i+1).includes("!"+e)
    ));
  }
</script>

<div class="tag-input">
  {#each value as tag (tag)}
    <div class="tag">
      <span>{tag}</span>
      <span class="comma">,</span>
      <span class="x" on:click={() => value = value.filter(v => v !== tag)}>
        <Icon name="times" />
      </span>
    </div>
  {/each}
  <input placeholder="Add tag (type , or press Ctrl+Enter to add)" on:keyup={onKey} bind:value={nextTag} />
</div>

<style lang="sass">
  @import "../../css/colors"

  div.tag-input
    width: calc(100% - 2ch)
    margin-bottom: 1em
    margin-top: 0.20em
    min-height: 2em

    background: $color-entryhalf
    color: $color-entry8
    border: none
    outline: none
    resize: vertical
    padding: 0.5em 1ch

    display: flex
    flex-direction: row
    flex-wrap: wrap

    > div.tag
      margin: 0.25em 0.5ch
      background-color: $color-entry1
      padding: 0.25em 1ch
      border-radius: 0.25em

      span.x
        font-size: 0.75em
        line-height: 1em
        user-select: none
        cursor: pointer

        &:hover
          color: $color-entry12

      span.comma
        font-size: 0

    > input
      margin-bottom: 0.125em
</style>