Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Get an immutable snapshot of a value and its children #554

Open
SamyPesse opened this issue Jul 20, 2023 · 0 comments
Open

Get an immutable snapshot of a value and its children #554

SamyPesse opened this issue Jul 20, 2023 · 0 comments
Assignees

Comments

@SamyPesse
Copy link
Contributor

When synchronizing a Yjs doc with an external data structure, it'd be great if there was a way to transform a Yjs type into an immutable data structure so that we can implement memoization on it.

For example liveblocks has toImmutable on all its low level types: https://github.com/liveblocks/liveblocks/blob/f4096d55f16c237a4718a5dc7ec5018e4cbdf438/packages/liveblocks-core/src/crdts/AbstractCrdt.ts#L363
It's really useful as a WeakMap can be used to cache transformation from these values to a computed value.

With Yjs, we initially implemented a solution using:

const mutationKeys: WeakMap<YJSInput, number> = new WeakMap();

/**
 * Observe mutations on a Yjs input and return a number that increments on each mutation.
 */
function getYMutationClock(input): number {
    observeMutations(input);
    return mutationKeys.get(input) || 0;
}

function observeMutations(input: YJSInput) {
    if (mutationKeys.has(input)) {
        return;
    }

    mutationKeys.set(input, 0);

    input.observeDeep(() => {
        const current = mutationKeys.get(input) || 0;
        mutationKeys.set(input, current + 1);
    });
}

But it seems to be inconsistent and corrupts the cache.

Any suggestion on alternatives ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants