1.0.2 • Published 3 years ago

svelte-useactions v1.0.2

Weekly downloads
-
License
ISC
Repository
github
Last release
3 years ago

npm.io

About

This library is based on the svelte-material-ui useActions implementation.

It enables you to use actions on custom components. Additionally you get type safety.

Installation

npm i svelte-useactions

#or

yarn add svelte-useactions

Basic Example

First create your component that accepts an array of actions.

<!-- Input.svelte -->

<script lang="ts">
  import { useActions } from 'svelte-useactions';
  import type { ActionList } from 'svelte-useactions';

  export let use: ActionList<HTMLDivElement> = [];
</script>

<input use:useActions="{use}" />

Next define your action function

// autofocus.ts

export const autofocus: Action<HTMLInputElement> = (node) => {
  node.focus();
};

Now you can define actions for components.

<!-- index.svelte -->

<script lang="ts">
  import { autofocus } from '$lib/autosize';
  import { createActionList } from 'svelte-useactions';
</script>

<input use={createActionList([[autofocus]])} />

You can also define parameters

// autofocus.ts

export const autofocus: Action<HTMLInputElement, string> = (node, text) => {
  node.focus();
  console.log(text);
};
<!-- Other code... -->

<Input use={createActionList([[autofocus, "hey!"]])} />

Note

createActionList is merely used for type-safety. If you don't care about it you can just input a normal action list.

Example:

<!-- Other code... -->

<Input use={[[autofocus, "hey!"]]} />

API

useActions

Used in tandem with the use directive. Accepts an action list as a parameter.

<script lang="ts">
  import { useActions } from 'svelte-useactions';
  import type { Actions } from 'svelte-useactions';

  export let use: Actions<HTMLDivElement> = [];
</script>

<input use:useActions={use}

createActionList

A wrapper function that provides better intellisense/type-checking.

Takes in an action list

<!-- No parameters -->
<input use="{createActionList([[autofocus]])}" />

<!-- With parameters  -->
<Input use={createActionList([[autofocus, "hey!"]])} />

<!-- Multiple Actions-->
<Input use={createActionList([[autofocus], [anotherAction, {foo: "bar"}]])} />

ActionList

An array of tuples where the first item is the action and optionally the parameters of the action as the second item.

let actions: ActionList<HTMLDivElement> = [];
const duration = 500;

// With one action
actions = [[autofocus]];

// One action with parameters
actions = [[longpress, duration]];

// Multiple actions
actions = [[longpress, duration], [autofocus]];