/* Adapted from https://stackoverflow.com/a/35373030 */ import { size } from '@planview/pv-utilities' const isJSDOM = typeof navigator !== 'undefined' && navigator.userAgent.includes('jsdom') /* Used as singletons with lazy setup */ let canvas: HTMLCanvasElement let context: CanvasRenderingContext2D const FONT_DEFAULT = 13 export function measureTextWidth( text: string, fontSize: number = FONT_DEFAULT, fontWeight = 'normal', fontFamily = 'ProximaNova, PromixaNovaRegular, sans-serif' ) { if (!context) { /** * JSDOM doesn't throw an error, but instead writes a console.error * if you attempt to call getContext. By testing explicitly for it * we can avoid the error in tests */ if (isJSDOM) { return size.small } canvas = window.document.createElement('canvas') const ctx = canvas.getContext('2d') if (ctx) { context = ctx } else { /* This should never be run since there are very limited cases where a canvas will return null for getContext */ return size.small } } context.font = `${fontWeight} ${fontSize}px ${fontFamily}` return context.measureText(text).width }