import { useRecoilValue } from 'recoil' import { canvasState, fontFamilyState, fontSizeState } from '@/store/canvasAtom' import { QLine } from '@/components/fabric/QLine' export const useLine = () => { const canvas = useRecoilValue(canvasState) const fontSize = useRecoilValue(fontSizeState) const fontFamily = useRecoilValue(fontFamilyState) const addLine = (points = [], options) => { const line = new QLine(points, { ...options, fontSize: fontSize, fontFamily: fontFamily, }) if (line.length < 1) { return null } canvas?.add(line) return line } const hideLine = (line) => { line.set({ visible: false, }) canvas ?.getObjects() .find((obj) => obj.parent === line) .set({ visible: false, }) canvas?.renderAll() } const showLine = (line) => { line.set({ visible: true, }) canvas ?.getObjects() .find((obj) => obj.parent === line) .set({ visible: true, }) canvas?.renderAll() } const removeLine = (line) => { removeLineText(line) canvas?.remove(line) canvas?.renderAll() } const removeLineText = (line) => { canvas?.remove(canvas?.getObjects().find((obj) => obj.parent === line)) } const getLengthByLine = (line) => { const scaleX = line.scaleX const scaleY = line.scaleY const x1 = line.left const y1 = line.top const x2 = line.left + line.width * scaleX const y2 = line.top + line.height * scaleY const dx = x2 - x1 const dy = y2 - y1 return Number(Math.sqrt(dx * dx + dy * dy).toFixed(1)) * 10 } const addPitchText = (line) => { removePitchText(line) const { startPoint, endPoint, direction, attributes } = line let left, top if (direction === 'top') { left = (startPoint.x + endPoint.x) / 2 top = (startPoint.y + endPoint.y) / 2 - 50 } else if (direction === 'bottom') { left = (startPoint.x + endPoint.x) / 2 top = (startPoint.y + endPoint.y) / 2 - 50 } else if (direction === 'left') { left = (startPoint.x + endPoint.x) / 2 + 50 top = (startPoint.y + endPoint.y) / 2 - 30 } else if (direction === 'right') { left = (startPoint.x + endPoint.x) / 2 + 50 top = (startPoint.y + endPoint.y) / 2 - 30 } const text = new fabric.Text( `${attributes.offset ? attributes.offset * 10 : attributes.width * 10}${attributes.pitch ? '-∠' + attributes.pitch : ''}`, { left, top, fontSize: 20, fill: 'black', name: 'pitchText', parentId: line.id, }, ) canvas.add(text) } const removePitchText = (line) => { const { id } = line const pitchText = canvas.getObjects().filter((obj) => obj.name === 'pitchText' && obj.parentId === id) // 기존 pitchText가 있으면 삭제 if (pitchText.length > 0) { canvas.remove(pitchText) } } const addPitchTextsByOuterLines = () => { canvas .getObjects() .filter((obj) => obj.name === 'outerLine') .forEach((line) => { addPitchText(line) }) } return { addLine, removeLine, hideLine, showLine, addPitchText, removePitchText, addPitchTextsByOuterLines, } }