All files / src index.js

100% Statements 255/255
100% Branches 70/70
100% Functions 10/10
100% Lines 255/255

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 2561x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 62x 62x 62x 62x 62x 62x 62x 62x 29x 24x 24x 29x 62x 33x 33x 62x 62x 6x 4x 6x 2x 2x 6x 62x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 53x 53x 53x 53x 53x 53x 52x 52x 52x 53x 1x 1x 51x 53x 1x 1x 50x 50x 50x 50x 50x 53x 3x 3x 3x 49x 49x 49x 49x 53x 1x 1x 1x 1x 1x 1x 1x 1x 1x 16x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 12x 12x 13x 13x 13x 23x 10x 10x 10x 3x 3x 10x 7x 7x 10x 13x 13x 13x 13x 13x 13x 16x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 63x 60x 60x 60x 60x 60x 60x 60x 60x 60x 63x 63x 58x 58x 58x 58x 58x 58x 63x 5x 5x 5x 58x 58x 63x 33x 33x 33x 33x 25x 63x 20x 15x 20x 20x 20x 20x 5x 5x 5x 9x 9x 2x 9x 1x 1x 1x 1x 1x 1x 9x 5x 5x 63x 5x 63x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 24x 24x 101x 101x 1x 24x 24x 3x 3x 3x 1x 1x 24x 24x 2x 2x 2x 1x 1x 2x 24x 24x 24x 24x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
// inspired by: https://github.com/pmndrs/valtio
 
/**
 * @typedef {Record<string, { $$count: number; $$props?: Listeners }>} Listeners
 */
 
/**
 * @callback UnsubscribeFunction
 */
 
import { batchHandler } from './batch.js'
import { kStaty, isValidForStaty } from './constants.js'
import { RefStaty } from './types/ref.js'
import { createProxy } from './proxy.js'
 
function _subscribe (state, handler, prop, opts = {}) {
  const { filter = null, before = false } = opts
 
  handler = { run: handler, filter, before }
 
  const subscriptions = state[kStaty].subscriptions
 
  if (prop) {
    if (!subscriptions.props.has(prop)) {
      subscriptions.props.set(prop, new Set())
    }
    subscriptions.props.get(prop).add(handler)
  } else {
    subscriptions.default.add(handler)
  }
 
  return () => {
    if (prop) {
      subscriptions.props.get(prop).delete(handler)
    } else {
      subscriptions.default.delete(handler)
    }
  }
}
 
const defaultOnReadOnly = (target, prop, value) => {
  console.warn('snapshots are readonly', { target, prop, value })
}
 
const CACHE = new WeakMap()
 
/**
 * Creates a new proxy-state
 *
 * @template {object} T
 * @param {T} target
 * @param {object} [opts]
 * @param {(target: T, prop: unknown, value: unknown) => {}} [opts.onReadOnly]
 * @param {(state: T) => {}} [opts.onAction]
 * @returns {T}
 */
export function staty (target, opts = {}) {
  const {
    onReadOnly = defaultOnReadOnly,
    onAction
  } = opts
 
  if (target?.[kStaty]) return target
 
  const targetType = Object.prototype.toString.call(target)
 
  if (!isValidForStaty(targetType)) {
    throw new Error('the `target` is not valid for staty')
  }
 
  if (CACHE.has(/** @type {object} */(target))) {
    return CACHE.get(/** @type {object} */(target))
  }
 
  const proxyOptions = { onReadOnly }
 
  const state = createProxy(proxyOptions, target, undefined, undefined, targetType)
 
  if (onAction) {
    onAction(state)
    state[kStaty].setOnAction(onAction)
  }
 
  CACHE.set(/** @type {object} */(target), state)
 
  return state
}
 
/**
 * Get subscription listeners count
 *
 * @template {object} T
 * @param {T} state
 * @returns {{ $$count: number, $$props: Listeners }}
 */
