diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 912f2ea..af91488 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -14,19 +14,11 @@ jobs:
run_install: true
- uses: CompeyDev/setup-rokit@v0.1.2
- - name: Setup Lute
- run: lute setup --with-luaurc
-
- name: Check code quality
- run: lute run check
-
- - name: Run ESLint and Prettier
- run: |
- pnpm eslint packages
- pnpm prettier --check packages
+ run: sh bin/check.sh
- name: Run tests
- run: lute run test
+ run: lune run test/spec.server.luau
- name: Build models
- run: lute run build
+ run: sh bin/build.sh
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 3bd512d..5bdee21 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -11,11 +11,8 @@ jobs:
- uses: actions/checkout@v4
- uses: CompeyDev/setup-rokit@v0.1.2
- - name: Setup Lute
- run: lute setup --with-luaurc
-
- name: Build models
- run: lute run build
+ run: sh bin/build.sh
- name: Upload release assets
uses: AButler/upload-release-assets@v3.0
diff --git a/.gitignore b/.gitignore
index d217e96..52e0af1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -2,7 +2,7 @@
/.pesde
/build
/packages/**/wally.lock
-/packages/**/LICENSE*
+/packages/**/LICENSE.md
/packages/**/README.md
/sourcemap.json
node_modules
diff --git a/.gitmodules b/.gitmodules
index 409278b..e1cba9d 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,3 +1,3 @@
-[submodule "tests/test"]
- path = tests/test
+[submodule "test/suite"]
+ path = test/suite
url = https://gist.github.com/littensy/fa9afcc5d66d25e86538634982be4ee4
diff --git a/.luaurc b/.luaurc
index c48b0f2..4c8043d 100644
--- a/.luaurc
+++ b/.luaurc
@@ -1,7 +1,6 @@
{
"languageMode": "strict",
- "aliases": {
- "lute": "~/.lute/typedefs/1.0.0/lute",
- "std": "~/.lute/typedefs/1.0.0/std"
+ "lint": {
+ "LocalShadow": false
}
}
diff --git a/.lute/build.luau b/.lute/build.luau
deleted file mode 100644
index b708003..0000000
--- a/.lute/build.luau
+++ /dev/null
@@ -1,6 +0,0 @@
-local fs = require("@std/fs")
-local process = require("@lute/process")
-
-fs.createDirectory("build")
-
-process.run({ "rojo", "build", "--output=build/charm.rbxm", "build.project.json" }, { stdio = "inherit" })
diff --git a/.lute/check.luau b/.lute/check.luau
deleted file mode 100644
index b5ad31b..0000000
--- a/.lute/check.luau
+++ /dev/null
@@ -1,33 +0,0 @@
-local fs = require("@std/fs")
-local net = require("@std/net")
-local process = require("@lute/process")
-
-process.run({ "rojo", "sourcemap", "--output=sourcemap.json" }, { stdio = "inherit" })
-
-fs.writeStringToFile(
- "roblox.d.luau",
- net.request("https://luau-lsp.pages.dev/globalTypes.None.d.luau", { method = "GET" }).body
-)
-
-local analyze = process.run({
- "luau-lsp",
- "analyze",
- "--sourcemap=sourcemap.json",
- "--ignore=**/node_modules/**",
- "--base-luaurc=.luaurc",
- "--definitions=roblox.d.luau",
- "--flag:LuauSolverV2=true",
- "packages",
- "tests",
- "benches",
-}, { stdio = "inherit" })
-
-fs.remove("roblox.d.luau")
-
-local stylua = process.run({ "stylua", "--check", "packages", "tests", "benches" }, { stdio = "inherit" })
-
-local eslint = process.run({ "pnpm", "eslint", "packages" }, { stdio = "inherit" })
-
-if not (analyze.ok and stylua.ok and eslint.ok) then
- process.exit(1)
-end
diff --git a/.lute/test.luau b/.lute/test.luau
deleted file mode 100644
index 4abbbb9..0000000
--- a/.lute/test.luau
+++ /dev/null
@@ -1 +0,0 @@
-(require)("../tests/run.server")
diff --git a/.npmrc b/.npmrc
new file mode 100644
index 0000000..b644580
--- /dev/null
+++ b/.npmrc
@@ -0,0 +1 @@
+public-hoist-pattern[]=*@rbxts*
diff --git a/LICENSE b/LICENSE
deleted file mode 100644
index d10b611..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright 2024-present Littensy
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000..ae1bb3d
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,7 @@
+Copyright 2024 Littensy
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
index 07d9641..b5a7a2f 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
Charm
- Fine-grained reactivity for Roblox
+ Manage state with reactive signals
npm package →
@@ -14,26 +14,27 @@

[](https://www.npmjs.com/package/@rbxts/charm)
-[](LICENSE)
+[](LICENSE.md)
-Charm is a reactive state management library designed for storing data in discrete containers called _signals_. Connect behavior to data with signals, ensuring systems stay up-to-date with their underlying data while reactivity eliminates the need for manual updates.
+**Charm** is a Roblox state management library inspired by the [reactive signals](https://preactjs.com/blog/introducing-signals/) from libraries like Preact and Solid. It's built on [alien-signals](https://github.com/stackblitz/alien-signals), modified for a wide range of use cases: from rendering user interfaces to handling game logic.
-**Build game state from simple building blocks:**
+**Charm works under a few core principles.**
-- Store data in [signals](#signalinitialvalue-equals): reactive state containers that hold a value
-- React to state changes with [effects](#effectcallback): re-run code when signals update
-- Derive new values from data with [computed signals](#computedgetter): memoize functions that access signals
+- Manage state with reactive signals: state containers that hold a value
+- React to state updates: reading a signal automatically subscribes to it
+- Combine multiple signals: derive new values from existing state that stay up-to-date
+- Fine-grained reactivity: make targeted updates in response to specific changes in the state
+- Data should be immutable: values are compared directly (`==`) to optimize change detection
-**Want to learn more about reactivity?**
+**Want to learn more about signals?**
-- https://dev.to/ryansolid/a-hands-on-introduction-to-fine-grained-reactivity-3ndf
- https://preactjs.com/blog/introducing-signals
- https://docs.solidjs.com/advanced-concepts/fine-grained-reactivity
-- https://github.com/roblox/signals
+- https://angular.dev/guide/signals
-[Migrating from an older version of Charm?](#migration)
+[Migrating from an older version?](#migration)
Table of Contents
@@ -43,17 +44,18 @@ Charm is a reactive state management library designed for storing data in discre
- [`signal(initialValue, equals?)`](#signalinitialvalue-equals)
- [`computed(getter)`](#computedgetter)
- [`effect(callback)`](#effectcallback)
- - [Nested effects](#nested-effects)
+ - [`reactive(initialValue)`](#reactiveinitialvalue)
+ - [`untracked(callback)`](#untrackedcallback)
+ - [`peek(callback)`](#peekcallback)
+ - [`batch(callback)`](#batchcallback)
- [`effectScope(callback)`](#effectscopecallback)
- [`listen(getter, callback)`](#listengetter-callback)
- - [Getter functions](#getter-functions)
- - [`observe(getter, callback)`](#observegetter-callback)
- [`subscribe(getter, callback)`](#subscribegetter-callback)
- - [`untracked(callback)`](#untrackedcallback)
- - [`batch(callback)`](#batchcallback)
- - [`mapped(getter, transform)`](#mappedgetter-transform)
+ - [`observe(getter, callback)`](#observegetter-callback)
+ - [`mapped(getter, mapper)`](#mappedgetter-mapper)
- [`onCleanup(callback, failSilently?)`](#oncleanupcallback-failsilently)
- [`atom(initialValue, equals?)`](#atominitialvalue-equals)
+ - [`recursive()`](#recursive)
- [`trigger(callback)`](#triggercallback)
- [`flags`](#flags)
- [Client-Server Sync](#client-server-sync)
@@ -62,12 +64,6 @@ Charm is a reactive state management library designed for storing data in discre
- [Server API](#config)
- [Client API](#clientaddsignalssetters)
- [Sync Caveats](#sync-caveats)
-- [Deep Reactivity](#deep-reactivity)
- - [Installation](#installation-2)
- - [`reactive(initialValue)`](#reactiveinitialvalue)
- - [Mutation vs. update function](#mutation-vs-update-function)
- - [`toRaw(value)`](#torawvalue)
- - [`isReactive(value)`](#isreactivevalue)
- [Migration](#migration)
- [Examples](#examples)
@@ -76,19 +72,19 @@ Charm is a reactive state management library designed for storing data in discre
## At a Glance
```luau
-local getTodos, setTodos = signal({} :: { string })
+local getTodos, setTodos = signal({} :: { [number]: string })
local getQuery, setQuery = signal("")
-observe(getTodos, function(todo: string, index: number)
+observe(getTodos, function(todo, index)
local instance = Instance.new("TextLabel")
- local getText = computed(function()
- return getTodos()[index] or ""
+ local getText = computed(function(prevText)
+ return getTodos()[index] or prevText
end)
effect(function()
instance.Text = getText()
- instance.Visible = string.match(getText(), getQuery()) ~= nil
+ instance.Visible = getText():match(getQuery()) ~= nil
end)
instance.LayoutOrder = index
@@ -101,31 +97,30 @@ observe(getTodos, function(todo: string, index: number)
end)
setTodos({ "Buy milk", "Buy eggs", "Play Roblox" })
-setQuery("Buy")
+setQuery("^Buy")
```
Explain code
```luau
--- Declare state for a todo list and a search query
-local getTodos, setTodos = signal({} :: { string })
+local getTodos, setTodos = signal({} :: { [number]: string })
local getQuery, setQuery = signal("")
-- Create a text label when an item is added to the list
observe(getTodos, function(todo, index)
local instance = Instance.new("TextLabel")
- -- Create a memoized function that only re-runs effects when the todo list
- -- updates or the function returns new text
- local getText = computed(function()
- return getTodos()[index] or ""
+ -- Create a computed signal that stores the current text, or the previous
+ -- value if the item was removed
+ local getText = computed(function(prevText)
+ return getTodos()[index] or prevText
end)
- -- Update instance properties when the text or query updates
+ -- Set properties when the text or query updates
effect(function()
instance.Text = getText()
- instance.Visible = string.match(getText(), getQuery()) ~= nil
+ instance.Visible = getText():match(getQuery()) ~= nil
end)
instance.LayoutOrder = index
@@ -140,8 +135,8 @@ end)
-- Add items to the todo list
setTodos({ "Buy milk", "Buy eggs", "Play Roblox" })
--- Filter for items containing "Buy"
-setQuery("Buy")
+-- Filter for items starting with "Buy"
+setQuery("^Buy")
```
@@ -155,7 +150,6 @@ pnpm add @rbxts/charm
```
```toml
-# wally.toml
[dependencies]
Charm = "littensy/charm@VERSION"
```
@@ -171,11 +165,11 @@ Signals are the core of reactivity in Charm. The `signal` function creates a rea
```luau
local getCounter, setCounter = signal(0)
+print(getCounter()) -- 0
setCounter(1)
setCounter(function(count)
return count + 1
end)
-print(getCounter()) -- 2
```
Accessing the signal's value in an effect or computed signal will subscribe to it as a dependency. Changing the value will immediately notify every effect and computed signal that depends on the signal, ensuring all of your state is correct and up-to-date.
@@ -193,7 +187,42 @@ setMax(-1) -- 2
```
> [!NOTE]
-> Looking for atoms? You can still use [`atom()`](#atominitialvalue-equals) to create a signal with a unified getter and setter.
+> Looking for atoms? You can still use [`atom()`](#atominitialvalue-equals) to create a signal with a combined getter and setter.
+
+---
+
+### `computed(getter)`
+
+The `computed` function creates a new signal with a value derived from multiple signals. The computed signal can be reacted to like a normal signal, and it returns the getter function's last return value.
+
+The computed signal will subscribe to signals accessed by the getter and track them as dependencies. Changes to these dependencies will re-execute the getter, and if it returns a new value, then the computed signal is updated to that value.
+
+```luau
+local getName, setName = signal("John")
+local getSurname, setSurname = signal("Doe")
+local getFullName = computed(function()
+ return `{getName()} {getSurname()}`
+end)
+
+print(getFullName()) -- "John Doe"
+setName("Jane")
+print(getFullName()) -- "Jane Doe"
+```
+
+The getter function also receives the previous state (or `nil` if running for the first time). You can use this for more complex state:
+
+```luau
+local getCounter, setCounter = signal(10)
+local getMax = computed(function(prevMax)
+ return math.max(getCounter(), prevMax or 0)
+end)
+
+print(getMax()) -- 10
+setCounter(5)
+print(getMax()) -- 10
+```
+
+Computed signals are updated lazily, meaning the getter will only re-execute once the computed signal is called _and_ if a dependency updated since the last call.
---
@@ -204,9 +233,10 @@ Effects are fundamental to reactivity, allowing you to react to signal updates.
```luau
local getCounter, setCounter = signal(0)
+-- Count is 0
effect(function()
print(`Count is {getCounter()}`)
-end) -- Count is 0
+end)
setCounter(1) -- Count is 1
```
@@ -227,29 +257,20 @@ setCounter(1) -- Cleanup 0
dispose() -- Cleanup 1
```
-### Nested Effects
-
-An effect is _nested_ if it was created during the execution of another effect. In Charm, when an effect with nested effects re-runs or gets cleaned up, the nested effects from the previous run are automatically cleaned up and re-created if needed. This prevents memory leaks and ensures that outer effects always run before their inner effects:
+Effects can be nested and they will clean up automatically when the parent effect re-runs or gets disposed. This means you don't have to manually clean up inner effects, and this applies to functions like `subscribe()` and `observe()`.
```luau
-local getPrintCount, setPrintCount = signal(true)
-local getCount, setCount = signal(1)
+local getCounter, setCounter = signal(0)
effect(function()
- if getPrintCount() then
- -- This inner effect is created when getPrintCount() is true
- effect(function()
- print(`Count is {getCount()}`)
- end)
- end
-end) -- Count is 1
+ print(`Outer: {getCounter()}`)
+ effect(function()
+ print(`Inner: {getcounter()}`)
+ end)
+end)
-setCount(2) -- Count is 2
-
--- This re-runs the outer effect and cleans up old inner effects
-setPrintCount(false)
-
-setCount(3) -- No output
+setCounter(1) -- Outer: 1, Inner: 1
+setCounter(2) -- Outer: 2, Inner: 2
```
> [!NOTE]
@@ -257,40 +278,127 @@ setCount(3) -- No output
---
-### `computed(getter)`
+### `reactive(initialValue)`
-The `computed` function creates a read-only signal whose value is derived from other signals. The computed signal caches the getter function's last result, and the value is only re-computed if a dependency has updated since the last computation.
+By default, Charm's signals are _shallowly reactive_, meaning only the value itself is reactive, and table properties are not tracked. Signal values must also be **immutable** in order to track changes in tables.
+
+You can opt-in to deep reactivity with **reactive proxies**. The `reactive()` function takes a mutable table and wraps it in a reactive proxy. Reading properties through the proxy will perform dependency tracking, and table values will also be wrapped in a reactive proxy.
+
+```luau
+local users, setUsers = reactive({
+ { name = "John", surname = "Doe" },
+})
+
+-- Output: John Doe
+effect(function()
+ print(`{users[1].name} {users[1].surname}`)
+end)
+
+-- Output: Jane Smith
+setUsers(function(state)
+ state[1].name = "Jane"
+ state[1].surname = "Smith"
+ table.insert(state, { name = "Steve", surname = "Doe" })
+end)
+
+-- You can also mutate the reactive proxy directly:
+users[1].name = "John" -- John Smith
+```
+
+> [!WARNING]
+> Because reactive proxies use metatables for reading and writing, functions like `table.insert` will not work on the proxy. Table functions should only be called on the raw table value.
+
+If you need to access the raw table through the reactive proxy, use the `toRaw()` function:
+
+```luau
+local raw = {}
+local proxy = reactive(raw)
+
+print(toRaw(proxy) == raw) -- true
+```
+
+---
+
+### `untracked(callback)`
+
+In case you want to opt-out of dependency tracking in an effect, you can use `untracked()` to call a function _outside_ the current scope, preventing signals and effects in the function from being tracked.
+
+```luau
+local getTracked, setTracked = signal(0)
+local getUntracked, setUntracked = signal(0)
+
+-- Tracked: 0, Untracked: 0
+effect(function()
+ print(`Tracked: {getTracked()}, Untracked: {untracked(getUntracked)}`)
+end)
+
+setTracked(1) -- Tracked: 1, Untracked: 0
+setUntracked(1) -- No output
+setTracked(2) -- Tracked: 2, Untracked: 1
+```
+
+Because `untracked()` executes the callback outside the current effect, nested effects created during the execution of the callback will not be tracked by the parent effect:
+
+```luau
+local stopEffect
+local stopScope = effectScope(function()
+ untracked(function()
+ stopEffect = effect(function()
+ return function()
+ print("Cleaned up untracked effect")
+ end
+ end)
+ end)
+end)
+
+stopScope() -- No output, the scope did not track the effect
+stopEffect() -- Cleaned up untracked effect
+```
+
+---
+
+### `peek(callback)`
+
+Similar to `untracked()`, but does not prevent the parent effect from tracking nested effects created in the callback. If your callback reads a signal and creates effects, only the signals get untracked.
+
+```luau
+local getCounter, setCounter = signal(0)
+
+-- Count is 0
+local disposeOuter = effect(function()
+ print(`Count is {peek(getCounter)}`)
+end)
+
+setCounter(1) -- No output; count was accessed in peek()
+```
+
+---
+
+### `batch(callback)`
+
+Combines multiple signal updates made by the callback into a single commit that triggers effects once the callback completes.
```luau
local getName, setName = signal("John")
local getSurname, setSurname = signal("Doe")
-local getFullName = computed(function()
- return `{getName()} {getSurname()}`
+
+effect(function()
+ print(`Full name: {getName()} {getSurname()}`)
end)
-print(getFullName()) -- "John Doe"
-setName("Jane")
-print(getFullName()) -- "Jane Doe"
-```
-
-The getter function also receives the previous result (or `nil` during the initial run). You can use this for computed signals that depend on the previous result:
-
-```luau
-local getCounter, setCounter = signal(10)
-local getMax = computed(function(prevMax)
- return math.max(getCounter(), prevMax or 0)
+-- Combines both writes into a single update.
+-- Once the callback completes, outputs "Full name: Foo Bar"
+batch(function()
+ setName("Foo")
+ setSurname("Bar")
end)
-
-print(getMax()) -- 10
-setCounter(5)
-print(getMax()) -- 10
```
---
### `effectScope(callback)`
-Scopes allow you to dispose multiple effects at once. The `effectScope` function creates a scope that tracks inner effects, so effects created during the execution of the callback will clean up when the scope disposes.
+Scopes allow you to dispose multiple effects at once. The `effectScope` function creates an effect with no dependencies, and effects created inside the callback clean up when the effect scope disposes.
```luau
local getCounter, setCounter = signal(0)
@@ -322,77 +430,15 @@ The callback also receives the previous value, or `nil` when running for the fir
```luau
local getCounter, setCounter = signal(0)
+-- Count is 0 (was nil)
listen(getCounter, function(count, prevCount)
print(`Count is {count} (was {prevCount})`)
-end) -- Count is 0 (was nil)
+end)
setCounter(1) -- Count is 1 (was 0)
```
-Note that the listener callback runs in `untracked()`, so nested effects are not cleaned up.
-
-### Getter functions
-
-In most Charm APIs, you can also subscribe to getter functions that call one or more signals, and they will automatically be tracked:
-
-```luau
-local getCounter, setCounter = signal(0)
-
-local function floorCounter()
- return math.floor(getCounter())
-end
-
-listen(floorCounter, function(count, prevCount)
- print(`Floor of count is {count} (was {prevCount})`)
-end) -- Floor of count is 0 (was nil)
-
-setCounter(0.5) -- Doesn't print anything, floor is still 0
-setCounter(1) -- Floor of count is 1 (was 0)
-```
-
----
-
-### `observe(getter, callback)`
-
-[Observers](https://sleitnick.github.io/RbxObservers/docs/observer-pattern) allow you to track the lifetime of a given state. The `observe` function executes the callback for every unique key added to a table, and disposes the callback when that key is removed.
-
-```luau
-local getItems, setItems = signal({ a = 0, b = 0 })
-
-observe(getItems, function(value, key)
- print(`Added {key}`)
- return function()
- print(`Removed {key}`)
- end
-end) -- Added a, Added b
-
-setItems({ a = 0, c = 0 }) -- Removed b, Added c
-```
-
-The callback runs in an effect scope, so effects created in the callback will be disposed when the key is removed:
-
-```luau
-local getItems, setItems = signal({})
-
-local dispose = observe(getItems, function(value, key)
- local getValue = computed(function(prevValue)
- return getItems()[key] or prevValue
- end)
-
- effect(function()
- local value = getValue()
- print(`Set {key} = {value}`)
- return function()
- print(`Cleanup {key} = {value}`)
- end
- end)
-end)
-
-setItems({ a = 0, b = 0 }) -- Set a = 0, Set b = 0
-setItems({ a = 1, b = 0 }) -- Cleanup a = 0, Set a = 1
-setItems({ a = 1 }) -- Cleanup b = 0
-dispose() -- Cleanup a = 1
-```
+Note that nested effects can be created inside `listen`, and they will clean up automatically when the listener re-runs or gets disposed.
---
@@ -411,72 +457,59 @@ end)
setCounter(1) -- Count is 1 (was 0)
```
+Note that nested effects can be created inside `subscribe`, and they will clean up automatically when the subscription re-runs or gets disposed.
+
---
-### `untracked(callback)`
+### `observe(getter, callback)`
-In case you want to opt-out of dependency tracking in an effect, you can use `untracked()` to call a function _outside_ the current scope, preventing signals and effects in the function from being tracked.
+[Observers](https://sleitnick.github.io/RbxObservers/docs/observer-pattern) allow you to track the lifetime of a given state. The `observe` function executes the callback for every unique key added to a table, and disposes the callback when that key is removed.
```luau
-local getTracked, setTracked = signal(0)
-local getUntracked, setUntracked = signal(0)
+local getItems, setItems = signal({ a = 0, b = 0 })
-effect(function()
- print(`Tracked: {getTracked()}, Untracked: {untracked(getUntracked)}`)
-end) -- Tracked: 0, Untracked: 0
+-- Added a, Added b
+observe(getItems, function(value, key)
+ print(`Added {key}`)
+ return function()
+ print(`Removed {key}`)
+ end
+end)
-setTracked(1) -- Tracked: 1, Untracked: 0
-setUntracked(1) -- No output
-setTracked(2) -- Tracked: 2, Untracked: 1
+setItems({ a = 0, c = 0 }) -- Removed b, Added c
```
-Because `untracked()` executes the callback outside the current effect, nested effects created during the execution of the callback will not be tracked by the parent effect:
+The callback runs in an effect scope, so effects created in the callback will be disposed when the key is removed:
```luau
-local stopEffect
-local stopScope = effectScope(function()
- untracked(function()
- stopEffect = effect(function()
- return function()
- print("Cleaned up untracked effect")
- end
- end)
+local getItems, setItems = signal({ a = 0, b = 0 })
+
+local dispose = observe(getItems, function(value, key)
+ local getValue = computed(function(prevValue)
+ return getItems()[key] or prevValue
+ end)
+
+ effect(function()
+ local value = getValue()
+ print(`{key} = {value}`)
+ return function()
+ print(`Cleanup {key} = {value}`)
+ end
end)
end)
-stopScope() -- No output, the scope did not track the effect
-stopEffect() -- Cleaned up untracked effect
+setItems({ a = 1, b = 0 }) -- Cleanup a = 0, a = 1
+setItems({ a = 1 }) -- Cleanup b = 0
+dispose() -- Cleanup a = 1
```
---
-### `batch(callback)`
+### `mapped(getter, mapper)`
-Combines multiple signal updates made by the callback into a single commit that triggers effects once the callback completes.
+The `mapped` function iterates over every key in a table and uses the mapper to assign them to a new key and value. The result is returned as a read-only signal containing the new keys and values. When a key's value changes, or a new key is added to the table, the mapper is called for that key and its current value.
-```luau
-local getName, setName = signal("John")
-local getSurname, setSurname = signal("Doe")
-
-effect(function()
- print(`Full name: {getName()} {getSurname()}`)
-end)
-
--- Combines both writes into a single update.
--- Once the callback completes, outputs "Full name: Foo Bar"
-batch(function()
- setName("Foo")
- setSurname("Bar")
-end)
-```
-
----
-
-### `mapped(getter, transform)`
-
-The `mapped` function iterates over every key in a table and uses the transform function to assign them to a new key and value. The result is returned as a read-only signal containing the new keys and values. When a key's value changes, or a new key is added to the table, `transform` is called for that key and its current value.
-
-The first value returned by the transform function is used as the new value:
+The first value returned by the mapper is used as the new value:
```luau
local getList, setList = signal({ "a", "b", "c" })
@@ -488,7 +521,7 @@ end)
print(getUppercase()) -- { "A", "B", "C" }
```
-If the transform function returns two values, the second value is used as the new key:
+If the mapper returns two values, the second value is used as the new key:
```luau
local getList, setList = signal({ "a", "b", "c" })
@@ -506,7 +539,7 @@ print(getSwapped()) -- { a = 1, b = 2, c = 3 }
The `onCleanup` function binds the callback to the currently running effect or effect scope. Multiple cleanup functions can be bound to the same effect.
-Unless `failSilently` is set to `true`, this function will emit a warning if there is no active effect or scope.
+If there is no active effect, a warning is logged, unless `failSilently` is set to `true`.
```luau
local dispose = effectScope(function()
@@ -549,6 +582,26 @@ max(-1) -- 1
---
+### `recursive()`
+
+By design, Charm's reactive system [does not allow recursion](https://github.com/stackblitz/alien-signals/issues/90#issuecomment-3489711800) in effects or computed signals. In case you need to opt out of recursion checks for an effect, you can call `recursive()` at the top of the effect callback:
+
+```luau
+local getCounter, setCounter = signal(0)
+
+effect(function()
+ recursive()
+ print(getCounter())
+ setCounter(function(count)
+ return math.min(count + 1, 3)
+ end)
+end)
+
+-- Output: 0, 1, 2, 3
+```
+
+---
+
### `trigger(callback)`
The `trigger()` function allows you to manually trigger updates for downstream dependencies when you've directly mutated a signal's value without using the signal setter:
@@ -596,13 +649,13 @@ print(total()) -- 2
Charm exposes the following global flags to customize behavior:
-| Flag | Default | Description |
-| ----------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| strict | `true`\* | Enforces synchronous, non-yielding behavior in signals, effects, and other critical code. |
-| frozen | `true`\* | Enforces data immutability by deep-freezing tables passed to signals, excluding objects with metatables. |
-| trackInnerEffects | `true` | Whether nested effects should be tracked and cleaned up when the parent effect re-runs. This should only be disabled to debug issues during migration. |
+| Flag | Default | Description |
+| ----------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| strict | `true`/`false` | Enforces synchronous, non-yielding behavior in signals, effects, and other critical code. |
+| frozen | `true`/`false` | Enforces data immutability by deep-freezing tables passed to signals. |
+| trackInnerEffects | `true` | Whether nested effects should be tracked and cleaned up when the parent effect re-runs. This should only be disabled to debug issues during migration. |
-The `strict` and `frozen` flags are automatically enabled in Roblox Studio.
+The `strict` and `frozen` flags are automatically enabled in Roblox Studio. More accurately, they are enabled for the Luau optimization levels `O1` and lower.
---
@@ -623,99 +676,72 @@ CharmSync = "littensy/charm-sync@VERSION"
### Quick Start
-Start by specifying the signals that the server should sync to clients. For this example, we'll replicate a round status and timer signal, and each player's inventory:
+Start by specifying the signals that the server should sync to clients. For this example, we'll use the first and last name signals:
```luau
--- store.luau
-
-local getStatus, setStatus = signal("intermission")
-local timerAtom = atom(20)
-local getInventories, setInventories = signal({} :: { [Username]: Inventory })
+-- nameStore
+local getName, setName = signal("John")
+local getSurname, setSurname = signal("Doe")
+local ageAtom = atom(20)
return {
- getStatus = getStatus,
- setStatus = setStatus,
- timerAtom = timerAtom,
- getInventories = getInventories,
- setInventories = setInventories,
+ getName = getName,
+ setName = setName,
+ getSurname = getSurname,
+ setSurname = setSurname,
+ ageAtom = ageAtom,
}
```
-#### Server setup
+When a player joins on the server, call `server.addSignalsToClient` with the keyed signals that the client should receive updates for. Once they leave, call `server.removeClient` to unsubscribe them from all updates.
-When a player notifies the server that they're ready to start syncing, call `server.addSignalsToClient` with the signals that the client should receive updates for. Once they leave, call `server.removeClient` to unsubscribe them from all updates.
-
-Then, use `server.connect` to specify how state updates should be sent to each client. Pass a callback function that fires a remote with the given target player and the state updates they subscribed to:
+Then, use `server.connect` to specify how state updates should be sent to each client. Pass a callback function that fires a remote with the given target player and the state updates they subscribed to.
```luau
--- sync.server.luau
-
-playerReadyEvent.OnServerEvent:Connect(function(player)
- -- Sync signal getters, computed signals, atoms, or reactive proxies
+local function onPlayerAdded(player: Player)
+ -- Add signal getters, computed signals, atoms, or reactive objects
server.addSignalsToClient(player, {
- status = store.getStatus,
- timer = store.timerAtom,
- -- Signals unique to a player should also have a key unique to
- -- that player, to avoid overwriting other synced signals
- [`inventory-{player.UserId}`] = computed(function()
- return store.getInventories()[player.Name]
- end),
+ name = nameStore.getName,
+ surname = nameStore.getSurname,
+ age = nameStore.ageAtom,
})
-end)
+end
+
+for _, player in Players:GetPlayers() do
+ onPlayerAdded(player)
+end
+
+Players.PlayerAdded:Connect(onPlayerAdded)
Players.PlayerRemoving:Connect(function(player)
server.removeClient(player)
end)
server.connect(function(player, updates)
- -- Customize how you replicate state updates to clients
+ -- Customize how you send state updates to clients
syncEvent:FireClient(player, updates)
end)
-
--- Changes now get replicated to clients
-store.setStatus("started")
-store.timerAtom(30)
```
-> [!WARNING]
-> On the server, make sure each key corresponds to the same signal across all players. In other words, if you're syncing a signal that is unique to a player, ensure that the key is also unique to that player.
->
-> If two players subscribe to the same key, but were assigned different signals for that key, Charm will output a warning.
-
-#### Client setup
+> [!NOTE]
+> On the server, make sure each key corresponds to the same signal across all players. If two players subscribe to the same key, but were given different signals, Charm will output a warning.
To sync the client with the server's state, call `client.addSignals` with a table of writable signals (setter functions or atoms) whose keys match their server counterparts.
After the client receives updates from the server, call `client.patch` to patch the client's signals with the incoming state updates.
```luau
--- sync.client.luau
-
--- The server is replicating a signal containing the client's
--- inventory, so this signal will receive those updates
-local getInventory, setInventory = signal({} :: Inventory)
-
--- Add signal setters, atoms, or reactive proxies
+-- Add signal setters, atoms, or reactive objects
client.addSignals({
- status = store.setStatus,
- timer = store.timerAtom,
- -- Signals unique to a player should also have a key unique to
- -- that player, to avoid name collisions
- [`inventory-{Players.LocalPlayer.UserId}`] = setInventory,
+ name = nameStore.setName,
+ surname = nameStore.setSurname,
+ age = nameStore.ageAtom,
})
-- Update client signals when receiving updates from the server
syncEvent.OnClientEvent:Connect(function(updates)
client.patch(updates)
end)
-
--- Notify the server that the client is ready to receive updates
-playerReadyEvent:FireServer()
-
--- The signals will now update to match the server's state
-subscribe(getInventory, function(inventory)
- print("My inventory is", table.concat(inventory))
-end)
```
---
@@ -728,49 +754,37 @@ A configuration table that customizes the behavior of Charm Sync on the server.
| --------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| interval | `0` | The frequency at which the server will send patches to the client, in seconds. A value of `0` sends updates on the next frame. Set to a negative value to disable the interval. |
| preserveHistory | `false` | Whether to preserve a full history of state changes since the last sync, at the cost of performance. This is useful if you need to replicate each individual change that occurs between sync events. |
-| fixArrays | `true` | When `true`, Charm will attempt to work around remote event limitations that cause data loss in array patches. Disable this if your networking library serializes remote arguments (Zap, ByteNet, etc.). |
-| validatePatches | `true` | When `true`, and both `fixArrays` and strict mode are enabled, synced values containing unsafe sparse arrays or mixed tables will emit a warning. See the [remote argument limitations](https://create.roblox.com/docs/scripting/events/remote#argument-limitations). |
+| fixArrays | `true` | When `true`, Charm will attempt to work around Roblox remote event limitations regarding array patches. Disable this if your networking library serializes remote arguments (Zap, ByteNet, etc.). |
+| validatePatches | `true` | When `true`, and both `fixArrays` and strict mode are enabled, synced values containing unsafe sparse arrays or mixed tables will throw an error. See the [remote argument limitations](https://create.roblox.com/docs/scripting/events/remote#argument-limitations). |
---
### `server.addSignalsToClient(client, getters)`
-The `addSignalsToClient` function replicates changes in the given signals to a specific client. When an update occurs, the client will receive a delta-compressed state patch containing only the values that changed.
+The `addSignalsToClient` function subscribes a client to updates in the given signals. When an update occurs, the client will receive a state patch of only the values that changed.
-You can pass signal getter functions, computed signals, atoms, and [reactive proxies](#reactiveinitialvalue) in the `getters` table. This function can also be called multiple times on the same client to subscribe to new signals.
+You can pass signal getter functions, computed signals, atoms, and [reactive objects](#reactiveinitialvalue) in the `getters` table. This function can also be called multiple times on the same client to subscribe to new signals.
```luau
-playerReadyEvent.OnServerEvent:Connect(function(player)
+Players.PlayerAdded:Connect(function(player)
server.addSignalsToClient(player, {
- status = store.getStatus,
- timer = store.timerAtom,
+ name = nameStore.getName,
+ surname = nameStore.getSurname,
+ age = nameStore.ageAtom,
})
end)
```
-You're also allowed to create new signals to sync to specific players, as long as the key is unique to that signal:
+You're also allowed to create new signals to sync to specific players, as long as the key is also unique to that player:
```luau
-playerReadyEvent.OnServerEvent:Connect(function(player)
- server.addSignalsToClient(player, {
- -- 🟢 Good: Player-specific signals are synced with a unique key
- [`playerData-{player.UserId}`] = computed(function()
- return clientStore.getPlayerData(player.UserId)
- end),
-
- -- 🔴 Bad: Syncing different signals with the same keys does not work
- playerData = computed(function()
- return clientStore.getPlayerData(player.UserId)
- end),
- })
-end)
+server.addSignalsToClient(player, {
+ [`data-{player.UserId}`] = computed(function()
+ return getPlayerData(player.UserId)
+ end),
+})
```
-> [!NOTE]
-> On the server, make sure each key corresponds to the same signal across all players. In other words, if you're syncing a signal that is unique to a player, ensure that the key is also unique to that player.
->
-> If two players subscribe to the same key, but were assigned different signals for that key, Charm will output a warning.
-
---
### `server.removeSignalsFromClient(client, ...keys)`
@@ -779,11 +793,11 @@ The `removeSignalsFromClient` function unsubscribes the client from a list of ke
```luau
server.addSignalsToClient(player, {
- status = store.getStatus,
- timer = store.timerAtom,
+ name = nameStore.getName,
+ surname = nameStore.getSurname,
})
-server.removeSignalsFromClient(player, "status")
+server.removeSignalsFromClient(player, "surname")
```
---
@@ -793,7 +807,7 @@ server.removeSignalsFromClient(player, "status")
The `removeClient` function unsubscribes a client from receiving all state updates from the server. You should call this function when a player leaves the game.
```luau
-playerReadyEvent.OnServerEvent:Connect(function(player)
+Players.PlayerAdded:Connect(function(player)
server.addSignalsToClient(player, signals)
end)
@@ -844,11 +858,9 @@ You can pass either writable signals, atoms, or [reactive objects](#reactiveinit
```luau
client.addSignals({
- status = store.setStatus,
- timer = store.timerAtom,
- -- Signals unique to a player should also have a key unique to
- -- that player, to avoid name collisions
- [`inventory-{Players.LocalPlayer.UserId}`] = clientStore.setInventory,
+ name = nameStore.setName,
+ surname = nameStore.setSurname,
+ age = nameStore.ageAtom,
})
```
@@ -860,11 +872,11 @@ Unsubscribes from each signal with the corresponding keys. The signals will reta
```luau
client.addSignals({
- status = store.setStatus,
- timer = store.timerAtom,
+ name = nameStore.setName,
+ surname = nameStore.setSurname,
})
-client.removeSignals("status")
+client.removeSignals("name")
```
---
@@ -877,9 +889,8 @@ You should call `patch` when receiving updates from the server from a remote eve
```luau
client.addSignals({
- status = store.setStatus,
- timer = store.timerAtom,
- [`inventory-{Players.LocalPlayer.UserId}`] = clientStore.setInventory,
+ name = nameStore.setName,
+ surname = nameStore.setSurname,
})
syncEvent.OnClientEvent:Connect(function(updates)
@@ -895,8 +906,8 @@ If you have a lot of signals to sync between the server and clients, it might be
```luau
local sharedState = {
- status = signalToAtom(store.getStatus, store.setStatus),
- inventories = signalToAtom(store.getInventories, store.setInventories),
+ name = signalToAtom(nameStore.getName, nameStore.setName),
+ surname = signalToAtom(nameStore.getSurname, nameStore.setSurname),
}
client.addSignals(sharedState)
@@ -909,124 +920,31 @@ server.addSignalsToClient(client, sharedState)
Charm Sync will only send clients the differences between the current state and the last-synced state through a process called _delta compression_. In this case, tables are recursively scanned for changes, and unchanged properties are omitted by setting them to `nil`.
-But it's hard to differentiate between an unchanged value and a removed value, as both cases are represented by `nil`. Charm addresses this by representing deleted values with a special `None` value denoted by `{ __none = "__none" }`.
+But it's hard to differentiate between an unchanged value and a removed value, as both cases are represented by `nil`. We chose to address this by representing deleted values with a special `None` symbol denoted by `{ __none = "__none" }`.
This means nilable values may be replaced with `None` in patches, and code working with update payloads (usually for remote argument serialization) should account for nilable values possibly being sent as `None` in the payload.
---
-## Deep Reactivity
-
-Charm's reactivity system is _shallow_ by default: only the top-level value is reactive, so table properties are not checked when determining whether a signal has updated. As a result, tables in Charm should be immutable (copied before writing) in order to signal that a table's properties have changed.
-
-Deep reactivity, on the other hand, uses proxy tables to perform dependency tracking on properties. You can subscribe to a property by indexing the proxy table, and setting a property will notify its subscribers. This approach to reactivity lets you work with mutable data, making state management more intuitive at the cost of added overhead.
-
-You can opt-in to deep reactivity with the Deep Charm library:
-
-### Installation
-
-> [!WARNING]
-> Deep Charm is an experimental library that is not fully documented, and the API is subject to breaking changes.
-
-```sh
-npm install @rbxts/deep-charm
-yarn add @rbxts/deep-charm
-pnpm add @rbxts/deep-charm
-```
-
-```toml
-[dependencies]
-DeepCharm = "littensy/deep-charm@VERSION"
-```
-
----
-
-### `reactive(initialValue)`
-
-The `reactive()` function takes a mutable table and wraps it in a reactive proxy. Reading properties through the proxy will perform dependency tracking, and nested tables will also be wrapped in a reactive proxy.
-
-```luau
-local users, updateUsers = reactive({
- { name = "John", surname = "Doe" },
-})
-
-effect(function()
- print(`{users[1].name} {users[1].surname}`)
-end) -- Output: John Doe
-
-updateUsers(function(raw)
- raw[1].name = "Jane"
- raw[1].surname = "Smith"
- table.insert(raw, { name = "Steve", surname = "Doe" })
-end) -- Output: Jane Smith
-
--- You can also mutate the reactive proxy directly:
-users[1].name = "John" -- John Smith
-```
-
-### Mutation vs. update function
-
-Because reactive proxies use metatables for reading and writing, functions like `table.insert` will not work on the proxy. Table functions should only be called on the raw table value, which you can access through the update function returned by `reactive()`.
-
-This update function (`updateUsers()` in the example above) passes the raw table for you to mutate. Once your callback is done executing, the updater will manually notify subscriptions to the reactive proxy and its nested properties. This process does not use metatables, so you should use this for table operations or batching updates.
-
----
-
-### `toRaw(value)`
-
-If you need to access the raw table through the reactive proxy, use the `toRaw()` function:
-
-```luau
-local raw = {}
-local proxy = reactive(raw)
-
-print(toRaw(proxy) == raw) -- true
-```
-
-Calling `toRaw()` on a proxy also subscribes to its changes. This allows you to use proxies with `observe()` and other Charm APIs that accept a getter function:
-
-```luau
-local proxy, updateProxy = reactive({})
-
-observe(function()
- return toRaw(proxy)
-end, function(value, key)
- print(`Value {value} added at key {key}`)
-end)
-
-updateProxy(function(state)
- table.insert(state, "foo")
-end) -- Value foo added at key 1
-```
-
----
-
-### `isReactive(value)`
-
-The `isReactive()` function returns `true` if the given value is a reactive proxy by checking its metatable.
-
-```lua
-local raw = {}
-local proxy = reactive(raw)
-
-print(isReactive(proxy)) -- true
-print(isReactive(raw)) -- false
-```
-
----
-
## Migration
-Charm v0.11 introduces several breaking changes, so this section should help you migrate from an older version.
+Charm v0.11 introduces _a lot_ of breaking changes, so below are some tips that might help you migrate from an older version.
-For reference, a signal is a state container with a separated getter and setter function. Atoms are a signal with a single function for getting and setting the state.
+
+Terminology changes
+
+- Signal: A state container with one function to get the state, and another to update it
+- Atom: A signal with the getter and setter combined into one function
+- Effect: Main way to react to state changes
+- `subscribe(getter, callback)`: Creates an effect that only subscribes to signals accessed in the getter
+
+
**What to look out for:**
1. Address all of the type errors introduced in your project after updating Charm. Most of them are caused by changes like:
- - `peek()` was changed to `untracked()` for parity with other state managers
- The second arguments of `atom()` changed from an `options` table to an equality function
- - Removed the second argument of `computed()` (you can do your own equality checks since the computed callback now receives the previous value)
+ - Removed the second argument of `computed()` (you can do your own equality checks now)
- Removed the cleanup argument in effect callbacks (`effect(function(cleanup) end)`)
2. If you use Charm Sync, you'll have to rewrite a lot of your sync code. Fortunately, most of the changes should make your code _less_ complicated:
@@ -1039,15 +957,24 @@ For reference, a signal is a state container with a separated getter and setter
- `frozen`: Tables passed to signals are deeply frozen to strictly enforce data immutability and prevent accidental mutations
4. Nested effects automatically clean up when the parent effect re-runs or gets disposed. In other words, all effects created during the execution of another effect will be added as a "child" and clean up with the parent effect. This might cause issues in code that relied on the old behavior, where effects were detached from the parent.
- - This feature applies to the observer function in `observe()`, which also automatically cleans up inner effects to prevent memory leaks. However, this does not apply to `subscribe()` or `listen()`.
+ - This feature applies to all reaction APIs, including the listener function in `subscribe()` and the observer function in `observe()`.
- Effects that should not be tracked by a parent effect/scope should be wrapped in [`untracked()`](#untrackedcallback).
- - This feature can introduce runtime bugs in migrated code. If you suspect this to be the cause, to help identify the issue, you can temporarily disable this feature by setting [`flags.trackInnerEffects`](#flags) to `false`.
+ - This feature can introduce runtime bugs in migrated code. If you suspect this to be the cause, to help identify the issue, you can disable this feature by setting [`flags.trackInnerEffects`](#flags) to `false`.
-5. Consider refactoring your code to use some new quality-of-life features. Many of these are made possible thanks to [alien-signals](https://github.com/stackblitz/alien-signals)!
- - [`signal()`](#signalinitialvalue-equals): make atom reads and writes more explicit
- - [`listen()`](#listengetter-callback): create a subscription that also runs once immediately
+> [!NOTE]
+> An example of nested effects causing a bug is an old implementation of [`VideCharm.useAtom`](./packages/vide-charm/src/init.luau) that did not wrap the source update in `untracked()`. Because Vide effects run immediately after a source updates, Vide will notify components during the execution of the Charm effect in `useAtom`.
+>
+> This meant effects created as a side effect of a source update would implicitly get added as a child of the `useAtom` effect, and they could get disposed at the wrong time and desync UI.
+
+5. Recursion is now disallowed in effects and computed signals by default. This change may introduce bugs in code relying on the old behavior.
+ - Recursive checks are opt-out. You can allow recursion for a specific effect by calling [`recursive()`](#recursive) at the top of the effect callback.
+
+6. Consider refactoring your code to use some new quality-of-life features. Many of these are made possible thanks to [alien-signals](https://github.com/stackblitz/alien-signals)!
+ - [`reactive()`](#reactiveinitialvalue): make mutable tables deeply reactive
+ - [`signal()`](#signalinitialvalue-equals): make reads and writes more explicit
+ - [`listen()`](#listengetter-callback): create a subscription that runs once immediately
- [`effectScope()`](#effectscopecallback): collect and clean up multiple effects at once
- - [`onCleanup()`](#oncleanupcallback-failsilently): bind a cleanup function to the active effect or scope
+ - [`onCleanup()`](#oncleanupcallback-failsilently): bind a cleanup function to the active effect
- [`trigger()`](#triggercallback): trigger updates for table mutations
---
@@ -1059,14 +986,10 @@ For reference, a signal is a state container with a separated getter and setter
### React Counter
```luau
-local Charm = require("@packages/charm")
-local ReactCharm = require("@packages/react-charm")
-local React = require("@packages/react")
-
-local getCounter, setCounter = Charm.signal(0)
+local getCounter, setCounter = signal(0)
local function Counter()
- local count = ReactCharm.useSignalState(getCounter)
+ local count = useSignalState(getCounter)
return React.createElement("TextButton", {
[React.Event.Activated] = function()
@@ -1081,16 +1004,10 @@ end
### Vide Counter
```luau
-local Charm = require("@packages/charm")
-local VideCharm = require("@packages/vide-charm")
-local Vide = require("@packages/vide")
-
-local create = Vide.create
-
-local getCounter, setCounter = Charm.signal(0)
+local getCounter, setCounter = signal(0)
local function Counter()
- local count = VideCharm.useSignalState(getCounter)
+ local count = useSignalState(getCounter)
return create "TextButton" {
Activated = function()
@@ -1109,11 +1026,11 @@ end
---
-Charm is released under the MIT License.
+Charm is released under the MIT License.
-[](LICENSE)
+[](LICENSE.md)
diff --git a/benches/bench.luau b/benches/bench.luau
index ffb839d..9c24c6e 100644
--- a/benches/bench.luau
+++ b/benches/bench.luau
@@ -20,8 +20,8 @@ local function run(name: string, test: () -> ())
table.insert(results, `{name}: \t{string.format("%.2f", elapsed / iter * 1000 * 1000)} us/iter`)
- for name, duration in times do
- table.insert(results, `{name}: \t{string.format("%.2f", duration / iter * 1000 * 1000)} us/iter`)
+ for name, elapsed in times do
+ table.insert(results, `{name}: \t{string.format("%.2f", elapsed / iter * 1000 * 1000)} us/iter`)
end
print(table.concat(results, " | "))
diff --git a/benches/mapped.luau b/benches/mapped.luau
index 695b7f5..27ca6bd 100644
--- a/benches/mapped.luau
+++ b/benches/mapped.luau
@@ -3,56 +3,55 @@ local bench = require("./bench")
local computed = Charm.computed
local mapped = Charm.mapped
+local setActiveSub = Charm.setActiveSub
local signal = Charm.signal
-type Key = number
-type Value = number
+type Entry = { number }
local count = 512
-local initialState: { [Key]: Value } = table.create(count, 0)
+local initialState: { Entry } = table.create(count)
-local function expensiveOperation()
- for _ = 1, 100 do
- continue
- end
+for i = 1, count do
+ initialState[i] = table.create(64, i)
end
-local function simpleMapped(
- source: () -> { [Key]: Value },
- mapper: (Value, Key) -> (Value, Key?)
-): () -> { [Key]: Value }
+local function mapper(value: Entry, key: number): (Entry, number)
+ return table.clone(value), key + 1
+end
+
+local function simpleMapped(source: () -> { Entry }, mapper: (Entry, number) -> (Entry, number)): () -> { Entry }
return computed(function()
local state = source()
local nextState = {}
- for keyIn, valueIn in state do
- local valueOut, keyOut = mapper(valueIn, keyIn)
- nextState[if keyOut == nil then keyIn else keyOut] = valueOut
+ for index, value in state do
+ local currentSub = setActiveSub(nil)
+ local success, valueOut, keyOut = pcall(mapper, value, index)
+ setActiveSub(currentSub)
+
+ if success then
+ nextState[keyOut] = valueOut
+ end
end
- return nextState
+ return state
end)
end
-local function updateRandomly(updateChance: number): ({ [Key]: Value }) -> { [Key]: Value }
+local function updatePercentage(percent: number): ({ Entry }) -> { Entry }
return function(state)
local nextState = table.clone(state)
- for key in state do
- if math.random() < updateChance then
- nextState[key] += 1
+ for index, value in state do
+ if math.random() < percent then
+ nextState[index] = table.clone(value)
end
end
return nextState
end
end
-for _, updateChance in { 0.1, 0.5, 1 } do
- local function mapper(value: Value, key: Key): (Value, Key?)
- expensiveOperation()
- return value + 1, key + 1
- end
-
- bench.run(`mapped {updateChance}`, function()
+for _, percent in { 0.1, 0.5, 1 } do
+ bench.run(`mapped {percent}`, function()
local src, setSrc = signal(initialState)
local out = mapped(src, mapper)
@@ -60,14 +59,14 @@ for _, updateChance in { 0.1, 0.5, 1 } do
out()
bench.profileend()
- setSrc(updateRandomly(updateChance))
+ setSrc(updatePercentage(percent))
bench.profilebegin("update")
out()
bench.profileend()
end)
- bench.run(`control {updateChance}`, function()
+ bench.run(`control {percent}`, function()
local src, setSrc = signal(initialState)
local out = simpleMapped(src, mapper)
@@ -75,7 +74,7 @@ for _, updateChance in { 0.1, 0.5, 1 } do
out()
bench.profileend()
- setSrc(updateRandomly(updateChance))
+ setSrc(updatePercentage(percent))
bench.profilebegin("update")
out()
diff --git a/benches/multi.luau b/benches/multi.luau
deleted file mode 100644
index 6c8235c..0000000
--- a/benches/multi.luau
+++ /dev/null
@@ -1,188 +0,0 @@
-local Charm = require("../packages/charm/src")
-local bench = require("./bench")
-
-type Atom = Charm.Atom
-
-local signal = Charm.atom
-local computed = Charm.computed
-local effect = Charm.effect
-
-local function busy(): number
- local a = 0
- for i = 1, 100 do
- a += 1
- end
- return a
-end
-
-do
- local head = signal(0)
- local computed1 = computed(function()
- return head()
- end)
- local computed2 = computed(function()
- computed1()
- return 0
- end)
- local computed3 = computed(function()
- busy() -- heavy computation
- return computed2() + 1
- end)
- local computed4 = computed(function()
- return computed3() + 2
- end)
- local computed5 = computed(function()
- return computed4() + 3
- end)
- effect(function()
- computed5()
- busy() -- heavy side effect
- end)
-
- bench.run("avoidablePropagation", function()
- head(1)
- assert(computed5() == 6)
- for i = 0, 999 do
- head(i)
- end
- assert(computed5() == 6)
- end)
-end
-
-do
- local head = signal(0)
- local double = computed(function()
- return head() * 2
- end)
- local inverse = computed(function()
- return -head()
- end)
- local current = computed(function()
- local result = 0
- for i = 0, 19 do
- result += if head() % 2 == 1 then double() else inverse()
- end
- return result
- end)
-
- local callCounter = 0
- effect(function()
- current()
- callCounter += 1
- end)
-
- bench.run("unstable", function()
- head(1)
- assert(current() == 40)
- callCounter = 0
- for i = 0, 99 do
- head(i)
- end
- assert(callCounter == 100)
- end)
-end
-
-do
- local head = signal(0)
- local double = computed(function()
- return head() * 2
- end)
- local inverse = computed(function()
- return -head()
- end)
- local current = computed(function()
- local result = 0
- for i = 0, 19 do
- result += if head() % 2 == 1 and i % 2 == 1 then double() else inverse()
- end
- return result
- end)
-
- local callCounter = 0
- effect(function()
- current()
- callCounter += 1
- end)
-
- bench.run("unstable 50%", function()
- head(1)
- assert(current() == 10)
- callCounter = 0
- for i = 0, 99 do
- head(i)
- end
- assert(callCounter == 100)
- end)
-end
-
-do
- local head = signal(0)
- local last: () -> number = head
- local callCounter = 0
-
- for i = 0, 49 do
- local current = computed(function()
- return head() + i
- end)
- local current2 = computed(function()
- return current() + 1
- end)
- effect(function()
- current2()
- callCounter += 1
- end)
- last = current2
- end
-
- bench.run("broadPropagation", function()
- head(1)
- callCounter = 0
- for i = 0, 49 do
- head(i)
- assert(last() == i + 50)
- end
- assert(callCounter == 50 * 50)
- end)
-end
-
-do
- local heads = {}
- for index = 0, 99 do
- heads[index] = signal(0)
- end
-
- local mux = computed(function()
- local result = {}
- for index = 0, 99 do
- result[index] = heads[index]()
- end
- return result
- end)
-
- local splited = {}
- for index = 0, 99 do
- local x = computed(function()
- return mux()[index]
- end)
- splited[index] = computed(function()
- return x() + 1
- end)
- end
-
- for _, x in splited do
- effect(function()
- x()
- end)
- end
-
- bench.run("mux", function()
- for i = 0, 9 do
- heads[i](i)
- assert(splited[i]() == i + 1)
- end
- for i = 0, 9 do
- heads[i](i * 2)
- assert(splited[i]() == i * 2 + 1)
- end
- end)
-end
diff --git a/benches/reactive.luau b/benches/reactive.luau
index c272651..2e499ca 100644
--- a/benches/reactive.luau
+++ b/benches/reactive.luau
@@ -1,9 +1,8 @@
local Charm = require("../packages/charm/src")
-local DeepCharm = require("../packages/deep-charm/src")
local bench = require("./bench")
local effect = Charm.effect
-local reactive = DeepCharm.reactive
+local reactive = Charm.reactive
do
local value = reactive({ a = 1 })
diff --git a/bin/build.sh b/bin/build.sh
new file mode 100644
index 0000000..f680537
--- /dev/null
+++ b/bin/build.sh
@@ -0,0 +1,4 @@
+#!/usr/bin/env bash
+
+mkdir build
+rojo build build.project.json -o build/charm.rbxm
diff --git a/bin/check.sh b/bin/check.sh
new file mode 100644
index 0000000..091c4a4
--- /dev/null
+++ b/bin/check.sh
@@ -0,0 +1,19 @@
+curl -o bin/roblox.d.luau https://raw.githubusercontent.com/JohnnyMorganz/luau-lsp/main/scripts/globalTypes.d.luau
+
+rojo sourcemap -o sourcemap.json
+
+luau-lsp analyze \
+ --defs=bin/roblox.d.luau \
+ --flag:LuauFixIndexerSubtypingOrdering=true \
+ --flag:LuauInstantiateInSubtyping=true \
+ --sourcemap=sourcemap.json \
+ --ignore="**/node_modules/**" \
+ packages test benches
+
+selene packages test benches
+
+stylua --check packages test benches
+
+pnpm eslint packages
+
+rm bin/roblox.d.luau
diff --git a/build.project.json b/build.project.json
index 53d32b4..8141b86 100644
--- a/build.project.json
+++ b/build.project.json
@@ -4,7 +4,6 @@
"$className": "Folder",
"Charm": { "$path": "packages/charm/src" },
"CharmSync": { "$path": "packages/charm-sync/src" },
- "DeepCharm": { "$path": "packages/deep-charm/src" },
"ReactCharm": { "$path": "packages/react-charm/src" },
"VideCharm": { "$path": "packages/vide-charm/src" }
}
diff --git a/default.project.json b/default.project.json
index 85d8f55..43a7d1a 100644
--- a/default.project.json
+++ b/default.project.json
@@ -19,25 +19,16 @@
},
"charm": {
"$className": "Folder",
- "src": { "$path": "packages/charm/src" },
- "test": { "$path": "packages/charm/test" }
- },
- "deep-charm": {
- "$className": "Folder",
- "src": { "$path": "packages/deep-charm/src" },
- "test": { "$path": "packages/deep-charm/test" },
- "Charm": { "$path": "packages/deep-charm/Charm.luau" }
+ "src": { "$path": "packages/charm/src" }
},
"charm-sync": {
"$className": "Folder",
"src": { "$path": "packages/charm-sync/src" },
- "test": { "$path": "packages/charm-sync/test" },
"Charm": { "$path": "packages/charm-sync/Charm.luau" }
},
"react-charm": {
"$className": "Folder",
"src": { "$path": "packages/react-charm/src" },
- "test": { "$path": "packages/react-charm/test" },
"React": { "$path": "packages/react-charm/React.luau" },
"ReactRoblox": { "$path": "packages/react-charm/ReactRoblox.luau" },
"Charm": { "$path": "packages/react-charm/Charm.luau" }
@@ -45,7 +36,6 @@
"vide-charm": {
"$className": "Folder",
"src": { "$path": "packages/vide-charm/src" },
- "test": { "$path": "packages/vide-charm/test" },
"Vide": { "$path": "packages/vide-charm/Vide.luau" },
"Charm": { "$path": "packages/vide-charm/Charm.luau" }
}
@@ -53,8 +43,8 @@
"@rbxts-js": {
"$path": "node_modules/@rbxts-js"
},
- "tests": {
- "$path": "tests"
+ "test": {
+ "$path": "test"
}
}
}
diff --git a/eslint.config.js b/eslint.config.js
deleted file mode 100644
index bfccfb4..0000000
--- a/eslint.config.js
+++ /dev/null
@@ -1,20 +0,0 @@
-const eslint = require("@eslint/js");
-const { defineConfig, globalIgnores } = require("eslint/config");
-const prettierRecommended = require("eslint-plugin-prettier/recommended");
-const roblox = require("eslint-plugin-roblox-ts");
-const tseslint = require("typescript-eslint");
-
-module.exports = defineConfig(
- eslint.configs.recommended,
- tseslint.configs.recommended,
- roblox.configs.tsRecommendedCompat,
- roblox.configs.recommended,
- {
- rules: {
- "@typescript-eslint/no-explicit-any": "off",
- "roblox-ts/no-any": "off",
- },
- },
- globalIgnores(["out/**", "eslint.config.js"]),
- prettierRecommended,
-);
diff --git a/eslint.config.ts b/eslint.config.ts
new file mode 100644
index 0000000..21ece76
--- /dev/null
+++ b/eslint.config.ts
@@ -0,0 +1,20 @@
+import eslint from "@eslint/js";
+import { defineConfig, globalIgnores } from "eslint/config";
+import prettierRecommended from "eslint-plugin-prettier/recommended";
+import roblox from "eslint-plugin-roblox-ts";
+import tseslint from "typescript-eslint";
+
+export default defineConfig(
+ eslint.configs.recommended,
+ tseslint.configs.recommended,
+ roblox.configs.tsRecommendedCompat,
+ roblox.configs.recommended,
+ {
+ rules: {
+ "@typescript-eslint/no-explicit-any": "off",
+ "roblox-ts/no-any": "off",
+ },
+ },
+ globalIgnores(["out/**"]),
+ prettierRecommended,
+);
diff --git a/package.json b/package.json
index d0bf03d..b9b8739 100644
--- a/package.json
+++ b/package.json
@@ -1,29 +1,30 @@
{
"private": true,
"scripts": {
- "test": "lute run test",
- "build": "lute run build",
- "check": "lute run check",
+ "test": "lune run test/spec.server.luau",
+ "build": "sh bin/build.sh",
+ "check": "sh bin/check.sh",
"publish:npm": "pnpm publish -r --access public",
"publish:wally": "pnpm -r --workspace-concurrency 1 publish:wally"
},
- "packageManager": "pnpm@12.8.1",
+ "packageManager": "pnpm@10.22.0",
"devDependencies": {
- "@eslint/js": "^9.39.4",
+ "@eslint/js": "^9.36.0",
"@rbxts/compiler-types": "3.0.0-types.0",
- "@rbxts/react": "17.3.7-ts.1",
- "@rbxts/react-roblox": "17.3.7-ts.1",
- "@rbxts/types": "^1.0.913",
- "@rbxts/vide": "^0.6.1",
- "@typescript-eslint/eslint-plugin": "^8.58.0",
- "@typescript-eslint/parser": "^8.58.0",
- "eslint": "^9.39.4",
+ "@rbxts/react": "17.3.5-alpha.1",
+ "@rbxts/react-roblox": "17.3.5-alpha.1",
+ "@rbxts/types": "^1.0.883",
+ "@rbxts/vide": "^0.5.7",
+ "@typescript-eslint/eslint-plugin": "^8.44.1",
+ "@typescript-eslint/parser": "^8.44.1",
+ "eslint": "^9.36.0",
"eslint-config-prettier": "^10.1.8",
- "eslint-plugin-prettier": "^5.5.5",
- "eslint-plugin-roblox-ts": "^1.4.0",
- "prettier": "^3.8.1",
+ "eslint-plugin-prettier": "^5.5.4",
+ "eslint-plugin-roblox-ts": "^1.2.1",
+ "jiti": "^2.6.0",
+ "prettier": "^3.6.2",
"roblox-ts": "^3.0.0",
- "typescript": "^5.9.3",
- "typescript-eslint": "^8.58.0"
+ "typescript": "^5.9.2",
+ "typescript-eslint": "^8.44.1"
}
}
diff --git a/packages/charm-sync/Charm.luau b/packages/charm-sync/Charm.luau
index 480f2d5..a589bde 100644
--- a/packages/charm-sync/Charm.luau
+++ b/packages/charm-sync/Charm.luau
@@ -4,6 +4,7 @@ end
local Charm = require(script.Parent.Parent.charm.src)
-export type Atom = Charm.Atom
+export type Atom = Charm.Atom
+export type ReactiveProxy = Charm.ReactiveProxy
return Charm
diff --git a/packages/charm-sync/package.json b/packages/charm-sync/package.json
index f2c84a3..9c494b2 100644
--- a/packages/charm-sync/package.json
+++ b/packages/charm-sync/package.json
@@ -1,6 +1,6 @@
{
"name": "@rbxts/charm-sync",
- "version": "0.4.1",
+ "version": "0.4.0-rc.5",
"description": "Simple server-to-client sync for Charm",
"license": "MIT",
"main": "src/init.luau",
@@ -11,17 +11,17 @@
"!wally.toml",
"!wally.lock",
"!default.project.json",
- "!test"
+ "!**/__tests__"
],
"repository": {
"type": "git",
"url": "git+https://github.com/littensy/charm.git"
},
"scripts": {
- "prepare": "cp ../../LICENSE . && cp ../../README.md .",
+ "prepare": "cp ../../LICENSE.md . && cp ../../README.md .",
"publish:wally": "wally publish"
},
"dependencies": {
- "@rbxts/charm": "workspace:^"
+ "@rbxts/charm": "workspace:*"
}
}
diff --git a/packages/charm-sync/test/client.test.luau b/packages/charm-sync/src/__tests__/client.spec.luau
similarity index 92%
rename from packages/charm-sync/test/client.test.luau
rename to packages/charm-sync/src/__tests__/client.spec.luau
index 20c41a8..10164a2 100644
--- a/packages/charm-sync/test/client.test.luau
+++ b/packages/charm-sync/src/__tests__/client.spec.luau
@@ -1,9 +1,11 @@
-local Charm = require("../Charm")
-local DeepCharm = require("../../deep-charm/src")
-local client = require("../src/client")
-local test = require("../../../tests/test")
+local Charm = require("../../Charm")
+local client = require("../client")
+local suite = require("../../../../test/suite")
-test.afterEach(function()
+local test = suite.test
+local afterEach = suite.afterEach
+
+afterEach(function()
client.removeAllSignals()
end)
@@ -39,7 +41,7 @@ test("should merge patch", function()
end)
test("should merge patch (reactive)", function()
- local a = DeepCharm.reactive({ b = 1, c = 2 })
+ local a = Charm.reactive({ b = 1, c = 2 })
local runs = 0
Charm.effect(function()
diff --git a/packages/charm-sync/test/e2e.test.luau b/packages/charm-sync/src/__tests__/e2e.spec.luau
similarity index 83%
rename from packages/charm-sync/test/e2e.test.luau
rename to packages/charm-sync/src/__tests__/e2e.spec.luau
index 62ca4a7..d8da3aa 100644
--- a/packages/charm-sync/test/e2e.test.luau
+++ b/packages/charm-sync/src/__tests__/e2e.spec.luau
@@ -1,11 +1,13 @@
-local Charm = require("../Charm")
-local DeepCharm = require("../../deep-charm/src")
-local client = require("../src/client")
-local config = require("../src/config")
-local server = require("../src/server")
-local test = require("../../../tests/test")
+local Charm = require("../../Charm")
+local client = require("../client")
+local config = require("../config")
+local server = require("../server")
+local suite = require("../../../../test/suite")
-test.afterEach(function()
+local afterEach = suite.afterEach
+local test = suite.test
+
+afterEach(function()
server.reset()
client.removeAllSignals()
config.preserveHistory = false
@@ -14,9 +16,9 @@ end)
test("should replicate server state to client", function()
local target = {}
local serverA = Charm.atom({ count = 0 })
- local serverB = DeepCharm.reactive({ count = 0 })
+ local serverB = Charm.reactive({ count = 0 })
local clientA = Charm.atom({ count = -1 })
- local clientB = DeepCharm.reactive({ count = -1 })
+ local clientB = Charm.reactive({ count = -1 })
client.addSignals({ a = clientA, b = clientB })
server.addSignalsToClient(target, { a = serverA, b = serverB })
@@ -51,9 +53,9 @@ end)
test("should replicate historical server state to client", function()
local target = {}
local serverA = Charm.atom({ count = 0 })
- local serverB = DeepCharm.reactive({ count = 0 })
+ local serverB = Charm.reactive({ count = 0 })
local clientA = Charm.atom({ count = -1 })
- local clientB = DeepCharm.reactive({ count = -1 })
+ local clientB = Charm.reactive({ count = -1 })
config.preserveHistory = true
diff --git a/packages/charm-sync/test/patch.test.luau b/packages/charm-sync/src/__tests__/patch.spec.luau
similarity index 94%
rename from packages/charm-sync/test/patch.test.luau
rename to packages/charm-sync/src/__tests__/patch.spec.luau
index 076544e..7ce89c2 100644
--- a/packages/charm-sync/test/patch.test.luau
+++ b/packages/charm-sync/src/__tests__/patch.spec.luau
@@ -1,8 +1,11 @@
-local config = require("../src/config")
-local patch = require("../src/patch")
-local test = require("../../../tests/test")
+local config = require("../config")
+local patch = require("../patch")
+local suite = require("../../../../test/suite")
-local function mockArraySerdes(object: { [any]: any }): { [any]: any }
+local test = suite.test
+local afterEach = suite.afterEach
+
+local function mockArraySerdes(object: {}): {}
if object[1] then
local copy = {}
for index = 1, #object do
@@ -20,7 +23,7 @@ local function mockArraySerdes(object: { [any]: any }): { [any]: any }
end
end
-test.afterEach(function()
+afterEach(function()
config.fixArrays = true
config.validatePatches = true
end)
diff --git a/packages/charm-sync/test/server.test.luau b/packages/charm-sync/src/__tests__/server.spec.luau
similarity index 82%
rename from packages/charm-sync/test/server.test.luau
rename to packages/charm-sync/src/__tests__/server.spec.luau
index d24970c..034fc54 100644
--- a/packages/charm-sync/test/server.test.luau
+++ b/packages/charm-sync/src/__tests__/server.spec.luau
@@ -1,12 +1,15 @@
-local Charm = require("../Charm")
-local DeepCharm = require("../../deep-charm/src")
-local config = require("../src/config")
-local patch = require("../src/patch")
-local server = require("../src/server")
-local test = require("../../../tests/test")
-local types = require("../src/types")
+local Charm = require("../../Charm")
+local config = require("../config")
+local patch = require("../patch")
+local server = require("../server")
+local suite = require("../../../../test/suite")
-test.afterEach(function()
+local afterEach = suite.afterEach
+local beforeEach = suite.beforeEach
+local describe = suite.describe
+local test = suite.test
+
+afterEach(function()
server.reset()
end)
@@ -15,7 +18,7 @@ test("should replicate state changes", function()
local a = Charm.atom(0)
local b = Charm.atom(0)
local c = Charm.atom(0)
- local target: unknown, payloads: { types.SyncPayload }
+ local target, payloads
server.addSignalsToClient(client, { a = a, b = b, c = c })
server.connect(function(...)
@@ -42,7 +45,7 @@ test("should replicate partial state patches", function()
local client = {}
local a = Charm.atom({ x = 0, y = 0 })
local b = Charm.atom(0 :: number?)
- local target: unknown, payloads: { types.SyncPayload }
+ local target, payloads
server.addSignalsToClient(client, { a = a, b = b })
server.connect(function(...)
@@ -68,8 +71,8 @@ end)
test("should replicate partial state patches (reactive)", function()
local client = {}
- local a = DeepCharm.reactive({ x = { y = 0 }, z = 0 :: number? })
- local target: unknown, payloads: { types.SyncPayload }
+ local a = Charm.reactive({ x = { y = 0 }, z = 0 :: number? })
+ local target, payloads
server.addSignalsToClient(client, { a = a })
server.connect(function(...)
@@ -101,7 +104,7 @@ end)
test("should handle nested proxies", function()
local client = {}
- local src = DeepCharm.reactive({ (DeepCharm.reactive({})) })
+ local src = Charm.reactive({ (Charm.reactive({})) })
local payloads: {}? = nil
server.addSignalsToClient(client, { src = src })
@@ -119,7 +122,7 @@ test("should init new clients", function()
local clientA = {}
local clientB = {}
local a = Charm.atom(0)
- local payloadsA: { types.SyncPayload }, payloadsB: { types.SyncPayload }
+ local payloadsA, payloadsB
server.addSignalsToClient(clientA, { a = a })
server.connect(function(target, payloads)
@@ -148,7 +151,7 @@ test("should init new atoms", function()
local client = {}
local a = Charm.atom(0)
local b = Charm.atom(0)
- local target: unknown, payloads: { types.SyncPayload }
+ local target, payloads
server.addSignalsToClient(client, { a = a })
server.connect(function(...)
@@ -173,7 +176,7 @@ test("should only replicate to synced clients", function()
local clientB = {}
local a = Charm.atom(0)
local b = Charm.atom(0)
- local payloadsA: { types.SyncPayload }, payloadsB: { types.SyncPayload }
+ local payloadsA, payloadsB
server.addSignalsToClient(clientA, { a = a })
server.addSignalsToClient(clientB, { b = b })
@@ -215,7 +218,7 @@ end)
test("should serialize state", function()
local client = {}
local a = Charm.atom({ 1, 2, 3, 4, 5 })
- local payloads: { types.SyncPayload }
+ local payloads
server.addSignalsToClient(client, { a = a })
server.connect(function(_, p)
@@ -232,7 +235,7 @@ end)
test("should not send unchanged state", function()
local client = {}
local a = Charm.atom(0)
- local payloads: { types.SyncPayload }
+ local payloads
server.addSignalsToClient(client, { a = a })
server.connect(function(_, p)
@@ -249,12 +252,12 @@ test("should not send unchanged state", function()
assert(#payloads == 0, "Expected no payloads to be sent for unchanged state")
end)
-test.describe("historical", function()
- test.beforeEach(function()
+describe("historical", function()
+ beforeEach(function()
config.preserveHistory = true
end)
- test.afterEach(function()
+ afterEach(function()
config.preserveHistory = false
end)
@@ -263,7 +266,7 @@ test.describe("historical", function()
local a = Charm.atom(0)
local b = Charm.atom(0)
local c = Charm.atom(0)
- local target: unknown, payloads: { types.SyncPayload }
+ local target, payloads
server.addSignalsToClient(client, { a = a, b = b, c = c })
server.connect(function(...)
@@ -290,10 +293,10 @@ test.describe("historical", function()
test("should replicate granular state changes (reactive)", function()
local client = {}
- local a = DeepCharm.reactive({ value = 0 })
- local b = DeepCharm.reactive({ value = 0 })
- local c = DeepCharm.reactive({ value = 0 })
- local target: unknown, payloads: { types.SyncPayload }
+ local a = Charm.reactive({ value = 0 })
+ local b = Charm.reactive({ value = 0 })
+ local c = Charm.reactive({ value = 0 })
+ local target, payloads
server.addSignalsToClient(client, { a = a, b = b, c = c })
server.connect(function(...)
@@ -322,7 +325,7 @@ test.describe("historical", function()
local clientA = {}
local clientB = {}
local a = Charm.atom(0)
- local payloadsA: { types.SyncPayload }, payloadsB: { types.SyncPayload }
+ local payloadsA, payloadsB
server.addSignalsToClient(clientA, { a = a })
server.connect(function(target, payloads)
@@ -358,7 +361,7 @@ test.describe("historical", function()
local client = {}
local a = Charm.atom(0)
local b = Charm.atom(0)
- local payloads: { types.SyncPayload }
+ local payloads
server.addSignalsToClient(client, { a = a })
server.connect(function(_, ...)
@@ -387,7 +390,7 @@ test.describe("historical", function()
test("should not send unchanged state", function()
local client = {}
local a = Charm.atom(0)
- local payloads: { types.SyncPayload }
+ local payloads
server.addSignalsToClient(client, { a = a })
server.connect(function(_, p)
@@ -403,54 +406,6 @@ test.describe("historical", function()
server.flush()
assert(#payloads == 0, "Expected no payloads to be sent for unchanged state")
end)
-
- test("should maintain patch list order for stale update", function()
- local a = Charm.atom({ x = 1 })
- local b = Charm.atom({ y = 1 })
- local payloads
-
- server.connect(function(_client, _payloads)
- payloads = _payloads
- end)
-
- server.addSignalsToClient("client", { a = a, b = b })
- server.flush()
-
- payloads = nil
- a({ x = 1 }) -- new table, same contents: diff is nil
- b({ y = 2 })
- server.flush()
- assert(payloads, "Expected payloads to be sent")
- assert(payloads[1].type == "patch", "Expected payload to be patch")
- assert(payloads[1].data.b.y == 2, "Expected payload to contain atom 'b'")
- end)
-end)
-
-test("addSignalsToClient should ignore tracking context", function()
- local counter = Charm.atom(0)
- local payloads: { any }?
-
- server.connect(function(_client, _payloads)
- payloads = _payloads
- end)
-
- local dispose = Charm.effectScope(function()
- server.addSignalsToClient("PLAYER_ID", { counter = counter })
- end)
-
- server.flush()
- assert(payloads, "Expected payloads to be sent")
- assert(payloads[1].type == "init", "Expected first payload to be init")
- assert(payloads[1].data.counter == 0, "Expected init payload to contain atom 'counter'")
-
- dispose()
-
- payloads = nil
- counter(1)
- server.flush()
- assert(payloads, "Expected payloads to be sent")
- assert(payloads[1].type == "patch", "Expected first payload to be patch")
- assert(payloads[1].data.counter == 1, "Expected patch payload to contain atom 'counter'")
end)
return {}
diff --git a/packages/charm-sync/src/__tests__/spec.luau b/packages/charm-sync/src/__tests__/spec.luau
new file mode 100644
index 0000000..8d07f04
--- /dev/null
+++ b/packages/charm-sync/src/__tests__/spec.luau
@@ -0,0 +1,23 @@
+local suite = require("../../../../test/suite")
+
+suite.describe("client", function()
+ require("./client.spec")
+end)
+
+suite.describe("e2e", function()
+ require("./e2e.spec")
+end)
+
+suite.describe("utils", function()
+ require("./utils.spec")
+end)
+
+suite.describe("patch", function()
+ require("./patch.spec")
+end)
+
+suite.describe("server", function()
+ require("./server.spec")
+end)
+
+return {}
diff --git a/packages/charm-sync/test/utils.test.luau b/packages/charm-sync/src/__tests__/utils.spec.luau
similarity index 65%
rename from packages/charm-sync/test/utils.test.luau
rename to packages/charm-sync/src/__tests__/utils.spec.luau
index 1d50f55..47d2e39 100644
--- a/packages/charm-sync/test/utils.test.luau
+++ b/packages/charm-sync/src/__tests__/utils.spec.luau
@@ -1,15 +1,16 @@
-local Charm = require("../Charm")
-local test = require("../../../tests/test")
-local utils = require("../src/utils")
+local Charm = require("../../Charm")
+local suite = require("../../../../test/suite")
+local utils = require("../utils")
+
+local test = suite.test
test("should flatten functions", function()
local input = {
a = Charm.atom(0),
b = { c = Charm.atom(0) },
- d = { e = { f = utils.signalToAtom<>(Charm.signal(0)) } },
+ d = { e = { f = utils.signalToAtom(Charm.signal(0)) } },
}
-
- local result = utils.flatten<<{ [string]: Charm.Atom }>>(input)
+ local result = utils.flatten(input)
assert(result.a == input.a, "should flatten the first level")
assert(result["b/c"] == input.b.c, "should flatten the second level")
diff --git a/packages/charm-sync/src/client.luau b/packages/charm-sync/src/client.luau
index 973a983..e02de4b 100644
--- a/packages/charm-sync/src/client.luau
+++ b/packages/charm-sync/src/client.luau
@@ -2,8 +2,8 @@ local Charm = require("../Charm")
local patch = require("./patch")
local types = require("./types")
+type ReactiveProxy = Charm.ReactiveProxy
type SyncPayload = types.SyncPayload
-type ReactiveProxy = types.ReactiveProxy
local trackedSignals: { [string]: (any) -> any } = {}
local trackedReactives: { [string]: ReactiveProxy } = {}
@@ -64,8 +64,6 @@ local function applyInitPayload(data: { [string]: any })
trackedSignals[key](value)
elseif trackedReactives[key] then
shallowMergeReactive(trackedReactives[key], value)
- else
- warn(`charm-sync failed to sync key '{key}' because it is not currently registered by addSignals()`)
end
end
end
@@ -82,8 +80,6 @@ local function applyPatchPayload(data: { [string]: any })
elseif trackedReactive then
patch.applyMutable(trackedReactive.__target, diffs)
Charm.trigger(trackedReactive.__track)
- else
- warn(`charm-sync failed to sync key '{key}' because it is not currently registered by addSignals()`)
end
end
end
@@ -94,7 +90,7 @@ end
@param payloads The state updates received from the server.
]]
-local function applyPatches(payloads: { SyncPayload })
+local function patch(payloads: { SyncPayload })
for _, payload in payloads do
if payload.type == "init" then
Charm.batch(applyInitPayload, payload.data)
@@ -108,5 +104,5 @@ return {
addSignals = addSignals,
removeSignals = removeSignals,
removeAllSignals = removeAllSignals,
- patch = applyPatches,
+ patch = patch,
}
diff --git a/packages/charm-sync/src/config.luau b/packages/charm-sync/src/config.luau
index c3ce27c..a101f05 100644
--- a/packages/charm-sync/src/config.luau
+++ b/packages/charm-sync/src/config.luau
@@ -9,22 +9,19 @@ return {
Whether the history of state changes since the client's last update
should be preserved. This is useful for values that change multiple
times per frame, where each individual change is important. Defaults
- to `false` for performance reasons.
+ to `false`.
]]
preserveHistory = false,
--[[
- When `true`, Charm will modify sparse arrays to prevent data loss from
- remote event limitations. When an unsafe array is detected, numeric
- indices will be converted to string keys so that the array can be sent
- safely and then converted back to an array on the receiving end.
-
+ When `true`, Charm will apply validation and serialize unsafe arrays
+ to address remote event argument limitations. Defaults to `true`.
This option should be disabled if your network library uses a custom
serialization method (i.e. Zap, ByteNet) to prevent interference.
]]
fixArrays = true,
--[[
When `true`, synced state containing unsafe sparse arrays or mixed
- tables will emit a warning. Only checked in strict mode and if
+ tables will throw an error. Only checked in strict mode and if
`fixArrays` is enabled. Defaults to `true`.
]]
validatePatches = true,
diff --git a/packages/charm-sync/src/index.d.ts b/packages/charm-sync/src/index.d.ts
index bb40eba..6519951 100644
--- a/packages/charm-sync/src/index.d.ts
+++ b/packages/charm-sync/src/index.d.ts
@@ -78,17 +78,14 @@ export const config: {
* Whether the history of state changes since the client's last update
* should be preserved. This is useful for values that change multiple
* times per frame, where each individual change is important. Defaults
- * to `false` for performance reasons.
+ * to `false`.
*
* @server
*/
preserveHistory: boolean;
/**
- * When `true`, Charm will modify sparse arrays to prevent data loss from
- * remote event limitations. When an unsafe array is detected, numeric
- * indices will be converted to string keys so that the array can be sent
- * safely and then converted back to an array on the receiving end.
- *
+ * When `true`, Charm will apply validation and serialize unsafe arrays
+ * to address remote event argument limitations. Defaults to `true`.
* This option should be disabled if your network library uses a custom
* serialization method (i.e. Zap, ByteNet) to prevent interference.
*
@@ -97,7 +94,7 @@ export const config: {
fixArrays: boolean;
/**
* When `true`, synced state containing unsafe sparse arrays or mixed
- * tables will emit a warning. Only checked in strict mode and if
+ * tables will throw an error. Only checked in strict mode and if
* `fixArrays` is enabled. Defaults to `true`.
*
* @server
@@ -245,7 +242,7 @@ export namespace patch {
* @param statePatch The patches to apply.
* @returns The new state with the patch applied.
*/
- export function applyImmutable(
+ export function apply(
currentState: State,
statePatch: SyncPatch,
): State;
diff --git a/packages/charm-sync/src/patch.luau b/packages/charm-sync/src/patch.luau
index d6b940f..b9a3be1 100644
--- a/packages/charm-sync/src/patch.luau
+++ b/packages/charm-sync/src/patch.luau
@@ -39,7 +39,7 @@ end
long as the target array is not sparse. This function ensures that the diff
function produces a patch that can be correctly applied.
]]
-local function stringifySparseArray(object: { [any]: any }): { [string | number]: any }
+local function stringifySparseArray(object: {}): { [string | number]: any }
local maxn = table.maxn(object)
if maxn == 0 or maxn == #object then
diff --git a/packages/charm-sync/src/server.luau b/packages/charm-sync/src/server.luau
index 6485e18..07ce4ba 100644
--- a/packages/charm-sync/src/server.luau
+++ b/packages/charm-sync/src/server.luau
@@ -4,6 +4,7 @@ local patch = require("./patch")
local types = require("./types")
local utils = require("./utils")
+type ReactiveProxy = Charm.ReactiveProxy
type SyncPayload = types.SyncPayload
type SyncStatus = number
@@ -34,22 +35,9 @@ local clients: { [any]: ClientKeys } = {}
local connection: RBXScriptConnection?
local syncCallback: ((client: any, payloads: { SyncPayload }) -> ())?
---[[
- Manually converts a reactive proxy to its raw representation to potentially
- support custom implementations of reactive proxies.
-]]
-local function toRaw(value: T): T
- local proxy = value :: types.ReactiveProxy
- if type(proxy) == "table" and type(proxy.__target) == "table" and type(proxy.__track) == "function" then
- proxy.__track()
- return toRaw(proxy.__target)
- end
- return value
-end
-
local function trackSignal(key: string, getter: () -> T, identifier: unknown)
if trackedStates[key] then
- -- Warn against name collisions with conflicting signals or proxies
+ -- Ignore duplicates, but warn against name collisions
if trackedStates[key].identifier ~= identifier then
warn("[Charm] Attempted to sync different states with the same key:", key)
end
@@ -58,12 +46,12 @@ local function trackSignal(key: string, getter: () -> T, identifier: unknown)
local trackedState: TrackedState
local initialValue = getter()
- local rawInitialValue = toRaw(initialValue)
+ local rawInitialValue = Charm.toRaw(initialValue)
local snapshot = if initialValue ~= rawInitialValue then utils.deepCopy(rawInitialValue) else initialValue
- local dispose = Charm.untracked(Charm.effect, function()
+ local dispose = Charm.effect(function()
local newValue = getter()
- local rawValue = toRaw(newValue)
+ local rawValue = Charm.toRaw(newValue)
local isReactive = newValue ~= rawValue
if not trackedState then
@@ -125,8 +113,8 @@ local function diffGlobalUpdateBuffer(): { any }
local patchCount = #globalUpdates
local patches = table.create(patchCount)
- for index, update in globalUpdates do
- patches[index] = patch.diff(update.oldValue, update.newValue)
+ for _, update in globalUpdates do
+ table.insert(patches, patch.diff(update.oldValue, update.newValue))
end
return patches
@@ -146,7 +134,7 @@ local function selectFromGlobalPatchList(client: any, globalPatches: { any }): {
for index, update in globalUpdates do
local patchData = globalPatches[index]
- if patchData == nil then
+ if not patchData then
continue
end
@@ -154,17 +142,15 @@ local function selectFromGlobalPatchList(client: any, globalPatches: { any }): {
local status = clientKeys[key]
if status == LISTENING_FOR_CHANGES then
- local payload: SyncPayload = {
+ table.insert(payloads, {
type = "patch",
data = { [key] = patchData },
- }
- table.insert(payloads, payload)
+ })
elseif status == PENDING_INITIAL_STATE then
- local payload: SyncPayload = {
+ table.insert(payloads, {
type = "init",
data = { [key] = update.newValue },
- }
- table.insert(payloads, payload)
+ })
clientKeys[key] = LISTENING_FOR_CHANGES
end
end
@@ -231,45 +217,16 @@ local function selectFromGlobalPatch(client: any, globalPatch: { [string]: any }
end
if next(initData) ~= nil then
- local payload: SyncPayload = {
- type = "init",
- data = initData,
- }
- table.insert(payloads, payload)
+ table.insert(payloads, { type = "init", data = initData })
end
if next(patchData) ~= nil then
- local payload: SyncPayload = {
- type = "patch",
- data = patchData,
- }
- table.insert(payloads, payload)
+ table.insert(payloads, { type = "patch", data = patchData })
end
return payloads
end
-local function startInterval(callback: () -> ())
- if not game then
- return
- end
-
- if connection then
- connection:Disconnect()
- end
-
- local timestamp = os.clock()
-
- connection = game:GetService("RunService").Heartbeat:Connect(function()
- if config.interval >= 0 and os.clock() >= timestamp + config.interval then
- timestamp = os.clock()
- debug.profilebegin("CharmSync")
- callback()
- debug.profileend()
- end
- end)
-end
-
--[[
Subscribes a client to the given signals. When an update occurs, the client
will receive a partial state patch to merge into their local state. May be
@@ -313,7 +270,6 @@ end
]]
local function removeClient(client: any)
clients[client] = nil
- purgeUntracked()
end
--[[
@@ -336,8 +292,6 @@ local function removeSignalsFromClient(client: any, ...: string)
if next(clientKeys) == nil then
removeClient(client)
- else
- purgeUntracked()
end
end
@@ -368,6 +322,7 @@ local function flush()
end
end
+ purgeUntracked()
table.clear(globalUpdates)
end
@@ -379,8 +334,32 @@ end
@param onSync Called when sending patches to a client.
]]
local function connect(onSync: (client: any, payloads: { SyncPayload }) -> ())
+ if connection then
+ connection:Disconnect()
+ end
+
syncCallback = onSync
- startInterval(flush)
+
+ if not game then
+ return
+ end
+
+ local timer = 0
+
+ connection = game:GetService("RunService").Heartbeat:Connect(function(deltaTime)
+ if config.interval < 0 then
+ return
+ end
+
+ timer += deltaTime
+
+ if timer >= config.interval then
+ timer = 0
+ debug.profilebegin("CharmSync")
+ flush()
+ debug.profileend()
+ end
+ end)
end
--[[
diff --git a/packages/charm-sync/src/types.luau b/packages/charm-sync/src/types.luau
index 664ee61..20af1f3 100644
--- a/packages/charm-sync/src/types.luau
+++ b/packages/charm-sync/src/types.luau
@@ -18,13 +18,4 @@ export type SyncPayload =
]]
export type None = { __none: "__none" }
-export type ReactiveProxy = typeof(setmetatable(
- {} :: {
- __track: () -> (),
- __target: T,
- __signals: { [unknown]: () -> unknown },
- },
- {} :: { __index: T }
-))
-
return {}
diff --git a/packages/charm-sync/src/utils.luau b/packages/charm-sync/src/utils.luau
index 4a49871..a4dae84 100644
--- a/packages/charm-sync/src/utils.luau
+++ b/packages/charm-sync/src/utils.luau
@@ -2,6 +2,10 @@ local Charm = require("../Charm")
type Atom = Charm.Atom
+type NestedTable = {
+ [any]: NestedTable | any,
+}
+
--[[
Flattens a nested table into a single table with slash-separated keys.
Useful for recursively collecting atoms returned by modules.
@@ -9,15 +13,15 @@ type Atom = Charm.Atom
@param input A nested table.
@return A flattened table with slash-separated keys.
]]
-local function flatten(input: { [any]: any }): Flattened
+local function flatten(input: {}): Flattened
local result = {}
- local function visit(node: { [any]: any }, path: string)
+ local function visit(node: {}, path: string)
for key, value in node do
local location = if path == "" then tostring(key) else path .. "/" .. tostring(key)
if type(value) == "table" then
- visit(value, location)
+ visit(value :: {}, location)
else
result[location] = value
end
diff --git a/packages/charm-sync/src/validate.luau b/packages/charm-sync/src/validate.luau
index dfba716..ac21161 100644
--- a/packages/charm-sync/src/validate.luau
+++ b/packages/charm-sync/src/validate.luau
@@ -1,11 +1,11 @@
-local function isTableUnsafe(object: { [any]: any })
- local firstKey = next(object)
+local function isTableUnsafe(object: {})
+ local key = next(object)
- if firstKey == nil then
+ if key == nil then
return false
end
- local keyType = type(firstKey)
+ local keyType = type(key)
local maxKey = 0
-- Keys must all be the same type
@@ -31,11 +31,13 @@ end
with remote argument limitations, such as sparse arrays or mixed tables.
@param value The table value.
+ @param key The key of the value.
]]
-local function validate(value: { [any]: any })
+local function validate(value: {})
if isTableUnsafe(value) then
warn(
- "Cannot sync tables unsupported by remote events! This can be for the following reasons:\n"
+ `Cannot sync tables unsupported by remote events! See the table below for more info.\n\n`
+ .. "This can be for the following reasons:\n"
.. "1. The table is a sparse array with non-sequential indices\n"
.. "2. The table is a mixed table (not all keys have the same type)\n\n"
.. "Read more: https://create.roblox.com/docs/scripting/events/remote#argument-limitations\n",
diff --git a/packages/charm-sync/test/init.luau b/packages/charm-sync/test/init.luau
deleted file mode 100644
index 111dc1d..0000000
--- a/packages/charm-sync/test/init.luau
+++ /dev/null
@@ -1,23 +0,0 @@
-local test = require("../../tests/test")
-
-test.describe("client", function()
- require("@self/client.test")
-end)
-
-test.describe("e2e", function()
- require("@self/e2e.test")
-end)
-
-test.describe("utils", function()
- require("@self/utils.test")
-end)
-
-test.describe("patch", function()
- require("@self/patch.test")
-end)
-
-test.describe("server", function()
- require("@self/server.test")
-end)
-
-return {}
diff --git a/packages/charm-sync/wally.toml b/packages/charm-sync/wally.toml
index 589e7ed..80e3061 100644
--- a/packages/charm-sync/wally.toml
+++ b/packages/charm-sync/wally.toml
@@ -1,15 +1,15 @@
[package]
name = "littensy/charm-sync"
-version = "0.4.1"
+version = "0.4.0-rc.5"
registry = "https://github.com/UpliftGames/wally-index"
realm = "shared"
exclude = [
"node_modules",
- "test",
+ "src/__tests__",
"src/index.d.ts",
"package.json",
"Charm.luau",
]
[dependencies]
-Charm = "littensy/charm@^0.11.0"
+Charm = "littensy/charm@^0.11.0-rc.3"
diff --git a/packages/charm/package.json b/packages/charm/package.json
index 7ef2e29..56cf80a 100644
--- a/packages/charm/package.json
+++ b/packages/charm/package.json
@@ -1,6 +1,6 @@
{
"name": "@rbxts/charm",
- "version": "0.11.1",
+ "version": "0.11.0-rc.3",
"description": "Atomic state management based on alien-signals",
"license": "MIT",
"main": "src/init.luau",
@@ -11,14 +11,14 @@
"!wally.toml",
"!wally.lock",
"!default.project.json",
- "!test"
+ "!**/__tests__"
],
"repository": {
"type": "git",
"url": "git+https://github.com/littensy/charm.git"
},
"scripts": {
- "prepare": "cp ../../LICENSE . && cp ../../README.md .",
+ "prepare": "cp ../../LICENSE.md . && cp ../../README.md .",
"publish:wally": "wally publish"
}
}
diff --git a/packages/charm/src/__tests__/computed.spec.luau b/packages/charm/src/__tests__/computed.spec.luau
new file mode 100644
index 0000000..3dd7284
--- /dev/null
+++ b/packages/charm/src/__tests__/computed.spec.luau
@@ -0,0 +1,106 @@
+local Charm = require("../")
+local suite = require("../../../../test/suite")
+
+local computed = Charm.computed
+local effect = Charm.effect
+local signal = Charm.signal
+local test = suite.test
+
+test("should correctly propagate changes through computed core", function()
+ local src, setSrc = signal(0)
+ local c1 = computed(function()
+ return src() % 2
+ end)
+ local c2 = computed(function()
+ return c1()
+ end)
+ local c3 = computed(function()
+ return c2()
+ end)
+
+ c3()
+ setSrc(1) -- c1 -> dirty, c2 -> toCheckDirty, c3 -> toCheckDirty
+ c2() -- c1 -> none, c2 -> none
+ setSrc(3) -- c1 -> dirty, c2 -> toCheckDirty
+
+ assert(c3() == 1, "bad final value")
+end)
+
+test("should propagate updated source value through chained computations", function()
+ local src, setSrc = signal(0)
+ local a = computed(function()
+ return src()
+ end)
+ local b = computed(function()
+ return a() % 2
+ end)
+ local c = computed(function()
+ return src()
+ end)
+ local d = computed(function()
+ return b() + c()
+ end)
+
+ assert(d() == 0, "bad initial value")
+ setSrc(2)
+ assert(d() == 2, "bad updated value")
+end)
+
+test("should handle flags are indirectly updated during checkDirty", function()
+ local a, setA = signal(false)
+ local b = computed(function()
+ return a()
+ end)
+ local c = computed(function()
+ b()
+ return 0
+ end)
+ local d = computed(function()
+ c()
+ return b()
+ end)
+
+ assert(d() == false, "bad initial value")
+ setA(true)
+ assert(d() == true, "bad updated value")
+end)
+
+test("should not update if the signal value is reverted", function()
+ local times = 0
+
+ local src, setSrc = signal(0)
+ local c1 = computed(function()
+ times += 1
+ return src()
+ end)
+ c1()
+ assert(times == 1, "computed did not run")
+ setSrc(1)
+ setSrc(0)
+ c1()
+ assert(times == 1, "computed ran when it should not")
+end)
+
+test("should receive previous value", function()
+ local calls = {}
+ local src, setSrc = signal(0)
+ local c1 = computed(function(current): number
+ local incoming = src()
+ return if current == incoming or incoming % 2 == 1 then current or incoming else incoming
+ end)
+
+ effect(function()
+ table.insert(calls, c1())
+ end)
+
+ setSrc(2)
+ setSrc(3)
+ assert(c1() == 2, "should skip odd value")
+
+ setSrc(4)
+ setSrc(5)
+ assert(c1() == 4, "should skip odd value")
+ assert(table.concat(calls) == "024", `should only call on even updates, got {table.concat(calls)}`)
+end)
+
+return {}
diff --git a/packages/charm/test/effect.test.luau b/packages/charm/src/__tests__/effect.spec.luau
similarity index 55%
rename from packages/charm/test/effect.test.luau
rename to packages/charm/src/__tests__/effect.spec.luau
index 17cd0a0..56fe9c1 100644
--- a/packages/charm/test/effect.test.luau
+++ b/packages/charm/src/__tests__/effect.spec.luau
@@ -1,14 +1,16 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local computed = Charm.computed
local effect = Charm.effect
local effectScope = Charm.effectScope
local endBatch = Charm.endBatch
local onCleanup = Charm.onCleanup
+local recursive = Charm.recursive
local setActiveSub = Charm.setActiveSub
local signal = Charm.signal
local startBatch = Charm.startBatch
+local test = suite.test
test("should clear subscriptions when untracked by all subscribers", function()
local bRunTimes = 0
@@ -239,11 +241,8 @@ test("should handle side effect with inner effects", function()
table.clear(order)
setB(1)
setA(1)
+ assert(table.concat(order) == "ba", `wrong order: {table.concat(order)}`)
end)
-
- -- DEVIATION: This assertion was moved outside of the effect so that it
- -- runs after the batch updates have been processed
- assert(table.concat(order) == "ba", `wrong order: {table.concat(order)}`)
end)
test("should handle flags are indirectly updated during checkDirty", function()
@@ -271,52 +270,33 @@ test("should handle flags are indirectly updated during checkDirty", function()
assert(triggers == 2, "did not update indirectly")
end)
-test("should not execute skipped effects from previous failed flush when updating unrelated signal", function()
- local a, setA = signal(0)
- local b, setB = signal(0)
- local c, setC = signal(0)
- local d = computed(function()
- c()
- return 0
- end)
+test("should handle effect recursion for the first execution", function()
+ local src1, setSrc1 = signal(0)
+ local src2, setSrc2 = signal(0)
- local effect3Executed = false
+ local triggers1 = 0
+ local triggers2 = 0
effect(function()
- a()
+ triggers1 += 1
+ setSrc1(math.min(src1() + 1, 5))
end)
effect(function()
- if a() == 2 then
- error("Error in effect 2")
- end
- end)
- effect(function()
- a()
- d()
- effect3Executed = true
- end)
- effect(function()
- b()
+ triggers2 += 1
+ setSrc2(math.min(src2() + 1, 5))
+ src2()
end)
- setA(1)
-
- effect3Executed = false
- local success, err = pcall(setA, 2)
- assert(not success and string.find(tostring(err), "Error in effect 2"), `bad error: {err}`)
-
- assert(not effect3Executed, "effect 3 should not have executed after failed flush")
- setB(1)
- assert(not effect3Executed, "effect 3 should not have executed after updating unrelated signal b")
- setC(1)
- assert(effect3Executed, "effect 3 should have executed after updating signal c")
+ assert(triggers1 == 1, `bad triggers1: {triggers1}`)
+ assert(triggers2 == 1, `bad triggers2: {triggers2}`)
end)
-test("should allow finite recursion", function()
+test("should opt in to recursion", function()
local src, setSrc = signal(0)
local order = {}
effect(function()
+ recursive()
table.insert(order, src())
setSrc(math.min(src() + 1, 5))
end)
@@ -408,186 +388,4 @@ test("should run cleanups outside any evaluation context", function()
assert(calls == 0, "should not run after b update")
end)
-test("should not retrigger the effect if the cleanup modifies one of the dependencies", function()
- local a, setA = signal(0)
- local calls = {}
-
- effect(function()
- table.insert(calls, a())
- return function()
- setA(2)
- end
- end)
- assert(#calls == 1, "should have run once initially")
- table.clear(calls)
-
- setA(1)
- assert(#calls == 1, "should run once after an update")
- assert(calls[1] == 2, `bad call: {calls[1]}`)
-end)
-
-test("should run the cleanup if the effect disposes itself", function()
- local a, setA = signal(0)
- local calls = 0
- local dispose: () -> ()
-
- dispose = effect(function()
- if a() > 0 then
- dispose()
- return function()
- calls += 1
- end
- end
- end)
- assert(calls == 0, "should not have called cleanup initially")
- setA(1)
- assert(calls == 1, "should have called cleanup once after first update")
- setA(2)
- assert(calls == 1, "should not call cleanup again after second update")
-end)
-
-test("should not run the effect if the cleanup function disposes it", function()
- local a, setA = signal(0)
- local calls = 0
- local dispose: () -> ()
-
- dispose = effect(function()
- a()
- calls += 1
- return function()
- dispose()
- end
- end)
- assert(calls == 1, "should have run effect once initially")
- setA(1)
- assert(calls == 1, "should not run effect again after update")
-end)
-
-test("should reset the cleanup if the effect throws", function()
- local a, setA = signal(0)
- local calls = 0
-
- effect(function()
- if a() == 0 then
- return function()
- calls += 1
- end
- else
- error("hello")
- end
- end)
- assert(calls == 0, "should not have called cleanup initially")
- local success, err = pcall(setA, 1)
- assert(not success and string.find(tostring(err), "hello"), `bad error: {err}`)
- assert(calls == 1, "should have called cleanup once after throwing")
- setA(0)
- assert(calls == 1, "should not call cleanup again after resetting value")
-end)
-
-test("recursive effects should run and cleanup in order", function()
- local a, setA = signal(0)
- local order: { string } = {}
-
- effect(function()
- local value = a()
- table.insert(order, `+{value}`)
- if value < 3 then
- setA(value + 1)
- end
- return function()
- table.insert(order, `-{value}`)
- end
- end)
- assert(table.concat(order) == "+0-0+1-1+2-2+3", `bad order: {table.concat(order)}`)
- table.clear(order)
- setA(100)
- assert(table.concat(order) == "-3+100", `bad order: {table.concat(order)}`)
-end)
-
-test("should effects dispose in order", function()
- local order: { number } = {}
-
- local src, setSrc = signal(false)
- local stopEffect = effect(function()
- src()
- for i = 1, 3 do
- effect(function()
- return function()
- table.insert(order, i)
- end
- end)
- end
- end)
-
- assert(#order == 0, "should not cleanup immediately")
- setSrc(true)
- assert(table.concat(order) == "123", `bad rerun order: {table.concat(order)}`)
- table.clear(order)
- stopEffect()
- assert(table.concat(order) == "123", `bad dispose order: {table.concat(order)}`)
- table.clear(order)
- setSrc(false)
- assert(#order == 0, "should not cleanup after dispose")
-end)
-
-test("should handle inner effect clearing outer effect's deps on rerun", function()
- local src, setSrc = signal(false)
- local stopEffect: () -> ()
- stopEffect = effect(function()
- src()
- effect(function()
- return function()
- stopEffect()
- end
- end)
- effect(function() end)
- end)
- setSrc(true)
-end)
-
-test.skip("should handle inner effect cleanup disposing outer effect", function()
- local order: { number } = {}
-
- local src, setSrc = signal(false)
- local stopEffect: () -> ()
- stopEffect = effect(function()
- src()
- table.insert(order, 0)
- for i = 1, 4 do
- effect(function()
- return function()
- table.insert(order, i)
- stopEffect()
- end
- end)
- end
- end)
- assert(table.concat(order) == "0", "should not cleanup immediately")
-
- table.clear(order)
- setSrc(true)
- assert(table.concat(order) == "1234", `bad rerun order: {table.concat(order)}`)
-
- table.clear(order)
- setSrc(false)
- assert(#order == 0, "should not cleanup after dispose")
-end)
-
-test.skip("should old inner effect dispose before outer effect re-runs", function()
- local order: { string } = {}
- local src, setSrc = signal(false)
- effect(function()
- src()
- table.insert(order, "outer")
- effect(function()
- return function()
- table.insert(order, "inner")
- end
- end)
- end)
- table.clear(order)
- setSrc(true)
- assert(table.concat(order) == "innerouter", `bad rerun order: {table.concat(order)}`)
-end)
-
return {}
diff --git a/packages/charm/test/effectScope.test.luau b/packages/charm/src/__tests__/effectScope.spec.luau
similarity index 73%
rename from packages/charm/test/effectScope.test.luau
rename to packages/charm/src/__tests__/effectScope.spec.luau
index 964b7d5..c484151 100644
--- a/packages/charm/test/effectScope.test.luau
+++ b/packages/charm/src/__tests__/effectScope.spec.luau
@@ -1,10 +1,11 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local effect = Charm.effect
local effectScope = Charm.effectScope
local signal = Charm.signal
local onCleanup = Charm.onCleanup
+local test = suite.test
test("should not trigger after stop", function()
local count, setCount = signal(1)
@@ -31,8 +32,8 @@ end)
test("should run indirect scope cleanup", function()
local cleanups = 0
- local cleanup: () -> ()
+ local cleanup
local stopScope = effectScope(function()
cleanup = effectScope(function()
onCleanup(function()
@@ -50,8 +51,8 @@ end)
test("should run indirect effect cleanup", function()
local cleanups = 0
- local a, setA = signal(false)
+ local a, setA = signal(false)
local stopScope = effectScope(function()
effect(function()
a()
@@ -70,26 +71,13 @@ test("should run indirect effect cleanup", function()
assert(cleanups == 2, "should not cleanup after update")
end)
-test("should dispose inner effects if created in an effect", function()
- local source, setSource = signal(1)
- local triggers = 0
- local dispose: () -> ()
-
- effect(function()
- dispose = effectScope(function()
- effect(function()
- source()
- triggers += 1
- end)
+test("should disallow yielding", function()
+ local success = pcall(function()
+ effectScope(function()
+ (if task then task.wait else coroutine.yield :: never)()
end)
- assert(triggers == 1, "did not run initially")
end)
-
- setSource(2)
- assert(triggers == 2, "did not run after update")
- dispose()
- setSource(3)
- assert(triggers == 2, "ran after dispose")
+ assert(not success, "should error on yield")
end)
return {}
diff --git a/packages/charm/test/gc.test.luau b/packages/charm/src/__tests__/gc.spec.luau
similarity index 50%
rename from packages/charm/test/gc.test.luau
rename to packages/charm/src/__tests__/gc.spec.luau
index aed0af1..d74196e 100644
--- a/packages/charm/test/gc.test.luau
+++ b/packages/charm/src/__tests__/gc.spec.luau
@@ -1,10 +1,14 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
+
+type ReactiveProxy = Charm.ReactiveProxy
local signal = Charm.signal
local computed = Charm.computed
local effect = Charm.effect
local effectScope = Charm.effectScope
+local reactive = Charm.reactive
+local test = suite.test
local function weakRef(value: T): { value: T? }
return setmetatable({ value = value }, { __mode = "v" }) :: any
@@ -26,7 +30,7 @@ end
immediately closing it, causing alien-signals to unlink the computed value
from its dependencies and allow it to be garbage collected.
]]
-local function unlink(getter: () -> unknown)
+local function unlink(getter: () -> ())
effectScope(function()
getter()
end)()
@@ -62,4 +66,62 @@ test("should not release effect for atom", function()
assert(effectCalls == 2, "should call effect again")
end)
+test("should release inner reactive proxy", function()
+ local valueRef = weakRef({})
+ local src: any = reactive({ value = valueRef.value })
+
+ local dispose = effect(function()
+ local _ = src.value -- create proxy
+ end)
+ src.value = nil :: any -- release proxy
+ dispose()
+
+ gc()
+ assert(src.__signals.value == nil, "should release signals")
+ assert(valueRef.value == nil, "should release inner proxy")
+end)
+
+test("should release reactive property deps", function()
+ local src: any = reactive({ foo = 1 })
+
+ local c = computed(function()
+ return src.foo
+ end)
+
+ c()
+ assert(src.__signals.foo ~= nil, "should have deps for foo")
+
+ c = nil :: any
+ gc()
+ assert(src.__signals.foo == nil, "should release deps for foo")
+end)
+
+test("should not release effect for reactive", function()
+ local src = reactive({ foo = 1 })
+ local calls = 0
+
+ effect(function()
+ calls += 1
+ local _ = src.foo
+ end)
+ assert(calls == 1, "should call effect once")
+
+ gc()
+ src.foo += 1
+ assert(calls == 2, "should call effect again")
+end)
+
+test("should not release tracked reactive", function()
+ local src = Charm.reactive({ users = {} :: { [string]: {}? } })
+ local user
+
+ effect(function()
+ user = src.users.user
+ end)
+
+ gc()
+ src.users.user = {}
+ assert(user ~= nil, "src.users.user should not be released")
+end)
+
return {}
diff --git a/packages/charm/test/listen.test.luau b/packages/charm/src/__tests__/listen.spec.luau
similarity index 56%
rename from packages/charm/test/listen.test.luau
rename to packages/charm/src/__tests__/listen.spec.luau
index 5d9c335..f3098d1 100644
--- a/packages/charm/test/listen.test.luau
+++ b/packages/charm/src/__tests__/listen.spec.luau
@@ -1,8 +1,10 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local signal = Charm.signal
local listen = Charm.listen
+local effect = Charm.effect
+local test = suite.test
test("should listen to selector", function()
local source, setSource = signal(0)
@@ -25,23 +27,32 @@ test("should listen to selector", function()
assert(current == 2 and previous == 1, "should not run after unsub")
end)
-test("should run in untracked", function()
+test("should run in peek", function()
local runs = 0
+ local cleanups = 0
local a, setA = signal(0)
local b, setB = signal(0)
listen(a, function()
runs += 1
b()
+ effect(function()
+ return function()
+ cleanups += 1
+ end
+ end)
end)
assert(runs == 1, "should run once on init")
+ assert(cleanups == 0, "should not cleanup yet")
+
setA(1)
- assert(runs == 2, "should run once on change")
+ assert(runs == 2, "should run on a change")
+ assert(cleanups == 1, "should cleanup first call")
+
setB(1)
assert(runs == 2, "should not run on b change")
- setA(2)
- assert(runs == 3, "should run on a change")
+ assert(cleanups == 1, "should not cleanup second call")
end)
test("should run if first value is nil", function()
@@ -57,6 +68,36 @@ test("should run if first value is nil", function()
assert(runs == 2, "should run once on change")
end)
+test("should track inner subs", function()
+ local order = {}
+ local a, setA = signal(1)
+
+ local unsub = listen(a, function()
+ table.insert(order, 1)
+ listen(a, function()
+ table.insert(order, 2)
+ end)
+ listen(a, function()
+ table.insert(order, 3)
+ end)
+ end)
+
+ assert(table.concat(order) == "123", `bad mount order: {table.concat(order)}`)
+
+ table.clear(order)
+ setA(a() + 1)
+ assert(table.concat(order) == "123", `bad order: {table.concat(order)}`)
+
+ table.clear(order)
+ setA(a() + 1)
+ assert(table.concat(order) == "123", `bad order: {table.concat(order)}`)
+
+ table.clear(order)
+ unsub()
+ setA(a() + 1)
+ assert(table.concat(order) == "", `bad order: {table.concat(order)}`)
+end)
+
test("should skip redundant updates", function()
local order = {}
local a, setA = signal(0)
diff --git a/packages/charm/test/mapped.test.luau b/packages/charm/src/__tests__/mapped.spec.luau
similarity index 78%
rename from packages/charm/test/mapped.test.luau
rename to packages/charm/src/__tests__/mapped.spec.luau
index 33620d4..b812aea 100644
--- a/packages/charm/test/mapped.test.luau
+++ b/packages/charm/src/__tests__/mapped.spec.luau
@@ -1,8 +1,9 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local signal = Charm.signal
local mapped = Charm.mapped
+local test = suite.test
test("should map state", function()
local src, setSrc = signal({ 1, 2, 3 })
@@ -104,25 +105,4 @@ test("should map keys", function()
assert(state.D == 4, "should add d")
end)
-test("should remove old key if mapper returns a new key", function()
- local src, setSrc = signal({ 1 })
- local map = mapped(src, function(value: number, index: number)
- return true, `{index}={value}`
- end)
-
- local state = map()
- assert(state["1=1"], "should have mapped first element to key 1=1")
-
- setSrc({ 2 })
- state = map()
- assert(state["1=1"] == nil, "should have removed old key 1=1")
- assert(state["1=2"], "should have remapped element to key 1=2")
-
- setSrc({ 3, 1 })
- state = map()
- assert(state["1=2"] == nil, "should have removed old key 1=2")
- assert(state["1=3"], "should have remapped element to key 1=3")
- assert(state["2=1"], "should have mapped second element to key 2=1")
-end)
-
return {}
diff --git a/packages/charm/test/observe.test.luau b/packages/charm/src/__tests__/observe.spec.luau
similarity index 79%
rename from packages/charm/test/observe.test.luau
rename to packages/charm/src/__tests__/observe.spec.luau
index 64bbd7d..f308477 100644
--- a/packages/charm/test/observe.test.luau
+++ b/packages/charm/src/__tests__/observe.spec.luau
@@ -1,18 +1,19 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local signal = Charm.signal
local computed = Charm.computed
local effect = Charm.effect
local effectScope = Charm.effectScope
local observe = Charm.observe
+local test = suite.test
test("should observe items", function()
local items, setItems = signal({ 0, 0, 0 })
local updates = {}
local cleanups = {}
- observe(items, function(_, key: number)
+ observe(items, function(_, key)
local get = computed(function()
return items()[key]
end)
@@ -91,11 +92,11 @@ end)
test("should handle recursive additions and removals", function()
local items, setItems = signal({ 1 })
- local edits: { string } = {}
+ local edits = {}
observe(items, function(item)
if item < 5 then
- setItems(function(state: { number })
+ setItems(function(state)
state = table.clone(state)
table.insert(state, item + 1)
return state
@@ -114,10 +115,10 @@ end)
test("should handle self removal", function()
local items, setItems = signal({ 1, 2, 3, 4 })
- local edits: { string } = {}
+ local edits = {}
observe(items, function(item, index)
- setItems(function(state: { number })
+ setItems(function(state)
state = table.clone(state)
state[index] = nil
return state
@@ -134,7 +135,7 @@ end)
test("should allow disposal during addition", function()
local items, setItems = signal({})
local edits = {}
- local dispose: () -> ()
+ local dispose
dispose = observe(items, function(item)
if item == 1 then
@@ -153,7 +154,7 @@ end)
test("should allow disposal during removal", function()
local items, setItems = signal({ 1, 2, 3, 4 })
local edits = {}
- local dispose: () -> ()
+ local dispose
dispose = observe(items, function(item)
table.insert(edits, `+{item}`)
@@ -167,32 +168,4 @@ test("should allow disposal during removal", function()
assert(table.concat(edits) == "+1+2+3+4-1-2-3-4", `bad edits: {table.concat(edits)}`)
end)
-test("should not hang on error after recursive update", function()
- local items, setItems = signal({})
-
- observe(items, function()
- setItems({ {} })
- error("test error")
- end)
-
- local success, err = pcall(function()
- setItems({ {} })
- end)
- assert(not success, "should error")
- assert(string.find(tostring(err), "test error"), `bad error: {err}`)
-end)
-
-test("should not hang on error after recursive init", function()
- local items, setItems = signal({ {} })
-
- local success, err = pcall(function()
- observe(items, function()
- setItems({ {} })
- error("test error")
- end)
- end)
- assert(not success, "should error")
- assert(string.find(tostring(err), "test error"), `bad error: {err}`)
-end)
-
return {}
diff --git a/packages/charm/src/__tests__/peek.spec.luau b/packages/charm/src/__tests__/peek.spec.luau
new file mode 100644
index 0000000..b786135
--- /dev/null
+++ b/packages/charm/src/__tests__/peek.spec.luau
@@ -0,0 +1,147 @@
+local Charm = require("../")
+local suite = require("../../../../test/suite")
+
+local signal = Charm.signal
+local computed = Charm.computed
+local effect = Charm.effect
+local peek = Charm.peek
+local test = suite.test
+
+test("should not run detached", function()
+ local a, setA = signal(1)
+ local spyCalls = 0
+
+ effect(function()
+ a()
+ peek(function()
+ effect(function()
+ return function()
+ spyCalls += 1
+ end
+ end)
+ end)
+ end)
+
+ assert(spyCalls == 0, "should not be called yet")
+ setA(2)
+ assert(spyCalls == 1, "should be called once")
+ setA(3)
+ assert(spyCalls == 2, "should be called twice")
+end)
+
+test("should block tracking inside effects", function()
+ local a, setA = signal(1)
+ local b, setB = signal(2)
+ local spyCalls = 0
+
+ effect(function()
+ peek(function()
+ spyCalls += 1
+ return a() + b()
+ end)
+ end)
+ assert(spyCalls == 1, "should be called once")
+
+ setA(10)
+ setB(20)
+ assert(spyCalls == 1, "should be called once")
+end)
+
+test("should block tracking even when run inside effect run inside peek", function()
+ local s, setS = signal(1)
+ local spyCalls = 0
+
+ peek(function()
+ effect(function()
+ peek(function()
+ spyCalls += 1
+ return s()
+ end)
+ end)
+ end)
+ assert(spyCalls == 1, "should be called once")
+
+ setS(2)
+ assert(spyCalls == 1, "should be called once")
+end)
+
+test("should not cause signal assignments to throw", function()
+ local a, setA = signal(1)
+ local aChangedTime, setAChangedTime = signal(0)
+
+ local dispose = effect(function()
+ a()
+ peek(function()
+ setAChangedTime(aChangedTime() + 1)
+ end)
+ end)
+
+ setA(2)
+ assert(aChangedTime() == 2, "aChangedTime should be 2")
+ setA(3)
+ assert(aChangedTime() == 3, "aChangedTime should be 3")
+
+ dispose()
+end)
+
+test("should block tracking inside computed signals", function()
+ local a, setA = signal(1)
+ local b, setB = signal(2)
+ local spyCalls = 0
+ local c = computed(function()
+ return peek(function()
+ spyCalls += 1
+ return a() + b()
+ end)
+ end)
+
+ assert(spyCalls == 0, "should not be called yet")
+ assert(c() == 3, "c should be 3")
+ setA(10)
+ c()
+ setB(20)
+ c()
+ assert(spyCalls == 1, "should be called once")
+ assert(c() == 3, "c should be 3")
+end)
+
+test("should track outside peek", function()
+ local a, setA = signal(1)
+ local b, setB = signal(2)
+ local c, setC = signal(3)
+ local spyCalls = 0
+
+ effect(function()
+ a()
+ peek(c)
+ b()
+ spyCalls += 1
+ end)
+
+ assert(spyCalls == 1, "should be called once")
+ setA(10)
+ assert(spyCalls == 2, "should be called twice")
+ setB(20)
+ assert(spyCalls == 3, "should be called three times")
+ setC(30)
+ assert(spyCalls == 3, "should not run on c change")
+end)
+
+test("should stack peek", function()
+ local a, setA = signal(1)
+ local spyCalls = 0
+
+ effect(function()
+ peek(function()
+ peek(a)
+ return a()
+ end)
+ spyCalls += 1
+ end)
+
+ assert(spyCalls == 1, "should be called once")
+ setA(2)
+ assert(spyCalls == 1, "should not be called twice")
+end)
+
+return {}
diff --git a/packages/deep-charm/test/reactive.test.luau b/packages/charm/src/__tests__/reactive.spec.luau
similarity index 70%
rename from packages/deep-charm/test/reactive.test.luau
rename to packages/charm/src/__tests__/reactive.spec.luau
index 41654b1..a2c2d0c 100644
--- a/packages/deep-charm/test/reactive.test.luau
+++ b/packages/charm/src/__tests__/reactive.spec.luau
@@ -1,13 +1,10 @@
-local Charm = require("../Charm")
-local DeepCharm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
-local batch = Charm.batch
-local computed = Charm.computed
local effect = Charm.effect
-local observe = Charm.observe
-local reactive = DeepCharm.reactive
-local toRaw = DeepCharm.toRaw
+local reactive = Charm.reactive
+local toRaw = Charm.toRaw
+local test = suite.test
test("should track nested properties", function()
local src, setSrc = reactive({ a = { b = { c = 0 } } })
@@ -52,10 +49,10 @@ test("should unwrap proxy assignments", function()
end)
src.a, src.b = src.a, src.b
- assert(runs == 1, `bad runs: {runs}`)
+ assert(runs == 1, runs)
src.a, src.b = src.b, src.a
- assert(runs == 3, `bad runs: {runs}`)
+ assert(runs == 3, runs)
end)
test("should track iteration", function()
@@ -128,10 +125,10 @@ test("should not track unread properties", function()
local _ = src.value.a
calls += 1
end)
- assert(calls == 1, `bad calls: {calls}`)
+ assert(calls == 1, calls)
src.value.b = 3
- assert(calls == 1, `bad calls: {calls}`)
+ assert(calls == 1, calls)
end)
test("should overwrite with table passed to setter", function()
@@ -162,10 +159,10 @@ test("should unwrap proxy", function()
assert(toRaw(src) == raw, "unwrap did not return the original table")
assert(toRaw(raw) == raw, "unwrap modified a non-proxy value")
- assert(runs == 1, `bad runs: {runs}`)
+ assert(runs == 1, runs)
src.x = 1
- assert(runs == 2, `bad runs: {runs}`)
+ assert(runs == 2, runs)
end)
test("should unwrap nested proxy", function()
@@ -180,53 +177,13 @@ test("should unwrap nested proxy", function()
end)
assert(toRaw(src) == raw, "unwrap did not return the original table")
- assert(runs == 1, `bad runs: {runs}`)
+ assert(runs == 1, runs)
inner.x = 1
- assert(runs == 2, `bad runs: {runs}`)
+ assert(runs == 2, runs)
src.y = 2
- assert(runs == 3, `bad runs: {runs}`)
-end)
-
-test("should observe items", function()
- local items, updateItems = reactive({ 0, 0, 0 })
- local updates = {}
- local cleanups = {}
-
- observe(function()
- return toRaw(items)
- end, function(_, key: number)
- local get = computed(function()
- return items[key]
- end)
-
- effect(function()
- table.insert(updates, get())
- end)
-
- return function()
- table.insert(cleanups, key)
- end
- end)
-
- assert(table.concat(updates) == "000", `bad mount: {table.concat(updates)}`)
-
- table.clear(updates)
- updateItems(function(state)
- state[1] = 1
- state[2] = 2
- state[3] = 3
- end)
- assert(table.concat(updates) == "123", `bad update: {table.concat(updates)}`)
-
- table.clear(updates)
- batch(function()
- items[3] = nil
- items[4] = 4
- end)
- assert(table.concat(updates) == "4", `should add 4: {table.concat(updates)}`)
- assert(table.concat(cleanups) == "3", `bad cleanup: {table.concat(cleanups)}`)
+ assert(runs == 3, runs)
end)
return {}
diff --git a/packages/charm/test/signal.test.luau b/packages/charm/src/__tests__/signal.spec.luau
similarity index 62%
rename from packages/charm/test/signal.test.luau
rename to packages/charm/src/__tests__/signal.spec.luau
index 21c1746..a9693f6 100644
--- a/packages/charm/test/signal.test.luau
+++ b/packages/charm/src/__tests__/signal.spec.luau
@@ -1,12 +1,13 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local signal = Charm.signal
local effect = Charm.effect
+local test = suite.test
test("should accept equality function", function()
local calls = {}
- local src, setSrc = signal(0, function(current: number, incoming: number)
+ local src, setSrc = signal(0, function(current, incoming)
return current == incoming or incoming % 2 == 1
end)
@@ -46,22 +47,4 @@ test("should not freeze values with metatables", function()
)
end)
-test("should setter return same value as getter even if equal", function()
- local src, setSrc = signal(0, function()
- return true
- end)
- assert(setSrc(1) == src(), `setSrc(1) expected 0, got {setSrc(1)}`)
-end)
-
-test("should setter return latest value", function()
- local src, setSrc = signal(0)
- effect(function()
- if src() == 1 then
- setSrc(2)
- end
- end)
- assert(setSrc(1) == 2, `setSrc(1) expected 2, got {setSrc(1)}`)
- assert(src() == 2, `src() expected 2, got {src()}`)
-end)
-
return {}
diff --git a/packages/charm/src/__tests__/spec.luau b/packages/charm/src/__tests__/spec.luau
new file mode 100644
index 0000000..17dd1f2
--- /dev/null
+++ b/packages/charm/src/__tests__/spec.luau
@@ -0,0 +1,46 @@
+local suite = require("../../../../test/suite")
+
+suite.describe("computed", function()
+ require("./computed.spec")
+end)
+suite.describe("effect", function()
+ require("./effect.spec")
+end)
+suite.describe("effectScope", function()
+ require("./effectScope.spec")
+end)
+suite.describe("gc", function()
+ require("./gc.spec")
+end)
+suite.describe("listen", function()
+ require("./listen.spec")
+end)
+suite.describe("mapped", function()
+ require("./mapped.spec")
+end)
+suite.describe("observe", function()
+ require("./observe.spec")
+end)
+suite.describe("peek", function()
+ require("./peek.spec")
+end)
+suite.describe("reactive", function()
+ require("./reactive.spec")
+end)
+suite.describe("signal", function()
+ require("./signal.spec")
+end)
+suite.describe("subscribe", function()
+ require("./subscribe.spec")
+end)
+suite.describe("topology", function()
+ require("./topology.spec")
+end)
+suite.describe("trigger", function()
+ require("./trigger.spec")
+end)
+suite.describe("untracked", function()
+ require("./untracked.spec")
+end)
+
+return {}
diff --git a/packages/charm/test/subscribe.test.luau b/packages/charm/src/__tests__/subscribe.spec.luau
similarity index 61%
rename from packages/charm/test/subscribe.test.luau
rename to packages/charm/src/__tests__/subscribe.spec.luau
index 10ab932..938931b 100644
--- a/packages/charm/test/subscribe.test.luau
+++ b/packages/charm/src/__tests__/subscribe.spec.luau
@@ -1,9 +1,12 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local signal = Charm.signal
local computed = Charm.computed
local subscribe = Charm.subscribe
+local listen = Charm.listen
+local effect = Charm.effect
+local test = suite.test
test("should subscribe to selector", function()
local source, setSource = signal(0)
@@ -26,27 +29,40 @@ test("should subscribe to selector", function()
assert(current == 2 and previous == 1, "should not run after unsub")
end)
-test("should run in untracked", function()
+test("should run in peek", function()
local runs = 0
+ local cleanups = 0
local a, setA = signal(0)
local b, setB = signal(0)
subscribe(a, function()
runs += 1
b()
+ effect(function()
+ return function()
+ cleanups += 1
+ end
+ end)
end)
assert(runs == 0, "should not run once on init")
+ assert(cleanups == 0, "should not cleanup yet")
+
setA(1)
assert(runs == 1, "should run once on change")
+ assert(cleanups == 0, "should not cleanup yet")
+
setB(1)
assert(runs == 1, "should not run on b change")
+ assert(cleanups == 0, "should not cleanup first call")
+
setA(2)
assert(runs == 2, "should run on a change")
+ assert(cleanups == 1, "should cleanup first call")
end)
test("should ensure correct execution order", function()
- local order: { number } = {}
+ local order = {}
local n1, setN1 = signal(0)
local n2, setN2 = signal(0)
local sum = computed(function()
@@ -71,8 +87,35 @@ test("should ensure correct execution order", function()
assert(table.concat(order) == "123", `bad order: {table.concat(order)}`)
end)
+test("should track inner subs", function()
+ local order = {}
+ local a, setA = signal(1)
+
+ local unsub = subscribe(a, function()
+ table.insert(order, 1)
+ listen(a, function()
+ table.insert(order, 2)
+ end)
+ listen(a, function()
+ table.insert(order, 3)
+ end)
+ end)
+
+ setA(a() + 1)
+ assert(table.concat(order) == "123", `bad order: {table.concat(order)}`)
+
+ table.clear(order)
+ setA(a() + 1)
+ assert(table.concat(order) == "123", `bad order: {table.concat(order)}`)
+
+ table.clear(order)
+ unsub()
+ setA(a() + 1)
+ assert(table.concat(order) == "", `bad order: {table.concat(order)}`)
+end)
+
test("should skip redundant updates", function()
- local order: { "even" | "odd" } = {}
+ local order = {}
local a, setA = signal(0)
subscribe(function(): "even" | "odd"
diff --git a/packages/charm/test/topology.test.luau b/packages/charm/src/__tests__/topology.spec.luau
similarity index 95%
rename from packages/charm/test/topology.test.luau
rename to packages/charm/src/__tests__/topology.spec.luau
index 3675b3d..6f1e1e0 100644
--- a/packages/charm/test/topology.test.luau
+++ b/packages/charm/src/__tests__/topology.spec.luau
@@ -1,9 +1,11 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local atom = Charm.atom
local computed = Charm.computed
local effect = Charm.effect
+local describe = suite.describe
+local test = suite.test
--[[
Tests adopted with thanks from preact-core implementation at
@@ -32,7 +34,7 @@ local effect = Charm.effect
SOFTWARE
]]
-test.describe("graph updates", function()
+describe("graph updates", function()
test("should drop A->B->A updates", function()
-- A
-- / |
@@ -439,19 +441,21 @@ test.describe("graph updates", function()
end)
end)
-test.describe("error handling", function()
+describe("error handling", function()
test("should keep graph consistent on errors during activation", function()
local a = atom(0)
- local b = computed(function(): nil
+ local b = computed(function()
error("fail")
end)
local c = computed(function()
return a()
end)
- local success, result = pcall(b)
+ local success, result = pcall(function()
+ b()
+ end)
assert(not success, "should throw")
- assert(string.match(tostring(result), "fail"), "should throw fail")
+ assert(string.match(result, "fail"), "should throw fail")
a(1)
assert(c() == 1, "c should recover and return 1")
@@ -459,7 +463,7 @@ test.describe("error handling", function()
test("should keep graph consistent on errors in computeds", function()
local a = atom(0)
- local b = computed(function(): number
+ local b = computed(function()
if a() == 1 then
error("fail")
end
@@ -472,9 +476,11 @@ test.describe("error handling", function()
assert(c() == 0, "c should be 0")
a(1)
- local success, result = pcall(b)
+ local success, result = pcall(function()
+ b()
+ end)
assert(not success, "should throw")
- assert(string.match(tostring(result), "fail"), "should throw fail")
+ assert(string.match(result, "fail"), "should throw fail")
a(2)
assert(c() == 2, "c should recover and return 2")
diff --git a/packages/charm/test/trigger.test.luau b/packages/charm/src/__tests__/trigger.spec.luau
similarity index 78%
rename from packages/charm/test/trigger.test.luau
rename to packages/charm/src/__tests__/trigger.spec.luau
index 20ebf32..d0b1938 100644
--- a/packages/charm/test/trigger.test.luau
+++ b/packages/charm/src/__tests__/trigger.spec.luau
@@ -1,18 +1,20 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local computed = Charm.computed
local effect = Charm.effect
-local listen = Charm.listen
local signal = Charm.signal
local subscribe = Charm.subscribe
local trigger = Charm.trigger
+local test = suite.test
+local beforeEach = suite.beforeEach
+local afterEach = suite.afterEach
-test.beforeEach(function()
+beforeEach(function()
Charm.flags.frozen = false
end)
-test.afterEach(function()
+afterEach(function()
Charm.flags.frozen = true
end)
@@ -68,7 +70,7 @@ test("should trigger effect once", function()
end)
test("should not notify the trigger function sub", function()
- local src1 = signal({} :: { number })
+ local src1 = signal({})
local src2 = computed(function()
return src1()
end)
@@ -91,21 +93,9 @@ test("should trigger updates for subscribe", function()
triggers += 1
end)
+ table.insert(src(), 1)
trigger(src)
assert(triggers == 1, "subscribe callback should run after trigger")
end)
-test("should trigger updates for listen", function()
- local src = signal({} :: { number })
- local triggers = 0
-
- listen(src, function()
- triggers += 1
- end)
- assert(triggers == 1, "listen callback should run once initially")
-
- trigger(src)
- assert(triggers == 2, "listen callback should run after trigger")
-end)
-
return {}
diff --git a/packages/charm/test/untracked.test.luau b/packages/charm/src/__tests__/untracked.spec.luau
similarity index 96%
rename from packages/charm/test/untracked.test.luau
rename to packages/charm/src/__tests__/untracked.spec.luau
index 3c7fea4..d4bfc4c 100644
--- a/packages/charm/test/untracked.test.luau
+++ b/packages/charm/src/__tests__/untracked.spec.luau
@@ -1,11 +1,12 @@
-local Charm = require("../src")
-local test = require("../../../tests/test")
+local Charm = require("../")
+local suite = require("../../../../test/suite")
local signal = Charm.signal
local computed = Charm.computed
local effect = Charm.effect
local effectScope = Charm.effectScope
local untracked = Charm.untracked
+local test = suite.test
test("should run detached from effect", function()
local a, setA = signal(1)
@@ -38,7 +39,7 @@ end)
test("should run detached from effect scope", function()
local effects = 0
- local stopEffect: () -> ()
+ local stopEffect
local stopScope = effectScope(function()
untracked(function()
diff --git a/packages/charm/src/index.d.ts b/packages/charm/src/index.d.ts
index e4689e5..132a5be 100644
--- a/packages/charm/src/index.d.ts
+++ b/packages/charm/src/index.d.ts
@@ -1,15 +1,15 @@
type Key = string | number | symbol;
-
type Cleanup = () => void;
export enum ReactiveFlags {
- None = 0b000000,
- Mutable = 0b000001,
- Watching = 0b000010,
- RecursedCheck = 0b000100,
- Recursed = 0b001000,
- Dirty = 0b010000,
- Pending = 0b100000,
+ None = 0b0000000,
+ Mutable = 0b0000001,
+ Watching = 0b0000010,
+ RecursedCheck = 0b0000100,
+ Recursed = 0b0001000,
+ Dirty = 0b0010000,
+ Pending = 0b0100000,
+ Peeking = 0b1000000,
}
export interface ReactiveNode {
@@ -31,15 +31,11 @@ export interface Link {
}
export interface Atom {
- (update: Update): T;
+ (newValue: T | ((currentValue: T) => T)): T;
(): T;
}
-export type Getter = () => T;
-
-export type Setter = (update: Update) => T;
-
-export type Update = ((currentValue: T) => T) | T;
+export type Setter = (newValue: T | ((currentValue: T) => T)) => T;
export type Equals = (current: T, incoming: T) => boolean;
@@ -50,12 +46,12 @@ export const flags: {
/**
* Enforces synchronous, non-yielding behavior in signals and effects.
* Also enables state validation in Charm Sync to catch sync errors early.
- * Enabled by default in Roblox Studio.
+ * Enabled if the optimization level is below 2, which is true in studio.
*/
strict: boolean;
/**
* Enforces immutability of tables by deep-freezing table values. Enabled
- * by default in Roblox Studio.
+ * if the optimization level is below 2, which is true in studio.
*/
frozen: boolean;
/**
@@ -75,8 +71,13 @@ export const flags: {
* @returns A tuple containing the getter and setter functions for the signal.
* @see https://github.com/littensy/charm?tab=readme-ov-file#signalinitialValue-equals
*/
-export function signal(initialValue: T, equals?: Equals): LuaTuple<[getter: Getter, setter: Setter]>;
-export function signal(): LuaTuple<[getter: Getter, setter: Setter]>;
+export function signal(
+ initialValue: T,
+ equals?: Equals,
+): LuaTuple<[getter: () => T, setter: (newValue: T | ((currentValue: T) => T)) => T]>;
+export function signal(): LuaTuple<
+ [getter: () => T | undefined, setter: (newValue: T | ((currentValue?: T) => T | undefined)) => T | undefined]
+>;
/**
* Creates a reactive atom that acts as both a signal getter and setter.
@@ -98,7 +99,7 @@ export function atom(): Atom;
* @param getter A function that produces the next value.
* @see https://github.com/littensy/charm?tab=readme-ov-file#computedgetter
*/
-export function computed(getter: (previousValue?: T) => T): Getter;
+export function computed(getter: (previousValue?: T) => T): () => T;
/**
* Creates an effect that runs a callback in response to signal state changes.
@@ -149,12 +150,10 @@ export function trigger(fn: () => void): void;
export function onCleanup(fn: Cleanup, failSilently?: boolean): void;
/**
- * Runs the function without subscribing to signal updates and prevents the
- * current effect or scope from tracking inner effects created within the
- * function.
+ * Runs the function without subscribing to signal updates or capturing inner
+ * effects in the parent effect or scope.
*
- * To avoid tracking signals while still allowing inner effects to be tracked
- * by parent effects/scopes, use `effectScope()` instead.
+ * For an alternative that still cleans up inner effects, use `peek` instead.
*
* @param fn A function that may read signals or create effects.
* @param args Arguments to pass to the function.
@@ -163,6 +162,19 @@ export function onCleanup(fn: Cleanup, failSilently?: boolean): void;
*/
export function untracked(fn: (...args: Args) => Result, ...args: Args): Result;
+/**
+ * Runs the function without subscribing to signal updates, but still captures
+ * inner effects so that they dispose with the parent effect.
+ *
+ * To avoid capturing inner effects, use `untracked` instead.
+ *
+ * @param fn A function that may read signals.
+ * @param args Arguments to pass to the function.
+ * @returns The return value of the function.
+ * @see https://github.com/littensy/charm?tab=readme-ov-file#peekcallback
+ */
+export function peek(fn: (...args: Args) => Result, ...args: Args): Result;
+
/**
* Combines multiple updates into a single "commit" that runs effects and
* computed signals after the provided function finishes running.
@@ -179,51 +191,54 @@ export function batch(fn: (...args: Args) => Result,
* when the value returned by the getter changes. The callback receives the new
* value and the previous value as arguments.
*
+ * Effects created within the callback are cleaned up when the listener runs
+ * or the listener is disposed.
+ *
* @param getter A function that returns the value to watch.
- * @param callback The function to run when the value changes.
+ * @param fn The function to run when the value changes.
* @returns A function for disposing the effect.
* @see https://github.com/littensy/charm?tab=readme-ov-file#listengetter-callback
*/
-export function listen(getter: Getter, callback: (value: T, previousValue: T | undefined) => void): Cleanup;
+export function listen(getter: () => T, fn: (value: T, previousValue: T | undefined) => void): Cleanup;
/**
* Creates an effect that only runs the callback when the value returned by the
* getter changes. The callback receives the new value and the previous value
* as arguments.
*
+ * Effects created within the callback are cleaned up when the listener runs
+ * or the listener is disposed.
+ *
* @param getter A function that returns the value to watch.
- * @param callback The function to run when the value changes.
+ * @param fn The function to run when the value changes.
* @returns A function for disposing the effect.
* @see https://github.com/littensy/charm?tab=readme-ov-file#subscribegetter-callback
*/
-export function subscribe(getter: Getter, callback: (value: T, previousValue: T) => void): Cleanup;
+export function subscribe(getter: () => T, fn: (value: T, previousValue: T) => void): Cleanup;
/**
* Creates a new read-only signal that is computed by mapping over the entries
- * of the source table. If the key is omitted from the transform function's
- * return value, the original key is preserved.
+ * of an existing atom. If the key is omitted from the mapper's return value,
+ * the original key is preserved.
*
- * This function is optimized to minimize unnecessary updates by only calling
- * the transform function for entries that have changed since the last run.
- *
- * @param getter A signal or function that returns a table
- * @param transform Function that maps each entry from the source to a new entry in the mapped table
- * @see https://github.com/littensy/charm?tab=readme-ov-file#mappedgetter-transform
+ * @param getter Returns the table to map over.
+ * @param mapper Transforms each value-key pair from the source into a new value or value-key pair for the resulting table.
+ * @see https://github.com/littensy/charm?tab=readme-ov-file#mappedgetter-mapper
*/
export function mapped(
- getter: Getter