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 WindowProps = {
width?: string;
height?: string;
initialState?: 'open' | 'closed' | 'minimized';
gravity?: number; // New gravity property
};
type WindowData = {
name: string;
Component: React.ComponentType;
windowProps: WindowProps;
};
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);
// Define grid size constant
const GRID_SIZE = 25;
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 · 539 lines Assistant2024-10-06 14:58 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 01m7h41wnd6m50v0j3wj7gkwzkSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 966427c3c5fd887ae0ed30f0f2809953
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
let width = windowProps.width
? parseSize(windowProps.width, 'width')
: 0.35 * window.innerWidth;
let height = windowProps.height
? parseSize(windowProps.height, 'height')
: 0.2 * window.innerHeight;
// Adjust width and height to align with grid
width = Math.round(width / GRID_SIZE) * GRID_SIZE;
height = Math.round(height / GRID_SIZE) * GRID_SIZE;
// 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;
}
// Adjust initial positions to align with grid
const initialX = Math.round((100 + index * 50) / GRID_SIZE) * GRID_SIZE;
const initialY = Math.round((100 + index * 50) / GRID_SIZE) * GRID_SIZE;
const windowData: WindowData = { name, Component, windowProps };
const windowState: WindowState = {
visible,
minimized,
maximized: false,
width,
height,
x: initialX,
y: initialY,
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,
};
const maxWidth = window.innerWidth - 20; // Adjusted width for spacing
const maxHeight = window.innerHeight - 20; // Adjusted height for spacing
// Adjust to align with grid
const adjustedWidth = Math.floor(maxWidth / GRID_SIZE) * GRID_SIZE;
const adjustedHeight = Math.floor(maxHeight / GRID_SIZE) * GRID_SIZE;
return {
...prev,
[name]: {
...state,
maximized: true,
...prevSizePosition,
x: 10, // Adjusted for spacing when maximized
y: 10, // Adjusted for spacing when maximized
width: adjustedWidth,
height: adjustedHeight,
},
};
} 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,
skipGrid = false
) => {
setWindowStates((prev) => {
let updatedState = {
...prev[name],
...newState,
};
code Copy code
if (!skipGrid) {
// Ensure positions and sizes align with the grid
updatedState.x = Math.round(updatedState.x / GRID_SIZE) * GRID_SIZE;
updatedState.y = Math.round(updatedState.y / GRID_SIZE) * GRID_SIZE;
updatedState.width = Math.round(updatedState.width / GRID_SIZE) * GRID_SIZE;
updatedState.height = Math.round(updatedState.height / GRID_SIZE) * GRID_SIZE;
}
return {
...prev,
[name]: updatedState,
};
});
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>
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)';
// 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)}
onDrag={(e, d) => {
updateWindowState(name, { x: d.x, y: d.y }, true); // skipGrid = true
}}
onDragStop={(e, d) => {
updateWindowState(name, { x: d.x, y: d.y }); // Snap to grid after drag ends
}}
onResize={(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,
},
true // skipGrid = true
);
}}
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,
}); // Snap to grid after resize ends
}}
minWidth={200}
minHeight={100}
grid={[25, 25]} // Snapping to 25px grid
dragHandleClassName="window-bar"
disableDragging={state.maximized}
enableResizing={!state.maximized}
bounds="parent"
style={{ zIndex: state.zIndex }}
code Copy code
<motion.div
code Copy code
{...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 window-bar" // Added 'window-bar' class
style={{ cursor: state.maximized ? 'default' : 'move' }}
>
<span className="pl-2">{name}</span>
<div className="flex">
<button
onClick={(e) => {
e.stopPropagation();
minimizeWindow(name);
}}
className="p-1 hover:bg-gray-300"
>
<AiOutlineMinus />
</button>
<button
onClick={(e) => {
e.stopPropagation();
maximizeWindow(name);
}}
className="p-1 hover:bg-gray-300"
>
<AiOutlineFullscreen />
</button>
<button
onClick={(e) => {
e.stopPropagation();
closeWindow(name);
}}
className="p-1 hover:bg-gray-300"
>
<AiOutlineClose />
</button>
</div>
</div>
{/* Window Content */}
<div className="flex-grow overflow-auto window-content">{children}</div>
</motion.div>
</Rnd>
export default DraggableWindows;
TASK: add props to windows for the intial X and intial Y position of teh window can be in px value or % values.
To add support for specifying initial positions (initialX and initialY) for windows in your app, you need to make the following adjustments to your WindowManagerContext.tsx file:
Update the WindowProps Type : Add initialX and initialY properties to the WindowProps type to allow windows to specify their initial positions.
Modify the parseSize Function : Adjust the parseSize function to handle 'x' and 'y' dimensions, so it can parse position values specified in pixels or percentages.
Update the Window Initialization Logic : Modify the code where windows are initialized to use the new initialX and initialY properties from windowProps.
Here’s how you can do it:
1. Update the WindowProps Type
Add initialX and initialY to the WindowProps type:
typescript Copy code
type WindowProps = {
width?: string;
height?: string;
initialX?: string;
initialY?: string;
initialState?: 'open' | 'closed' | 'minimized';
gravity?: number; // New gravity property
};
2. Modify the parseSize Function
Update the parseSize function to also handle 'x' and 'y' dimensions:
typescript Copy code
function parseSize(size: string, dimension: 'width' | 'height' | 'x' | 'y'): number {
if (typeof window === 'undefined') return 400;
if (size.endsWith('%')) {
const percentage = parseFloat(size) / 100;
if (dimension === 'width' || dimension === 'x') {
return percentage * window.innerWidth;
} else if (dimension === 'height' || dimension === 'y') {
return percentage * window.innerHeight;
}
} else if (size.endsWith('px')) {
return parseFloat(size);
} else {
return dimension === 'width' || dimension === 'x' ? 400 : 300;
}
}
3. Update the Window Initialization Logic
In the importWindows function within the useEffect hook, adjust how you calculate initialX and initialY:
typescript Copy code
useEffect(() => {
// Dynamically import window components
const importWindows = async () => {
// ... existing code ...
const windowsDataPromises: Promise<WindowDataAndState>[] = windowFiles.map(
async (file: string, index: number): Promise<WindowDataAndState> => {
// ... existing code ...
// Parse initial size
let width = windowProps.width
? parseSize(windowProps.width, 'width')
: 0.35 * window.innerWidth;
let height = windowProps.height
? parseSize(windowProps.height, 'height')
: 0.2 * window.innerHeight;
// Adjust width and height to align with grid
width = Math.round(width / GRID_SIZE) * GRID_SIZE;
height = Math.round(height / GRID_SIZE) * GRID_SIZE;
// Parse initial position
let initialX = windowProps.initialX
? parseSize(windowProps.initialX, 'x')
: 100 + index * 50; // Default position if not specified
let initialY = windowProps.initialY
? parseSize(windowProps.initialY, 'y')
: 100 + index * 50; // Default position if not specified
// Adjust initial positions to align with grid
initialX = Math.round(initialX / GRID_SIZE) * GRID_SIZE;
initialY = Math.round(initialY / GRID_SIZE) * GRID_SIZE;
// ... existing code ...
const windowState: WindowState = {
visible,
minimized,
maximized: false,
width,
height,
x: initialX,
y: initialY,
zIndex: zIndexCounter++,
};
return { windowData, windowState };
}
);
// ... existing code ...
};
importWindows();
}, []);
Now, when you define your window components, you can specify initialX and initialY in their windowProps. For example:
typescript Copy code
// windows/MyWindow.tsx
import React from 'react';
export const windowProps = {
width: '50%',
height: '50%',
initialX: '25%',
initialY: '25%',
initialState: 'open',
};
const MyWindow: React.FC = () => {
return <div>Content of MyWindow</div>;
};
export default MyWindow;
This will position MyWindow at 25% of the screen width from the left and 25% of the screen height from the top, with a width and height of 50% of the screen size.
Note : The values specified in initialX and initialY can be in pixels (e.g., '200px') or percentages (e.g., '50%').
Full Updated WindowManagerContext.tsx
Here's the full updated code with the modifications:
Testing the Implementation
To test if this works:
Define a window component and specify initialX and initialY in windowProps.
Run your application and ensure the window appears at the specified position.
Try different values (both pixels and percentages) for initialX and initialY to verify they are correctly parsed and applied.
Notes
Grid Alignment : The positions and sizes are adjusted to align with the grid defined by GRID_SIZE. If you don't want this behavior, you can adjust or remove the alignment logic.
Default Positions : If initialX and initialY are not specified, the windows will be placed at default positions that offset by index to prevent overlap.
Error Handling : The parseSize function assumes valid inputs. You might want to add error handling to manage invalid values.
By following these steps, you now have windows that can specify their initial positions using initialX and initialY in their properties, accepting pixel or percentage values.
Show full message · 367 lines Copy first response
Not yet included in a published release.
// contexts/WindowManagerContext.tsx
'use client';
import React, { createContext, useContext, useState, useEffect } from 'react';
type WindowProps = {
width?: string;
height?: string;
initialX?: string;
initialY?: string;
initialState?: 'open' | 'closed' | 'minimized';
gravity?: number; // New gravity property
};
type WindowData = {
name: string;
Component: React.ComponentType;
windowProps: WindowProps;
};
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<WindowState>) => 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);
// Define grid size constant
const GRID_SIZE = 25;
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();
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
let width = windowProps.width
? parseSize(windowProps.width, 'width')
: 0.35 * window.innerWidth;
let height = windowProps.height
? parseSize(windowProps.height, 'height')
: 0.2 * window.innerHeight;
// Adjust width and height to align with grid
width = Math.round(width / GRID_SIZE) * GRID_SIZE;
height = Math.round(height / GRID_SIZE) * GRID_SIZE;
// Parse initial position
let initialX = windowProps.initialX
? parseSize(windowProps.initialX, 'x')
: 100 + index * 50; // Default position if not specified
let initialY = windowProps.initialY
? parseSize(windowProps.initialY, 'y')
: 100 + index * 50; // Default position if not specified
// Adjust initial positions to align with grid
initialX = Math.round(initialX / GRID_SIZE) * GRID_SIZE;
initialY = Math.round(initialY / GRID_SIZE) * GRID_SIZE;
// 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: initialX,
y: initialY,
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();
}, []);
// ... existing code ...
function parseSize(size: string, dimension: 'width' | 'height' | 'x' | 'y'): number {
if (typeof window === 'undefined') return 400;
if (size.endsWith('%')) {
const percentage = parseFloat(size) / 100;
if (dimension === 'width' || dimension === 'x') {
return percentage * window.innerWidth;
} else if (dimension === 'height' || dimension === 'y') {
return percentage * window.innerHeight;
}
} else if (size.endsWith('px')) {
return parseFloat(size);
} else {
return dimension === 'width' || dimension === 'x' ? 400 : 300;
}
}
// ... existing code ...
return (
<WindowManagerContext.Provider
value={{
windows,
windowStates,
openWindow,
closeWindow,
minimizeWindow,
restoreWindow,
maximizeWindow,
updateWindowState,
bringToFront,
}}
>
{children}
</WindowManagerContext.Provider>
);
};