export function listeners (state) {
  if (!state || !state[kStaty] || state[kStaty].isRef) throw new Error('state is not valid')
 
  const internal = state[kStaty]
 
  const subscriptions = internal.subscriptions
 
  /** @type {Listeners} */
  const props = {}
 
  let count = subscriptions.default.size
 
  subscriptions.props.forEach((listeners, prop) => {
    props[prop] = { $$count: listeners.size }
    count += listeners.size
  })
 
  internal.forEach((val, prop) => {
    if (val?.[kStaty] && !val[kStaty].isRef) {
      const res = listeners(val)
      count += res.$$count
      if (props[prop]) {
        props[prop].$$count += res.$$count
        props[prop].$$props = res.$$props
      } else {
        props[prop] = res
      }
    }
  })
 
  return {
    $$count: count,
    $$props: props
  }
}
 
/**
 * Subscribe for changes in the state
 *
 * @template {object} T
 * @param {T} state
 * @param {() => void} handler
 * @param {Object} [opts]
 * @param {string|string[]} [opts.props] props to subscribe
 * @param {(actionName: string) => boolean} [opts.filter] subscribe only for specific action names
 * @param {boolean} [opts.batch=false] execute in batch turning the subscription into async
 * @param {boolean} [opts.autorun=false] run immediately
 * @param {boolean} [opts.before=false] run before finish the action. A good place to validate changes
 * @returns {UnsubscribeFunction}
 */
export function subscribe (state, handler, opts = {}) {
  if (!state || !state[kStaty] || state[kStaty].isRef) throw new Error('state is not valid')
 
  const {
    props,
    filter,
    batch = false,
    autorun = false,
    before = false
  } = opts
 
  if (batch && before) throw new Error('batch=true with before=true is not possible')
  if (autorun && before) throw new Error('autorun=true with before=true is not possible')
 
  const subscribeProps = {
    filter,
    before
  }
 
  if (batch) {
    const userHandler = handler
    handler = () => batchHandler(userHandler)
  }
 
  let dispose
  if (!props) {
    dispose = _subscribe(state, handler, null, subscribeProps)
    if (autorun) handler()
    return dispose
  }
 
  if (!Array.isArray(props)) {
    dispose = _subscribe(state, () => {
      return handler()
    }, props, subscribeProps)
    if (autorun) handler()
    return dispose
  }
 
  let scheduled = false
  const unsubscribes = props.map(prop => {
    return _subscribe(state, () => {
      if (!batch) return handler()
 
      if (!scheduled) {
        scheduled = true
        queueMicrotask(() => {
          scheduled = false
        })
        return handler()
      }
    }, prop, subscribeProps)
  })
 
  if (autorun) handler()
  return () => unsubscribes.forEach(unsubscribe => unsubscribe())
}
 
/**
 * Add a ref to another object
 *
 * @template {object} T
 * @template {object | T} M
 * @param {T} value
 * @param {(ref: T) => M} [mapSnapshot]
 * @param {boolean} [cache] enable cache
 * @returns {T & RefStaty}
 */
export function ref (value, mapSnapshot, cache) {
  const internal = new RefStaty(value, mapSnapshot, cache)
 
  const obj = new Proxy(internal, {
    get (_, prop) {
      if (prop === kStaty) return internal
      if (typeof internal.value[prop] === 'function') return (...args) => internal.value[prop](...args)
      return internal.value[prop]
    },
    getOwnPropertyDescriptor (_, prop) {
      try {
        return Reflect.getOwnPropertyDescriptor(internal.value, prop)
      } catch (err) {
        return undefined
      }
    },
    ownKeys () {
      try {
        return Reflect.ownKeys(internal.value)
      } catch (err) {
        return []
      }
    }
  })
 
  return /** @type {T & RefStaty} */(obj)
}
 
// /**
//  * @param {Proxy<} target
//  * @returns {Proxy<target> is target}
//  */
// export function release (target) {
//   return new Proxy(target, {
//     get: () => {
//       return null
//     }
//   })
// }
 
export { snapshot } from './snapshot.js'
export { action } from './action.js'