git clone https://garage44.eu/jeroen/midas.git.. /web/src/components/measured.ts
import m, {MithrilComponent} from '@garage44/mithril'
import {local} from '@/lib/reactive'
/**
* A component drawn at its container's real width, so an SVG's text stays its
* own size on a phone instead of being scaled down with a viewBox. `width` is
* 0 until the first measure; the view should draw nothing until then.
*/
export abstract class Measured<A = {}> extends MithrilComponent<A> {
private size = local({width: 0})
get width(): number {
return this.size.width
}
private el: Element | null = null
private observer: ResizeObserver | null = null
oncreate(vnode: m.Vnode<A> & {dom?: Element}) {
this.el = vnode.dom ?? null
if (!this.el) return
this.observer = new ResizeObserver(() => this.measure())
this.observer.observe(this.el)
this.measure()
}
onremove() {
this.observer?.disconnect()
}
private measure() {
const w = Math.floor(this.el?.clientWidth ?? 0)
if (w !== this.size.width) this.size.width = w
}
}