diff --git a/code/addons/measure/src/box-model/canvas.ts b/code/addons/measure/src/box-model/canvas.ts index 653e3f005ac1..e40c8a22d306 100644 --- a/code/addons/measure/src/box-model/canvas.ts +++ b/code/addons/measure/src/box-model/canvas.ts @@ -1,5 +1,6 @@ /* eslint-disable no-param-reassign */ import { global } from '@storybook/global'; +import invariant from 'tiny-invariant'; interface Size { width: number; @@ -24,7 +25,7 @@ function getDocumentWidthAndHeight() { function createCanvas(): CanvasState { const canvas = global.document.createElement('canvas'); canvas.id = 'storybook-addon-measure'; - const context = canvas.getContext('2d'); + const context = canvas.getContext('2d') as CanvasRenderingContext2D; // Set canvas width & height const { width, height } = getDocumentWidthAndHeight(); setCanvasWidthAndHeight(canvas, context, { width, height }); @@ -67,16 +68,18 @@ export function init() { export function clear() { if (state.context) { - state.context.clearRect(0, 0, state.width, state.height); + state.context.clearRect(0, 0, state.width ?? 0, state.height ?? 0); } } -export function draw(callback: (context: CanvasRenderingContext2D) => void) { +export function draw(callback: (context?: CanvasRenderingContext2D) => void) { clear(); callback(state.context); } export function rescale() { + invariant(state.canvas, 'Canvas should exist in the state.'); + invariant(state.context, 'Context should exist in the state.'); // First reset so that the canvas size doesn't impact the container size setCanvasWidthAndHeight(state.canvas, state.context, { width: 0, height: 0 }); @@ -91,7 +94,7 @@ export function rescale() { export function destroy() { if (state.canvas) { clear(); - state.canvas.parentNode.removeChild(state.canvas); + state.canvas.parentNode?.removeChild(state.canvas); state = {}; } } diff --git a/code/addons/measure/src/box-model/labels.ts b/code/addons/measure/src/box-model/labels.ts index 80bbf440c92e..022dfdd786c2 100644 --- a/code/addons/measure/src/box-model/labels.ts +++ b/code/addons/measure/src/box-model/labels.ts @@ -285,7 +285,7 @@ export function labelStacks( acc[l.position] = []; } - acc[l.position].push(l); + acc[l.position]?.push(l); return acc; }, {});