Skip to content

Instantly share code, notes, and snippets.

@paoloricciuti
Created December 19, 2023 15:18
Show Gist options
  • Select an option

  • Save paoloricciuti/f32e8f5f28d7be315df7941717dbfa65 to your computer and use it in GitHub Desktop.

Select an option

Save paoloricciuti/f32e8f5f28d7be315df7941717dbfa65 to your computer and use it in GitHub Desktop.
Apply Action action
/* 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