From d6fa38f9af3be1aa7b675b861fbcef80e0a7015e Mon Sep 17 00:00:00 2001 From: Adrien Burgun Date: Sun, 22 Jan 2023 18:37:56 +0100 Subject: [PATCH] :pencil: Document PixelPerfectCanvas, use onCleanup for cleanup --- src/solid/PixelPerfectCanvas.tsx | 39 +++++++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/src/solid/PixelPerfectCanvas.tsx b/src/solid/PixelPerfectCanvas.tsx index e0b7c91..aa130c8 100644 --- a/src/solid/PixelPerfectCanvas.tsx +++ b/src/solid/PixelPerfectCanvas.tsx @@ -1,27 +1,49 @@ -import { JSX, Component, createEffect } from "solid-js"; +import { JSX, Component, createEffect, onCleanup } from "solid-js"; import { attachCanvas } from '../index'; import styles from './PixelPerfectCanvas.module.css'; export type PixelPerfectCanvasProps = { - style?: JSX.CSSProperties, + /** + * Style to be applied to the container. + **/ + style?: Omit, + /** + * Class name(s) to give to the container. Make sure that they do not override the required + * properties (namely `overflow`) + **/ class?: string, + /** + * Fallback text when canvases are not supported, + **/ children?: JSX.Element, + /** + * Callback called each time the canvas changes dimensions or DPR (devicePixelRatio). + **/ onResize?: (canvas: HTMLCanvasElement, width: number, height: number) => void, + /** + * Callback called after the event listeners for dimension and DPR changes are attached. + **/ onAttach?: (canvas: HTMLCanvasElement) => void, + /** + * Callback called after the event listeners for dimension and DPR changes are detached. + **/ + onDetach?: (canvas: HTMLCanvasElement) => void, } /** + * A canvas that is wrapped in a container (which will be styled with `style` or `class`), + * and that will automatically resize when the DPR changes or when the container resizes. * + * `onAttach` is called after the canvas is attached (ie. after the event listeners for + * size change and DPR change are attached) and `onDetach` is called after the canvas is detached. + * + * `onResize` is called after the canvas changes dimensions or DPR. **/ export const PixelPerfectCanvas: Component = (props) => { let canvasRef: HTMLCanvasElement; let containerRef: HTMLDivElement; createEffect>((old) => { - if (old) { - old.unbind(); - } - const result = attachCanvas(canvasRef, { container: containerRef, onResize: props.onResize, @@ -29,6 +51,11 @@ export const PixelPerfectCanvas: Component = (props) => props.onAttach?.(result); + onCleanup(() => { + result.unbind(); + props.onDetach?.(result); + }); + return result; });