Skip to content

Commit

Permalink
feat: Add destory handler
Browse files Browse the repository at this point in the history
  • Loading branch information
manzt committed Jul 14, 2024
1 parent 704cb49 commit af980b2
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export interface VizarrViewer {
addImage(config: ImageLayerConfig): void;
setViewState(viewState: ViewState): void;
on<E extends keyof Events>(event: E, cb: (data: Events[E]) => void): void;
destroy(): void;
}

/** switch to Promise.withResolvers when it's available */
Expand All @@ -44,12 +45,17 @@ export function createViewer(element: HTMLElement): Promise<VizarrViewer> {
atom<ViewState | undefined>(undefined),
({ zoom, target }) => emitter.emit('viewStateChange', { zoom, target })
);
let { promise, resolve } = defer<VizarrViewer>();
const { promise, resolve } = defer<VizarrViewer>();

function App() {
const addImage = useSetAtom(addImageAtom);
const setViewState = useSetAtom(viewStateAtom);
React.useImperativeHandle(ref, () => ({ addImage, setViewState, on: emitter.on }), []);
React.useImperativeHandle(ref, () => ({
addImage,
setViewState,
on: emitter.on,
destroy: () => root.unmount()
}), []);
React.useEffect(() => {
if (ref.current) {
resolve(ref.current);
Expand All @@ -62,13 +68,13 @@ export function createViewer(element: HTMLElement): Promise<VizarrViewer> {
</>
);
}
ReactDOM.createRoot(element).render(
let root = ReactDOM.createRoot(element);
root.render(
<ThemeProvider theme={theme}>
<Provider>
<App />
</Provider>
</ThemeProvider>
);

return promise;
}

0 comments on commit af980b2

Please sign in to comment.