aboutsummaryrefslogtreecommitdiffstats
path: root/helpers/windowActions.js
blob: 8ff361bfc0ea038f40e4721a04c5a36afd3c2263 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
export const close = (appName, setApps) => {setApps(apps => apps.filter(a => a.name !== appName))}

export const open = ({appName, buttons, height, width}, setApps) => {
  setApps(apps => (
    !apps.some(a => a.name === appName)
      ? [...apps, {name: appName, min: false, max: false, height, width, pos: [], buttons}]
      : apps
  ))
}

export const focus = (appName, setApps) => {
  setApps(apps => {
    const i = 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, setApps) => {
  setApps(apps => ([
    ...apps.map(a => a.name === appName ? {...a, min: !a.min} : a )
  ]))
  unfocus(appName, setApps)
}

export const toggleMax = (appName, setApps) => setApps(apps => ([
  ...apps.map(a => a.name === appName ? {...a, max: !a.max} : a )
]))


export const move = (appName, winRef, setApps) => {
  winRef.current.onmousedown = (event) => {
    if (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(appName, setApps)

      function moveAt(pageX, pageY) {
        const x = pageX - shiftX
        const y = pageY - shiftY - 32

        setApps(apps => ([...apps.map(a => a.name === appName
          ? {...a, pos: [x + 'px', y < 0 ? 0 : 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
}