feat: add ignoreUnhydrated option

This commit is contained in:
Richard 2024-09-20 02:01:17 -07:00
parent d962724ac6
commit 4c1b60b17b
2 changed files with 16 additions and 5 deletions

5
src/index.d.ts vendored
View file

@ -290,6 +290,11 @@ declare namespace Charm {
* The atoms to synchronize with the server. * The atoms to synchronize with the server.
*/ */
atoms: Atoms; atoms: Atoms;
/**
* Whether to ignore patches sent before the client has been hydrated.
* Defaults to `true`.
*/
ignoreUnhydrated?: boolean;
} }
interface ServerOptions<Molecules extends MoleculeMap> { interface ServerOptions<Molecules extends MoleculeMap> {

View file

@ -9,6 +9,11 @@ type ClientOptions = {
The atoms to synchronize with the server. The atoms to synchronize with the server.
]=] ]=]
atoms: { [string]: Atom<any> }, atoms: { [string]: Atom<any> },
--[=[
Whether to ignore patches sent before the client has been hydrated.
Default is `true`.
]=]
ignoreUnhydrated: boolean?,
} }
type ClientSyncer = { type ClientSyncer = {
@ -30,21 +35,22 @@ type ClientSyncer = {
]=] ]=]
local function client(options: ClientOptions): ClientSyncer local function client(options: ClientOptions): ClientSyncer
local atoms = options.atoms local atoms = options.atoms
local ignoreUnhydrated = options.ignoreUnhydrated ~= false
local self = {} :: ClientSyncer local self = {} :: ClientSyncer
local ready = false local hydrated = false
-- Apply the state changes sent by the server. -- Apply the state changes sent by the server.
function self:sync(...) function self:sync(...)
for index = 1, select("#", ...) do for index = 1, select("#", ...) do
local payload: SyncPayload = select(index, ...) local payload: SyncPayload = select(index, ...)
if payload.type ~= "init" and not ready then if ignoreUnhydrated and payload.type ~= "init" and not hydrated then
-- If the client has not been hydrated yet, ignore patches. -- If the client is not initialized, ignore patches. This is
-- This is to prevent the client from patching incomplete state. -- to prevent patching incomplete state.
continue continue
end end
ready = true hydrated = true
store.batch(function() store.batch(function()
for key, state in next, payload.data do for key, state in next, payload.data do