export const close = (appName, setApps) => { setApps(apps => apps.filter(a => a && a.name !== appName)) } const findSmallestMissing = (arr = []) => { let count = 1; if(!arr?.length){ return count; }; while(arr.indexOf(count) !== -1){ count++; }; return count; }; export const open = ({ appName, buttons, height, width }, setApps, props = {}) => { setApps(apps => { const untouched = apps.filter(a => a.pos.length === 1).map(a => a.pos[0]) const newPos = findSmallestMissing(untouched); return ( apps && apps.length > 0 ? !apps.some(a => a.name === appName) ? [...apps, { name: appName, min: false, max: false, height, width, pos: [newPos], buttons, props }] : apps : [{ name: appName, min: false, max: false, height, width, pos: [newPos], buttons, props }] ) }) } export const focus = (appName, setApps) => { setApps(apps => { const i = apps.length > 0 && apps.findIndex(a => a.name === appName) return i !== apps.length - 1 ? [...apps.filter((_, n) => n !== i), apps[i]] : apps }) } export const unfocus = (appName, setApps) => { setApps(apps => { const i = apps.findIndex(a => a.name === appName) return i !== 0 ? [apps[i], ...apps.filter((_, n) => n !== i)] : apps }) } export const toggleMin = (appName, apps, setApps) => { setApps(apps => ([ ...apps.map(a => a.name === appName ? { ...a, min: !a.min } : a) ])) apps.find(a => a.name === appName).min ? focus(appName, setApps) : unfocus(appName, setApps) } export const toggleMax = (appName, setApps) => setApps(apps => ([ ...apps.map(a => a.name === appName ? { ...a, max: !a.max } : a) ])) export const move = (app, winRef, setApps) => { winRef.current.onmousedown = (event) => { if (!app.max && event.target.classList && event.target.classList.contains('window__title')) { const shiftX = event.clientX - winRef.current.getBoundingClientRect().left const shiftY = event.clientY - winRef.current.getBoundingClientRect().top winRef.current.classList.add('moving') focus(app.name, setApps) function moveAt (pageX, pageY) { const x = pageX - shiftX const y = pageY - shiftY setApps(apps => ([...apps.map(a => a && a.name === app.name ? { ...a, pos: [x + 'px', y < '32' ? '32px' : y + 'px'] } : a )])) } const onMouseMove = (event) => { moveAt(event.pageX, event.pageY) } document.addEventListener('mousemove', onMouseMove) document.onmouseup = () => { document.removeEventListener('mousemove', onMouseMove) winRef.current.classList.remove('moving') document.onmouseup = null } } } winRef.current.ondragstart = () => null }