Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feat] action types #7121

Merged
merged 11 commits into from Feb 26, 2022
1 change: 1 addition & 0 deletions .gitignore
Expand Up @@ -9,6 +9,7 @@ node_modules
/compiler.*js
/index.*js
/ssr.*js
/action
/internal
/store
/easing
Expand Down
3 changes: 3 additions & 0 deletions package.json
Expand Up @@ -39,6 +39,9 @@
"import": "./compiler.mjs",
"require": "./compiler.js"
},
"./action": {
"types": "./types/runtime/action/index.d.ts"
},
"./animate": {
"types": "./types/runtime/animate/index.d.ts",
"import": "./animate/index.mjs",
Expand Down
42 changes: 42 additions & 0 deletions src/runtime/action/index.ts
@@ -0,0 +1,42 @@
/**
* Actions can return an object containing the two properties defined in this interface. Both are optional.
* - update: An action can have a parameter. This method will be called whenever that parameter changes,
* immediately after Svelte has applied updates to the markup.
* - destroy: Method that is called after the element is unmounted
*
* Example usage:
* ```ts
* export function myAction(node: HTMLElement, paramater: Parameter): ActionReturn<Parameter> {
* // ...
* return {
* update: (updatedParameter) => {...},
* destroy: () => {...}
* };
* }
* ```
*
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
*/
export interface ActionReturn<Parameter = any> {
update?: (parameter: Parameter) => void;
destroy?: () => void;
}

/**
* Actions are functions that are called when an element is created.
* You can use this interface to type such actions.
* The following example defines an action that only works on `<div>` elements
* and optionally accepts a parameter which it has a default value for:
* ```ts
* export const myAction: Action<HTMLDivElement, { someProperty: boolean }> = (node, param = { someProperty: true }) => {
* // ...
* }
* ```
* You can return an object with methods `update` and `destroy` from the function.
* See interface `ActionReturn` for more details.
*
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
*/
export interface Action<Element = HTMLElement, Parameter = any> {
<Node extends Element>(node: Node, parameter?: Parameter): void | ActionReturn<Parameter>;
}