import { PathId } from "../../routes.js";
import { useActiveEntities } from "../../store/active-entities.js";
import { useLayout } from "../../hooks/useLayout.js";
import { useSidebar } from "../../hooks/useSidebar.js";
import { createInitialRequest } from "../../store/requests.js";
import { useWorkspace } from "../../store/store.js";
import HttpMethod_default from "../../components/HttpMethod/HttpMethod.vue.js";
import Sidebar_default from "../../components/Sidebar/Sidebar.vue.js";
import ScalarAsciiArt_default from "../../components/ScalarAsciiArt.vue.js";
import rabbit_default from "../../assets/rabbit.ascii.virtual.js";
import rabbitjump_default from "../../assets/rabbitjump.ascii.virtual.js";
import WorkspaceDropdown_default from "./components/WorkspaceDropdown.vue.js";
import SidebarButton_default from "../../components/Sidebar/SidebarButton.vue.js";
import EnvironmentSelector_default from "../../components/EnvironmentSelector/EnvironmentSelector.vue.js";
import { useSearch } from "../../components/Search/useSearch.js";
import { dragHandlerFactory } from "./handle-drag.js";
import RequestSidebarItemMenu_default from "./RequestSidebarItemMenu.vue.js";
import { isGettingStarted } from "./RequestSection/helpers/getting-started.js";
import RequestSidebarItem_default from "./RequestSidebarItem.vue.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, isRef, normalizeClass, onBeforeUnmount, onMounted, openBlock, reactive, ref, renderList, toDisplayString, unref, useId, vShow, watch, withCtx, withDirectives, withKeys, withModifiers } from "vue";
import { ScalarButton, ScalarIcon, ScalarSearchResultItem, ScalarSearchResultList, ScalarSidebarSearchInput } from "@scalar/components";
import { useToasts } from "@scalar/use-toasts";
import { useRouter } from "vue-router";
import { LibraryIcon } from "@scalar/icons/library";
//#region src/views/Request/RequestSidebar.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "bg-b-1 sticky top-0 z-20 flex h-12 items-center px-3" };
var _hoisted_2 = {
	key: 1,
	class: "text-c-3"
};
var _hoisted_3 = ["aria-pressed"];
var _hoisted_4 = { class: "sr-only" };
var _hoisted_5 = {
	key: 0,
	class: "search-button-fade sticky top-12 z-10 px-3 py-2.5 pt-0 focus-within:z-20",
	role: "search"
};
var _hoisted_6 = {
	key: 1,
	class: "contents"
};
var _hoisted_7 = {
	key: 0,
	class: "empty-sidebar-item-content px-2.5 py-2.5"
};
var _hoisted_8 = { class: "rabbit-ascii relative m-auto mt-2 h-[68px] w-[60px]" };
var RequestSidebar_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */ defineComponent({
	__name: "RequestSidebar",
	emits: ["newTab", "clearDrafts"],
	setup(__props, { emit: __emit }) {
		const emit = __emit;
		const { isSidebarOpen, setCollapsedSidebarFolder, toggleSidebarOpen } = useSidebar();
		const { layout } = useLayout();
		const workspaceContext = useWorkspace();
		const { activeCollection, activeWorkspaceCollections, activeRequest, activeWorkspaceRequests, activeWorkspace } = useActiveEntities();
		const { findRequestParents, events, requestMutators, requests } = workspaceContext;
		const { handleDragEnd, isDroppable } = dragHandlerFactory(activeWorkspace, workspaceContext);
		const { replace } = useRouter();
		const openCommandPaletteImport = () => {
			events.commandPalette.emit({ commandName: "Import from OpenAPI/Swagger/Postman/cURL" });
		};
		const searchResultsId = useId();
		const { toast } = useToasts();
		/** The currently selected sidebarMenuItem for the context menu */
		const menuItem = reactive({ open: false });
		const isSearchVisible = ref(false);
		/** Watch to see if activeRequest changes and ensure we open any folders */
		watch(activeRequest, (request) => {
			if (!request) return;
			findRequestParents(request).forEach((uid) => setCollapsedSidebarFolder(uid, true));
		}, { immediate: true });
		const { searchText, searchResultsWithPlaceholderResults, selectedSearchResult, onSearchResultClick, fuseSearch, searchInputRef, searchResultRefs, navigateSearchResults, selectSearchResult } = useSearch();
		const searchToggleRef = ref();
		/** Handle hotkey events from the bus */
		const handleHotKey = (event) => {
			if (!event) return;
			if (event.toggleSidebar) toggleSidebarOpen();
			if (event.focusRequestSearch) searchInputRef.value?.focus();
		};
		onMounted(() => events.hotKeys.on(handleHotKey));
		/**
		* Need to manually remove listener on unmount due to vueuse memory leak
		*
		* @see https://github.com/vueuse/vueuse/issues/3498#issuecomment-2055546566
		*/
		onBeforeUnmount(() => {
			events.hotKeys.off(handleHotKey);
		});
		const handleToggleWatchMode = (item) => {
			if (item?.documentUrl) {
				item.watchMode = !item.watchMode;
				const currentCollection = activeWorkspaceCollections.value.find((collection) => collection.uid === item.entity.uid);
				if (currentCollection) currentCollection.watchMode = item.watchMode;
			}
		};
		watch(() => activeWorkspaceCollections.value.map((collection) => collection.watchMode), (newWatchModes, oldWatchModes) => {
			newWatchModes.forEach((newWatchMode, index) => {
				if (layout !== "modal" && newWatchMode !== oldWatchModes[index] && activeWorkspaceCollections.value[index]?.info?.title !== "Drafts" && activeWorkspaceCollections.value[index]) {
					const currentCollection = activeWorkspaceCollections.value[index];
					if (!currentCollection) return;
					toast(`${currentCollection.info?.title}: Watch Mode ${newWatchMode ? "enabled" : "disabled"}`, "info");
				}
			});
		});
		/** Screen reader label for the search input */
		const srLabel = computed(() => {
			const results = searchResultsWithPlaceholderResults.value;
			if (!results.length) return "No results found";
			const result = results[selectedSearchResult.value]?.item;
			if (!result) return "No result selected";
			const resultsFoundLabel = searchText.value.length ? `${results.length} result${results.length === 1 ? "" : "s"} found, ` : "";
			const selectedResultDescription = `, HTTP Method ${result.httpVerb}, Path ${result.path}`;
			return `${resultsFoundLabel}Selected: ${`${result.title} ${selectedResultDescription}`}`;
		});
		const handleClearDrafts = () => {
			const draftCollection = activeWorkspaceCollections.value.find((collection) => collection.info?.title === "Drafts");
			if (draftCollection) draftCollection.requests.forEach((requestUid) => {
				if (requests[requestUid]) requestMutators.delete(requests[requestUid], draftCollection.uid);
			});
			if (activeWorkspaceRequests.value.length) {
				const firstRequest = activeWorkspaceCollections.value[0]?.requests[0];
				if (firstRequest) replace({
					name: "request",
					params: { [PathId.Request]: firstRequest }
				});
			} else {
				const { request } = createInitialRequest();
				if (draftCollection) {
					requestMutators.add(request, draftCollection.uid);
					replace({
						name: "request",
						params: { [PathId.Request]: request.uid }
					});
				}
			}
		};
		watch(isSearchVisible, (isVisible) => {
			if (!isVisible) searchText.value = "";
		});
		const showGettingStarted = computed(() => isGettingStarted(activeWorkspaceCollections.value, activeWorkspaceRequests.value, requests));
		/** We ensure in modal mode we only show the current requests collection */
		const collections = computed(() => {
			if (layout === "modal" && activeCollection.value) return [activeCollection.value];
			return activeWorkspaceCollections.value;
		});
		/** Hide the search input if the text is empty */
		function handleBlur(e) {
			if (!searchText.value && e.relatedTarget !== searchToggleRef.value) isSearchVisible.value = false;
		}
		return (_ctx, _cache) => {
			return openBlock(), createElementBlock(Fragment, null, [withDirectives(createVNode(unref(Sidebar_default), { class: normalizeClass([unref(isSidebarOpen) ? "sidebar-active-width" : ""]) }, createSlots({
				content: withCtx(() => [
					createElementVNode("div", _hoisted_1, [
						createElementVNode("div", { class: normalizeClass(["size-8", { "xl:hidden": unref(layout) !== "modal" }]) }, null, 2),
						unref(layout) !== "modal" ? (openBlock(), createBlock(unref(WorkspaceDropdown_default), { key: 0 })) : createCommentVNode("", true),
						unref(layout) !== "modal" ? (openBlock(), createElementBlock("span", _hoisted_2, " / ")) : createCommentVNode("", true),
						unref(layout) !== "modal" ? (openBlock(), createBlock(EnvironmentSelector_default, { key: 2 })) : createCommentVNode("", true),
						createElementVNode("button", {
							ref_key: "searchToggleRef",
							ref: searchToggleRef,
							"aria-pressed": isSearchVisible.value,
							class: "ml-auto",
							type: "button",
							onClick: _cache[0] || (_cache[0] = ($event) => isSearchVisible.value = !isSearchVisible.value)
						}, [createElementVNode("span", _hoisted_4, toDisplayString(isSearchVisible.value ? "Hide" : "Show") + " search ", 1), createVNode(unref(ScalarIcon), {
							class: "text-c-3 hover:bg-b-2 max-h-8 max-w-8 rounded-lg p-1.75 text-sm",
							icon: "Search"
						})], 8, _hoisted_3)
					]),
					isSearchVisible.value ? (openBlock(), createElementBlock("div", _hoisted_5, [createVNode(unref(ScalarSidebarSearchInput), {
						ref_key: "searchInputRef",
						ref: searchInputRef,
						modelValue: unref(searchText),
						"onUpdate:modelValue": _cache[1] || (_cache[1] = ($event) => isRef(searchText) ? searchText.value = $event : null),
						autofocus: "",
						"aria-controls": unref(searchResultsId),
						label: srLabel.value,
						onInput: unref(fuseSearch),
						onKeydown: [
							_cache[2] || (_cache[2] = withKeys(withModifiers(($event) => unref(navigateSearchResults)("down"), ["stop"]), ["down"])),
							_cache[3] || (_cache[3] = withKeys(withModifiers(($event) => unref(selectSearchResult)(), ["stop"]), ["enter"])),
							_cache[4] || (_cache[4] = withKeys(withModifiers(($event) => unref(navigateSearchResults)("up"), ["stop"]), ["up"]))
						],
						onBlur: handleBlur
					}, null, 8, [
						"modelValue",
						"aria-controls",
						"label",
						"onInput"
					])])) : createCommentVNode("", true),
					createElementVNode("div", {
						class: normalizeClass(["gap-1/2 flex flex-1 flex-col overflow-visible overflow-y-auto px-3 pt-0 pb-3", [{ "pb-14": unref(layout) !== "modal" }, { "h-[calc(100%-273.5px)]": showGettingStarted.value }]]),
						onDragenter: _cache[7] || (_cache[7] = withModifiers(() => {}, ["prevent"])),
						onDragover: _cache[8] || (_cache[8] = withModifiers(() => {}, ["prevent"]))
					}, [unref(searchText) ? (openBlock(), createBlock(unref(ScalarSearchResultList), {
						key: 0,
						id: unref(searchResultsId),
						"aria-label": "Search Results",
						class: "gap-px",
						noResults: !unref(searchResultsWithPlaceholderResults).length
					}, {
						default: withCtx(() => [(openBlock(true), createElementBlock(Fragment, null, renderList(unref(searchResultsWithPlaceholderResults), (entry, index) => {
							return openBlock(), createBlock(unref(ScalarSearchResultItem), {
								id: `#search-input-${entry.item.id}`,
								key: entry.refIndex,
								ref_for: true,
								ref: (el) => unref(searchResultRefs)[index] = el,
								selected: unref(selectedSearchResult) === index,
								class: "px-2",
								href: entry.item.link,
								onClick: withModifiers(($event) => unref(onSearchResultClick)(entry), ["prevent"]),
								onFocus: ($event) => selectedSearchResult.value = index
							}, {
								addon: withCtx(() => [_cache[10] || (_cache[10] = createElementVNode("span", { class: "sr-only" }, "HTTP Method:", -1)), createVNode(HttpMethod_default, {
									class: "font-bold",
									method: entry.item.httpVerb ?? "get"
								}, null, 8, ["method"])]),
								default: withCtx(() => [createTextVNode(toDisplayString(entry.item.title) + " ", 1)]),
								_: 2
							}, 1032, [
								"id",
								"selected",
								"href",
								"onClick",
								"onFocus"
							]);
						}), 128))]),
						_: 1
					}, 8, ["id", "noResults"])) : (openBlock(), createElementBlock("nav", _hoisted_6, [(openBlock(true), createElementBlock(Fragment, null, renderList(collections.value, (collection) => {
						return openBlock(), createBlock(RequestSidebarItem_default, {
							key: collection.uid,
							isDraggable: unref(layout) !== "modal" && collection.info?.title !== "Drafts",
							isDroppable: unref(isDroppable),
							menuItem,
							parentUids: [],
							uid: collection.uid,
							onNewTab: _cache[5] || (_cache[5] = (name, uid) => emit("newTab", {
								name,
								uid
							})),
							onOnDragEnd: unref(handleDragEnd),
							onOpenMenu: _cache[6] || (_cache[6] = (item) => Object.assign(menuItem, item))
						}, {
							leftIcon: withCtx(() => [collection.info?.title === "Drafts" ? (openBlock(), createBlock(unref(ScalarIcon), {
								key: 0,
								class: "text-sidebar-c-2",
								icon: "Scribble",
								thickness: "2.25"
							})) : (openBlock(), createBlock(unref(LibraryIcon), {
								key: 1,
								class: "text-sidebar-c-2 size-3.5 min-w-3.5 stroke-2",
								src: collection["x-scalar-icon"] || "interface-content-folder"
							}, null, 8, ["src"]))]),
							_: 2
						}, 1032, [
							"isDraggable",
							"isDroppable",
							"menuItem",
							"uid",
							"onOnDragEnd"
						]);
					}), 128))]))], 34)
				]),
				button: withCtx(() => [createElementVNode("div", { class: normalizeClass({ "empty-sidebar-item": showGettingStarted.value }) }, [
					showGettingStarted.value ? (openBlock(), createElementBlock("div", _hoisted_7, [createElementVNode("div", _hoisted_8, [createVNode(ScalarAsciiArt_default, {
						art: unref(rabbit_default),
						class: "rabbitsit font-bold"
					}, null, 8, ["art"]), createVNode(ScalarAsciiArt_default, {
						art: unref(rabbitjump_default),
						class: "rabbitjump absolute top-0 left-0 font-bold"
					}, null, 8, ["art"])]), _cache[11] || (_cache[11] = createElementVNode("div", { class: "mt-2 mb-2 text-center text-sm text-balance" }, [createElementVNode("b", { class: "font-medium" }, "Let's Get Started"), createElementVNode("p", { class: "mt-2" }, " Create request, folder, collection or import from OpenAPI/Postman ")], -1))])) : createCommentVNode("", true),
					unref(layout) !== "modal" ? (openBlock(), createBlock(unref(ScalarButton), {
						key: 1,
						class: normalizeClass(["mb-1.5 hidden h-fit w-full p-1.5 opacity-0", { "flex opacity-100": showGettingStarted.value }]),
						onClick: openCommandPaletteImport
					}, {
						default: withCtx(() => [..._cache[12] || (_cache[12] = [createTextVNode(" Import Collection ", -1)])]),
						_: 1
					}, 8, ["class"])) : createCommentVNode("", true),
					unref(layout) !== "modal" ? (openBlock(), createBlock(SidebarButton_default, {
						key: 2,
						click: unref(events).commandPalette.emit,
						hotkey: "K"
					}, {
						title: withCtx(() => [..._cache[13] || (_cache[13] = [createTextVNode(" Add Item ", -1)])]),
						_: 1
					}, 8, ["click"])) : createCommentVNode("", true)
				], 2)]),
				_: 2
			}, [unref(layout) !== "modal" ? {
				name: "header",
				fn: withCtx(() => []),
				key: "0"
			} : void 0]), 1032, ["class"]), [[vShow, unref(isSidebarOpen)]]), unref(layout) !== "modal" && menuItem ? (openBlock(), createBlock(RequestSidebarItemMenu_default, {
				key: 0,
				menuItem,
				onClearDrafts: handleClearDrafts,
				onCloseMenu: _cache[9] || (_cache[9] = ($event) => menuItem.open = false),
				onToggleWatchMode: handleToggleWatchMode
			}, null, 8, ["menuItem"])) : createCommentVNode("", true)], 64);
		};
	}
});
//#endregion
export { RequestSidebar_vue_vue_type_script_setup_true_lang_default as default };

//# sourceMappingURL=RequestSidebar.vue.script.js.map