From daec0cdebf95d15736edc52a4101fdd14c231f47 Mon Sep 17 00:00:00 2001 From: Hatem Hosny Date: Fri, 6 Sep 2024 00:42:29 +0300 Subject: [PATCH] feat(renderer): resize chart on resizing root element --- src/lib/race.ts | 12 +++++++++--- src/lib/renderer/index.ts | 1 + src/lib/renderer/resize-observer.ts | 18 ++++++++++++++++++ 3 files changed, 28 insertions(+), 3 deletions(-) create mode 100644 src/lib/renderer/resize-observer.ts diff --git a/src/lib/race.ts b/src/lib/race.ts index 5d75cf8..887652f 100644 --- a/src/lib/race.ts +++ b/src/lib/race.ts @@ -1,7 +1,12 @@ import * as d3 from './d3'; import { getDateString, prepareData, computeNextDateSubscriber, safeName } from './utils'; import type { Data, WideData } from './data'; -import { createRenderer, rendererSubscriber, type Renderer } from './renderer'; +import { + createRenderer, + createResizeObserver, + rendererSubscriber, + type Renderer, +} from './renderer'; import { createTicker } from './ticker'; import { styleInject } from './styles'; import { actions, createStore, rootReducer, type Store } from './store'; @@ -60,7 +65,8 @@ export async function race( } const events = registerEvents(store, ticker); - window.addEventListener('resize', resize); + const resizeObserver = createResizeObserver(resize); + resizeObserver?.observe(root); function subscribeToStore(store: Store, renderer: Renderer, data: Data[]) { const subscriptions = [ @@ -235,7 +241,7 @@ export async function race( ticker.stop(); store.unsubscribeAll(); events.unregister(); - window.removeEventListener('resize', resize); + resizeObserver?.unobserve(root); root.innerHTML = ''; document.getElementById(stylesId)?.remove(); for (const method of Object.keys(this)) { diff --git a/src/lib/renderer/index.ts b/src/lib/renderer/index.ts index 4910cc0..e7c6b77 100644 --- a/src/lib/renderer/index.ts +++ b/src/lib/renderer/index.ts @@ -1,4 +1,5 @@ export { createRenderer } from './create-renderer'; +export { createResizeObserver } from './resize-observer'; export { elements } from './elements'; export { rendererSubscriber } from './renderer-subscriber'; export type { Renderer } from './renderer.models'; diff --git a/src/lib/renderer/resize-observer.ts b/src/lib/renderer/resize-observer.ts new file mode 100644 index 0000000..acc9cec --- /dev/null +++ b/src/lib/renderer/resize-observer.ts @@ -0,0 +1,18 @@ +export function createResizeObserver(resizeFn: () => void) { + if (window.ResizeObserver && window.requestAnimationFrame) { + return new ResizeObserver((entries) => { + window.requestAnimationFrame((): void | undefined => { + if (!entries?.length) return; + resizeFn(); + }); + }); + } + return { + observe: () => { + window.addEventListener('resize', resizeFn); + }, + unobserve: () => { + window.removeEventListener('resize', resizeFn); + }, + }; +}