diff options
author | ab <abdullah_ahmed@brown.edu> | 2019-07-23 11:38:10 -0400 |
---|---|---|
committer | ab <abdullah_ahmed@brown.edu> | 2019-07-23 11:38:10 -0400 |
commit | 13c016d7f7765acda7f6ce2d69c14597469f55d7 (patch) | |
tree | 6fcf409ee4f0035443aa4fb67a05d24aae09689d /src/new_fields/ScriptField.ts | |
parent | bd841fe56540e1a9177d2872310b10fefcb4acd1 (diff) | |
parent | d880e4b2fcb4e7bab3ee25d63209b173efcf37c0 (diff) |
merged
Diffstat (limited to 'src/new_fields/ScriptField.ts')
-rw-r--r-- | src/new_fields/ScriptField.ts | 32 |
1 files changed, 31 insertions, 1 deletions
diff --git a/src/new_fields/ScriptField.ts b/src/new_fields/ScriptField.ts index e2994ed70..e5ec34f57 100644 --- a/src/new_fields/ScriptField.ts +++ b/src/new_fields/ScriptField.ts @@ -4,6 +4,8 @@ import { Copy, ToScriptString, Parent, SelfProxy } from "./FieldSymbols"; import { serializable, createSimpleSchema, map, primitive, object, deserialize, PropSchema, custom, SKIP } from "serializr"; import { Deserializable } from "../client/util/SerializationHelper"; import { Doc } from "../new_fields/Doc"; +import { Plugins } from "./util"; +import { computedFn } from "mobx-utils"; function optional(propSchema: PropSchema) { return custom(value => { @@ -86,11 +88,39 @@ export class ScriptField extends ObjectField { @Deserializable("computed", deserializeScript) export class ComputedField extends ScriptField { //TODO maybe add an observable cache based on what is passed in for doc, considering there shouldn't really be that many possible values for doc - value(doc: Doc) { + value = computedFn((doc: Doc) => { const val = this.script.run({ this: doc }); if (val.success) { return val.result; } return undefined; + }); +} + +export namespace ComputedField { + let useComputed = true; + export function DisableComputedFields() { + useComputed = false; + } + + export function EnableComputedFields() { + useComputed = true; + } + + export const undefined = "__undefined"; + + export function WithoutComputed<T>(fn: () => T) { + DisableComputedFields(); + try { + return fn(); + } finally { + EnableComputedFields(); + } } + + Plugins.addGetterPlugin((doc, _, value) => { + if (useComputed && value instanceof ComputedField) { + return { value: value.value(doc), shouldReturn: true }; + } + }); }
\ No newline at end of file |