tldraw/components/canvas/shape.tsx

113 lines
2.7 KiB
TypeScript
Raw Normal View History

2021-05-12 22:08:53 +00:00
import React, { useCallback, useRef, memo } from "react"
2021-05-12 21:11:17 +00:00
import state, { useSelector } from "state"
import { getPointerEventInfo } from "utils/utils"
2021-05-12 22:08:53 +00:00
import shapes from "lib/shapes"
import styled from "styles"
2021-05-09 21:22:25 +00:00
function Shape({ id }: { id: string }) {
2021-05-12 21:11:17 +00:00
const rGroup = useRef<SVGGElement>(null)
2021-05-09 21:22:25 +00:00
const shape = useSelector((state) => {
const { currentPageId, document } = state.data
return document.pages[currentPageId].shapes[id]
})
2021-05-12 21:11:17 +00:00
const isSelected = useSelector((state) => state.values.selectedIds.has(id))
const handlePointerDown = useCallback(
(e: React.PointerEvent) => {
e.stopPropagation()
rGroup.current.setPointerCapture(e.pointerId)
state.send("POINTED_SHAPE", { id, ...getPointerEventInfo(e) })
},
[id]
)
const handlePointerUp = useCallback(
(e: React.PointerEvent) => {
e.stopPropagation()
rGroup.current.releasePointerCapture(e.pointerId)
state.send("STOPPED_POINTING_SHAPE", { id, ...getPointerEventInfo(e) })
},
[id]
)
const handlePointerEnter = useCallback(
(e: React.PointerEvent) =>
state.send("HOVERED_SHAPE", { id, ...getPointerEventInfo(e) }),
[id]
)
const handlePointerLeave = useCallback(
(e: React.PointerEvent) =>
state.send("UNHOVERED_SHAPE", { id, ...getPointerEventInfo(e) }),
[id]
)
return (
<StyledGroup
ref={rGroup}
isSelected={isSelected}
transform={`translate(${shape.point})`}
onPointerDown={handlePointerDown}
onPointerUp={handlePointerUp}
onPointerEnter={handlePointerEnter}
onPointerLeave={handlePointerLeave}
>
<defs>
2021-05-12 22:08:53 +00:00
{shapes[shape.type] ? shapes[shape.type].render(shape) : null}
2021-05-12 21:11:17 +00:00
</defs>
<HoverIndicator as="use" xlinkHref={"#" + id} />
<use xlinkHref={"#" + id} {...shape.style} />
<Indicator as="use" xlinkHref={"#" + id} />
</StyledGroup>
)
2021-05-09 21:22:25 +00:00
}
2021-05-12 21:11:17 +00:00
const Indicator = styled("path", {
fill: "none",
stroke: "transparent",
2021-05-12 22:08:53 +00:00
zStrokeWidth: 1,
2021-05-12 21:11:17 +00:00
pointerEvents: "none",
strokeLineCap: "round",
strokeLinejoin: "round",
})
const HoverIndicator = styled("path", {
fill: "none",
stroke: "transparent",
2021-05-12 22:08:53 +00:00
zStrokeWidth: 8,
2021-05-12 21:11:17 +00:00
pointerEvents: "all",
strokeLinecap: "round",
strokeLinejoin: "round",
})
const StyledGroup = styled("g", {
[`& ${HoverIndicator}`]: {
opacity: "0",
},
variants: {
isSelected: {
true: {
[`& ${Indicator}`]: {
stroke: "$selected",
},
[`&:hover ${HoverIndicator}`]: {
opacity: "1",
stroke: "$hint",
},
},
false: {
[`&:hover ${HoverIndicator}`]: {
opacity: "1",
stroke: "$hint",
},
},
},
},
})
export { Indicator, HoverIndicator }
2021-05-09 21:22:25 +00:00
export default memo(Shape)