UNPKG

vasille-jsx

Version:

The same framework which is designed to build bulletproof frontends (JSX components)

76 lines (75 loc) 2.12 kB
import { IValue, Expression, Reference, SetModel, MapModel, ArrayModel } from "vasille"; export function expr(ctx, func, values) { return new Expression(func, values, ctx); } /** * It transforms a non-reactive value to a reactive one. * 1. `let a = 0` to `const a = ref(0)` */ export function ref(v) { return new Reference(v); } /** * create a `Set` model * 1. translate `new Set(#)` to `set(ctx, #)` */ export function setModel(ctx, data) { return new SetModel(data, ctx); } /** * create a `Map` model * 1. `new Map(#)` to `mapModel(ctx, #)` */ export function mapModel(ctx, data) { return new MapModel(data, ctx); } /** * create an `Array` model * 1. `[...]` to `arrayModel(ctx, [...])` */ export function arrayModel(ctx, data) { return new ArrayModel(data, ctx); } /** * Use when a value must be IValue but can be undefined * 1. `let a = obj.$key` to `const a = ensure(obj.$key)` */ export function ensure(obj, key) { return !obj ? ref(undefined) : key in obj ? obj[key] : (obj[key] = ref(undefined)); } /** * Used for destruction with computed values * 1. `{[a]: a1} = {x: 2}` to `{[a]: a1 = match("a1")} = {x: 2}` * 1. `{[a]: a1 = 3} = {x: 2}` to `{[a]: a1 = match("a1", 3)} = {x: 2}` */ export function match(name, data, createRef = ref) { const iValueRequired = typeof name === "string" && name.startsWith("$"); const isIValue = data instanceof IValue; if (iValueRequired && !isIValue) { return createRef(data); } if (!iValueRequired && isIValue) { return data.V; } return data; } /** * Set a value of a field (alternative to proxies) * 1. `obj.$key = 23` to `set(obj, "$key", 23)` * 2. `arr[0] = 23` to `set(arr, 0, 23)` */ export function set(o, key, value, createRef = ref) { if (o[key] instanceof IValue) { o[key].V = value; } else if (o instanceof ArrayModel && typeof key === "number") { o.replace(key, value); } else if (typeof key === "string" && key.charAt(0) === "$") { o[key] = createRef(value); } else { o[key] = value; } return value; }