Skip to content

Instantly share code, notes, and snippets.

@erukiti
Created March 9, 2019 02:25
Show Gist options
  • Save erukiti/a37201c227d0bf373c512a705a31b552 to your computer and use it in GitHub Desktop.
Save erukiti/a37201c227d0bf373c512a705a31b552 to your computer and use it in GitHub Desktop.
マウスでDnDできる付箋紙というかカンバンっぽい何かを実験してみた
import React, { useState, useCallback } from 'react'
import styled from 'styled-components'
const MovableItem = styled.div`
position: fixed;
top: 0;
left: 0;
width: 450px;
height: 200px;
opacity: 0.8;
cursor: default;
z-index: 10000;
background-color: #888888;
border: 1 solid #88ccff;
border-radius: 4px;
user-select: none;
`
const BaseFrame = styled.div`
width: 1000px;
height: 600px;
background-color: #dddddd;
`
export const Fragment = props => {
const { x, y, grabbed } = props
const [editing, setEditing] = useState(false)
const [value, setValue] = useState(props.value || '')
const cursor = grabbed ? 'move' : 'default'
return (
<MovableItem
onMouseDown={e => props.onMouseDown(e)}
style={{ transform: `translate3D(${x}px, ${y}px, 0px)`, cursor }}
>
{editing ? (
<textarea
style={{ width: '400px', height: '150px' }}
onChange={e => setValue(e.target.value)}
onBlur={() => setEditing(false)}
/>
) : (
<>
<div style={{ width: '400px', height: '150px' }}>{value}</div>
<button onClick={() => setEditing(true)}>edit</button>
</>
)}
</MovableItem>
)
}
export default () => {
const [grabbed, setGrabbed] = useState(false)
const [x, setX] = useState(0)
const [y, setY] = useState(0)
const [grabbedOffsetX, setGrabbedOffsetX] = useState(0)
const [grabbedOffsetY, setGrabbedOffsetY] = useState(0)
const onMouseDown = useCallback(
e => {
setGrabbed(true)
setGrabbedOffsetX(e.clientX - x)
setGrabbedOffsetY(e.clientY - y)
},
[x, y]
)
const onMouseMove = useCallback(
e => {
if (grabbed) {
setX(e.clientX - grabbedOffsetX)
setY(e.clientY - grabbedOffsetY)
console.log(e.clientX, x, grabbedOffsetX)
}
},
[grabbed]
)
const onMouseUp = useCallback(() => {
console.log('up')
setGrabbed(false)
}, [])
return (
<BaseFrame onMouseMove={e => onMouseMove(e)} onMouseUp={e => onMouseUp()}>
<Fragment
x={x}
y={y}
onMouseDown={e => onMouseDown(e)}
grabbed={grabbed}
/>
</BaseFrame>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment