webextension-state
v0.6.79
Published
Library for managing the state of webextensions, employing reactivity, wrapping and uniting usage of different storages' values and common variables with a simple universal interface
Downloads
823
Maintainers
Readme
Webextension State
Library for managing the state of webextensions, employing reactivity, wrapping and uniting usage of different storages' values and common variables with a simple universal interface.
How to install and prepare
Install the library through
npm install webextension-statethen import with
import State from 'webextension-state'in your script file.
Contents
- Usage
1.1 Creation.add()/.addPersistent()/.changes.*()
1.2 Dynamic reevaluation (ReactiveFunction)
1.3 Accessing.get()
1.4 Mutating.set()/.reset()
1.5 Listening.onChange()/.removeListener()
1.6 Data encapsulation.actions()
1.7 Namespacing.get(Namespace)
1.8 Method chaining - Shortcuts
- Example
Usage
The library object features the following methods and properties:
.add ()
.addPersistent ()
.get ()
.set ()
.reset ()
.changes {}
.onChange ()
.removeListener ()
.actions ()
.namespace () // just returns the string value of the current namespaceCreation .add()/.addPersistent()
Values are added to the store with add or addPersistent methods. They perform the same functionality, except addPersistent saves state to the storage and lets you reuse it between browser sessions.
async State.add(
KeysValues {
key1: value1,
key2: value2,
key3: ReactiveFunction(...valueNames[]) => computedValue
...
}
) => StateWhere:KeysValues {} - a standard object with keys and values, where key is a name of piece of state, and value is a default value or ReactiveFunctionReactiveFunction - re-evalutes and updates its value automatically each time arguments in valueNames list change. valueNames are any state values defined before the ReactiveFunction. computedValues are not saved in storage.
[!WARNING]
addandaddPersistentare asynchronous operations; you mustawaitor usePromise.thento ensure all the data is ready to work with!
Dynamic reevaluation (ReactiveFunction)
Values can change automatically with the help of ReactiveFunctions when one or more of the other values in the namespace change.
ReactiveFunction (...valueNames[]) => computedValuePut the names of dependencies in the valueNames arguments list of the ReactiveFunction, and describe the calculation in the body of the function.
State.add({
a: 1
b: 2,
c: (a, b) => a + b // 3
})Accessing .get()
Values are accessed with:
State.get() => NamespaceValues {}Where:NamespaceValues {} - an object representing all the values in the current namespace at the current moment
Mutating .set()/.reset()/.changes.*()
Values are mutated with:
async State.set(
KeysValues {
key: value
...
}
) => State
To reset values back to defaults:
async State.reset(Keys []) => StateWhere:Keys[] (optional) - array of keys to return to default values. If omitted all values will be returned to defaults.
For more control over the timing of state changes in the namespace, use .changes {} methods collection.
State.changes.add(KeysValues {}) // => adds pending changes in the current namespace
State.changes.reset(Keys []) // => adds pending changes that will reset some of the keys
State.changes.get() // => gets pending changes in the current namespace
State.changes.flush() // => returns and then empties the pending changes object
State.changes.commit() // => actually commits all accumulated pending changes in the namespace[!WARNING] Values are mutated asynchronously; don't assume the script will recognize the change immediately on the next line. Instead,
awaitor make use ofonChangelisteners!
Listening .onChange()/.removeListener()
To listen and react to state changes:
State.onChange(
Keys[],
ChangeCallback(ChangedKeys [], State) => void
) => StateWhere:Keys[] (optional) - array of keys of the state in the current namespace that you want to listen to. If omitted, ChangeCallback will run on any value change in the namespace.
ChangeCallback - a function to run when the change happens. Takes ChangedKeys[] array of keys that have been changed as the first argument, and a State instance as the second.
To remove the listener:
State.removeListener(
Keys[],
ChangeCallback(ChangedKeys [], State) => void
) => Statethe same parameter usage.
Data encapsulation .actions()
Hide away all public data access and mutation into dedicated functions with the help of StateActions.
State.actions({
KeysActions {
key1: StateAction1 (State, ...arguments[]) => void
key2: StateAction2 (State, ...arguments[]) => void
...
}
})StateAction function type binds State instance as the first argument, followed by all other arguments provided by the user at the time of the call.
These actions reside in the same scope as regular variables. So you can access them by the keys defined in KeysActions object through the .get() method.
State.add({ x: 1 });
State.actions({
changeX: (state, newX) => state.set({ x: newX }),
}),
State.get().changeX(10);Namespacing .get(Namespace)
To avoid name collisions, put keys with the same name in different namespaces. You can create a new or get an existing namespace with
State.get(Namespace string) => Statewhich will return a new instance of State with the specified Namespace.
Method chaining
Methods .add, .addPersistent, .set(), .reset(), .onChange(), and .removeListener() all return a new instance of State with the same namespace, so method chaining is possible.
Shortcuts
The library/namespace object itself can be called with different types of arguments, which will mirror almost all of its API.
State() -> State.get()
State(String namespace) -> State.get(namespace)
State({ key: value }) -> State.set({ key: value })
State([], () => {}) -> State.onChange([], () => {})
State(() => {}) -> State.onChange(() => {}) Example
function onChange(changes, store) {
console.log("onChange", store.get());
}
State.add({
a: 10,
b: 20,
c: (a, b) => a + b,
});
await State.addPersistent({
d: 40,
});
console.log(State.get()); // {a: 10, b: 20, c: 30, d: 40}
State.onChange(["a", "b", "c", "d"], onChange);
State.onChange(onChange);
await State.set({ a: 20, b: 88, d: 60 });
console.log(State.get()); // {a: 20, b: 88, c: 108, d: 60}
await State.reset(["b"]);
console.log(State.get()); // {a: 20, b: 20, c: 40, d: 60}
await State.reset();
console.log(State.get()); // {a: 10, b: 20, c: 30, d: 40}
State.removeListener(["a", "b", "c", "d"], onChange);
State.removeListener(onChange);
const newNamespace = State("new namespace");
await newNamespace.add({
x: 1,
y: 2,
z: 3,
});
newNamespace.actions({
logValues: ({ get }) => {
const { x, y, z } = get();
console.log(`x: ${x}, y: ${y}, z: ${z}`);
},
multiplyX: ({ get, set }, num) => set({ x: get().x * num }),
incrementY: ({ get, set }) => set({ y: get().y + 1 }),
})
const { logValues, multiplyX, incrementY } = newNamespace.get();
logValues(); // x: 1, y: 2, z: 3
multiplyX(10)
incrementY();
logValues(); // x: 10, y: 3, z: 3
await newNamespace({ z: 110 });
console.log(State("new namespace").get()); // {x: 10, y: 3, z: 110, logValues: ƒ, multiplyX: ƒ, …}
const thirdNamespace = State("third namespace");
thirdNamespace.add({
phrase: "Hello",
to: "world",
});
thirdNamespace.changes.add({ phrase: "Greetings" });
thirdNamespace.changes.add({ to: "you" });
console.log(thirdNamespace.get()) // {phrase: 'Hello', to: 'world'}
thirdNamespace.changes.commit();
console.log(thirdNamespace.get()) // {phrase: 'Greetings', to: 'you'}
