aboutsummaryrefslogtreecommitdiff
path: root/src/new_fields
diff options
context:
space:
mode:
Diffstat (limited to 'src/new_fields')
-rw-r--r--src/new_fields/CursorField.ts5
-rw-r--r--src/new_fields/DateField.ts5
-rw-r--r--src/new_fields/Doc.ts362
-rw-r--r--src/new_fields/FieldSymbols.ts3
-rw-r--r--src/new_fields/HtmlField.ts5
-rw-r--r--src/new_fields/IconField.ts5
-rw-r--r--src/new_fields/InkField.ts8
-rw-r--r--src/new_fields/List.ts5
-rw-r--r--src/new_fields/ObjectField.ts5
-rw-r--r--src/new_fields/Proxy.ts5
-rw-r--r--src/new_fields/RefField.ts3
-rw-r--r--src/new_fields/RichTextField.ts5
-rw-r--r--src/new_fields/RichTextUtils.ts6
-rw-r--r--src/new_fields/SchemaHeaderField.ts5
-rw-r--r--src/new_fields/ScriptField.ts22
-rw-r--r--src/new_fields/URLField.ts5
-rw-r--r--src/new_fields/documentSchemas.ts33
-rw-r--r--src/new_fields/util.ts38
18 files changed, 321 insertions, 204 deletions
diff --git a/src/new_fields/CursorField.ts b/src/new_fields/CursorField.ts
index fd86031a8..28467377b 100644
--- a/src/new_fields/CursorField.ts
+++ b/src/new_fields/CursorField.ts
@@ -2,7 +2,7 @@ import { ObjectField } from "./ObjectField";
import { observable } from "mobx";
import { Deserializable } from "../client/util/SerializationHelper";
import { serializable, createSimpleSchema, object, date } from "serializr";
-import { OnUpdate, ToScriptString, Copy } from "./FieldSymbols";
+import { OnUpdate, ToScriptString, ToString, Copy } from "./FieldSymbols";
export type CursorPosition = {
x: number,
@@ -60,4 +60,7 @@ export default class CursorField extends ObjectField {
[ToScriptString]() {
return "invalid";
}
+ [ToString]() {
+ return "invalid";
+ }
} \ No newline at end of file
diff --git a/src/new_fields/DateField.ts b/src/new_fields/DateField.ts
index 4f999e5e8..a925148c2 100644
--- a/src/new_fields/DateField.ts
+++ b/src/new_fields/DateField.ts
@@ -1,7 +1,7 @@
import { Deserializable } from "../client/util/SerializationHelper";
import { serializable, date } from "serializr";
import { ObjectField } from "./ObjectField";
-import { Copy, ToScriptString } from "./FieldSymbols";
+import { Copy, ToScriptString, ToString } from "./FieldSymbols";
import { scriptingGlobal, Scripting } from "../client/util/Scripting";
@scriptingGlobal
@@ -26,6 +26,9 @@ export class DateField extends ObjectField {
[ToScriptString]() {
return `new DateField(new Date(${this.date.toISOString()}))`;
}
+ [ToString]() {
+ return this.date.toISOString();
+ }
}
Scripting.addGlobal(function d(...dateArgs: any[]) {
diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts
index e0ab5d97c..b1c1fda05 100644
--- a/src/new_fields/Doc.ts
+++ b/src/new_fields/Doc.ts
@@ -1,21 +1,23 @@
-import { observable, ObservableMap, runInAction, action, untracked } from "mobx";
+import { observable, ObservableMap, runInAction, action, computed } from "mobx";
import { alias, map, serializable } from "serializr";
import { DocServer } from "../client/DocServer";
import { DocumentType } from "../client/documents/DocumentTypes";
import { Scripting, scriptingGlobal } from "../client/util/Scripting";
import { afterDocDeserialize, autoObject, Deserializable, SerializationHelper } from "../client/util/SerializationHelper";
-import { Copy, HandleUpdate, Id, OnUpdate, Parent, Self, SelfProxy, ToScriptString, Update } from "./FieldSymbols";
+import { Copy, HandleUpdate, Id, OnUpdate, Parent, Self, SelfProxy, ToScriptString, ToString, Update } from "./FieldSymbols";
import { List } from "./List";
import { ObjectField } from "./ObjectField";
import { PrefetchProxy, ProxyField } from "./Proxy";
import { FieldId, RefField } from "./RefField";
import { listSpec } from "./Schema";
import { ComputedField, ScriptField } from "./ScriptField";
-import { BoolCast, Cast, FieldValue, NumCast, PromiseValue, StrCast, ToConstructor } from "./Types";
+import { BoolCast, Cast, FieldValue, NumCast, StrCast, ToConstructor } from "./Types";
import { deleteProperty, getField, getter, makeEditable, makeReadOnly, setter, updateFunction } from "./util";
import { intersectRect } from "../Utils";
import { UndoManager } from "../client/util/UndoManager";
import { computedFn } from "mobx-utils";
+import { RichTextField } from "./RichTextField";
+import { Script } from "vm";
export namespace Field {
export function toKeyValueString(doc: Doc, key: string): string {
@@ -36,6 +38,18 @@ export namespace Field {
return field[ToScriptString]();
}
}
+ export function toString(field: Field): string {
+ if (typeof field === "string") {
+ return field;
+ } else if (typeof field === "number" || typeof field === "boolean") {
+ return String(field);
+ } else if (field instanceof ObjectField) {
+ return field[ToString]();
+ } else if (field instanceof RefField) {
+ return field[ToString]();
+ }
+ return "(null)";
+ }
export function IsField(field: any): field is Field;
export function IsField(field: any, includeUndefined: true): field is Field | undefined;
export function IsField(field: any, includeUndefined: boolean = false): field is Field | undefined {
@@ -75,6 +89,8 @@ export function DocListCast(field: FieldResult): Doc[] {
export const WidthSym = Symbol("Width");
export const HeightSym = Symbol("Height");
+export const DataSym = Symbol("Data");
+export const LayoutSym = Symbol("Layout");
export const UpdatingFromServer = Symbol("UpdatingFromServer");
const CachedUpdates = Symbol("Cached updates");
@@ -96,8 +112,11 @@ export class Doc extends RefField {
get: getter,
// getPrototypeOf: (target) => Cast(target[SelfProxy].proto, Doc) || null, // TODO this might be able to replace the proto logic in getter
has: (target, key) => key in target.__fields,
- ownKeys: target => Object.keys(target.__fields),
+ ownKeys: target => Object.keys(target.__allfields),
getOwnPropertyDescriptor: (target, prop) => {
+ if (prop.toString() === "__LAYOUT__") {
+ return Reflect.getOwnPropertyDescriptor(target, prop);
+ }
if (prop in target.__fields) {
return {
configurable: true,//TODO Should configurable be true?
@@ -124,6 +143,13 @@ export class Doc extends RefField {
private get __fields() {
return this.___fields;
}
+ private get __allfields() {
+ let obj = {} as any;
+ Object.assign(obj, this.___fields);
+ runInAction(() => obj.__LAYOUT__ = this.__LAYOUT__);
+ return obj;
+ }
+
private set __fields(value) {
this.___fields = value;
@@ -150,12 +176,25 @@ export class Doc extends RefField {
private [Self] = this;
private [SelfProxy]: any;
- public [WidthSym] = () => NumCast(this[SelfProxy].width);
- public [HeightSym] = () => NumCast(this[SelfProxy].height);
+ public [WidthSym] = () => NumCast(this[SelfProxy]._width);
+ public [HeightSym] = () => NumCast(this[SelfProxy]._height);
+ public get [DataSym]() { return Cast(this[SelfProxy].resolvedDataDoc, Doc, null) || this[SelfProxy]; }
+ public get [LayoutSym]() { return this[SelfProxy].__LAYOUT__; }
+ @computed get __LAYOUT__() {
+ const templateLayoutDoc = Cast(Doc.LayoutField(this[SelfProxy]), Doc, null);
+ if (templateLayoutDoc) {
+ const renderFieldKey = (templateLayoutDoc[StrCast(templateLayoutDoc.layoutKey, "layout")] as string).split("'")[1];
+ return Cast(this[SelfProxy][renderFieldKey + "-layout[" + templateLayoutDoc[Id] + "]"], Doc, null) || templateLayoutDoc;
+ }
+ return undefined;
+ }
[ToScriptString]() {
return "invalid";
}
+ [ToString]() {
+ return "Doc";
+ }
private [CachedUpdates]: { [key: string]: () => void | Promise<any> } = {};
public static CurrentUserEmail: string = "";
@@ -403,92 +442,85 @@ export namespace Doc {
doc.title = title;
return doc;
}
- export function MakeAlias(doc: Doc) {
- const alias = !GetT(doc, "isPrototype", "boolean", true) ? Doc.MakeCopy(doc) : Doc.MakeDelegate(doc);
- const layout = Doc.Layout(alias);
- if (layout instanceof Doc && layout !== alias) {
+ export function MakeAlias(doc: Doc, id?: string) {
+ const alias = !GetT(doc, "isPrototype", "boolean", true) ? Doc.MakeCopy(doc, undefined, id) : Doc.MakeDelegate(doc, id);
+ const layout = Doc.LayoutField(alias);
+ if (layout instanceof Doc && layout !== alias && layout === Doc.Layout(alias)) {
Doc.SetLayout(alias, Doc.MakeAlias(layout));
}
- const aliasNumber = Doc.GetProto(doc).aliasNumber = NumCast(Doc.GetProto(doc).aliasNumber) + 1;
- alias.title = ComputedField.MakeFunction(`renameAlias(this, ${aliasNumber})`);
+ alias.aliasOf = doc;
+ alias.title = ComputedField.MakeFunction(`renameAlias(this, ${Doc.GetProto(doc).aliasNumber = NumCast(Doc.GetProto(doc).aliasNumber) + 1})`);
return alias;
}
//
// Determines whether the combination of the layoutDoc and dataDoc represents
- // a template relationship. If so, the layoutDoc will be expanded into a new
- // document that inherits the properties of the original layout while allowing
- // for individual layout properties to be overridden in the expanded layout.
+ // a template relationship : there is a dataDoc and it doesn't match the layoutDoc an
+ // the lyouatDoc's layout is layout string (not a document)
//
export function WillExpandTemplateLayout(layoutDoc: Doc, dataDoc?: Doc) {
- return BoolCast(layoutDoc.isTemplateField) && dataDoc && layoutDoc !== dataDoc && !(layoutDoc[StrCast(layoutDoc.layoutKey, "layout")] instanceof Doc);
+ return (layoutDoc.isTemplateForField || layoutDoc.isTemplateDoc) && dataDoc && layoutDoc !== dataDoc && !(Doc.LayoutField(layoutDoc) instanceof Doc);
}
//
- // Returns an expanded template layout for a target data document.
- // First it checks if an expanded layout already exists -- if so it will be stored on the dataDoc
- // using the template layout doc's id as the field key.
- // If it doesn't find the expanded layout, then it makes a delegate of the template layout and
- // saves it on the data doc indexed by the template layout's id
+ // Returns an expanded template layout for a target data document if there is a template relationship
+ // between the two. If so, the layoutDoc is expanded into a new document that inherits the properties
+ // of the original layout while allowing for individual layout properties to be overridden in the expanded layout.
//
- export function expandTemplateLayout(templateLayoutDoc: Doc, dataDoc?: Doc) {
- if (!WillExpandTemplateLayout(templateLayoutDoc, dataDoc) || !dataDoc) return templateLayoutDoc;
- // if we have a data doc that doesn't match the layout, then we're rendering a template.
- // ... which means we change the layout to be an expanded view of the template layout.
- // This allows the view override the template's properties and be referenceable as its own document.
-
- const expandedLayoutFieldKey = "Layout[" + templateLayoutDoc[Id] + "]";
- const expandedTemplateLayout = dataDoc[expandedLayoutFieldKey];
- if (expandedTemplateLayout instanceof Doc) {
- return expandedTemplateLayout;
- }
- if (expandedTemplateLayout === undefined) {
- setTimeout(() => dataDoc[expandedLayoutFieldKey] === undefined &&
- (dataDoc[expandedLayoutFieldKey] = Doc.MakeDelegate(templateLayoutDoc, undefined, "[" + templateLayoutDoc.title + "]")), 0);
+ export function expandTemplateLayout(templateLayoutDoc: Doc, targetDoc?: Doc) {
+ if (!WillExpandTemplateLayout(templateLayoutDoc, targetDoc) || !targetDoc) return templateLayoutDoc;
+
+ const templateField = StrCast(templateLayoutDoc.isTemplateForField); // the field that the template renders
+ // First it checks if an expanded layout already exists -- if so it will be stored on the dataDoc
+ // using the template layout doc's id as the field key.
+ // If it doesn't find the expanded layout, then it makes a delegate of the template layout and
+ // saves it on the data doc indexed by the template layout's id.
+ //
+ const layoutFielddKey = Doc.LayoutFieldKey(templateLayoutDoc);
+ const expandedLayoutFieldKey = (templateField || layoutFielddKey) + "-layout[" + templateLayoutDoc[Id] + "]";
+ let expandedTemplateLayout = targetDoc?.[expandedLayoutFieldKey];
+ if (templateLayoutDoc.resolvedDataDoc instanceof Promise) {
+
+ expandedTemplateLayout = undefined;
+ } else if (templateLayoutDoc.resolvedDataDoc === Doc.GetDataDoc(targetDoc)) {
+ expandedTemplateLayout = templateLayoutDoc;
+ } else if (expandedTemplateLayout === undefined) {
+ setTimeout(action(() => {
+ if (!targetDoc[expandedLayoutFieldKey]) {
+ const newLayoutDoc = Doc.MakeDelegate(templateLayoutDoc, undefined, "[" + templateLayoutDoc.title + "]");
+ newLayoutDoc.expandedTemplate = targetDoc;
+ targetDoc[expandedLayoutFieldKey] = newLayoutDoc;
+ const dataDoc = Doc.GetDataDoc(targetDoc);
+ newLayoutDoc.resolvedDataDoc = dataDoc;
+ if (dataDoc[templateField] === undefined && templateLayoutDoc[templateField] instanceof List && Cast(templateLayoutDoc[templateField], listSpec(Doc), []).length) {
+ dataDoc[templateField] = ComputedField.MakeFunction(`ObjectField.MakeCopy(templateLayoutDoc["${templateField}"] as List)`, { templateLayoutDoc: Doc.name }, { templateLayoutDoc: templateLayoutDoc });
+ }
+ }
+ }), 0);
}
- return undefined; // use the templateLayout when it's not a template or the expandedTemplate is pending.
+ return expandedTemplateLayout instanceof Doc ? expandedTemplateLayout : undefined; // layout is undefined if the expandedTemplate is pending.
}
- export function GetLayoutDataDocPair(doc: Doc, dataDoc: Doc | undefined, fieldKey: string, childDocLayout: Doc) {
- let layoutDoc: Doc | undefined = childDocLayout;
- const resolvedDataDoc = !doc.isTemplateField && dataDoc !== doc && dataDoc ? Doc.GetDataDoc(dataDoc) : undefined;
- if (resolvedDataDoc && Doc.WillExpandTemplateLayout(childDocLayout, resolvedDataDoc)) {
- const extensionDoc = fieldExtensionDoc(resolvedDataDoc, StrCast(childDocLayout.templateField, StrCast(childDocLayout.title)));
- layoutDoc = Doc.expandTemplateLayout(childDocLayout, extensionDoc !== resolvedDataDoc ? extensionDoc : undefined);
- setTimeout(() => layoutDoc && (layoutDoc.resolvedDataDoc = resolvedDataDoc), 0);
- } else layoutDoc = childDocLayout;
- return { layout: layoutDoc, data: resolvedDataDoc };
- }
-
- //
- // Resolves a reference to a field by returning 'doc' if no field extension is specified,
- // otherwise, it returns the extension document stored in doc.<fieldKey>_ext.
- // This mechanism allows any fields to be extended with an extension document that can
- // be used to capture field-specific metadata. For example, an image field can be extended
- // to store annotations, ink, and other data.
- //
- export function fieldExtensionDoc(doc: Doc, fieldKey: string) {
- const extension = doc[fieldKey + "_ext"];
- if (doc instanceof Doc && extension === undefined) {
- setTimeout(() => CreateDocumentExtensionForField(doc, fieldKey), 0);
- }
- return extension ? extension as Doc : undefined;
- }
- export function fieldExtensionDocSync(doc: Doc, fieldKey: string) {
- return (doc[fieldKey + "_ext"] as Doc) || CreateDocumentExtensionForField(doc, fieldKey);
+ // if the childDoc is a template for a field, then this will return the expanded layout with its data doc.
+ // otherwise, it just returns the childDoc
+ export function GetLayoutDataDocPair(containerDoc: Doc, containerDataDoc: Opt<Doc>, childDoc: Doc) {
+ const resolvedDataDoc = containerDataDoc === containerDoc || !containerDataDoc || (!childDoc.isTemplateDoc && !childDoc.isTemplateForField) ? undefined : containerDataDoc;
+ return { layout: Doc.expandTemplateLayout(childDoc, resolvedDataDoc), data: resolvedDataDoc };
}
-
export function CreateDocumentExtensionForField(doc: Doc, fieldKey: string) {
- const docExtensionForField = new Doc(doc[Id] + fieldKey, true);
- docExtensionForField.title = fieldKey + ".ext"; // courtesy field--- shouldn't be needed except maybe for debugging
- docExtensionForField.extendsDoc = doc; // this is used by search to map field matches on the extension doc back to the document it extends.
- docExtensionForField.extendsField = fieldKey; // this can be used by search to map matches on the extension doc back to the field that was extended.
- docExtensionForField.type = DocumentType.EXTENSION;
let proto: Doc | undefined = doc;
while (proto && !Doc.IsPrototype(proto) && proto.proto) {
proto = proto.proto;
}
- (proto ? proto : doc)[fieldKey + "_ext"] = new PrefetchProxy(docExtensionForField);
+ let docExtensionForField = ((proto || doc)[fieldKey + "_ext"] as Doc);
+ if (!docExtensionForField) {
+ docExtensionForField = new Doc(doc[Id] + fieldKey, true);
+ docExtensionForField.title = fieldKey + ".ext"; // courtesy field--- shouldn't be needed except maybe for debugging
+ docExtensionForField.extendsDoc = doc; // this is used by search to map field matches on the extension doc back to the document it extends.
+ docExtensionForField.extendsField = fieldKey; // this can be used by search to map matches on the extension doc back to the field that was extended.
+ docExtensionForField.type = DocumentType.EXTENSION;
+ (proto || doc)[fieldKey + "_ext"] = new PrefetchProxy(docExtensionForField);
+ }
return docExtensionForField;
}
@@ -517,7 +549,9 @@ export namespace Doc {
export function MakeCopy(doc: Doc, copyProto: boolean = false, copyProtoId?: string): Doc {
const copy = new Doc(copyProtoId, true);
+ const exclude = Cast(doc.excludeFields, listSpec("string"), []);
Object.keys(doc).forEach(key => {
+ if (exclude.includes(key)) return;
const cfield = ComputedField.WithoutComputed(() => FieldValue(doc[key]));
const field = ProxyField.WithoutProxy(() => doc[key]);
if (key === "proto" && copyProto) {
@@ -530,7 +564,7 @@ export namespace Doc {
} else if (cfield instanceof ComputedField) {
copy[key] = ComputedField.MakeFunction(cfield.script.originalScript);
} else if (field instanceof ObjectField) {
- copy[key] = ObjectField.MakeCopy(field);
+ copy[key] = key.includes("layout[") && doc[key] instanceof Doc ? Doc.MakeCopy(doc[key] as Doc, false) : ObjectField.MakeCopy(field);
} else if (field instanceof Promise) {
debugger; //This shouldn't happend...
} else {
@@ -557,68 +591,68 @@ export namespace Doc {
let _applyCount: number = 0;
export function ApplyTemplate(templateDoc: Doc) {
if (templateDoc) {
- const applied = ApplyTemplateTo(templateDoc, Doc.MakeDelegate(new Doc()), "layoutCustom", templateDoc.title + "(..." + _applyCount++ + ")");
+ const applied = ApplyTemplateTo(templateDoc, Doc.MakeDelegate(new Doc()), "layout", templateDoc.title + "(..." + _applyCount++ + ")");
applied && (Doc.GetProto(applied).layout = applied.layout);
return applied;
}
return undefined;
}
- export function ApplyTemplateTo(templateDoc: Doc, target: Doc, targetKey: string, titleTarget: string | undefined = undefined) {
+ export function ApplyTemplateTo(templateDoc: Doc, target: Doc, targetKey: string, titleTarget: string | undefined) {
if (!templateDoc) {
target.layout = undefined;
- target.nativeWidth = undefined;
- target.nativeHeight = undefined;
+ target._nativeWidth = undefined;
+ target._nativeHeight = undefined;
target.onClick = undefined;
target.type = undefined;
return;
}
- if ((target[targetKey] as Doc)?.proto !== templateDoc) {
- const layoutCustomLayout = Doc.MakeDelegate(templateDoc);
-
+ if (!Doc.AreProtosEqual(target[targetKey] as Doc, templateDoc)) {
titleTarget && (Doc.GetProto(target).title = titleTarget);
- Doc.GetProto(target).type = DocumentType.TEMPLATE;
- target.onClick = templateDoc.onClick instanceof ObjectField && templateDoc.onClick[Copy]();
-
- Doc.GetProto(target)[targetKey] = layoutCustomLayout;
+ Doc.GetProto(target)[targetKey] = new PrefetchProxy(templateDoc);
}
target.layoutKey = targetKey;
return target;
}
- export function MakeMetadataFieldTemplate(fieldTemplate: Doc, templateDataDoc: Doc, suppressTitle: boolean = false): boolean {
- // move data doc fields to layout doc as needed (nativeWidth/nativeHeight, data, ??)
- const metadataFieldName = StrCast(fieldTemplate.title).replace(/^-/, "");
- let fieldLayoutDoc = fieldTemplate;
- if (fieldTemplate.layout instanceof Doc) {
- fieldLayoutDoc = Doc.MakeDelegate(fieldTemplate.layout);
- }
-
- fieldTemplate.templateField = metadataFieldName;
- fieldTemplate.title = metadataFieldName;
- fieldTemplate.isTemplateField = true;
- /* move certain layout properties from the original data doc to the template layout to avoid
- inheriting them from the template's data doc which may also define these fields for its own use.
- */
- fieldTemplate.ignoreAspect = fieldTemplate.ignoreAspect === undefined ? undefined : BoolCast(fieldTemplate.ignoreAspect);
- fieldTemplate.singleColumn = BoolCast(fieldTemplate.singleColumn);
- fieldTemplate.nativeWidth = Cast(fieldTemplate.nativeWidth, "number");
- fieldTemplate.nativeHeight = Cast(fieldTemplate.nativeHeight, "number");
- fieldTemplate.type = fieldTemplate.type;
- fieldTemplate.panX = 0;
- fieldTemplate.panY = 0;
- fieldTemplate.scale = 1;
- fieldTemplate.showTitle = suppressTitle ? undefined : "title";
- const data = fieldTemplate.data;
- // setTimeout(action(() => {
- !templateDataDoc[metadataFieldName] && data instanceof ObjectField && (Doc.GetProto(templateDataDoc)[metadataFieldName] = ObjectField.MakeCopy(data));
- const layout = StrCast(fieldLayoutDoc.layout).replace(/fieldKey={'[^']*'}/, `fieldKey={'${metadataFieldName}'}`);
- const layoutDelegate = Doc.Layout(fieldTemplate);
- layoutDelegate.layout = layout;
- fieldTemplate.layout = layoutDelegate !== fieldTemplate ? layoutDelegate : layout;
- if (fieldTemplate.backgroundColor !== templateDataDoc.defaultBackgroundColor) fieldTemplate.defaultBackgroundColor = fieldTemplate.backgroundColor;
- fieldTemplate.proto = templateDataDoc;
- // }), 0);
+ //
+ // This function converts a generic field layout display into a field layout that displays a specific
+ // metadata field indicated by the title of the template field (not the default field that it was rendering)
+ //
+ export function MakeMetadataFieldTemplate(templateField: Doc, templateDoc: Opt<Doc>): boolean {
+
+ // find the metadata field key that this template field doc will display (indicated by its title)
+ const metadataFieldKey = StrCast(templateField.title).replace(/^-/, "");
+
+ // update the original template to mark it as a template
+ templateField.isTemplateForField = metadataFieldKey;
+ templateField.title = metadataFieldKey;
+
+ // move any data that the template field had been rendering over to the template doc so that things will still be rendered
+ // when the template field is adjusted to point to the new metadatafield key.
+ // note 1: if the template field contained a list of documents, each of those documents will be converted to templates as well.
+ // note 2: this will not overwrite any field that already exists on the template doc at the field key
+ if (!templateDoc?.[metadataFieldKey] && templateField.data instanceof ObjectField) {
+ Cast(templateField.data, listSpec(Doc), [])?.map(d => d instanceof Doc && MakeMetadataFieldTemplate(d, templateDoc));
+ (Doc.GetProto(templateField)[metadataFieldKey] = ObjectField.MakeCopy(templateField.data));
+ }
+ if (templateField.data instanceof RichTextField && (templateField.data.Text || templateField.data.Data.toString().includes("dashField"))) {
+ templateField._textTemplate = ComputedField.MakeFunction(`copyField(this.${metadataFieldKey})`, { this: Doc.name });
+ }
+
+ // get the layout string that the template uses to specify its layout
+ const templateFieldLayoutString = StrCast(Doc.LayoutField(Doc.Layout(templateField)));
+
+ // change itto render the target metadata field instead of what it was rendering before and assign it to the template field layout document.
+ Doc.Layout(templateField).layout = templateFieldLayoutString.replace(/fieldKey={'[^']*'}/, `fieldKey={'${metadataFieldKey}'}`);
+
+ // assign the template field doc a delegate of any extension document that was previously used to render the template field (since extension doc's carry rendering informatino)
+ Doc.Layout(templateField)[metadataFieldKey + "_ext"] = Doc.MakeDelegate(templateField[templateFieldLayoutString?.split("'")[1] + "_ext"] as Doc);
+
+ if (templateField.backgroundColor !== templateDoc?.defaultBackgroundColor) {
+ templateField.defaultBackgroundColor = templateField.backgroundColor;
+ }
+
return true;
}
@@ -627,12 +661,12 @@ export namespace Doc {
const doc1Layout = Doc.Layout(doc1);
const x2 = NumCast(doc2.x) - clusterDistance;
const y2 = NumCast(doc2.y) - clusterDistance;
- const w2 = NumCast(doc2Layout.width) + clusterDistance;
- const h2 = NumCast(doc2Layout.height) + clusterDistance;
+ const w2 = NumCast(doc2Layout._width) + clusterDistance;
+ const h2 = NumCast(doc2Layout._height) + clusterDistance;
const x = NumCast(doc1.x) - clusterDistance;
const y = NumCast(doc1.y) - clusterDistance;
- const w = NumCast(doc1Layout.width) + clusterDistance;
- const h = NumCast(doc1Layout.height) + clusterDistance;
+ const w = NumCast(doc1Layout._width) + clusterDistance;
+ const h = NumCast(doc1Layout._height) + clusterDistance;
return doc1.z === doc2.z && intersectRect({ left: x, top: y, width: w, height: h }, { left: x2, top: y2, width: w2, height: h2 });
}
@@ -657,9 +691,10 @@ export namespace Doc {
// the document containing the view layout information - will be the Document itself unless the Document has
// a layout field. In that case, all layout information comes from there unless overriden by Document
- export function Layout(doc: Doc) { return Doc.LayoutField(doc) instanceof Doc ? doc[StrCast(doc.layoutKey, "layout")] as Doc : doc; }
+ export function Layout(doc: Doc): Doc { return doc[LayoutSym] || doc; }
export function SetLayout(doc: Doc, layout: Doc | string) { doc[StrCast(doc.layoutKey, "layout")] = layout; }
export function LayoutField(doc: Doc) { return doc[StrCast(doc.layoutKey, "layout")]; }
+ export function LayoutFieldKey(doc: Doc): string { return StrCast(Doc.Layout(doc).layout).split("'")[1]; }
const manager = new DocData();
export function SearchQuery(): string { return manager._searchQuery; }
export function SetSearchQuery(query: string) { runInAction(() => manager._searchQuery = query); }
@@ -692,7 +727,7 @@ export namespace Doc {
export function LinkOtherAnchor(linkDoc: Doc, anchorDoc: Doc) { return Doc.AreProtosEqual(anchorDoc, Cast(linkDoc.anchor1, Doc) as Doc) ? Cast(linkDoc.anchor2, Doc) as Doc : Cast(linkDoc.anchor1, Doc) as Doc; }
- export function LinkEndpoint(linkDoc: Doc, anchorDoc: Doc) { return Doc.AreProtosEqual(anchorDoc, Cast(linkDoc.anchor1, Doc) as Doc) ? "layoutKey1" : "layoutKey2"; }
+ export function LinkEndpoint(linkDoc: Doc, anchorDoc: Doc) { return Doc.AreProtosEqual(anchorDoc, Cast(linkDoc.anchor1, Doc) as Doc) ? "layout_key1" : "layout_key2"; }
export function linkFollowUnhighlight() {
Doc.UnhighlightAll();
@@ -700,9 +735,9 @@ export namespace Doc {
}
let dt = 0;
- export function linkFollowHighlight(destDoc: Doc) {
+ export function linkFollowHighlight(destDoc: Doc, dataAndDisplayDocs = true) {
linkFollowUnhighlight();
- Doc.HighlightDoc(destDoc);
+ Doc.HighlightDoc(destDoc, dataAndDisplayDocs);
document.removeEventListener("pointerdown", linkFollowUnhighlight);
document.addEventListener("pointerdown", linkFollowUnhighlight);
const x = dt = Date.now();
@@ -716,10 +751,10 @@ export namespace Doc {
export function IsHighlighted(doc: Doc) {
return highlightManager.HighlightedDoc.get(doc) || highlightManager.HighlightedDoc.get(Doc.GetDataDoc(doc));
}
- export function HighlightDoc(doc: Doc) {
+ export function HighlightDoc(doc: Doc, dataAndDisplayDocs = true) {
runInAction(() => {
highlightManager.HighlightedDoc.set(doc, true);
- highlightManager.HighlightedDoc.set(Doc.GetDataDoc(doc), true);
+ dataAndDisplayDocs && highlightManager.HighlightedDoc.set(Doc.GetDataDoc(doc), true);
});
}
export function UnHighlightDoc(doc: Doc) {
@@ -746,61 +781,66 @@ export namespace Doc {
source.dragFactory instanceof Doc && source.dragFactory.isTemplateDoc ? source.dragFactory :
source && source.layout instanceof Doc && source.layout.isTemplateDoc ? source.layout : undefined;
}
+ export function setChildDetailedLayout(target: Doc, source?: Doc) {
+ target.childDetailed = source && source.isTemplateDoc ? source : source &&
+ source.dragFactory instanceof Doc && source.dragFactory.isTemplateDoc ? source.dragFactory :
+ source && source.layout instanceof Doc && source.layout.isTemplateDoc ? source.layout : undefined;
+ }
+
+ export function matchFieldValue(doc: Doc, key: string, value: any): boolean {
+ const fieldVal = doc[key];
+ if (Cast(fieldVal, listSpec("string"), []).length) {
+ const vals = Cast(fieldVal, listSpec("string"), []);
+ return vals.some(v => v === value);
+ }
+ const fieldStr = Field.toString(fieldVal as Field);
+ return fieldStr === value;
+ }
- export function MakeDocFilter(docFilters: string[]) {
- let docFilterText = "";
+ export function setNativeView(doc: any) {
+ const prevLayout = StrCast(doc.layoutKey).split("_")[1];
+ const deiconify = prevLayout === "icon" && StrCast(doc.deiconifyLayout) ? "layout_" + StrCast(doc.deiconifyLayout) : "";
+ doc.deiconifyLayout = undefined;
+ if (StrCast(doc.title).endsWith("_" + prevLayout)) doc.title = StrCast(doc.title).replace("_" + prevLayout, "");
+ doc.layoutKey = deiconify || "layout";
+ }
+ export function setDocFilter(container: Doc, key: string, value: any, modifiers?: string) {
+ const docFilters = Cast(container._docFilter, listSpec("string"), []);
for (let i = 0; i < docFilters.length; i += 3) {
- const key = docFilters[i];
- const value = docFilters[i + 1];
- const modifiers = docFilters[i + 2];
- const scriptText = `${modifiers === "x" ? "!" : ""}matchFieldValue(doc, "${key}", "${value}")`;
- docFilterText = docFilterText ? docFilterText + " || " + scriptText : scriptText;
+ if (docFilters[i] === key && docFilters[i + 1] === value) {
+ docFilters.splice(i, 3);
+ break;
+ }
+ }
+ if (modifiers !== undefined) {
+ docFilters.push(key);
+ docFilters.push(value);
+ docFilters.push(modifiers);
+ container._docFilter = new List<string>(docFilters);
}
- return docFilterText ? "(" + docFilterText + ")" : "";
}
}
Scripting.addGlobal(function renameAlias(doc: any, n: any) { return StrCast(Doc.GetProto(doc).title).replace(/\([0-9]*\)/, "") + `(${n})`; });
Scripting.addGlobal(function getProto(doc: any) { return Doc.GetProto(doc); });
Scripting.addGlobal(function setChildLayout(target: any, source: any) { Doc.setChildLayout(target, source); });
+Scripting.addGlobal(function setChildDetailedLayout(target: any, source: any) { Doc.setChildDetailedLayout(target, source); });
Scripting.addGlobal(function getAlias(doc: any) { return Doc.MakeAlias(doc); });
Scripting.addGlobal(function getCopy(doc: any, copyProto: any) { return doc.isTemplateDoc ? Doc.ApplyTemplate(doc) : Doc.MakeCopy(doc, copyProto); });
Scripting.addGlobal(function copyField(field: any) { return ObjectField.MakeCopy(field); });
Scripting.addGlobal(function aliasDocs(field: any) { return new List<Doc>(field.map((d: any) => Doc.MakeAlias(d))); });
Scripting.addGlobal(function docList(field: any) { return DocListCast(field); });
Scripting.addGlobal(function sameDocs(doc1: any, doc2: any) { return Doc.AreProtosEqual(doc1, doc2); });
+Scripting.addGlobal(function setNativeView(doc: any) { Doc.setNativeView(doc); });
Scripting.addGlobal(function undo() { return UndoManager.Undo(); });
Scripting.addGlobal(function redo() { return UndoManager.Redo(); });
+Scripting.addGlobal(function curPresentationItem() {
+ const curPres = Doc.UserDoc().curPresentation as Doc;
+ return curPres && DocListCast(curPres[Doc.LayoutFieldKey(curPres)])[NumCast(curPres._itemIndex)];
+})
Scripting.addGlobal(function selectDoc(doc: any) { Doc.UserDoc().SelectedDocs = new List([doc]); });
Scripting.addGlobal(function selectedDocs(container: Doc, excludeCollections: boolean, prevValue: any) {
const docs = DocListCast(Doc.UserDoc().SelectedDocs).filter(d => !Doc.AreProtosEqual(d, container) && !d.annotationOn && d.type !== DocumentType.DOCUMENT && d.type !== DocumentType.KVP && (!excludeCollections || !Cast(d.data, listSpec(Doc), null)));
return docs.length ? new List(docs) : prevValue;
});
-Scripting.addGlobal(function matchFieldValue(doc: Doc, key: string, value: any) {
- const fieldVal = doc[key] ? doc[key] : doc[key + "_ext"];
- if (StrCast(fieldVal, null) !== undefined) return StrCast(fieldVal) === value;
- if (NumCast(fieldVal, null) !== undefined) return NumCast(fieldVal) === value;
- if (Cast(fieldVal, listSpec("string"), []).length) {
- const vals = Cast(fieldVal, listSpec("string"), []);
- return vals.some(v => v === value);
- }
- return false;
-});
-Scripting.addGlobal(function setDocFilter(container: Doc, key: string, value: any, modifiers: string) {
- const docFilters = Cast(container.docFilter, listSpec("string"), []);
- let found = false;
- for (let i = 0; i < docFilters.length && !found; i += 3) {
- if (docFilters[i] === key && docFilters[i + 1] === value) {
- found = true;
- docFilters.splice(i, 3);
- }
- }
- if (!found || modifiers !== "none") {
- docFilters.push(key);
- docFilters.push(value);
- docFilters.push(modifiers);
- container.docFilter = new List<string>(docFilters);
- }
- const docFilterText = Doc.MakeDocFilter(docFilters);
- container.viewSpecScript = docFilterText ? ScriptField.MakeFunction(docFilterText, { doc: Doc.name }) : undefined;
-}); \ No newline at end of file
+Scripting.addGlobal(function setDocFilter(container: Doc, key: string, value: any, modifiers?: string) { Doc.setDocFilter(container, key, value, modifiers); }); \ No newline at end of file
diff --git a/src/new_fields/FieldSymbols.ts b/src/new_fields/FieldSymbols.ts
index b5b3aa588..4aadb81a2 100644
--- a/src/new_fields/FieldSymbols.ts
+++ b/src/new_fields/FieldSymbols.ts
@@ -7,4 +7,5 @@ export const Id = Symbol("Id");
export const OnUpdate = Symbol("OnUpdate");
export const Parent = Symbol("Parent");
export const Copy = Symbol("Copy");
-export const ToScriptString = Symbol("ToScriptString"); \ No newline at end of file
+export const ToScriptString = Symbol("ToScriptString");
+export const ToString = Symbol("ToString"); \ No newline at end of file
diff --git a/src/new_fields/HtmlField.ts b/src/new_fields/HtmlField.ts
index f952acff9..6e8bba977 100644
--- a/src/new_fields/HtmlField.ts
+++ b/src/new_fields/HtmlField.ts
@@ -1,7 +1,7 @@
import { Deserializable } from "../client/util/SerializationHelper";
import { serializable, primitive } from "serializr";
import { ObjectField } from "./ObjectField";
-import { Copy, ToScriptString } from "./FieldSymbols";
+import { Copy, ToScriptString, ToString} from "./FieldSymbols";
@Deserializable("html")
export class HtmlField extends ObjectField {
@@ -20,4 +20,7 @@ export class HtmlField extends ObjectField {
[ToScriptString]() {
return "invalid";
}
+ [ToString]() {
+ return this.html;
+ }
}
diff --git a/src/new_fields/IconField.ts b/src/new_fields/IconField.ts
index 62b2cd254..76c4ddf1b 100644
--- a/src/new_fields/IconField.ts
+++ b/src/new_fields/IconField.ts
@@ -1,7 +1,7 @@
import { Deserializable } from "../client/util/SerializationHelper";
import { serializable, primitive } from "serializr";
import { ObjectField } from "./ObjectField";
-import { Copy, ToScriptString } from "./FieldSymbols";
+import { Copy, ToScriptString, ToString } from "./FieldSymbols";
@Deserializable("icon")
export class IconField extends ObjectField {
@@ -20,4 +20,7 @@ export class IconField extends ObjectField {
[ToScriptString]() {
return "invalid";
}
+ [ToString]() {
+ return "ICONfield";
+ }
}
diff --git a/src/new_fields/InkField.ts b/src/new_fields/InkField.ts
index e2aa7ee16..4a44b4f55 100644
--- a/src/new_fields/InkField.ts
+++ b/src/new_fields/InkField.ts
@@ -1,14 +1,15 @@
import { Deserializable } from "../client/util/SerializationHelper";
import { serializable, custom, createSimpleSchema, list, object, map } from "serializr";
import { ObjectField } from "./ObjectField";
-import { Copy, ToScriptString } from "./FieldSymbols";
+import { Copy, ToScriptString, ToString } from "./FieldSymbols";
export enum InkTool {
None,
Pen,
Highlighter,
Eraser,
- Scrubber
+ Scrubber,
+ Stamp
}
export interface PointData {
@@ -44,4 +45,7 @@ export class InkField extends ObjectField {
[ToScriptString]() {
return "invalid";
}
+ [ToString]() {
+ return "InkField";
+ }
}
diff --git a/src/new_fields/List.ts b/src/new_fields/List.ts
index bb48b1bb3..a43f11e82 100644
--- a/src/new_fields/List.ts
+++ b/src/new_fields/List.ts
@@ -6,7 +6,7 @@ import { observable, action } from "mobx";
import { ObjectField } from "./ObjectField";
import { RefField } from "./RefField";
import { ProxyField } from "./Proxy";
-import { Self, Update, Parent, OnUpdate, SelfProxy, ToScriptString, Copy } from "./FieldSymbols";
+import { Self, Update, Parent, OnUpdate, SelfProxy, ToScriptString, ToString, Copy } from "./FieldSymbols";
import { Scripting } from "../client/util/Scripting";
const listHandlers: any = {
@@ -292,6 +292,9 @@ class ListImpl<T extends Field> extends ObjectField {
[ToScriptString]() {
return `new List([${(this as any).map((field: any) => Field.toScriptString(field))}])`;
}
+ [ToString]() {
+ return "List";
+ }
}
export type List<T extends Field> = ListImpl<T> & (T | (T extends RefField ? Promise<T> : never))[];
export const List: { new <T extends Field>(fields?: T[]): List<T> } = ListImpl as any;
diff --git a/src/new_fields/ObjectField.ts b/src/new_fields/ObjectField.ts
index 65ada91c0..566104b40 100644
--- a/src/new_fields/ObjectField.ts
+++ b/src/new_fields/ObjectField.ts
@@ -1,6 +1,6 @@
import { Doc } from "./Doc";
import { RefField } from "./RefField";
-import { OnUpdate, Parent, Copy, ToScriptString } from "./FieldSymbols";
+import { OnUpdate, Parent, Copy, ToScriptString, ToString } from "./FieldSymbols";
import { Scripting } from "../client/util/Scripting";
export abstract class ObjectField {
@@ -9,11 +9,12 @@ export abstract class ObjectField {
abstract [Copy](): ObjectField;
abstract [ToScriptString](): string;
+ abstract [ToString](): string;
}
export namespace ObjectField {
export function MakeCopy<T extends ObjectField>(field: T) {
- return field[Copy]();
+ return field?.[Copy]();
}
}
diff --git a/src/new_fields/Proxy.ts b/src/new_fields/Proxy.ts
index c6292e37c..d50c0f14e 100644
--- a/src/new_fields/Proxy.ts
+++ b/src/new_fields/Proxy.ts
@@ -5,7 +5,7 @@ import { observable, action } from "mobx";
import { DocServer } from "../client/DocServer";
import { RefField } from "./RefField";
import { ObjectField } from "./ObjectField";
-import { Id, Copy, ToScriptString } from "./FieldSymbols";
+import { Id, Copy, ToScriptString, ToString } from "./FieldSymbols";
import { scriptingGlobal } from "../client/util/Scripting";
import { Plugins } from "./util";
@@ -32,6 +32,9 @@ export class ProxyField<T extends RefField> extends ObjectField {
[ToScriptString]() {
return "invalid";
}
+ [ToString]() {
+ return "ProxyField";
+ }
@serializable(primitive())
readonly fieldId: string = "";
diff --git a/src/new_fields/RefField.ts b/src/new_fields/RefField.ts
index f7bea8c94..b6ef69750 100644
--- a/src/new_fields/RefField.ts
+++ b/src/new_fields/RefField.ts
@@ -1,6 +1,6 @@
import { serializable, primitive, alias } from "serializr";
import { Utils } from "../Utils";
-import { Id, HandleUpdate, ToScriptString } from "./FieldSymbols";
+import { Id, HandleUpdate, ToScriptString, ToString } from "./FieldSymbols";
import { afterDocDeserialize } from "../client/util/SerializationHelper";
export type FieldId = string;
@@ -17,4 +17,5 @@ export abstract class RefField {
protected [HandleUpdate]?(diff: any): void | Promise<void>;
abstract [ToScriptString](): string;
+ abstract [ToString](): string;
}
diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts
index fd5459876..a0f21f45e 100644
--- a/src/new_fields/RichTextField.ts
+++ b/src/new_fields/RichTextField.ts
@@ -1,7 +1,7 @@
import { ObjectField } from "./ObjectField";
import { serializable } from "serializr";
import { Deserializable } from "../client/util/SerializationHelper";
-import { Copy, ToScriptString } from "./FieldSymbols";
+import { Copy, ToScriptString, ToString } from "./FieldSymbols";
import { scriptingGlobal } from "../client/util/Scripting";
@scriptingGlobal
@@ -26,5 +26,8 @@ export class RichTextField extends ObjectField {
[ToScriptString]() {
return `new RichTextField("${this.Data}", "${this.Text}")`;
}
+ [ToString]() {
+ return this.Text;
+ }
} \ No newline at end of file
diff --git a/src/new_fields/RichTextUtils.ts b/src/new_fields/RichTextUtils.ts
index 682206aa2..c50f8cc48 100644
--- a/src/new_fields/RichTextUtils.ts
+++ b/src/new_fields/RichTextUtils.ts
@@ -273,8 +273,8 @@ export namespace RichTextUtils {
const guid = Utils.GenerateDeterministicGuid(src);
const backingDocId = StrCast(textNote[guid]);
if (!backingDocId) {
- const backingDoc = Docs.Create.ImageDocument(src, { width: 300, height: 300 });
- DocumentView.makeCustomViewClicked(backingDoc, undefined);
+ const backingDoc = Docs.Create.ImageDocument(src, { _width: 300, _height: 300 });
+ DocumentView.makeCustomViewClicked(backingDoc, undefined, Docs.Create.FreeformDocument);
docid = backingDoc[Id];
textNote[guid] = docid;
} else {
@@ -403,7 +403,7 @@ export namespace RichTextUtils {
let exported = (await Cast(linkDoc.anchor2, Doc))!;
if (!exported.customLayout) {
exported = Doc.MakeAlias(exported);
- DocumentView.makeCustomViewClicked(exported, undefined);
+ DocumentView.makeCustomViewClicked(exported, undefined, Docs.Create.FreeformDocument);
linkDoc.anchor2 = exported;
}
url = Utils.shareUrl(exported[Id]);
diff --git a/src/new_fields/SchemaHeaderField.ts b/src/new_fields/SchemaHeaderField.ts
index 42a8485ac..07c90f5a2 100644
--- a/src/new_fields/SchemaHeaderField.ts
+++ b/src/new_fields/SchemaHeaderField.ts
@@ -1,7 +1,7 @@
import { Deserializable } from "../client/util/SerializationHelper";
import { serializable, primitive } from "serializr";
import { ObjectField } from "./ObjectField";
-import { Copy, ToScriptString, OnUpdate } from "./FieldSymbols";
+import { Copy, ToScriptString, ToString, OnUpdate } from "./FieldSymbols";
import { scriptingGlobal } from "../client/util/Scripting";
import { ColumnType } from "../client/views/collections/CollectionSchemaView";
@@ -116,4 +116,7 @@ export class SchemaHeaderField extends ObjectField {
[ToScriptString]() {
return `invalid`;
}
+ [ToString]() {
+ return `SchemaHeaderField`;
+ }
} \ No newline at end of file
diff --git a/src/new_fields/ScriptField.ts b/src/new_fields/ScriptField.ts
index b5ad4a7f6..4c78ea3aa 100644
--- a/src/new_fields/ScriptField.ts
+++ b/src/new_fields/ScriptField.ts
@@ -1,9 +1,9 @@
import { ObjectField } from "./ObjectField";
import { CompiledScript, CompileScript, scriptingGlobal, ScriptOptions } from "../client/util/Scripting";
-import { Copy, ToScriptString, Parent, SelfProxy } from "./FieldSymbols";
+import { Copy, ToScriptString, ToString, Parent, SelfProxy } from "./FieldSymbols";
import { serializable, createSimpleSchema, map, primitive, object, deserialize, PropSchema, custom, SKIP } from "serializr";
import { Deserializable, autoObject } from "../client/util/SerializationHelper";
-import { Doc } from "../new_fields/Doc";
+import { Doc, Field } from "../new_fields/Doc";
import { Plugins } from "./util";
import { computedFn } from "mobx-utils";
import { ProxyField } from "./Proxy";
@@ -101,17 +101,21 @@ export class ScriptField extends ObjectField {
[ToScriptString]() {
return "script field";
}
- public static CompileScript(script: string, params: object = {}, addReturn = false) {
+ [ToString]() {
+ return "script field";
+ }
+ public static CompileScript(script: string, params: object = {}, addReturn = false, capturedVariables?: { [name: string]: Field }) {
const compiled = CompileScript(script, {
params: { this: Doc.name, _last_: "any", ...params },
typecheck: false,
editable: true,
- addReturn: addReturn
+ addReturn: addReturn,
+ capturedVariables
});
return compiled;
}
- public static MakeFunction(script: string, params: object = {}) {
- const compiled = ScriptField.CompileScript(script, params, true);
+ public static MakeFunction(script: string, params: object = {}, capturedVariables?: { [name: string]: Field }) {
+ const compiled = ScriptField.CompileScript(script, params, true, capturedVariables);
return compiled.compiled ? new ScriptField(compiled) : undefined;
}
@@ -127,12 +131,12 @@ export class ComputedField extends ScriptField {
_lastComputedResult: any;
//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 = computedFn((doc: Doc) => this._lastComputedResult = this.script.run({ this: doc, _last_: this._lastComputedResult }, console.log).result);
- public static MakeScript(script: string, params: object = {}, ) {
+ public static MakeScript(script: string, params: object = {}) {
const compiled = ScriptField.CompileScript(script, params, false);
return compiled.compiled ? new ComputedField(compiled) : undefined;
}
- public static MakeFunction(script: string, params: object = {}) {
- const compiled = ScriptField.CompileScript(script, params, true);
+ public static MakeFunction(script: string, params: object = {}, capturedVariables?: { [name: string]: Field }) {
+ const compiled = ScriptField.CompileScript(script, params, true, capturedVariables);
return compiled.compiled ? new ComputedField(compiled) : undefined;
}
}
diff --git a/src/new_fields/URLField.ts b/src/new_fields/URLField.ts
index eabd04e0f..fb71160ca 100644
--- a/src/new_fields/URLField.ts
+++ b/src/new_fields/URLField.ts
@@ -1,7 +1,7 @@
import { Deserializable } from "../client/util/SerializationHelper";
import { serializable, custom } from "serializr";
import { ObjectField } from "./ObjectField";
-import { ToScriptString, Copy } from "./FieldSymbols";
+import { ToScriptString, ToString, Copy } from "./FieldSymbols";
import { Scripting, scriptingGlobal } from "../client/util/Scripting";
function url() {
@@ -32,6 +32,9 @@ export abstract class URLField extends ObjectField {
[ToScriptString]() {
return `new ${this.constructor.name}("${this.url.href}")`;
}
+ [ToString]() {
+ return this.url.href;
+ }
[Copy](): this {
return new (this.constructor as any)(this.url);
diff --git a/src/new_fields/documentSchemas.ts b/src/new_fields/documentSchemas.ts
index 909fdc6c3..cb35c0681 100644
--- a/src/new_fields/documentSchemas.ts
+++ b/src/new_fields/documentSchemas.ts
@@ -4,27 +4,33 @@ import { Doc } from "./Doc";
import { DateField } from "./DateField";
export const documentSchema = createSchema({
- layout: "string", // this is the native layout string for the document. templates can be added using other fields and setting layoutKey below (see layoutCustom as an example)
+ layout: "string", // this is the native layout string for the document. templates can be added using other fields and setting layoutKey below (see layout_custom as an example)
layoutKey: "string", // holds the field key for the field that actually holds the current lyoat
- layoutCustom: Doc, // used to hold a custom layout (there's nothing special about this field .. any field could hold a custom layout that can be selected by setting 'layoutKey')
+ layout_custom: Doc, // used to hold a custom layout (there's nothing special about this field .. any field could hold a custom layout that can be selected by setting 'layoutKey')
title: "string", // document title (can be on either data document or layout)
- nativeWidth: "number", // native width of document which determines how much document contents are scaled when the document's width is set
- nativeHeight: "number", // "
- width: "number", // width of document in its container's coordinate system
- height: "number", // "
+ dropAction: "string", // override specifying what should happen when this document is dropped (can be "alias" or "copy")
+ childDropAction: "string", // specify the override for what should happen when the child of a collection is dragged from it and dropped (can be "alias" or "copy")
+ _nativeWidth: "number", // native width of document which determines how much document contents are scaled when the document's width is set
+ _nativeHeight: "number", // "
+ _width: "number", // width of document in its container's coordinate system
+ _height: "number", // "
+ _freeformLayoutEngine: "string",// the string ID for the layout engine to use to layout freeform view documents
+ _LODdisable: "boolean", // whether to disbale LOD switching for CollectionFreeFormViews
+ _pivotField: "string", // specifies which field should be used as the timeline/pivot axis
color: "string", // foreground color of document
backgroundColor: "string", // background color of document
opacity: "number", // opacity of document
creationDate: DateField, // when the document was created
links: listSpec(Doc), // computed (readonly) list of links associated with this document
- dropAction: "string", // override specifying what should happen when this document is dropped (can be "alias" or "copy")
removeDropProperties: listSpec("string"), // properties that should be removed from the alias/copy/etc of this document when it is dropped
onClick: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop)
+ onPointerDown: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop)
+ onPointerUp: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop)
onDragStart: ScriptField, // script to run when document is dragged (without being selected). the script should return the Doc to be dropped.
dragFactory: Doc, // the document that serves as the "template" for the onDragStart script. ie, to drag out copies of the dragFactory document.
ignoreAspect: "boolean", // whether aspect ratio should be ignored when laying out or manipulating the document
autoHeight: "boolean", // whether the height of the document should be computed automatically based on its contents
- isTemplateField: "boolean", // whether this document acts as a template layout for describing how other documents should be displayed
+ isTemplateForField: "string",// when specifies a field key, then the containing document is a template that renders the specified field
isBackground: "boolean", // whether document is a background element and ignores input events (can only selet with marquee)
type: "string", // enumerated type of document
treeViewOpen: "boolean", // flag denoting whether the documents sub-tree (contents) is visible or hidden
@@ -46,7 +52,6 @@ export const documentSchema = createSchema({
isButton: "boolean", // whether document functions as a button (overiding native interactions of its content)
ignoreClick: "boolean", // whether documents ignores input clicks (but does not ignore manipulation and other events)
isAnimating: "string", // whether the document is in the midst of animating between two layouts (used by icons to de/iconify documents). value is undefined|"min"|"max"
- animateToDimensions: listSpec("number"), // layout information about the target rectangle a document is animating towards
scrollToLinkID: "string", // id of link being traversed. allows this doc to scroll/highlight/etc its link anchor. scrollToLinkID should be set to undefined by this doc after it sets up its scroll,etc.
strokeWidth: "number",
fontSize: "string",
@@ -54,7 +59,8 @@ export const documentSchema = createSchema({
xPadding: "number", // pixels of padding on left/right of collectionfreeformview contents when fitToBox is set
yPadding: "number", // pixels of padding on left/right of collectionfreeformview contents when fitToBox is set
LODarea: "number", // area (width*height) where CollectionFreeFormViews switch from a label to rendering contents
- LODdisable: "boolean", // whether to disbale LOD switching for CollectionFreeFormViews
+ letterSpacing: "string",
+ textTransform: "string"
});
export const positionSchema = createSchema({
@@ -64,6 +70,13 @@ export const positionSchema = createSchema({
z: "number",
});
+export const collectionSchema = createSchema({
+ childLayout: Doc, // layout template for children of a collecion
+ childDetailed: Doc, // layout template to apply to a child when its clicked on in a collection and opened (requires onChildClick or other script to use this field)
+ onChildClick: ScriptField, // script to run for each child when its clicked
+ onCheckedClick: ScriptField, // script to run when a checkbox is clicked next to a child in a tree view
+});
+
export type Document = makeInterface<[typeof documentSchema]>;
export const Document = makeInterface(documentSchema);
diff --git a/src/new_fields/util.ts b/src/new_fields/util.ts
index 4147be278..ebc0a1272 100644
--- a/src/new_fields/util.ts
+++ b/src/new_fields/util.ts
@@ -1,19 +1,20 @@
import { UndoManager } from "../client/util/UndoManager";
-import { Doc, Field, FieldResult, UpdatingFromServer } from "./Doc";
+import { Doc, Field, FieldResult, UpdatingFromServer, LayoutSym } from "./Doc";
import { SerializationHelper } from "../client/util/SerializationHelper";
-import { ProxyField } from "./Proxy";
+import { ProxyField, PrefetchProxy } from "./Proxy";
import { RefField } from "./RefField";
import { ObjectField } from "./ObjectField";
import { action, trace } from "mobx";
import { Parent, OnUpdate, Update, Id, SelfProxy, Self } from "./FieldSymbols";
import { DocServer } from "../client/DocServer";
+import { props } from "bluebird";
function _readOnlySetter(): never {
throw new Error("Documents can't be modified in read-only mode");
}
export function TraceMobx() {
- //trace();
+ // trace();
}
export interface GetterResult {
@@ -35,6 +36,7 @@ const _setterImpl = action(function (target: any, prop: string | symbol | number
target[prop] = value;
return true;
}
+
if (typeof prop === "symbol") {
target[prop] = value;
return true;
@@ -52,7 +54,7 @@ const _setterImpl = action(function (target: any, prop: string | symbol | number
value = new ProxyField(value);
}
if (value instanceof ObjectField) {
- if (value[Parent] && value[Parent] !== receiver) {
+ if (value[Parent] && value[Parent] !== receiver && !(value instanceof PrefetchProxy)) {
throw new Error("Can't put the same object in multiple documents at the same time");
}
value[Parent] = receiver;
@@ -98,11 +100,35 @@ export function makeEditable() {
_setter = _setterImpl;
}
-export function setter(target: any, prop: string | symbol | number, value: any, receiver: any): boolean {
+let layoutProps = ["panX", "panY", "width", "height", "nativeWidth", "nativeHeight", "fitWidth", "fitToBox",
+ "LODdisable", "chromeStatus", "viewType", "gridGap", "xMargin", "yMargin", "autoHeight"];
+export function setter(target: any, in_prop: string | symbol | number, value: any, receiver: any): boolean {
+ let prop = in_prop;
+ if (typeof prop === "string" && prop !== "__id" && prop !== "__fields" && (prop.startsWith("_") || layoutProps.includes(prop))) {
+ if (!prop.startsWith("_")) {
+ console.log(prop + " is deprecated - switch to _" + prop);
+ prop = "_" + prop;
+ }
+ if (target.__LAYOUT__) {
+ target.__LAYOUT__[prop] = value;
+ return true;
+ }
+ }
return _setter(target, prop, value, receiver);
}
-export function getter(target: any, prop: string | symbol | number, receiver: any): any {
+export function getter(target: any, in_prop: string | symbol | number, receiver: any): any {
+ let prop = in_prop;
+ if (prop === LayoutSym) {
+ return target.__LAYOUT__;
+ }
+ if (typeof prop === "string" && prop !== "__id" && prop !== "__fields" && (prop.startsWith("_") || layoutProps.includes(prop))) {
+ if (!prop.startsWith("_")) {
+ console.log(prop + " is deprecated - switch to _" + prop);
+ prop = "_" + prop;
+ }
+ if (target.__LAYOUT__) return target.__LAYOUT__[prop];
+ }
if (prop === "then") {//If we're being awaited
return undefined;
}