import { T as PathId, r as useWorkspace, w as useActiveEntities } from "./store-DpSUVhjp.js";
import { r as useSidebar } from "./useSidebar-DLTwHDI-.js";
import { t as CodeInput_default } from "./CodeInput-C-igR77V.js";
import { t as Sidebar_default } from "./Sidebar-C6AdX6-N.js";
import { t as ViewLayout_default } from "./ViewLayout-BOXN0IYo.js";
import { t as ViewLayoutContent_default } from "./ViewLayoutContent-CvMoJYPF.js";
import { t as ViewLayoutSection_default } from "./ViewLayoutSection-mUqKbQry.js";
import { t as EditSidebarListElement_default } from "./EditSidebarListElement-CodWPnM6.js";
import { n as EnvironmentColorModal_default, t as EnvironmentModal_default } from "./EnvironmentModal-DBEJ4Kzj.js";
import { t as SidebarButton_default } from "./SidebarButton-BAagdMDe.js";
import { n as SidebarList_default, t as SidebarListElement_default } from "./SidebarListElement-BfTPiihc.js";
import { Fragment, computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createSlots, createTextVNode, createVNode, defineComponent, normalizeClass, onBeforeUnmount, onMounted, openBlock, ref, renderList, toDisplayString, unref, vShow, watch, withCtx, withDirectives, withModifiers } from "vue";
import { ScalarButton, ScalarIcon, ScalarModal, useModal } from "@scalar/components";
import { useToasts } from "@scalar/use-toasts";
import { useRoute, useRouter } from "vue-router";
import { LibraryIcon } from "@scalar/icons/library";
//#region src/views/Environment/handle-drag.ts
/** Create environment DnD handlers */
function environmentDragHandlerFactory(activeWorkspaceCollections, collectionMutator) {
	/** Drag handler that mutates the collection's environments order */
	const handleDragEnd = (draggingItem, hoveredItem) => {
		if (!draggingItem || !hoveredItem) return;
		const { id: draggingUid, parentId: draggingParentUid } = draggingItem;
		const { id: hoveredUid, parentId: hoveredParentUid, offset } = hoveredItem;
		if (draggingParentUid !== hoveredParentUid) return;
		const collection = activeWorkspaceCollections.value.find((c) => c.uid === draggingParentUid);
		if (!collection || !collection["x-scalar-environments"]) return;
		const environments = collection["x-scalar-environments"];
		const envKeys = Object.keys(environments);
		({ ...environments });
		const draggedIndex = envKeys.findIndex((key) => key === draggingUid);
		envKeys.splice(draggedIndex, 1);
		const targetIndex = envKeys.findIndex((key) => key === hoveredUid) + (offset === 1 ? 1 : 0);
		envKeys.splice(targetIndex, 0, draggingUid);
		collection["x-scalar-environments"] = envKeys.reduce((acc, key) => {
			const env = environments[key];
			if (env) acc[key] = env;
			return acc;
		}, {});
		collectionMutator.edit(collection.uid, "x-scalar-environments", collection["x-scalar-environments"]);
	};
	/** Ensure only environments within the same collection can be dropped */
	const isDroppable = (draggingItem, hoveredItem) => {
		return draggingItem.parentId === hoveredItem.parentId;
	};
	return {
		handleDragEnd,
		isDroppable
	};
}
//#endregion
//#region src/views/Environment/Environment.vue?vue&type=script&setup=true&lang.ts
var _hoisted_1 = { class: "flex-1" };
var _hoisted_2 = ["onClick"];
var _hoisted_3 = { class: "flex h-5 max-w-[14px] items-center justify-center" };
//#endregion
//#region src/views/Environment/Environment.vue
var Environment_default = /* @__PURE__ */ defineComponent({
	__name: "Environment",
	setup(__props) {
		const router = useRouter();
		const route = useRoute();
		const { activeWorkspace, activeEnvironment, activeWorkspaceCollections, activeEnvVariables } = useActiveEntities();
		const { events, workspaceMutators, collectionMutators } = useWorkspace();
		const { collapsedSidebarFolders, toggleSidebarFolder } = useSidebar();
		const colorModal = useModal();
		const environmentModal = useModal();
		const editModal = useModal();
		const colorModalEnvironment = ref(null);
		const currentEnvironmentId = ref("default");
		const selectedColor = ref("");
		const selectedCollectionId = ref(void 0);
		const selectedEnvironmentId = ref(void 0);
		const tempEnvironmentName = ref(void 0);
		const { toast } = useToasts();
		const parseEnvironmentValue = (value) => JSON.parse(value);
		function environmentNameToast(environmentNameUsed, collection, collectionId) {
			if (environmentNameUsed) if (collection.uid === collectionId) toast(`Environment name already used in ${collection.info?.title}`, "error");
			else toast("Environment name already used in another collection", "error");
		}
		const nonDraftWorkspaceCollections = computed(() => {
			return activeWorkspaceCollections.value.filter((collection) => collection.info?.title !== "Drafts");
		});
		function addEnvironment(environment) {
			if (nonDraftWorkspaceCollections.value.some((collection) => {
				const enviromentName = Object.keys(collection["x-scalar-environments"] || {}).includes(environment.name);
				environmentNameToast(enviromentName, collection, environment.collectionId);
				return enviromentName;
			})) return;
			if (environment.collectionId) {
				collectionMutators.addEnvironment(environment.name, {
					variables: {},
					color: environment.color
				}, environment.collectionId);
				if (!collapsedSidebarFolders[environment.collectionId]) toggleSidebarFolder(environment.collectionId);
				router.push({
					name: "environment.collection",
					params: {
						[PathId.Collection]: environment.collectionId,
						[PathId.Environment]: environment.name
					}
				});
			}
			environmentModal.hide();
		}
		function handleEnvironmentUpdate(raw) {
			if (!activeEnvironment) return;
			const updatedValue = parseEnvironmentValue(raw);
			if (currentEnvironmentId.value === "default") workspaceMutators.edit(activeWorkspace.value?.uid, "environments", updatedValue);
			else {
				const collection = activeWorkspaceCollections.value.find((c) => c["x-scalar-environments"]?.[currentEnvironmentId.value ?? ""]);
				if (collection?.["x-scalar-environments"]?.[currentEnvironmentId.value ?? ""]) {
					const environment = collection["x-scalar-environments"][currentEnvironmentId.value ?? ""];
					if (environment) {
						environment.variables = updatedValue;
						collectionMutators.edit(collection.uid, "x-scalar-environments", collection["x-scalar-environments"]);
					}
				}
			}
		}
		const openEnvironmentModal = (collectionId) => {
			selectedCollectionId.value = collectionId;
			environmentModal.show();
		};
		const openRenameModal = (environmentId, collectionId) => {
			selectedEnvironmentId.value = environmentId;
			selectedCollectionId.value = collectionId;
			tempEnvironmentName.value = environmentId;
			editModal.show();
		};
		const handleOpenColorModal = (uid) => {
			colorModalEnvironment.value = uid;
			selectedColor.value = activeWorkspaceCollections.value.find((collection) => collection["x-scalar-environments"]?.[uid])?.["x-scalar-environments"]?.[uid]?.color ?? "";
			colorModal.show();
		};
		const submitColorChange = (color) => {
			const environmentId = colorModalEnvironment.value;
			if (typeof environmentId === "string") {
				if (activeWorkspaceCollections.value.some((collection) => collection["x-scalar-environments"]?.[environmentId])) activeWorkspaceCollections.value.forEach((collection) => {
					if (collection["x-scalar-environments"]?.[environmentId]) {
						collection["x-scalar-environments"][environmentId].color = color;
						collectionMutators.edit(collection.uid, "x-scalar-environments", collection["x-scalar-environments"]);
					}
				});
				colorModal.hide();
			}
		};
		function removeCollectionEnvironment(environmentName) {
			nonDraftWorkspaceCollections.value.forEach((collection) => {
				collectionMutators.removeEnvironment(environmentName, collection.uid);
			});
			const remainingCollectionEnvironments = nonDraftWorkspaceCollections.value.flatMap((collection) => Object.keys(collection["x-scalar-environments"] || {}));
			if (remainingCollectionEnvironments.length > 0) {
				const lastCollectionEnvironment = remainingCollectionEnvironments[remainingCollectionEnvironments.length - 1];
				if (!lastCollectionEnvironment) return;
				const currentCollection = activeWorkspaceCollections.value.find((collection) => Object.keys(collection["x-scalar-environments"] || {}).includes(lastCollectionEnvironment));
				currentEnvironmentId.value = lastCollectionEnvironment;
				router.push({
					name: "environment.collection",
					params: {
						[PathId.Collection]: currentCollection?.uid,
						[PathId.Environment]: lastCollectionEnvironment
					}
				});
				if (currentCollection && !collapsedSidebarFolders[currentCollection.uid]) toggleSidebarFolder(currentCollection.uid);
			} else {
				currentEnvironmentId.value = "default";
				router.push({
					name: "environment.default",
					params: { [PathId.Workspace]: activeWorkspace.value?.uid }
				});
			}
		}
		const getEnvironmentName = () => {
			return currentEnvironmentId.value === "default" ? "Global Environment" : currentEnvironmentId.value;
		};
		const getEnvironmentValue = () => {
			return currentEnvironmentId.value === "default" ? JSON.stringify(activeWorkspace.value?.environments, null, 2) : JSON.stringify(activeWorkspaceCollections.value.find((collection) => collection["x-scalar-environments"]?.[currentEnvironmentId.value ?? ""])?.["x-scalar-environments"]?.[currentEnvironmentId.value ?? ""]?.variables, null, 2);
		};
		const showChildren = (key) => {
			return collapsedSidebarFolders[key];
		};
		const handleHotKey = (event) => {
			if (event?.createNew && route.name === "environment") openEnvironmentModal();
		};
		watch(() => [route.params[PathId.Collection], route.params[PathId.Environment]], ([newCollectionId, newEnvironmentId]) => {
			if (newCollectionId) currentEnvironmentId.value = newEnvironmentId;
			else currentEnvironmentId.value = "default";
		});
		onMounted(() => {
			currentEnvironmentId.value = route.params[PathId.Environment] || "default";
			events.hotKeys.on(handleHotKey);
			const collectionId = route.params[PathId.Collection];
			if (collectionId && !collapsedSidebarFolders[collectionId]) toggleSidebarFolder(collectionId);
		});
		onBeforeUnmount(() => events.hotKeys.off(handleHotKey));
		const handleNavigation = (event, uid, collectionId) => {
			const to = collectionId ? {
				name: "environment.collection",
				params: {
					[PathId.Workspace]: activeWorkspace.value?.uid,
					[PathId.Collection]: collectionId,
					[PathId.Environment]: uid
				}
			} : {
				name: "environment.default",
				params: {
					[PathId.Workspace]: activeWorkspace.value?.uid,
					[PathId.Environment]: uid
				}
			};
			if (event.metaKey) window.open(router.resolve(to).href, "_blank");
			else router.push(to);
		};
		function handleCancelRename() {
			selectedEnvironmentId.value = void 0;
			selectedCollectionId.value = void 0;
			tempEnvironmentName.value = void 0;
			editModal.hide();
		}
		function handleRename(newName) {
			if (nonDraftWorkspaceCollections.value.some((collection) => {
				const enviromentName = Object.keys(collection["x-scalar-environments"] || {}).includes(newName);
				environmentNameToast(enviromentName, collection, selectedCollectionId.value);
				return enviromentName;
			})) return;
			if (newName && selectedEnvironmentId.value !== "default") activeWorkspaceCollections.value.forEach((collection) => {
				if (collection["x-scalar-environments"]?.[selectedEnvironmentId.value ?? ""]) {
					const environments = collection["x-scalar-environments"];
					const orderedEnvs = {};
					Object.keys(environments).forEach((key) => {
						const environment = environments[key];
						if (!environment) return;
						if (key === selectedEnvironmentId.value) orderedEnvs[newName] = environment;
						else orderedEnvs[key] = environment;
					});
					collection["x-scalar-environments"] = orderedEnvs;
					collectionMutators.edit(collection.uid, "x-scalar-environments", collection["x-scalar-environments"]);
				}
			});
			if (newName && currentEnvironmentId.value === selectedEnvironmentId.value) currentEnvironmentId.value = newName;
			selectedEnvironmentId.value = void 0;
			selectedCollectionId.value = void 0;
			tempEnvironmentName.value = void 0;
			editModal.hide();
		}
		const { handleDragEnd, isDroppable } = environmentDragHandlerFactory(activeWorkspaceCollections, collectionMutators);
		watch(() => route.query.openEnvironmentModal, (newVal) => {
			if (newVal === "true") openEnvironmentModal();
		}, { immediate: true });
		return (_ctx, _cache) => {
			return openBlock(), createBlock(ViewLayout_default, null, {
				default: withCtx(() => [
					createVNode(Sidebar_default, { title: "Collections" }, {
						content: withCtx(() => [createElementVNode("div", _hoisted_1, [createVNode(SidebarList_default, null, {
							default: withCtx(() => [(openBlock(), createBlock(SidebarListElement_default, {
								key: "default",
								class: "text-xs",
								isCopyable: false,
								to: {
									name: "environment",
									params: { [unref(PathId).Environment]: "default" }
								},
								type: "environment",
								variable: {
									name: "Global Environment",
									uid: "default",
									icon: "Globe",
									isDefault: true
								}
							}, null, 8, ["to"])), (openBlock(true), createElementBlock(Fragment, null, renderList(nonDraftWorkspaceCollections.value, (collection) => {
								return openBlock(), createElementBlock("li", {
									key: collection.uid,
									class: "gap-1/2 flex flex-col"
								}, [createElementVNode("button", {
									class: "hover:bg-b-2 group flex w-full items-center gap-1.5 rounded p-1.5 text-left text-sm font-medium break-words",
									type: "button",
									onClick: ($event) => unref(toggleSidebarFolder)(collection.uid)
								}, [createElementVNode("span", _hoisted_3, [createVNode(unref(LibraryIcon), {
									class: "text-sidebar-c-2 size-3.5 min-w-3.5 stroke-2 group-hover:hidden",
									src: collection["x-scalar-icon"] || "interface-content-folder"
								}, null, 8, ["src"]), createElementVNode("div", { class: normalizeClass({ "rotate-90": unref(collapsedSidebarFolders)[collection.uid] }) }, [createVNode(unref(ScalarIcon), {
									class: "text-c-3 hover:text-c-1 hidden text-sm group-hover:block",
									icon: "ChevronRight",
									size: "md"
								})], 2)]), createTextVNode(" " + toDisplayString(collection.info?.title ?? ""), 1)], 8, _hoisted_2), withDirectives(createElementVNode("div", { class: normalizeClass({ "before:bg-border relative mb-[.5px] before:pointer-events-none before:absolute before:top-0 before:left-3 before:z-1 before:h-[calc(100%_+_.5px)] before:w-[.5px] last:mb-0 last:before:h-full": Object.keys(collection["x-scalar-environments"] || {}).length > 0 }) }, [(openBlock(true), createElementBlock(Fragment, null, renderList(collection["x-scalar-environments"], (environment, environmentName) => {
									return openBlock(), createBlock(SidebarListElement_default, {
										key: environmentName,
										class: "text-xs",
										collectionId: collection.uid,
										isCopyable: false,
										isDeletable: true,
										isRenameable: true,
										isDraggable: true,
										isDroppable: unref(isDroppable),
										to: {
											name: "environment.collection",
											params: {
												[unref(PathId).Collection]: collection.uid,
												[unref(PathId).Environment]: environmentName
											}
										},
										type: "environment",
										variable: {
											name: environmentName,
											uid: environmentName,
											color: environment.color ?? "#FFFFFF",
											isDefault: false
										},
										warningMessage: `Are you sure you want to delete this environment?`,
										onClick: withModifiers(($event) => handleNavigation($event, environmentName, collection.uid), ["prevent"]),
										onColorModal: ($event) => handleOpenColorModal(environmentName),
										onDelete: ($event) => removeCollectionEnvironment(environmentName),
										onRename: ($event) => openRenameModal(environmentName, collection.uid),
										onOnDragEnd: unref(handleDragEnd)
									}, null, 8, [
										"collectionId",
										"isDroppable",
										"to",
										"variable",
										"onClick",
										"onColorModal",
										"onDelete",
										"onRename",
										"onOnDragEnd"
									]);
								}), 128)), Object.keys(collection["x-scalar-environments"] || {}).length === 0 ? (openBlock(), createBlock(unref(ScalarButton), {
									key: 0,
									class: "text-c-1 hover:bg-b-2 flex h-8 w-full justify-start gap-1.5 py-0 pl-6 text-xs",
									variant: "ghost",
									onClick: ($event) => openEnvironmentModal(collection.uid)
								}, {
									default: withCtx(() => [createVNode(unref(ScalarIcon), {
										icon: "Add",
										size: "sm"
									}), _cache[2] || (_cache[2] = createElementVNode("span", null, "Add Environment", -1))]),
									_: 1
								}, 8, ["onClick"])) : createCommentVNode("", true)], 2), [[vShow, showChildren(collection.uid)]])]);
							}), 128))]),
							_: 1
						})])]),
						button: withCtx(() => [createVNode(SidebarButton_default, {
							click: openEnvironmentModal,
							hotkey: "N"
						}, {
							title: withCtx(() => [..._cache[3] || (_cache[3] = [createTextVNode(" Add Environment ", -1)])]),
							_: 1
						})]),
						_: 1
					}),
					createVNode(ViewLayoutContent_default, { class: "flex-1" }, {
						default: withCtx(() => [createVNode(ViewLayoutSection_default, null, createSlots({
							default: withCtx(() => [currentEnvironmentId.value && unref(activeWorkspace) ? (openBlock(), createBlock(CodeInput_default, {
								key: 0,
								class: "py-2 pr-2 pl-px md:px-4",
								envVariables: unref(activeEnvVariables),
								environment: unref(activeEnvironment),
								language: "json",
								lineNumbers: "",
								lint: "",
								modelValue: getEnvironmentValue(),
								workspace: unref(activeWorkspace),
								"onUpdate:modelValue": handleEnvironmentUpdate
							}, null, 8, [
								"envVariables",
								"environment",
								"modelValue",
								"workspace"
							])) : createCommentVNode("", true)]),
							_: 2
						}, [currentEnvironmentId.value ? {
							name: "title",
							fn: withCtx(() => [createElementVNode("span", null, toDisplayString(getEnvironmentName()), 1)]),
							key: "0"
						} : void 0]), 1024)]),
						_: 1
					}),
					createVNode(EnvironmentColorModal_default, {
						selectedColor: selectedColor.value,
						state: unref(colorModal),
						onCancel: _cache[0] || (_cache[0] = ($event) => unref(colorModal).hide()),
						onSubmit: submitColorChange
					}, null, 8, ["selectedColor", "state"]),
					createVNode(EnvironmentModal_default, {
						activeWorkspaceCollections: nonDraftWorkspaceCollections.value,
						collectionId: selectedCollectionId.value,
						state: unref(environmentModal),
						onCancel: _cache[1] || (_cache[1] = ($event) => unref(environmentModal).hide()),
						onSubmit: addEnvironment
					}, null, 8, [
						"activeWorkspaceCollections",
						"collectionId",
						"state"
					]),
					createVNode(unref(ScalarModal), {
						size: "xxs",
						state: unref(editModal),
						title: `Edit ${selectedEnvironmentId.value}`
					}, {
						default: withCtx(() => [createVNode(EditSidebarListElement_default, {
							name: tempEnvironmentName.value ?? "",
							onClose: handleCancelRename,
							onEdit: handleRename
						}, null, 8, ["name"])]),
						_: 1
					}, 8, ["state", "title"])
				]),
				_: 1
			});
		};
	}
});
//#endregion
export { Environment_default as default };

//# sourceMappingURL=Environment-DJatRQIg.js.map