Created
December 19, 2023 15:18
-
-
Save paoloricciuti/f32e8f5f28d7be315df7941717dbfa65 to your computer and use it in GitHub Desktop.
Apply Action action
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* eslint-disable @typescript-eslint/no-explicit-any */ | |
| export type Action = { | |
| id: string; | |
| action: ( | |
| node: HTMLElement, | |
| props?: any | |
| ) => { update?: (newProps: any) => void; destroy?: () => void }; | |
| props?: any; | |
| }; | |
| /** | |
| * An action that takes an array of action and apply each one to the element, useful when you want | |
| * to pass an action or a series of actions to a component | |
| */ | |
| export function applyActions(node: HTMLElement, actions: Array<Action>) { | |
| const returns = new Map<string, { retval: ReturnType<Action['action']>; props?: unknown }>(); | |
| for (const { action, props, id } of actions) { | |
| returns.set(id, { retval: action(node, props), props }); | |
| } | |
| return { | |
| update(actions: Array<Action>) { | |
| for (const { props, id } of actions) { | |
| const { props: old_props, retval } = returns.get(id) ?? {}; | |
| if (props !== old_props && retval?.update) { | |
| retval.update(props); | |
| } | |
| } | |
| }, | |
| destroy() { | |
| for (const [, actions] of returns) { | |
| actions?.retval?.destroy?.(); | |
| } | |
| }, | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment