Giter VIP home page Giter VIP logo

proxy-live-document's Introduction

Proxy Live Document

An opinionated, mutable, single store state management library that allows fine grained observers over what changes.

Current status

  • alpha version
  • api likely to change
  • all apis are well tested

Installation

npm i proxy-live-document

Core ideas

Changes mutate the data

Any change we want to make should be made with a mutation, just like in the old days.

If you want to modify something in your state, write just the change, without having to worry about immutability, efficient re-rendering of the UI or anything like that.

const state = {}
// ...
state.someValue = 32
// ...

Is a valid way of setting a key in the state object.

Any object {} can be observed and used as the root of the state

This means that we have complete freedom of how we want to structure our content, how nested the values can be.

const state = {}

select(state, ['someValue'], (currentState, patches) => {
  console.log(`running selector`, currentState.someValue)
})

mutate(state, (currentState) => {
  currentState.someValue = 32
})

// will log `running selector` 32

Class instances are supported

class State {

  someValue: number = 0

  changeValue (newValue: number) {
    this.someValue = newValue
  }
}

const theAppState = new State()

select(theAppState, ['someValue'], (currentState, patches) => {
  console.log(`running selector`, currentState.someValue)
})

mutate(theAppState, (currentState) => {
  currentState.changeValue(32)
})

// will log `running selector` 32

No support for arrays / lists (yet?)

Observations of changes don't know how to reason about arrays, only objects are supported for now.

If you have arrays in your state, consider changing them to { key: value, key2: value2 } representations. The UI rendering in general - regardless of UI framework used - would benefit greatly by this change.

API Overview

mutate

mutate<T>(state: T, callback(stateLikeObject: T) => void)

mutate is a function that wraps the root state into a proxy and keeps track of changes happening in it.

  • The type <T> of state will identical to the first paremeter of the callback
  • Changes will only be observed if they are done on the stateLikeObject or on sub-objects accessed from the stateLikeObject
  • If an error is thrown in the mutate function, NO CHANGES will be made on the state and no observable will be triggered.

select

select<T>(
  state: T, 
  selectors: string[], 
  callback(
    stateLikeObject: T, 
    patches: JSONPatchEnchanged[]
  ) => unknown
)

select is a function that gets the root state and an array of paths of interest similar to the paths used to match folders inside a directory structure. When any change done in mutate functions happens on those selected paths, the callback parameter will run.

mutateFromPatches

Mutate functions return an array of type JSONPatchEnchaned[]. These are like a git commit. They contain only what was changed and what was the original value of the thing that changed.

const patches = mutate(state, (currentState) => {...})

console.log(patches) // would be an array [{op: 'add', ...}]

In some situations, like in the case of a history undo or redo operation, we might want to "replay" or "revert" a change.

In order to produce a change based on existing patch objects, not on a callback like in the case of mutate we have the mutateFromPatches method:

const state1 = {}
const state2 = {}
const patches = mutate(state1, (s) => {s.value = 1})

mutateFromPatches(state2, patches)

console.log(state2.value === state1.value) // true

The combination of mutate and mutateFromPatches, with the help of another library function inversePatch can be used to implement history undo and redo, as well as a basic server synchronization and real time collaboration.

proxy-live-document's People

Contributors

dependabot[bot] avatar jayakrishnanamburu avatar vladnicula avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

proxy-live-document's Issues

Add Readme and Mini Docs

We need to add a small readme with the public API of the library and some additional details about the direction this mini library is taking.

Select patches are all patches of the mutation

const state = { a: { }, b: { } }

select(state, ['b/**'], (doc, patches) =>{
    // patches will be an array of 2 with both b.interesting and a.notinteresting
})

mutate(state, (s) => {
    s.b.interesting = true
    s.a.notinteresting = true
})

Consider switching from JSONPatch to JSON0 (or 1)

We are currently producing changes from the proxy in the form of JSON patches.

There seem to be some better alternatives out there:
https://github.com/ottypes/json0
https://github.com/ottypes/json1

I found out about json0 when playing with sharedb recently. The format is more simplified and encodes the same information with less characters.

One thing missing in json0 (and jsonpatch) is the move operation. It seems that JSON0 with a small extension could support move operations as well.

Explore support for getters and setters

Currently there is no support for reacting to changes made on getters and setters. This merits an exploration to what it would take to support this way of defining class instance properties.

https://codesandbox.io/s/proxy-setters-and-getters-86qgg would be a starting point to how the observation of setting data would work.

It's unclear how the getter would be visible in the outside world, and how the computed value would be "observed" even though nobody called it.

[TODO] Add autoRun method

The authoRun method should have a similar behaviour to mobx autoRun or to solidjs createMemo. It would run the function every single time the entities read are inside the function are changed by a mutate, and reevaluated the entities of each function on every run.

It would act as a creator of a selector under the hood and it will recreate the selector on each run.

autoRun(stateTree, (state) => {
   if ( state.ui.isToggled ) {
      setSomeUIFrameworkState(state.ui.foo)
   } else {
      setSomeUIFrameworkState(state.bar)
   }
})

For the example above:

  • Let's say that initially state.ui.isToggled === false
  • The auto-run would end up running setSomeUIFrameworkState(state.bar) and would listen to state.ui.isToggled, state.bar, state.ui, and state. If any of these change, (they are re-assigned or deleted) the function runs again.
  • Let's say we make a change to state.bar. We run the autoRun function again. This recreates the same selector.
  • Let's say we make a change to state.ui.isToggled === true. We run the autoRun function again. This recreates the selector, but now we no longer listen to state.bar as we are on the if branch. The selector now listens to. state.ui.isToggled, state.ui.foo, state.ui, and state.

Array operations must not be merged

If we remove the first item in the array twice, via unshift or splice, we are actually doing two consecutive operations. This is different compared to delete item.key which can be merged if we call delete twice on the same key.

const state = {
      words: ['array0', 'array1', 'array2']
    }

    const stateTarget = JSON.parse(JSON.stringify(state))

    const patchesForReplace = mutate(state, (modifiable) => {
      // remove array[1]
      modifiable.words.splice(1, 1)
      // remove array[1] agian, remaining with one item in the array.
      modifiable.words.splice(1, 1)
    }) ?? []

    mutateFromPatches(stateTarget, patchesForReplace)

    // console.log('state', state)
    // console.log('stateTarget', stateTarget)

    expect(stateTarget).toEqual(state)

A test like this one should remove the same item as position 1 twice, so from 3 items in the array we should end up with one. This operation is not possible now.

[Explore] Matching patches for selectors

There could be a smart way to allow select functions to get only patches of interest in an efficient way.
Selectors that don't request these matching selectors don't allocate CPU work for the matching selectors.

If #30 makes it it the lib, then autorun should also have the same capabilities.

[TODO] Optimise selector runner

Let's say we have a patch that needs to run selectors ['bar', 'something']
Let's say we have 1000 selectors that select for ['foo'] and one selector that selects for ['bar/*']

With the current implementation of the matching algorithm

processPatches(stateTree:T, combinedPatches: JSONPatchEnhanced[]) {

We end up iterating over 1000 selectors and failing early. This is not ideal. We could do even better by adding a hierarchy of selectors of sorts.

[Explore] Async Mutate

Would it be possible to have a async mutation that only publishes patches and triggers selectors at the end of the mutation?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.