<template>
    <TreeRoot v-slot="{ flattenItems }" class="list-none select-none text-light-100 dark:text-dark-100 text-sm" :items="model" :get-key="getKey" :defaultExpanded="flatten(model)">
        <TreeItem v-for="item in flattenItems" v-slot="{ isExpanded }" :key="item._id" :style="{ 'padding-left': `${item.level / 2 - 0.5}em` }" v-bind="item.bind" class="flex items-center ps-2 outline-none relative cursor-pointer">
            <slot :isExpanded="isExpanded" :item="item" />
        </TreeItem>
    </TreeRoot>
</template>

<script setup lang="ts" generic="T extends Record<string, any>">
const { getKey } = defineProps<{
    getKey: (val: T) => string
}>();

const model = defineModel<T[]>();

function flatten(arr: T[]): string[]
{
    return arr.filter(e => e.open).flatMap(e => [getKey(e), ...flatten(e.children ?? [])]);
}
</script>