|
| 1 | +import { Button } from '@/components/ui'; |
| 2 | +import { Maximize, Minus, Plus } from 'lucide-react'; |
| 3 | +import { useLayoutEffect } from 'react'; |
| 4 | +import { Panel, useViewport, useReactFlow } from 'reactflow'; |
| 5 | + |
| 6 | +const MAX_ZOOM = 2; |
| 7 | +const MIN_ZOOM = 0.5; |
| 8 | + |
| 9 | +export const Controls = () => { |
| 10 | + const { x, y, zoom } = useViewport(); |
| 11 | + const { setViewport } = useReactFlow(); |
| 12 | + |
| 13 | + const zoomPercent = Math.round((zoom - 1) * 100); |
| 14 | + |
| 15 | + const handleZoomIn = () => { |
| 16 | + setViewport({ |
| 17 | + zoom: zoom >= MAX_ZOOM ? MAX_ZOOM : zoom + 0.25, |
| 18 | + x, |
| 19 | + y, |
| 20 | + }); |
| 21 | + }; |
| 22 | + |
| 23 | + const handleZoomOut = () => { |
| 24 | + setViewport({ |
| 25 | + zoom: zoom <= MIN_ZOOM ? MIN_ZOOM : zoom - 0.25, |
| 26 | + x, |
| 27 | + y, |
| 28 | + }); |
| 29 | + }; |
| 30 | + |
| 31 | + const handleFitView = () => { |
| 32 | + setViewport({ |
| 33 | + zoom: 2, |
| 34 | + x: 0, |
| 35 | + y: 0, |
| 36 | + }); |
| 37 | + }; |
| 38 | + |
| 39 | + useLayoutEffect(() => { |
| 40 | + setViewport({ |
| 41 | + zoom: 1.5, |
| 42 | + x: 0, |
| 43 | + y: 0, |
| 44 | + }); |
| 45 | + }, [setViewport]); |
| 46 | + |
| 47 | + return ( |
| 48 | + <Panel position="bottom-left"> |
| 49 | + <div className="flex h-12 items-center bg-card shadow px-2 select-none gap-2 rounded-md"> |
| 50 | + <div className="flex items-center gap-2"> |
| 51 | + <Button size="icon" variant="ghost" onClick={handleZoomIn}> |
| 52 | + <Plus className="w-4 h-4" /> |
| 53 | + </Button> |
| 54 | + <span className="w-9 h-9 flex items-center justify-center"> |
| 55 | + {zoomPercent > 100 ? '100%' : `${zoomPercent}%`} |
| 56 | + </span> |
| 57 | + <Button size="icon" variant="ghost" onClick={handleZoomOut}> |
| 58 | + <Minus className="w-4 h-4" /> |
| 59 | + </Button> |
| 60 | + </div> |
| 61 | + <Button size="icon" variant="ghost" onClick={handleFitView}> |
| 62 | + <Maximize className="w-4 h-4" /> |
| 63 | + </Button> |
| 64 | + </div> |
| 65 | + </Panel> |
| 66 | + ); |
| 67 | +}; |
0 commit comments