import {Box} from "@mui/material";import {useEffect,useRef} from "react";import type {Gallery_Plot_Session} from "../session/gallery_plot_session";import {use_element_size} from "../hooks/use_element_size";
function modifiers(event: {shiftKey:boolean;ctrlKey:boolean;altKey:boolean;metaKey:boolean}): number {return(event.shiftKey?1:0)|(event.ctrlKey?2:0)|(event.altKey?4:0)|(event.metaKey?8:0);}
export function Plot_Canvas({session}:{session:Gallery_Plot_Session}) {const shell_ref=useRef<HTMLDivElement>(null),canvas_ref=useRef<HTMLCanvasElement>(null);const size=use_element_size(shell_ref);useEffect(()=>{const canvas=canvas_ref.current;if(!canvas)return;session.attach_canvas(canvas);return()=>session.detach_canvas();},[session]);useEffect(()=>{if(size.width&&size.height)session.resize(size.width,size.height);},[session,size]);const position=(event:React.PointerEvent<HTMLCanvasElement>|React.WheelEvent<HTMLCanvasElement>)=>{const canvas=canvas_ref.current!;const rect=canvas.getBoundingClientRect();return{x:(event.clientX-rect.left)*canvas.width/Math.max(1,rect.width),y:(event.clientY-rect.top)*canvas.height/Math.max(1,rect.height)};};const pointer=(type:"pointer_move"|"pointer_press"|"pointer_release",event:React.PointerEvent<HTMLCanvasElement>)=>session.pointer(type,{...position(event),button:["left","middle","right"][event.button]??"none",buttons:event.buttons,modifiers:modifiers(event)});return <Box ref={shell_ref} tabIndex={0} sx={{position:"relative",aspectRatio:"16 / 10",minHeight:220,bgcolor:"#03080e",outline:"none",overflow:"hidden"}} onKeyDown={event=>session.key("key_press",{key:event.key,nativeKey:event.keyCode,repeat:event.repeat,modifiers:modifiers(event)})} onKeyUp={event=>session.key("key_release",{key:event.key,nativeKey:event.keyCode,repeat:false,modifiers:modifiers(event)})}><Box component="canvas" ref={canvas_ref} aria-label="Core2 后端像素画布" sx={{width:"100%",height:"100%",display:"block"}} onPointerMove={event=>pointer("pointer_move",event)} onPointerDown={event=>{if(event.button!==2){shell_ref.current?.focus();event.currentTarget.setPointerCapture(event.pointerId);pointer("pointer_press",event);}}} onPointerUp={event=>event.button!==2&&pointer("pointer_release",event)} onPointerLeave={()=>session.leave()} onWheel={event=>{event.preventDefault();session.wheel({...position(event),pixelDeltaX:event.deltaX,pixelDeltaY:event.deltaY,angleDeltaX:-event.deltaX*8,angleDeltaY:-event.deltaY*8,buttons:event.buttons,modifiers:modifiers(event)});}}/></Box>;}
