import React from "react"; import { type Windows, type WindowData, type WindowElements, type WindowIconType, type NewWindowArguments, } from "./types"; import { ProcessContextState } from "../process/useProcessContextState"; import { PREVENT_SCROLL } from "@/utils/constants"; import merge from "lodash.merge"; // Function to set window settings with optional deep copy export const setWindowSetting = (windowID: string, settings: Partial, deepCopy = true) => (currentWindows: Windows): Windows => { const { ...newWindows } = currentWindows; if (newWindows[windowID]) { if (deepCopy) { newWindows[windowID] = merge(newWindows[windowID], settings); } else { newWindows[windowID] = { ...newWindows[windowID], ...settings, }; } } return newWindows; }; export const closeWindow = ( windowID: string, closing?: boolean, removeWindowIDFromProcess?: ProcessContextState["removeWindowIDFromProcess"] ) => (currentWindows: Windows): Windows => { if (closing) { return setWindowSetting(windowID, { closing })(currentWindows); } const { [windowID]: _closedWindow, ...remainingWindows } = currentWindows; if (_closedWindow) { if (_closedWindow.process && removeWindowIDFromProcess) { removeWindowIDFromProcess(_closedWindow.process.pid, windowID); } } return remainingWindows; }; export const maximizeWindow = (windowID: string) => (currentWindows: Windows): Windows => { const newMaximizedState = !currentWindows[windowID]?.maximized; if (newMaximizedState) { const { componentWindow } = currentWindows[windowID]; requestAnimationFrame(() => componentWindow?.focus(PREVENT_SCROLL)); } return setWindowSetting(windowID, { maximized: newMaximizedState, })(currentWindows); }; export const minimizeWindow = (windowID: string) => (currentWindows: Windows): Windows => setWindowSetting(windowID, { minimized: !currentWindows[windowID]?.minimized, })(currentWindows); export const setIcon = (windowID: string, icon: WindowIconType) => (currentWindows: Windows): Windows => setWindowSetting(windowID, { icon })(currentWindows); export const setTitle = (windowID: string, title: string) => (currentWindows: Windows): Windows => setWindowSetting(windowID, { title })(currentWindows); export const setWindowElement = (windowID: string, name: keyof WindowElements, element: HTMLElement) => (currentWindows: Windows): Windows => setWindowSetting(windowID, { [name]: element })(currentWindows); export const createNewWindow = (newWindowID: string, windowObj: NewWindowArguments) => (currentWindows: Windows): Windows => { // eslint-disable-next-line @typescript-eslint/no-explicit-any let Component: React.ComponentType; if (React.isValidElement(windowObj.Component)) { // Wrap ReactNode in a component Component = () => windowObj.Component as React.ReactElement; } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any Component = windowObj.Component as React.ComponentType; } return { ...currentWindows, [newWindowID]: { ...windowObj, id: newWindowID, Component, }, }; };