@expressive/react
Version:
Use classes to define state in React!
134 lines (131 loc) • 3.41 kB
JavaScript
// src/model.as.ts
import { Model } from "@expressive/mvc";
import { createProvider } from "./context";
Model.as = function(render) {
if (this === Model)
throw new Error("Cannot create component from base Model.");
const Component = (props) => {
const local = this.use((self) => {
self.set(props);
if (props.is)
return props.is(self);
});
local.set(props);
return createProvider(
local,
render(props, local),
props.fallback || local.fallback,
String(local)
);
};
Component.Model = this;
Component.displayName = this.name;
return Component;
};
// src/model.use.ts
import { Model as Model2, Context, createEffect } from "@expressive/mvc";
import { Pragma } from "./adapter";
Model2.use = function(argument, repeat) {
const context = Context.use(true);
const render = Pragma.useFactory((refresh) => {
let ready;
let local;
const instance = new this(argument);
context.include(instance);
const unwatch = createEffect(instance, (current) => {
local = current;
if (ready)
refresh();
});
function didMount() {
ready = true;
return () => {
unwatch();
context.pop();
instance.set(null);
};
}
return (props) => {
Pragma.useLifecycle(didMount);
if (ready && repeat && props) {
ready = false;
if (typeof props == "function") {
props.call(instance, instance);
props = void 0;
}
const update = instance.set(props);
if (update)
update.then(() => ready = true);
else
ready = true;
}
return local;
};
});
return render(argument);
};
// src/model.get.ts
import { createEffect as createEffect2, Model as Model3 } from "@expressive/mvc";
import { Pragma as Pragma2 } from "./adapter";
Model3.get = function(argument) {
const context = Pragma2.useContext();
const render = Pragma2.useFactory((refresh) => {
const instance = context.get(this);
if (!instance)
if (argument === false)
return () => void 0;
else
throw new Error(`Could not find ${this} in context.`);
let ready;
let value;
const unwatch = createEffect2(instance, (current) => {
if (typeof argument === "function") {
const next = argument.call(current, current, update);
if (next === value)
return;
value = next;
} else
value = current;
if (ready)
refresh();
}, argument === true);
if (value instanceof Promise) {
let error;
unwatch();
value.then((x) => value = x, (e) => error = e).finally(refresh);
value = null;
return () => {
if (error)
throw error;
return value === void 0 ? null : value;
};
}
if (value === null) {
unwatch();
return () => null;
}
;
function update(action) {
if (typeof action == "function")
action = action();
refresh();
if (action)
return action.finally(refresh);
}
function didMount() {
ready = true;
return unwatch;
}
return () => {
Pragma2.useLifecycle(didMount);
return value === void 0 ? null : value;
};
});
return render();
};
// src/adapter.ts
var Pragma3 = {};
export {
Pragma3 as Pragma
};
//# sourceMappingURL=adapter.js.map