UNPKG

alinea

Version:

[![npm](https://img.shields.io/npm/v/alinea.svg)](https://npmjs.org/package/alinea) [![install size](https://packagephobia.com/badge?p=alinea)](https://packagephobia.com/result?p=alinea)

96 lines (94 loc) 2.46 kB
import { YMap } from "../../chunks/chunk-OYP4EJOA.js"; import "../../chunks/chunk-O6EXLFU2.js"; import "../../chunks/chunk-U5RRZUYZ.js"; // src/core/shape/RecordShape.ts import { entries, keys } from "../util/Objects.js"; var RecordShape = class _RecordShape { constructor(label, properties, initialValue) { this.label = label; this.properties = properties; this.initialValue = initialValue; } innerTypes(parents) { return entries(this.properties).flatMap(([name, shape]) => { return shape.innerTypes(parents.concat(name)); }); } concat(that) { if (!that) return this; return new _RecordShape(that.label, { ...this.properties, ...that.properties }); } create() { return this.initialValue ?? Object.fromEntries( Object.entries(this.properties).map(([key, field]) => { return [key, field.create()]; }) ); } typeOfChild(yValue, child) { return this.properties[child]; } toY(value) { const self = value || {}; const map = new YMap(); for (const key of keys(this.properties)) { map.set(key, this.properties[key].toY(self[key])); } return map; } fromY(map) { const res = {}; for (const key of keys(this.properties)) { res[key] = this.properties[key].fromY(map?.get(key)); } return res; } applyY(value, map, key) { const current = "getMap" in map ? map.getMap(key) : map.get(key); if (!current) return void map.set(key, this.toY(value)); const self = value ?? {}; for (const key2 of keys(this.properties)) { this.properties[key2].applyY(self[key2], current, key2); } } init(parent, key) { if (!parent.has(key)) parent.set(key, this.toY(this.create())); } watch(parent, key) { return (fun) => { const record = !key ? parent : parent.get(key); record.observe(fun); return () => record.unobserve(fun); }; } mutator(parent, key, readOnly) { return { set: (k, v) => { if (readOnly) return; const record = parent.get(key); const field = this.properties[k]; record.set(k, field.toY(v)); } }; } async applyLinks(value, loader) { const obj = value || {}; const tasks = []; for (const [key, shape] of entries(this.properties)) { tasks.push(shape.applyLinks(obj[key], loader)); } await Promise.all(tasks); } }; export { RecordShape };