// contexts/WindowManagerContext.tsx 'use client'; import… · The Chat Archive
Explore / Programming // contexts/WindowManagerContext.tsx 'use client'; import React, { createContext,… Save Share Download ▾ Report// contexts/WindowManagerContext.tsx
'use client';
import React, { createContext, useContext, useState, useEffect } from 'react';
type WindowData = {
name: string;
Component: React.ComponentType;
windowProps: {
width?: string;
height?: string;
};
};
type WindowState = {
visible: boolean;
minimized: boolean;
maximized: boolean;
width: number;
height: number;
x: number;
y: number;
zIndex: number;
prevWidth?: number;
prevHeight?: number;
prevX?: number;
prevY?: number;
};
type WindowManagerContextType = {
windows: { [key: string]: WindowData };
windowStates: { [key: string]: WindowState };
openWindow: (name: string) => void;
closeWindow: (name: string) => void;
minimizeWindow: (name: string) => void;
restoreWindow: (name: string) => void;
maximizeWindow: (name: string) => void;
updateWindowState: (name: string, newState: Partial) => void;
bringToFront: (name: string) => void;
};
const WindowManagerContext = createContext<WindowManagerContextType | undefined>(undefined);
export const useWindowManager = () => {
const context = useContext(WindowManagerContext);
if (!context) {
throw new Error('useWindowManager must be used within a WindowManagerProvider');
}
return context;
};
export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [windows, setWindows] = useState<{ [key: string]: WindowData }>({});
const [windowStates, setWindowStates] = useState<{ [key: string]: WindowState }>({});
const [nextZIndex, setNextZIndex] = useState(1);
type WindowDataAndState = {
windowData: WindowData;
windowState: WindowState;
};
useEffect(() => {
// Dynamically import window components
const importWindows = async () => {
const windowsContext = require.context('../windows', false, /.tsx$/);
const windowFiles = windowsContext.keys();
Show full message · 537 lines Assistant2024-10-06 10:15 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language en
Conversation date Oct 6, 2024
Added to archive Nov 16, 2026
ID 01m7h41wndmv5hkga7n0rjftgqSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 0905fee774727b867f3133b3e93ac89e
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
let zIndexCounter = 1;
const windowsDataPromises: Promise<WindowDataAndState>[] = windowFiles.map(
async (file: string, index: number): Promise<WindowDataAndState> => {
const mod = await windowsContext(file);
const name = file.replace('./', '').replace('.tsx', '');
const Component = mod.default;
const windowProps = mod.windowProps || {};
// Parse initial size
const width = windowProps.width
? parseSize(windowProps.width, 'width')
: 0.35 * window.innerWidth;
const height = windowProps.height
? parseSize(windowProps.height, 'height')
: 0.2 * window.innerHeight;
const windowData: WindowData = { name, Component, windowProps };
const windowState: WindowState = {
visible: true,
minimized: false,
maximized: false,
width,
height,
x: 100 + index * 50,
y: 100 + index * 50,
zIndex: zIndexCounter++,
};
return { windowData, windowState };
}
);
const windowsDataArray: WindowDataAndState[] = await Promise.all(windowsDataPromises);
const newWindows: { [key: string]: WindowData } = {};
const newWindowStates: { [key: string]: WindowState } = {};
windowsDataArray.forEach(({ windowData, windowState }) => {
newWindows[windowData.name] = windowData;
newWindowStates[windowData.name] = windowState;
});
setWindows(newWindows);
setWindowStates(newWindowStates);
setNextZIndex(zIndexCounter);
};
importWindows();
const bringToFront = (name: string) => {
setWindowStates((prev) => {
const maxZ = nextZIndex;
setNextZIndex(maxZ + 1);
return {
...prev,
[name]: {
...prev[name],
zIndex: maxZ,
},
};
});
};
const openWindow = (name: string) => {
setWindowStates((prev) => ({
...prev,
[name]: {
...prev[name],
visible: true,
minimized: false,
},
}));
bringToFront(name);
};
const closeWindow = (name: string) => {
setWindowStates((prev) => ({
...prev,
[name]: {
...prev[name],
visible: false,
minimized: false,
},
}));
};
const minimizeWindow = (name: string) => {
setWindowStates((prev) => ({
...prev,
[name]: {
...prev[name],
minimized: true,
visible: false,
},
}));
};
const restoreWindow = (name: string) => {
setWindowStates((prev) => ({
...prev,
[name]: {
...prev[name],
minimized: false,
visible: true,
},
}));
bringToFront(name);
};
const maximizeWindow = (name: string) => {
setWindowStates((prev) => {
const state = prev[name];
const isMaximized = !state.maximized;
code Copy code
if (isMaximized) {
// Store previous size and position
const prevSizePosition = {
prevWidth: state.width,
prevHeight: state.height,
prevX: state.x,
prevY: state.y,
};
return {
...prev,
[name]: {
...state,
maximized: true,
...prevSizePosition,
x: 0,
y: 0,
width: window.innerWidth,
height: window.innerHeight,
},
};
} else {
// Restore previous size and position
return {
...prev,
[name]: {
...state,
maximized: false,
width: state.prevWidth || state.width,
height: state.prevHeight || state.height,
x: state.prevX || state.x,
y: state.prevY || state.y,
},
};
}
});
bringToFront(name);
const updateWindowState = (name: string, newState: Partial) => {
setWindowStates((prev) => ({
...prev,
[name]: {
...prev[name],
...newState,
},
}));
};
function parseSize(size: string, dimension: 'width' | 'height'): number {
if (typeof window === 'undefined') return 400;
if (size.endsWith('%')) {
const percentage = parseFloat(size) / 100;
if (dimension === 'width') {
return percentage * window.innerWidth;
} else {
return percentage * window.innerHeight;
}
} else if (size.endsWith('px')) {
return parseFloat(size);
} else {
return dimension === 'width' ? 400 : 300;
}
}
return (
<WindowManagerContext.Provider
value={{
windows,
windowStates,
openWindow,
closeWindow,
minimizeWindow,
restoreWindow,
maximizeWindow,
updateWindowState,
bringToFront,
}}
>
{children}
</WindowManagerContext.Provider>
);
};
// app/DraggableWindows.tsx
import React from 'react';
import { Rnd } from 'react-rnd';
import {
AiOutlineClose,
AiOutlineMinus,
AiOutlineFullscreen,
} from 'react-icons/ai';
import { useWindowManager } from '../contexts/WindowManagerContext';
import { motion, AnimatePresence } from 'framer-motion';
const DraggableWindows: React.FC = () => {
const {
windows,
windowStates,
closeWindow,
minimizeWindow,
maximizeWindow,
updateWindowState,
bringToFront,
} = useWindowManager();
return (
{Object.keys(windows).map((name) => {
const { Component } = windows[name];
const state = windowStates[name];
code Copy code
if (!Component) return null;
const isVisible = state.visible && !state.minimized;
return (
<AnimatePresence key={name}>
{isVisible && (
<WindowWrapper
key={name}
name={name}
state={state}
bringToFront={bringToFront}
updateWindowState={updateWindowState}
minimizeWindow={minimizeWindow}
maximizeWindow={maximizeWindow}
closeWindow={closeWindow}
>
<Component />
</WindowWrapper>
)}
</AnimatePresence>
);
})}
</div>
// Define the WindowState interface here
interface WindowState {
visible: boolean;
minimized: boolean;
maximized: boolean;
width: number;
height: number;
x: number;
y: number;
zIndex: number;
}
interface WindowWrapperProps {
name: string;
state: WindowState;
bringToFront: (name: string) => void;
updateWindowState: (name: string, newState: Partial) => void;
minimizeWindow: (name: string) => void;
maximizeWindow: (name: string) => void;
closeWindow: (name: string) => void;
children: React.ReactNode;
}
const WindowWrapper: React.FC = ({
name,
state,
bringToFront,
updateWindowState,
minimizeWindow,
maximizeWindow,
closeWindow,
children,
}) => {
const { windowStates } = useWindowManager();
// Determine if the window is the topmost window
const maxZIndex = Math.max(...Object.values(windowStates).map((w) => w.zIndex));
const isTopWindow = state.zIndex === maxZIndex;
// Determine box shadow based on zIndex
const boxShadow = isTopWindow
? '0px 0px 10px rgba(0,0,0,0.5)'
: '0px 0px 5px rgba(0,0,0,0.2)';
// Remove the scale effect to fix blurriness
// Use layout animations for smooth transitions
const windowMotionProps = {
layout: true,
initial: { opacity: 0 },
animate: { opacity: 1 },
exit: { opacity: 0 },
transition: { duration: 0.2 },
};
return (
<Rnd
size={{ width: state.width, height: state.height }}
position={{ x: state.x, y: state.y }}
onMouseDown={() => bringToFront(name)}
onDragStart={() => bringToFront(name)}
onResizeStart={() => bringToFront(name)}
onDragStop={(e, d) => {
updateWindowState(name, { x: d.x, y: d.y });
}}
onResizeStop={(e, direction, ref, delta, position) => {
const newWidth = parseInt(ref.style.width, 10);
const newHeight = parseInt(ref.style.height, 10);
updateWindowState(name, {
width: newWidth,
height: newHeight,
x: position.x,
y: position.y,
});
}}
minWidth={200}
minHeight={100}
cancel=".window-content"
disableDragging={state.maximized}
enableResizing={!state.maximized}
bounds="parent"
style={{ zIndex: state.zIndex }}
>
<motion.div
{...windowMotionProps}
className="bg-white border border-gray-500 flex flex-col h-full"
style={{ boxShadow }}
onMouseDown={() => bringToFront(name)}
>
{/* Window Bar /}
<div
className="flex items-center justify-between bg-gray-200 p-1"
style={{ cursor: state.maximized ? 'default' : 'move' }}
>
{name}
<button
onClick={(e) => {
e.stopPropagation();
minimizeWindow(name);
}}
className="p-1 hover:bg-gray-300"
>
<button
onClick={(e) => {
e.stopPropagation();
maximizeWindow(name);
}}
className="p-1 hover:bg-gray-300"
>
<button
onClick={(e) => {
e.stopPropagation();
closeWindow(name);
}}
className="p-1 hover:bg-gray-300"
>
{/ Window Content */}
{children}
</motion.div>
);
};
export default DraggableWindows;
import React from 'react';
import { useWindowManager } from '../contexts/WindowManagerContext';
const Taskbar: React.FC = () => {
const { windows, windowStates, openWindow, restoreWindow } = useWindowManager();
return (
{Object.keys(windows).map((name) => {
const state = windowStates[name];
if (!state) return null;
code Copy code
let buttonStyle = 'bg-gray-600 text-white px-4 py-1 mx-1 rounded hover:bg-gray-500';
if (state.visible && !state.minimized) {
// Window is open
buttonStyle = 'bg-blue-600 text-white px-4 py-1 mx-1 rounded hover:bg-blue-500';
} else if (state.minimized) {
// Window is minimized
buttonStyle = 'bg-yellow-500 text-white px-4 py-1 mx-1 rounded hover:bg-yellow-400';
} else {
// Window is closed
buttonStyle = 'bg-gray-600 text-white px-4 py-1 mx-1 rounded hover:bg-gray-500';
}
const handleClick = () => {
if (state.visible && !state.minimized) {
// Window is open and not minimized, minimize it
// You might want to change this behavior depending on your needs
} else if (state.minimized) {
// Restore minimized window
restoreWindow(name);
} else {
// Open window
openWindow(name);
}
};
return (
<button key={name} onClick={handleClick} className={buttonStyle}>
{name}
</button>
);
})}
</div>
export const windowProps = {
width: '35%', // Set width as percentage or pixel value
height: '20%', // Set height as percentage or pixel value
};
const Window1 = () => {
return (
Hello World
);
};
TAKS: I want another prop for windows that will determine what defualt state the window is in e.g. open, closed, minimised and the window will be rendered in that state.
To add a new property to determine the default state of the windows (e.g., open, closed, minimized), you can modify the windowProps object and the window initialization logic in your WindowManagerContext.tsx.
Here's how you can achieve this:
1. Update windowProps to include initialState:
In your window components (e.g., windows/Window1.tsx), add a new property initialState to the windowProps object. This property will determine the default state of the window when it first loads.
jsx Copy code
// windows/Window1.tsx
export const windowProps = {
width: '35%', // Set width as percentage or pixel value
height: '20%', // Set height as percentage or pixel value
initialState: 'open', // 'open', 'closed', or 'minimized'
};
const Window1 = () => {
return (
<div className="p-4">
<h1>Hello World</h1>
</div>
);
};
export default Window1;
You can set initialState to 'open', 'closed', or 'minimized' depending on how you want the window to be rendered initially.
2. Update the WindowProps Type Definition:
In your WindowManagerContext.tsx, update the WindowProps type to include initialState:
tsx Copy code
// contexts/WindowManagerContext.tsx
type WindowProps = {
width?: string;
height?: string;
initialState?: 'open' | 'closed' | 'minimized';
};
type WindowData = {
name: string;
Component: React.ComponentType;
windowProps: WindowProps; // Use the updated WindowProps type
};
// ... rest of your code
3. Modify the Window Initialization Logic:
In the importWindows function inside the useEffect, update the logic to set the initial state (visible, minimized, maximized) based on the initialState from windowProps:
tsx Copy code
// contexts/WindowManagerContext.tsx
useEffect(() => {
// Dynamically import window components
const importWindows = async () => {
const windowsContext = require.context('../windows', false, /\.tsx$/);
const windowFiles = windowsContext.keys();
let zIndexCounter = 1;
const windowsDataPromises: Promise<WindowDataAndState>[] = windowFiles.map(
async (file: string, index: number): Promise<WindowDataAndState> => {
const mod = await windowsContext(file);
const name = file.replace('./', '').replace('.tsx', '');
const Component = mod.default;
const windowProps = mod.windowProps || {};
// Parse initial size
const width = windowProps.width
? parseSize(windowProps.width, 'width')
: 0.35 * window.innerWidth;
const height = windowProps.height
? parseSize(windowProps.height, 'height')
: 0.2 * window.innerHeight;
// Determine initial state
const initialState = windowProps.initialState || 'open';
let visible = true;
let minimized = false;
switch (initialState) {
case 'open':
visible = true;
minimized = false;
break;
case 'closed':
visible = false;
minimized = false;
break;
case 'minimized':
visible = false;
minimized = true;
break;
default:
visible = true;
minimized = false;
break;
}
const windowData: WindowData = { name, Component, windowProps };
const windowState: WindowState = {
visible,
minimized,
maximized: false,
width,
height,
x: 100 + index * 50,
y: 100 + index * 50,
zIndex: zIndexCounter++,
};
return { windowData, windowState };
}
);
const windowsDataArray: WindowDataAndState[] = await Promise.all(windowsDataPromises);
const newWindows: { [key: string]: WindowData } = {};
const newWindowStates: { [key: string]: WindowState } = {};
windowsDataArray.forEach(({ windowData, windowState }) => {
newWindows[windowData.name] = windowData;
newWindowStates[windowData.name] = windowState;
});
setWindows(newWindows);
setWindowStates(newWindowStates);
setNextZIndex(zIndexCounter);
};
importWindows();
}, []);
4. Update the WindowState Type (if needed):
Ensure that your WindowState type includes the visible and minimized properties:
tsx Copy code
type WindowState = {
visible: boolean;
minimized: boolean;
maximized: boolean;
width: number;
height: number;
x: number;
y: number;
zIndex: number;
prevWidth?: number;
prevHeight?: number;
prevX?: number;
prevY?: number;
};
With these changes, your windows will now initialize in the state specified by the initialState property in windowProps. Here's how each initialState value affects the window:
'open': The window is visible and not minimized.
'closed': The window is not visible and not minimized.
'minimized': The window is minimized and not visible.
Example Usage in Window Components:
jsx Copy code
// windows/MyWindow.tsx
export const windowProps = {
width: '50%',
height: '50%',
initialState: 'minimized', // Start the window in a minimized state
};
const MyWindow = () => {
return (
<div className="p-4">
<h1>My Window Content</h1>
</div>
);
};
export default MyWindow;
Notes:
The visible property controls whether the window is rendered on the screen.
The minimized property indicates whether the window is minimized.
When a window is minimized, you can decide whether to render it off-screen or not render it at all based on your application's logic.
Action in Taskbar:
Make sure your Taskbar component handles the new initial states accordingly. If a window starts as minimized or closed, the taskbar should reflect that state.
tsx Copy code
// app/Taskbar.tsx
// ... existing code
const handleClick = () => {
if (state.visible && !state.minimized) {
// Window is open and not minimized, minimize it
minimizeWindow(name);
} else if (state.minimized) {
// Restore minimized window
restoreWindow(name);
} else {
// Open window
openWindow(name);
}
};
// ... existing code
Putting It All Together:
By adding the initialState property to your windowProps and updating your window initialization logic, you give each window control over its default state. This allows you to set up your application windows exactly as you need them when your app starts.
Show full message · 224 lines Copy first response
Not yet included in a published release.