aboutsummaryrefslogtreecommitdiff
path: root/src/new_fields
diff options
context:
space:
mode:
Diffstat (limited to 'src/new_fields')
-rw-r--r--src/new_fields/DateField.ts4
-rw-r--r--src/new_fields/Doc.ts220
-rw-r--r--src/new_fields/InkField.ts23
-rw-r--r--src/new_fields/List.ts7
-rw-r--r--src/new_fields/RichTextField.ts10
-rw-r--r--src/new_fields/RichTextUtils.ts83
-rw-r--r--src/new_fields/Schema.ts2
-rw-r--r--src/new_fields/SchemaHeaderField.ts11
-rw-r--r--src/new_fields/ScriptField.ts15
-rw-r--r--src/new_fields/documentSchemas.ts18
-rw-r--r--src/new_fields/util.ts6
11 files changed, 247 insertions, 152 deletions
diff --git a/src/new_fields/DateField.ts b/src/new_fields/DateField.ts
index abec91e06..4f999e5e8 100644
--- a/src/new_fields/DateField.ts
+++ b/src/new_fields/DateField.ts
@@ -19,6 +19,10 @@ export class DateField extends ObjectField {
return new DateField(this.date);
}
+ toString() {
+ return `${this.date.toISOString()}`;
+ }
+
[ToScriptString]() {
return `new DateField(new Date(${this.date.toISOString()}))`;
}
diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts
index 6aad4a6be..e0ab5d97c 100644
--- a/src/new_fields/Doc.ts
+++ b/src/new_fields/Doc.ts
@@ -1,4 +1,4 @@
-import { observable, ObservableMap, runInAction, action } from "mobx";
+import { observable, ObservableMap, runInAction, action, untracked } from "mobx";
import { alias, map, serializable } from "serializr";
import { DocServer } from "../client/DocServer";
import { DocumentType } from "../client/documents/DocumentTypes";
@@ -10,17 +10,18 @@ import { ObjectField } from "./ObjectField";
import { PrefetchProxy, ProxyField } from "./Proxy";
import { FieldId, RefField } from "./RefField";
import { listSpec } from "./Schema";
-import { ComputedField } from "./ScriptField";
+import { ComputedField, ScriptField } from "./ScriptField";
import { BoolCast, Cast, FieldValue, NumCast, PromiseValue, 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";
export namespace Field {
export function toKeyValueString(doc: Doc, key: string): string {
const onDelegate = Object.keys(doc).includes(key);
- let field = ComputedField.WithoutComputed(() => FieldValue(doc[key]));
+ const field = ComputedField.WithoutComputed(() => FieldValue(doc[key]));
if (Field.IsField(field)) {
return (onDelegate ? "=" : "") + (field instanceof ComputedField ? `:=${field.script.originalScript}` : Field.toScriptString(field));
}
@@ -254,9 +255,9 @@ export namespace Doc {
return GetT(doc, "isPrototype", "boolean", true);
}
export async function SetInPlace(doc: Doc, key: string, value: Field | undefined, defaultProto: boolean) {
- let hasProto = doc.proto instanceof Doc;
- let onDeleg = Object.getOwnPropertyNames(doc).indexOf(key) !== -1;
- let onProto = hasProto && Object.getOwnPropertyNames(doc.proto).indexOf(key) !== -1;
+ const hasProto = doc.proto instanceof Doc;
+ const onDeleg = Object.getOwnPropertyNames(doc).indexOf(key) !== -1;
+ const onProto = hasProto && Object.getOwnPropertyNames(doc.proto).indexOf(key) !== -1;
if (onDeleg || !hasProto || (!onProto && !defaultProto)) {
doc[key] = value;
} else doc.proto![key] = value;
@@ -289,14 +290,13 @@ export namespace Doc {
* @param fields the fields to project onto the target. Its type signature defines a mapping from some string key
* to a potentially undefined field, where each entry in this mapping is optional.
*/
- export function assign<K extends string>(doc: Doc, fields: Partial<Record<K, Opt<Field>>>) {
+ export function assign<K extends string>(doc: Doc, fields: Partial<Record<K, Opt<Field>>>, skipUndefineds: boolean = false) {
for (const key in fields) {
if (fields.hasOwnProperty(key)) {
const value = fields[key];
- // Do we want to filter out undefineds?
- // if (value !== undefined) {
- doc[key] = value;
- // }
+ if (!skipUndefineds || value !== undefined) { // Do we want to filter out undefineds?
+ doc[key] = value;
+ }
}
}
return doc;
@@ -305,10 +305,10 @@ export namespace Doc {
// compare whether documents or their protos match
export function AreProtosEqual(doc?: Doc, other?: Doc) {
if (!doc || !other) return false;
- let r = (doc === other);
- let r2 = (Doc.GetProto(doc) === other);
- let r3 = (Doc.GetProto(other) === doc);
- let r4 = (Doc.GetProto(doc) === Doc.GetProto(other) && Doc.GetProto(other) !== undefined);
+ const r = (doc === other);
+ const r2 = (Doc.GetProto(doc) === other);
+ const r3 = (Doc.GetProto(other) === doc);
+ const r4 = (Doc.GetProto(doc) === Doc.GetProto(other) && Doc.GetProto(other) !== undefined);
return r || r2 || r3 || r4;
}
@@ -317,7 +317,7 @@ export namespace Doc {
return doc && (Doc.GetT(doc, "isPrototype", "boolean", true) ? doc : (doc.proto || doc));
}
export function GetDataDoc(doc: Doc): Doc {
- let proto = Doc.GetProto(doc);
+ const proto = Doc.GetProto(doc);
return proto === doc ? proto : Doc.GetDataDoc(proto);
}
@@ -342,9 +342,9 @@ export namespace Doc {
if (listDoc[key] === undefined) {
Doc.GetProto(listDoc)[key] = new List<Doc>();
}
- let list = Cast(listDoc[key], listSpec(Doc));
+ const list = Cast(listDoc[key], listSpec(Doc));
if (list) {
- let ind = list.indexOf(doc);
+ const ind = list.indexOf(doc);
if (ind !== -1) {
list.splice(ind, 1);
return true;
@@ -356,10 +356,10 @@ export namespace Doc {
if (listDoc[key] === undefined) {
Doc.GetProto(listDoc)[key] = new List<Doc>();
}
- let list = Cast(listDoc[key], listSpec(Doc));
+ const list = Cast(listDoc[key], listSpec(Doc));
if (list) {
if (allowDuplicates !== true) {
- let pind = list.reduce((l, d, i) => d instanceof Doc && d[Id] === doc[Id] ? i : l, -1);
+ const pind = list.reduce((l, d, i) => d instanceof Doc && d[Id] === doc[Id] ? i : l, -1);
if (pind !== -1) {
list.splice(pind, 1);
}
@@ -368,7 +368,7 @@ export namespace Doc {
list.splice(0, 0, doc);
}
else {
- let ind = relativeTo ? list.indexOf(relativeTo) : -1;
+ const ind = relativeTo ? list.indexOf(relativeTo) : -1;
if (ind === -1) {
if (reversed) list.splice(0, 0, doc);
else list.push(doc);
@@ -387,9 +387,9 @@ export namespace Doc {
// Computes the bounds of the contents of a set of documents.
//
export function ComputeContentBounds(docList: Doc[]) {
- let bounds = docList.reduce((bounds, doc) => {
- var [sptX, sptY] = [NumCast(doc.x), NumCast(doc.y)];
- let [bptX, bptY] = [sptX + doc[WidthSym](), sptY + doc[HeightSym]()];
+ const bounds = docList.reduce((bounds, doc) => {
+ const [sptX, sptY] = [NumCast(doc.x), NumCast(doc.y)];
+ const [bptX, bptY] = [sptX + doc[WidthSym](), sptY + doc[HeightSym]()];
return {
x: Math.min(sptX, bounds.x), y: Math.min(sptY, bounds.y),
r: Math.max(bptX, bounds.r), b: Math.max(bptY, bounds.b)
@@ -399,16 +399,17 @@ export namespace Doc {
}
export function MakeTitled(title: string) {
- let doc = new Doc();
+ const doc = new Doc();
doc.title = title;
return doc;
}
export function MakeAlias(doc: Doc) {
- let alias = !GetT(doc, "isPrototype", "boolean", true) ? Doc.MakeCopy(doc) : Doc.MakeDelegate(doc);
- if (alias.layout instanceof Doc) {
- alias.layout = Doc.MakeAlias(alias.layout);
+ const alias = !GetT(doc, "isPrototype", "boolean", true) ? Doc.MakeCopy(doc) : Doc.MakeDelegate(doc);
+ const layout = Doc.Layout(alias);
+ if (layout instanceof Doc && layout !== alias) {
+ Doc.SetLayout(alias, Doc.MakeAlias(layout));
}
- let aliasNumber = Doc.GetProto(doc).aliasNumber = NumCast(Doc.GetProto(doc).aliasNumber) + 1;
+ const aliasNumber = Doc.GetProto(doc).aliasNumber = NumCast(Doc.GetProto(doc).aliasNumber) + 1;
alias.title = ComputedField.MakeFunction(`renameAlias(this, ${aliasNumber})`);
return alias;
}
@@ -436,8 +437,8 @@ export namespace Doc {
// ... 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.
- let expandedLayoutFieldKey = "Layout[" + templateLayoutDoc[Id] + "]";
- let expandedTemplateLayout = dataDoc[expandedLayoutFieldKey];
+ const expandedLayoutFieldKey = "Layout[" + templateLayoutDoc[Id] + "]";
+ const expandedTemplateLayout = dataDoc[expandedLayoutFieldKey];
if (expandedTemplateLayout instanceof Doc) {
return expandedTemplateLayout;
}
@@ -450,10 +451,11 @@ export namespace Doc {
export function GetLayoutDataDocPair(doc: Doc, dataDoc: Doc | undefined, fieldKey: string, childDocLayout: Doc) {
let layoutDoc: Doc | undefined = childDocLayout;
- let resolvedDataDoc = !doc.isTemplateField && dataDoc !== doc && dataDoc ? Doc.GetDataDoc(dataDoc) : undefined;
+ const resolvedDataDoc = !doc.isTemplateField && dataDoc !== doc && dataDoc ? Doc.GetDataDoc(dataDoc) : undefined;
if (resolvedDataDoc && Doc.WillExpandTemplateLayout(childDocLayout, resolvedDataDoc)) {
- let extensionDoc = fieldExtensionDoc(resolvedDataDoc, StrCast(childDocLayout.templateField, StrCast(childDocLayout.title)));
+ 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 };
}
@@ -466,15 +468,21 @@ export namespace Doc {
// to store annotations, ink, and other data.
//
export function fieldExtensionDoc(doc: Doc, fieldKey: string) {
- let extension = doc[fieldKey + "_ext"] as Doc;
- (extension === undefined) && setTimeout(() => CreateDocumentExtensionForField(doc, fieldKey), 0);
- return extension ? extension : undefined;
+ 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);
}
export function CreateDocumentExtensionForField(doc: Doc, fieldKey: string) {
- let docExtensionForField = new Doc(doc[Id] + fieldKey, true);
- docExtensionForField.title = fieldKey + ".ext";
+ 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) {
@@ -510,7 +518,7 @@ export namespace Doc {
export function MakeCopy(doc: Doc, copyProto: boolean = false, copyProtoId?: string): Doc {
const copy = new Doc(copyProtoId, true);
Object.keys(doc).forEach(key => {
- let cfield = ComputedField.WithoutComputed(() => FieldValue(doc[key]));
+ const cfield = ComputedField.WithoutComputed(() => FieldValue(doc[key]));
const field = ProxyField.WithoutProxy(() => doc[key]);
if (key === "proto" && copyProto) {
if (doc[key] instanceof Doc) {
@@ -549,7 +557,7 @@ export namespace Doc {
let _applyCount: number = 0;
export function ApplyTemplate(templateDoc: Doc) {
if (templateDoc) {
- let applied = ApplyTemplateTo(templateDoc, Doc.MakeDelegate(new Doc()), "layoutCustom", templateDoc.title + "(..." + _applyCount++ + ")");
+ const applied = ApplyTemplateTo(templateDoc, Doc.MakeDelegate(new Doc()), "layoutCustom", templateDoc.title + "(..." + _applyCount++ + ")");
applied && (Doc.GetProto(applied).layout = applied.layout);
return applied;
}
@@ -565,20 +573,22 @@ export namespace Doc {
return;
}
- let layoutCustomLayout = Doc.MakeDelegate(templateDoc);
+ if ((target[targetKey] as Doc)?.proto !== templateDoc) {
+ const layoutCustomLayout = Doc.MakeDelegate(templateDoc);
- titleTarget && (Doc.GetProto(target).title = titleTarget);
- target.type = DocumentType.TEMPLATE;
- target.onClick = templateDoc.onClick instanceof ObjectField && templateDoc.onClick[Copy]();
+ 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] = layoutCustomLayout;
+ }
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, ??)
- let metadataFieldName = StrCast(fieldTemplate.title).replace(/^-/, "");
+ const metadataFieldName = StrCast(fieldTemplate.title).replace(/^-/, "");
let fieldLayoutDoc = fieldTemplate;
if (fieldTemplate.layout instanceof Doc) {
fieldLayoutDoc = Doc.MakeDelegate(fieldTemplate.layout);
@@ -599,30 +609,30 @@ export namespace Doc {
fieldTemplate.panY = 0;
fieldTemplate.scale = 1;
fieldTemplate.showTitle = suppressTitle ? undefined : "title";
- let data = fieldTemplate.data;
- setTimeout(action(() => {
- !templateDataDoc[metadataFieldName] && data instanceof ObjectField && (Doc.GetProto(templateDataDoc)[metadataFieldName] = ObjectField.MakeCopy(data));
- let layout = StrCast(fieldLayoutDoc.layout).replace(/fieldKey={"[^"]*"}/, `fieldKey={"${metadataFieldName}"}`);
- let 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);
+ 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);
return true;
}
export function overlapping(doc1: Doc, doc2: Doc, clusterDistance: number) {
- let doc2Layout = Doc.Layout(doc2);
- let doc1Layout = Doc.Layout(doc1);
- var x2 = NumCast(doc2.x) - clusterDistance;
- var y2 = NumCast(doc2.y) - clusterDistance;
- var w2 = NumCast(doc2Layout.width) + clusterDistance;
- var h2 = NumCast(doc2Layout.height) + clusterDistance;
- var x = NumCast(doc1.x) - clusterDistance;
- var y = NumCast(doc1.y) - clusterDistance;
- var w = NumCast(doc1Layout.width) + clusterDistance;
- var h = NumCast(doc1Layout.height) + clusterDistance;
+ const doc2Layout = Doc.Layout(doc2);
+ 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 x = NumCast(doc1.x) - clusterDistance;
+ const y = NumCast(doc1.y) - 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 });
}
@@ -636,27 +646,38 @@ export namespace Doc {
}
export class DocBrush {
- @observable BrushedDoc: ObservableMap<Doc, boolean> = new ObservableMap();
+ BrushedDoc: ObservableMap<Doc, boolean> = new ObservableMap();
}
const brushManager = new DocBrush();
export class DocData {
@observable _user_doc: Doc = undefined!;
- @observable BrushedDoc: ObservableMap<Doc, boolean> = new ObservableMap();
+ @observable _searchQuery: string = "";
}
// 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 SetLayout(doc: Doc, layout: Doc | string) { doc[StrCast(doc.layoutKey, "layout")] = layout; }
export function LayoutField(doc: Doc) { return doc[StrCast(doc.layoutKey, "layout")]; }
const manager = new DocData();
+ export function SearchQuery(): string { return manager._searchQuery; }
+ export function SetSearchQuery(query: string) { runInAction(() => manager._searchQuery = query); }
export function UserDoc(): Doc { return manager._user_doc; }
export function SetUserDoc(doc: Doc) { manager._user_doc = doc; }
export function IsBrushed(doc: Doc) {
- return brushManager.BrushedDoc.has(doc) || brushManager.BrushedDoc.has(Doc.GetDataDoc(doc));
+ return computedFn(function IsBrushed(doc: Doc) {
+ return brushManager.BrushedDoc.has(doc) || brushManager.BrushedDoc.has(Doc.GetDataDoc(doc));
+ })(doc);
+ }
+ // don't bother memoizing (caching) the result if called from a non-reactive context. (plus this avoids a warning message)
+ export function IsBrushedDegreeUnmemoized(doc: Doc) {
+ return brushManager.BrushedDoc.has(doc) ? 2 : brushManager.BrushedDoc.has(Doc.GetDataDoc(doc)) ? 1 : 0;
}
export function IsBrushedDegree(doc: Doc) {
- return brushManager.BrushedDoc.has(Doc.GetDataDoc(doc)) ? 2 : brushManager.BrushedDoc.has(doc) ? 1 : 0;
+ return computedFn(function IsBrushDegree(doc: Doc) {
+ return brushManager.BrushedDoc.has(doc) ? 2 : brushManager.BrushedDoc.has(Doc.GetDataDoc(doc)) ? 1 : 0;
+ })(doc);
}
export function BrushDoc(doc: Doc) {
brushManager.BrushedDoc.set(doc, true);
@@ -669,6 +690,8 @@ export namespace Doc {
return 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 linkFollowUnhighlight() {
@@ -682,7 +705,7 @@ export namespace Doc {
Doc.HighlightDoc(destDoc);
document.removeEventListener("pointerdown", linkFollowUnhighlight);
document.addEventListener("pointerdown", linkFollowUnhighlight);
- let x = dt = Date.now();
+ const x = dt = Date.now();
window.setTimeout(() => dt === x && linkFollowUnhighlight(), 5000);
}
@@ -691,8 +714,7 @@ export namespace Doc {
}
const highlightManager = new HighlightBrush();
export function IsHighlighted(doc: Doc) {
- let IsHighlighted = highlightManager.HighlightedDoc.get(doc) || highlightManager.HighlightedDoc.get(Doc.GetDataDoc(doc));
- return IsHighlighted;
+ return highlightManager.HighlightedDoc.get(doc) || highlightManager.HighlightedDoc.get(Doc.GetDataDoc(doc));
}
export function HighlightDoc(doc: Doc) {
runInAction(() => {
@@ -707,10 +729,10 @@ export namespace Doc {
});
}
export function UnhighlightAll() {
- let mapEntries = highlightManager.HighlightedDoc.keys();
+ const mapEntries = highlightManager.HighlightedDoc.keys();
let docEntry: IteratorResult<Doc>;
while (!(docEntry = mapEntries.next()).done) {
- let targetDoc = docEntry.value;
+ const targetDoc = docEntry.value;
targetDoc && Doc.UnHighlightDoc(targetDoc);
}
@@ -724,8 +746,19 @@ 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 MakeDocFilter(docFilters: string[]) {
+ let docFilterText = "";
+ 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;
+ }
+ 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); });
@@ -737,4 +770,37 @@ Scripting.addGlobal(function aliasDocs(field: any) { return new List<Doc>(field.
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 undo() { return UndoManager.Undo(); });
-Scripting.addGlobal(function redo() { return UndoManager.Redo(); }); \ No newline at end of file
+Scripting.addGlobal(function redo() { return UndoManager.Redo(); });
+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
diff --git a/src/new_fields/InkField.ts b/src/new_fields/InkField.ts
index d94834e91..e2aa7ee16 100644
--- a/src/new_fields/InkField.ts
+++ b/src/new_fields/InkField.ts
@@ -2,7 +2,6 @@ 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 { DeepCopy } from "../Utils";
export enum InkTool {
None,
@@ -12,19 +11,15 @@ export enum InkTool {
Scrubber
}
-export interface StrokeData {
- pathData: Array<{ x: number, y: number }>;
- color: string;
- width: string;
- tool: InkTool;
- displayTimecode: number;
- creationTime: number;
+export interface PointData {
+ X: number;
+ Y: number;
}
-export type InkData = Map<string, StrokeData>;
+export type InkData = Array<PointData>;
const pointSchema = createSimpleSchema({
- x: true, y: true
+ X: true, Y: true
});
const strokeDataSchema = createSimpleSchema({
@@ -34,16 +29,16 @@ const strokeDataSchema = createSimpleSchema({
@Deserializable("ink")
export class InkField extends ObjectField {
- @serializable(map(object(strokeDataSchema)))
+ @serializable(list(object(strokeDataSchema)))
readonly inkData: InkData;
- constructor(data?: InkData) {
+ constructor(data: InkData) {
super();
- this.inkData = data || new Map;
+ this.inkData = data;
}
[Copy]() {
- return new InkField(DeepCopy(this.inkData));
+ return new InkField(this.inkData);
}
[ToScriptString]() {
diff --git a/src/new_fields/List.ts b/src/new_fields/List.ts
index 0c7b77fa5..bb48b1bb3 100644
--- a/src/new_fields/List.ts
+++ b/src/new_fields/List.ts
@@ -270,8 +270,8 @@ class ListImpl<T extends Field> extends ObjectField {
}
[Copy]() {
- let copiedData = this[Self].__fields.map(f => f instanceof ObjectField ? f[Copy]() : f);
- let deepCopy = new ListImpl<T>(copiedData as any);
+ const copiedData = this[Self].__fields.map(f => f instanceof ObjectField ? f[Copy]() : f);
+ const deepCopy = new ListImpl<T>(copiedData as any);
return deepCopy;
}
@@ -290,8 +290,7 @@ class ListImpl<T extends Field> extends ObjectField {
private [SelfProxy]: any;
[ToScriptString]() {
- return "invalid";
- // return `new List([${(this as any).map((field => Field.toScriptString(field))}])`;
+ return `new List([${(this as any).map((field: any) => Field.toScriptString(field))}])`;
}
}
export type List<T extends Field> = ListImpl<T> & (T | (T extends RefField ? Promise<T> : never))[];
diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts
index d2f76c969..fd5459876 100644
--- a/src/new_fields/RichTextField.ts
+++ b/src/new_fields/RichTextField.ts
@@ -10,17 +10,21 @@ export class RichTextField extends ObjectField {
@serializable(true)
readonly Data: string;
- constructor(data: string) {
+ @serializable(true)
+ readonly Text: string;
+
+ constructor(data: string, text: string = "") {
super();
this.Data = data;
+ this.Text = text;
}
[Copy]() {
- return new RichTextField(this.Data);
+ return new RichTextField(this.Data, this.Text);
}
[ToScriptString]() {
- return `new RichTextField("${this.Data}")`;
+ return `new RichTextField("${this.Data}", "${this.Text}")`;
}
} \ No newline at end of file
diff --git a/src/new_fields/RichTextUtils.ts b/src/new_fields/RichTextUtils.ts
index 601939ed2..682206aa2 100644
--- a/src/new_fields/RichTextUtils.ts
+++ b/src/new_fields/RichTextUtils.ts
@@ -8,7 +8,6 @@ import { Opt, Doc } from "./Doc";
import Color = require('color');
import { sinkListItem } from "prosemirror-schema-list";
import { Utils } from "../Utils";
-import { RouteStore } from "../server/RouteStore";
import { Docs } from "../client/documents/Documents";
import { schema } from "../client/util/RichTextSchema";
import { GooglePhotos } from "../client/apis/google_docs/GooglePhotosClientUtils";
@@ -17,7 +16,7 @@ import { Cast, StrCast } from "./Types";
import { Id } from "./FieldSymbols";
import { DocumentView } from "../client/views/nodes/DocumentView";
import { AssertionError } from "assert";
-import { Identified } from "../client/Network";
+import { Networking } from "../client/Network";
export namespace RichTextUtils {
@@ -26,8 +25,8 @@ export namespace RichTextUtils {
export const Initialize = (initial?: string) => {
- let content: any[] = [];
- let state = {
+ const content: any[] = [];
+ const state = {
doc: {
type: "doc",
content,
@@ -52,37 +51,37 @@ export namespace RichTextUtils {
};
export const Synthesize = (plainText: string, oldState?: RichTextField) => {
- return new RichTextField(ToProsemirrorState(plainText, oldState));
+ return new RichTextField(ToProsemirrorState(plainText, oldState), plainText);
};
export const ToPlainText = (state: EditorState) => {
// Because we're working with plain text, just concatenate all paragraphs
- let content = state.doc.content;
- let paragraphs: Node<any>[] = [];
+ const content = state.doc.content;
+ const paragraphs: Node<any>[] = [];
content.forEach(node => node.type.name === "paragraph" && paragraphs.push(node));
// Functions to flatten ProseMirror paragraph objects (and their components) to plain text
// Concatentate paragraphs and string the result together
- let textParagraphs: string[] = paragraphs.map(paragraph => {
- let text: string[] = [];
+ const textParagraphs: string[] = paragraphs.map(paragraph => {
+ const text: string[] = [];
paragraph.content.forEach(node => node.text && text.push(node.text));
return text.join(joiner) + delimiter;
});
- let plainText = textParagraphs.join(joiner);
+ const plainText = textParagraphs.join(joiner);
return plainText.substring(0, plainText.length - 1);
};
export const ToProsemirrorState = (plainText: string, oldState?: RichTextField) => {
// Remap the text, creating blocks split on newlines
- let elements = plainText.split(delimiter);
+ const elements = plainText.split(delimiter);
// Google Docs adds in an extra carriage return automatically, so this counteracts it
!elements[elements.length - 1].length && elements.pop();
// Preserve the current state, but re-write the content to be the blocks
- let parsed = JSON.parse(oldState ? oldState.Data : Initialize());
+ const parsed = JSON.parse(oldState ? oldState.Data : Initialize());
parsed.doc.content = elements.map(text => {
- let paragraph: any = { type: "paragraph" };
+ const paragraph: any = { type: "paragraph" };
text.length && (paragraph.content = [{ type: "text", marks: [], text }]); // An empty paragraph gets treated as a line break
return paragraph;
});
@@ -98,7 +97,7 @@ export namespace RichTextUtils {
export const Export = async (state: EditorState): Promise<GoogleApiClientUtils.Docs.Content> => {
const nodes: (Node<any> | null)[] = [];
- let text = ToPlainText(state);
+ const text = ToPlainText(state);
state.doc.content.forEach(node => {
if (!node.childCount) {
nodes.push(null);
@@ -129,7 +128,7 @@ export namespace RichTextUtils {
return { baseUrl, filename };
});
- const uploads = await Identified.PostToServer(RouteStore.googlePhotosMediaDownload, { mediaItems });
+ const uploads = await Networking.PostToServer("/googlePhotosMediaDownload", { mediaItems });
if (uploads.length !== mediaItems.length) {
throw new AssertionError({ expected: mediaItems.length, actual: uploads.length, message: "Error with internally uploading inlineObjects!" });
@@ -169,20 +168,20 @@ export namespace RichTextUtils {
const title = document.title!;
const { text, paragraphs } = GoogleApiClientUtils.Docs.Utils.extractText(document);
let state = FormattedTextBox.blankState();
- let structured = parseLists(paragraphs);
+ const structured = parseLists(paragraphs);
let position = 3;
- let lists: ListGroup[] = [];
+ const lists: ListGroup[] = [];
const indentMap = new Map<ListGroup, BulletPosition[]>();
let globalOffset = 0;
const nodes: Node<any>[] = [];
- for (let element of structured) {
+ for (const element of structured) {
if (Array.isArray(element)) {
lists.push(element);
- let positions: BulletPosition[] = [];
- let items = element.map(paragraph => {
- let item = listItem(state.schema, paragraph.contents);
- let sinks = paragraph.bullet!;
+ const positions: BulletPosition[] = [];
+ const items = element.map(paragraph => {
+ const item = listItem(state.schema, paragraph.contents);
+ const sinks = paragraph.bullet!;
positions.push({
value: position + globalOffset,
sinks
@@ -209,7 +208,7 @@ export namespace RichTextUtils {
}
});
} else {
- let paragraph = paragraphNode(state.schema, element.contents);
+ const paragraph = paragraphNode(state.schema, element.contents);
nodes.push(paragraph);
position += paragraph.nodeSize;
}
@@ -217,11 +216,11 @@ export namespace RichTextUtils {
}
state = state.apply(state.tr.replaceWith(0, 2, nodes));
- let sink = sinkListItem(state.schema.nodes.list_item);
- let dispatcher = (tr: Transaction) => state = state.apply(tr);
- for (let list of lists) {
- for (let pos of indentMap.get(list)!) {
- let resolved = state.doc.resolve(pos.value);
+ const sink = sinkListItem(state.schema.nodes.list_item);
+ const dispatcher = (tr: Transaction) => state = state.apply(tr);
+ for (const list of lists) {
+ for (const pos of indentMap.get(list)!) {
+ const resolved = state.doc.resolve(pos.value);
state = state.apply(state.tr.setSelection(new TextSelection(resolved)));
for (let i = 0; i < pos.sinks; i++) {
sink(state, dispatcher);
@@ -237,9 +236,9 @@ export namespace RichTextUtils {
type PreparedParagraphs = (ListGroup | Paragraph)[];
const parseLists = (paragraphs: ListGroup) => {
- let groups: PreparedParagraphs = [];
+ const groups: PreparedParagraphs = [];
let group: ListGroup = [];
- for (let paragraph of paragraphs) {
+ for (const paragraph of paragraphs) {
if (paragraph.bullet !== undefined) {
group.push(paragraph);
} else {
@@ -263,8 +262,8 @@ export namespace RichTextUtils {
};
const paragraphNode = (schema: any, runs: docs_v1.Schema$TextRun[]): Node => {
- let children = runs.map(run => textNode(schema, run)).filter(child => child !== undefined);
- let fragment = children.length ? Fragment.from(children) : undefined;
+ const children = runs.map(run => textNode(schema, run)).filter(child => child !== undefined);
+ const fragment = children.length ? Fragment.from(children) : undefined;
return schema.node("paragraph", null, fragment);
};
@@ -285,7 +284,7 @@ export namespace RichTextUtils {
};
const textNode = (schema: any, run: docs_v1.Schema$TextRun) => {
- let text = run.content!.removeTrailingNewlines();
+ const text = run.content!.removeTrailingNewlines();
return text.length ? schema.text(text, styleToMarks(schema, run.textStyle)) : undefined;
};
@@ -300,17 +299,17 @@ export namespace RichTextUtils {
if (!textStyle) {
return undefined;
}
- let marks: Mark[] = [];
+ const marks: Mark[] = [];
Object.keys(textStyle).forEach(key => {
let value: any;
- let targeted = key as keyof docs_v1.Schema$TextStyle;
+ const targeted = key as keyof docs_v1.Schema$TextStyle;
if (value = textStyle[targeted]) {
- let attributes: any = {};
+ const attributes: any = {};
let converted = StyleToMark.get(targeted) || targeted;
value.url && (attributes.href = value.url);
if (value.color) {
- let object = value.color.rgbColor;
+ const object = value.color.rgbColor;
attributes.color = Color.rgb(["red", "green", "blue"].map(color => object[color] * 255 || 0)).hex();
}
if (value.magnitude) {
@@ -321,13 +320,13 @@ export namespace RichTextUtils {
converted = ImportFontFamilyMapping.get(value.fontFamily) || "timesNewRoman";
}
- let mapped = schema.marks[converted];
+ const mapped = schema.marks[converted];
if (!mapped) {
alert(`No mapping found for ${converted}!`);
return;
}
- let mark = schema.mark(mapped, attributes);
+ const mark = schema.mark(mapped, attributes);
mark && marks.push(mark);
}
});
@@ -367,9 +366,9 @@ export namespace RichTextUtils {
const ignored = ["user_mark"];
const marksToStyle = async (nodes: (Node<any> | null)[]): Promise<docs_v1.Schema$Request[]> => {
- let requests: docs_v1.Schema$Request[] = [];
+ const requests: docs_v1.Schema$Request[] = [];
let position = 1;
- for (let node of nodes) {
+ for (const node of nodes) {
if (node === null) {
position += 2;
continue;
@@ -383,7 +382,7 @@ export namespace RichTextUtils {
};
let mark: Mark<any>;
const markMap = BuildMarkMap(marks);
- for (let markName of Object.keys(schema.marks)) {
+ for (const markName of Object.keys(schema.marks)) {
if (ignored.includes(markName) || !(mark = markMap[markName])) {
continue;
}
diff --git a/src/new_fields/Schema.ts b/src/new_fields/Schema.ts
index b1a449e08..3f0ff4284 100644
--- a/src/new_fields/Schema.ts
+++ b/src/new_fields/Schema.ts
@@ -23,7 +23,7 @@ export type makeInterface<T extends Interface[]> = AllToInterface<T> & Doc & { p
// export function makeInterface<T extends Interface[], U extends Doc>(schemas: T): (doc: U) => All<T, U>;
// export function makeInterface<T extends Interface, U extends Doc>(schema: T): (doc: U) => makeInterface<T, U>;
export function makeInterface<T extends Interface[]>(...schemas: T): InterfaceFunc<T> {
- let schema: Interface = {};
+ const schema: Interface = {};
for (const s of schemas) {
for (const key in s) {
schema[key] = s[key];
diff --git a/src/new_fields/SchemaHeaderField.ts b/src/new_fields/SchemaHeaderField.ts
index 92d0aec9a..42a8485ac 100644
--- a/src/new_fields/SchemaHeaderField.ts
+++ b/src/new_fields/SchemaHeaderField.ts
@@ -41,6 +41,17 @@ export const PastelSchemaPalette = new Map<string, string>([
export const RandomPastel = () => Array.from(PastelSchemaPalette.values())[Math.floor(Math.random() * PastelSchemaPalette.size)];
+export const DarkPastelSchemaPalette = new Map<string, string>([
+ ["pink2", "#c932b0"],
+ ["purple4", "#913ad6"],
+ ["bluegreen1", "#3978ed"],
+ ["bluegreen7", "#2adb3e"],
+ ["bluegreen5", "#21b0eb"],
+ ["yellow4", "#edcc0c"],
+ ["red2", "#eb3636"],
+ ["orange1", "#f2740f"],
+]);
+
@scriptingGlobal
@Deserializable("schemaheader")
export class SchemaHeaderField extends ObjectField {
diff --git a/src/new_fields/ScriptField.ts b/src/new_fields/ScriptField.ts
index cdc9871a8..b5ad4a7f6 100644
--- a/src/new_fields/ScriptField.ts
+++ b/src/new_fields/ScriptField.ts
@@ -102,8 +102,8 @@ export class ScriptField extends ObjectField {
return "script field";
}
public static CompileScript(script: string, params: object = {}, addReturn = false) {
- let compiled = CompileScript(script, {
- params: { this: Doc.name, ...params },
+ const compiled = CompileScript(script, {
+ params: { this: Doc.name, _last_: "any", ...params },
typecheck: false,
editable: true,
addReturn: addReturn
@@ -111,12 +111,12 @@ export class ScriptField extends ObjectField {
return compiled;
}
public static MakeFunction(script: string, params: object = {}) {
- let compiled = ScriptField.CompileScript(script, params, true);
+ const compiled = ScriptField.CompileScript(script, params, true);
return compiled.compiled ? new ScriptField(compiled) : undefined;
}
public static MakeScript(script: string, params: object = {}) {
- let compiled = ScriptField.CompileScript(script, params, false);
+ const compiled = ScriptField.CompileScript(script, params, false);
return compiled.compiled ? new ScriptField(compiled) : undefined;
}
}
@@ -124,14 +124,15 @@ export class ScriptField extends ObjectField {
@scriptingGlobal
@Deserializable("computed", deserializeScript)
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.script.run({ this: doc }, console.log).result);
+ value = computedFn((doc: Doc) => this._lastComputedResult = this.script.run({ this: doc, _last_: this._lastComputedResult }, console.log).result);
public static MakeScript(script: string, params: object = {}, ) {
- let compiled = ScriptField.CompileScript(script, params, false);
+ const compiled = ScriptField.CompileScript(script, params, false);
return compiled.compiled ? new ComputedField(compiled) : undefined;
}
public static MakeFunction(script: string, params: object = {}) {
- let compiled = ScriptField.CompileScript(script, params, true);
+ const compiled = ScriptField.CompileScript(script, params, true);
return compiled.compiled ? new ComputedField(compiled) : undefined;
}
}
diff --git a/src/new_fields/documentSchemas.ts b/src/new_fields/documentSchemas.ts
index e2730914f..909fdc6c3 100644
--- a/src/new_fields/documentSchemas.ts
+++ b/src/new_fields/documentSchemas.ts
@@ -27,22 +27,34 @@ export const documentSchema = createSchema({
isTemplateField: "boolean", // whether this document acts as a template layout for describing how other documents should be displayed
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
+ treeViewExpandedView: "string", // name of field whose contents are being displayed as the document's subtree
+ preventTreeViewOpen: "boolean", // ignores the treeViewOpen flag (for allowing a view to not be slaved to other views of the document)
currentTimecode: "number", // current play back time of a temporal document (video / audio)
summarizedDocs: listSpec(Doc), // documents that are summarized by this document (and which will typically be opened by clicking this document)
maximizedDocs: listSpec(Doc), // documents to maximize when clicking this document (generally this document will be an icon)
maximizeLocation: "string", // flag for where to place content when following a click interaction (e.g., onRight, inPlace, inTab)
- lockedPosition: "boolean", // whether the document can be spatially manipulated
+ lockedPosition: "boolean", // whether the document can be moved (dragged)
+ lockedTransform: "boolean", // whether the document can be panned/zoomed
inOverlay: "boolean", // whether the document is rendered in an OverlayView which handles selection/dragging differently
borderRounding: "string", // border radius rounding of document
searchFields: "string", // the search fields to display when this document matches a search in its metadata
heading: "number", // the logical layout 'heading' of this document (used by rule provider to stylize h1 header elements, from h2, etc)
showCaption: "string", // whether editable caption text is overlayed at the bottom of the document
- showTitle: "string", // whether an editable title banner is displayed at tht top of the document
+ showTitle: "string", // the fieldkey whose contents should be displayed at the top of the document
+ showTitleHover: "string", // the showTitle should be shown only on hover
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: "boolean", // whether the document is in the midst of animating between two layouts (used by icons to de/iconify documents).
+ 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",
+ fitToBox: "boolean", // whether freeform view contents should be zoomed/panned to fill the area of the document view
+ 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
});
export const positionSchema = createSchema({
diff --git a/src/new_fields/util.ts b/src/new_fields/util.ts
index 04194509c..4147be278 100644
--- a/src/new_fields/util.ts
+++ b/src/new_fields/util.ts
@@ -4,7 +4,7 @@ import { SerializationHelper } from "../client/util/SerializationHelper";
import { ProxyField } from "./Proxy";
import { RefField } from "./RefField";
import { ObjectField } from "./ObjectField";
-import { action } from "mobx";
+import { action, trace } from "mobx";
import { Parent, OnUpdate, Update, Id, SelfProxy, Self } from "./FieldSymbols";
import { DocServer } from "../client/DocServer";
@@ -12,6 +12,10 @@ function _readOnlySetter(): never {
throw new Error("Documents can't be modified in read-only mode");
}
+export function TraceMobx() {
+ //trace();
+}
+
export interface GetterResult {
value: FieldResult;
shouldReturn?: boolean;