{{>
  function treeToContent(tree) {
    return Array.from([
      ...tree.folders?.entries() || [],
      ...tree.files?.entries() || [],
    ]).sort(([a], [b]) => a.localeCompare(b));
  }
}}

{{ layout "layout.vto" { title: collection.label } }}
  {{ function folder(collection, content) }}
    {{ for entry of content }}
      {{> const [name, child] = entry }}

      {{ if "label" in child /* It's a file */ }}
        <li>
          <a
            href='{{ ["collection", collection.name, child.name, "edit"] |> path }}'
            class="list-item"
            title="{{ child.label |> escape }}"
          >
            {{ if child.icon }}
              <u-icon name="{{ child.icon }}"></u-icon>
            {{ else }}
              <u-icon-file path="{{ child.name }}"></u-icon-file>
            {{ /if }}
            <div class="list-item-header">
              {{ name }}
              {{ for key, value of child.flags }}
                <span title="{{ key }}" class="tag">{{ value }}</span>
              {{ /for }}
            </div>
          </a>
        </li>
      {{ else }}
        <li>
          {{ set subContent = treeToContent(child) }}
          <details class="accordion is-folder">
            <summary title="{{ subContent.length }} item(s)">
              {{ name }}
            </summary>
            <ul>
              {{ folder(collection, subContent) }}
            </ul>
          </details>
          <div class="list-actions">
            <a
              href='{{ ["collection", collection.name, "create"] |> path }}?folder={{ child.path }}'
              title='{{ t("document.list.action.create") |> escape }}'
              class="buttonIcon"
            >
              <u-icon name="plus-circle"></u-icon>
            </a>
          </div>
        </li>
      {{ /if }}
    {{ /for }}
  {{ /function }}

  <header class="header">
    {{ include "breadcrumb.vto" }}

    <h1 class="header-title">{{ collection.label }}</h1>

    {{ if collection.description }}
      <p class="header-description">{{ collection.description }}</p>
    {{ /if }}
  </header>

  {{ set content = folder(collection, treeToContent(tree)).trim() }}

  {{ if content }}
    <u-filter
      data-placeholder="Filter {{ collection.label }}"
      data-selector="#list > li"
    >
    </u-filter>
  {{ /if }}

  <nav class="navigation">
    {{ if user.canCreate(collection) }}
      <a
        href='{{ ["collection", collection.name, "create"] |> path }}'
        class="button is-primary"
      >
        <u-icon name="plus-circle"></u-icon>
        {{ t("document.list.action.add") }}
      </a>
    {{ /if }}
  </nav>

  {{ if content }}
    <u-tree data-name="collection-{{ collection.name }}">
      <ul id="list" class="list">{{ content }}</ul>
    </u-tree>
  {{ else }}
    <p class="emptyState">{{ t("document.list.empty") }}</p>
  {{ /if }}
{{ /layout }}
