import React, {useState, useRef, useEffect} from 'react' import {DateTime} from 'luxon' import {Button} from '~/components/form' import styles from '~/styles/shippingLabel.module.css' import useLocalStorage from '~/hooks/useLocalStorage' OrderLabel.getInitialProps = async ({ctx: {axios, query: {id}}}) => { const {data: order} = await axios.get(`/api/orders/${id}`) return {order} } export default function OrderLabel({order}){ const [printCache, setPrintCache] = useLocalStorage('admin:orderlabelview', {}) const [imgLoaded, setImgLoaded] = useState(false) const imgRef = useRef() const currentRotation = parseInt(printCache[order.uuid]?.rotation || '0deg', 10) // On first load, if we haven't already decided rotation for this image, // determine based on aspect ratio useEffect(() => { if(printCache[order.uuid] || !imgRef.current || !imgLoaded) return; const {current: img} = imgRef if(img.naturalWidth > img.naturalHeight) setRotation(90) }, [printCache, imgLoaded, imgRef.current]) function setRotation(deg) { setPrintCache(printCache => { return clearCache({ ...printCache, [order.uuid]: { uuid: order.uuid, rotation: deg + 'deg', timestamp: DateTime.local().toISO() } }) }) } function rotateRight() { setRotation((currentRotation + 90) % 360) } function rotateLeft() { setRotation((currentRotation - 90) % 360) } function print() { printLabel(imgRef.current, currentRotation) } return ( <>