Skip to content

Commit

Permalink
feat(renderer): resize chart on resizing root element
Browse files Browse the repository at this point in the history
  • Loading branch information
hatemhosny committed Sep 5, 2024
1 parent a023795 commit daec0cd
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/lib/race.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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 = [
Expand Down Expand Up @@ -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)) {
Expand Down
1 change: 1 addition & 0 deletions src/lib/renderer/index.ts
Original file line number Diff line number Diff line change
@@ -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';
18 changes: 18 additions & 0 deletions src/lib/renderer/resize-observer.ts
Original file line number Diff line number Diff line change
@@ -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);
},
};
}

0 comments on commit daec0cd

Please sign in to comment.