alinea
Version:
Headless git-based CMS
103 lines (101 loc) • 2.75 kB
JavaScript
import {
YMap
} from "../../chunks/chunk-QUIANN6B.js";
import "../../chunks/chunk-AJJSW27C.js";
import "../../chunks/chunk-NZLE2WMY.js";
// src/core/shape/RecordShape.ts
import { entries, keys } from "../util/Objects.js";
var RecordShape = class _RecordShape {
constructor(label, shapes, initialValue) {
this.label = label;
this.shapes = shapes;
this.initialValue = initialValue;
}
concat(that) {
if (!that) return this;
return new _RecordShape(that.label, {
...this.shapes,
...that.shapes
});
}
create() {
return this.initialValue ?? Object.fromEntries(
Object.entries(this.shapes).map(([key, field]) => {
return [key, field.create()];
})
);
}
toY(value) {
const self = value || {};
const map = new YMap();
for (const key of keys(this.shapes)) {
map.set(key, this.shapes[key].toY(self[key]));
}
return map;
}
fromY(map) {
const res = {};
for (const key of keys(this.shapes)) {
res[key] = this.shapes[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.shapes)) {
this.shapes[key2].init(current, key2);
if (key2 in self) this.shapes[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) {
return {
set: (k, v) => {
const record = parent.get(key);
const field = this.shapes[k];
record.set(k, field.toY(v));
}
};
}
async applyLinks(value, loader) {
const obj = value || {};
const tasks = [];
for (const [key, shape] of entries(this.shapes)) {
tasks.push(shape.applyLinks(obj[key], loader));
}
await Promise.all(tasks);
}
toV1(value) {
const self = value || {};
const res = {};
for (const key of keys(this.shapes)) {
const isUnderscored = key.startsWith("_");
const oldValue = isUnderscored ? self[key.slice(1)] : self[key];
const value2 = self[key] ?? oldValue;
if (value2 !== void 0) res[key] = this.shapes[key].toV1(value2);
}
return res;
}
searchableText(value) {
let res = "";
const self = value || {};
for (const key of keys(this.shapes)) {
res += this.shapes[key].searchableText(self[key]);
}
return res;
}
};
export {
RecordShape
};