Created
April 15, 2019 12:23
-
-
Save icodeforlove/143581ce512cff76a3fd3a120e3f44d0 to your computer and use it in GitHub Desktop.
Custom window resize handle for nw.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
const { | |
resizeWindowTo | |
} = nw.global; | |
function ResizeHandle () { | |
let timeout, | |
startW, | |
startH, | |
startX, | |
startY, | |
currentX, | |
currentY, | |
lastResize = new Date(), | |
delayMS = 10, | |
isResizing = false; | |
function onResize () { | |
lastResize = new Date(); | |
let width = startW + (currentX - startX), | |
height = startH + (currentY - startY); | |
resizeWindowTo(width, height); | |
} | |
function onMouseMove (event) { | |
if (isResizing) { | |
currentX = event.x; | |
currentY = event.y; | |
if (new Date() - lastResize > delayMS) { | |
onResize(); | |
} | |
// ensure we pickup the last movement | |
clearTimeout(timeout); | |
timeout = setTimeout(onResize, delayMS); | |
} | |
} | |
function onMouseDown (event) { | |
startX = event.pageX; | |
startY = event.pageY; | |
startW = window.outerWidth; | |
startH = window.outerHeight; | |
isResizing = true; | |
} | |
function onMouseUp (event) { | |
isResizing = false; | |
} | |
useEffect(() => { | |
window.addEventListener('mousemove', onMouseMove); | |
window.addEventListener('mouseup', onMouseUp); | |
return () => { | |
window.removeEventListener('mousemove', onMouseMove); | |
window.removeEventListener('mouseup', onMouseUp); | |
}; | |
}); | |
return <div | |
onMouseDown={onMouseDown} | |
style={{ | |
WebkitAppRegion: 'no-drag', | |
WebkitUserSelect: 'none', | |
cursor: 'nwse-resize', | |
width: 20, | |
height: 20, | |
position: 'absolute', | |
right: -8, | |
bottom: -8, | |
border: '1px solid red' | |
}} | |
></div>; | |
} | |
module.exports = ResizeHandle; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment