<svelte:options accessors={true} />

<script lang="ts">
	import type { Gradio } from "@gradio/utils";
	import { File } from "@gradio/icons";
	import type { FolderNode } from "./shared/types";
	import { Block, BlockLabel } from "@gradio/atoms";
	import DirectoryExplorer from "./shared/DirectoryExplorer.svelte";

	import { StatusTracker } from "@gradio/statustracker";
	import type { LoadingStatus } from "@gradio/statustracker";

	export let elem_id = "";
	export let elem_classes: string[] = [];
	export let visible: boolean | "hidden" = true;
	export let value: string[][] | null;
	let old_value: string[][] | null;
	export let label: string;
	export let show_label: boolean;
	export let height: number | string | undefined;
	export let min_height: number | string | undefined;
	export let max_height: number | string | undefined;
	export let loading_status: LoadingStatus;
	export let container = true;
	export let scale: number | null = null;
	export let min_width: number | undefined = undefined;
	export let gradio: Gradio<{
		change: never;
		clear_status: LoadingStatus;
	}>;
	export let server: {
		ls: (path: string[]) => Promise<FolderNode[]>;
	};
	export let interactive: boolean;

	// Dispatch the 'change' event to Gradio's backend whenever the `value` prop changes.
	$: if (JSON.stringify(value) !== JSON.stringify(old_value)) {
		old_value = value;
		gradio.dispatch("change");
	}
</script>

<Block
	{visible}
	variant={"solid"}
	border_mode={"base"}
	padding={false}
	{elem_id}
	{elem_classes}
	{container}
	{scale}
	{min_width}
	allow_overflow={false}
	{height}
	{max_height}
	{min_height}
>
	<StatusTracker
		{...loading_status}
		autoscroll={gradio.autoscroll}
		i18n={gradio.i18n}
		on:clear_status={() => gradio.dispatch("clear_status", loading_status)}
	/>

	<BlockLabel
		{show_label}
		Icon={File}
		label={label || "FolderExplorer"}
		float={false}
	/>
	
	<div class="body-wrap">		
		<DirectoryExplorer
			bind:value
			{interactive}
			ls_fn={server.ls}
		/>
	</div>
</Block>

<style>
	/* Ensures the block fills the available vertical space. */
	:global(.gradio-block.padded) {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	/* The main content area that scrolls if the content overflows. */
	.body-wrap {
		flex-grow: 1;
		overflow-y: auto;
		min-height: 0;
	}
</style>