From 2b79008596351f6948d8de80c7887446d97b068c Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Fri, 15 May 2020 00:03:41 -0700 Subject: renamed new_fields to fields --- src/fields/ScriptField.ts | 193 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 src/fields/ScriptField.ts (limited to 'src/fields/ScriptField.ts') diff --git a/src/fields/ScriptField.ts b/src/fields/ScriptField.ts new file mode 100644 index 000000000..f05f431ac --- /dev/null +++ b/src/fields/ScriptField.ts @@ -0,0 +1,193 @@ +import { ObjectField } from "./ObjectField"; +import { CompiledScript, CompileScript, scriptingGlobal, ScriptOptions, CompileError, CompileResult } from "../client/util/Scripting"; +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, Field } from "./Doc"; +import { Plugins, setter } from "./util"; +import { computedFn } from "mobx-utils"; +import { ProxyField } from "./Proxy"; +import { Cast } from "./Types"; + +function optional(propSchema: PropSchema) { + return custom(value => { + if (value !== undefined) { + return propSchema.serializer(value); + } + return SKIP; + }, (jsonValue: any, context: any, oldValue: any, callback: (err: any, result: any) => void) => { + if (jsonValue !== undefined) { + return propSchema.deserializer(jsonValue, callback, context, oldValue); + } + return SKIP; + }); +} + +const optionsSchema = createSimpleSchema({ + requiredType: true, + addReturn: true, + typecheck: true, + editable: true, + readonly: true, + params: optional(map(primitive())) +}); + +const scriptSchema = createSimpleSchema({ + options: object(optionsSchema), + originalScript: true +}); + +async function deserializeScript(script: ScriptField) { + const captures: ProxyField = (script as any).captures; + if (captures) { + const doc = (await captures.value())!; + const captured: any = {}; + const keys = Object.keys(doc); + const vals = await Promise.all(keys.map(key => doc[key]) as any); + keys.forEach((key, i) => captured[key] = vals[i]); + (script.script.options as any).capturedVariables = captured; + } + const comp = CompileScript(script.script.originalScript, script.script.options); + if (!comp.compiled) { + throw new Error("Couldn't compile loaded script"); + } + (script as any).script = comp; +} + +@scriptingGlobal +@Deserializable("script", deserializeScript) +export class ScriptField extends ObjectField { + @serializable(object(scriptSchema)) + readonly script: CompiledScript; + @serializable(object(scriptSchema)) + readonly setterscript: CompiledScript | undefined; + + @serializable(autoObject()) + private captures?: ProxyField; + + constructor(script: CompiledScript, setterscript?: CompileResult) { + super(); + + if (script?.options.capturedVariables) { + const doc = Doc.assign(new Doc, script.options.capturedVariables); + this.captures = new ProxyField(doc); + } + this.setterscript = setterscript?.compiled ? setterscript : undefined; + this.script = script; + } + + // init(callback: (res: Field) => any) { + // const options = this.options!; + // const keys = Object.keys(options.options.capturedIds); + // Server.GetFields(keys).then(fields => { + // let captured: { [name: string]: Field } = {}; + // keys.forEach(key => captured[options.options.capturedIds[key]] = fields[key]); + // const opts: ScriptOptions = { + // addReturn: options.options.addReturn, + // params: options.options.params, + // requiredType: options.options.requiredType, + // capturedVariables: captured + // }; + // const script = CompileScript(options.script, opts); + // if (!script.compiled) { + // throw new Error("Can't compile script"); + // } + // this._script = script; + // callback(this); + // }); + // } + + [Copy](): ObjectField { + return new ScriptField(this.script); + } + toString() { + return `${this.script.originalScript}`; + } + + [ToScriptString]() { + return "script field"; + } + [ToString]() { + return this.script.originalScript; + } + public static CompileScript(script: string, params: object = {}, addReturn = false, capturedVariables?: { [name: string]: Field }) { + const compiled = CompileScript(script, { + params: { this: Doc.name, self: Doc.name, _last_: "any", ...params }, + typecheck: false, + editable: true, + addReturn: addReturn, + capturedVariables + }); + return compiled; + } + 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; + } + + public static MakeScript(script: string, params: object = {}, capturedVariables?: { [name: string]: Field }) { + const compiled = ScriptField.CompileScript(script, params, false, capturedVariables); + return compiled.compiled ? new ScriptField(compiled) : undefined; + } +} + +@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._valueOutsideReaction(doc)); + _valueOutsideReaction = (doc: Doc) => this._lastComputedResult = this.script.run({ this: doc, self: Cast(doc.rootDocument, Doc, null) || doc, _last_: this._lastComputedResult }, console.log).result; + + + constructor(script: CompiledScript, setterscript?: CompiledScript) { + super(script, + !setterscript && script?.originalScript.includes("self.timecode") ? + ScriptField.CompileScript("self['x' + self.timecode] = value", { value: "any" }, true) : setterscript); + } + + 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 = {}, capturedVariables?: { [name: string]: Field }, setterScript?: string) { + const compiled = ScriptField.CompileScript(script, params, true, capturedVariables); + const setCompiled = setterScript ? ScriptField.CompileScript(setterScript, params, true, capturedVariables) : undefined; + return compiled.compiled ? new ComputedField(compiled, setCompiled?.compiled ? setCompiled : undefined) : undefined; + } + public static MakeInterpolated(fieldKey: string, interpolatorKey: string) { + const getField = ScriptField.CompileScript(`(self['${fieldKey}-indexed'])[self.${interpolatorKey}]`, {}, true, {}); + const setField = ScriptField.CompileScript(`(self['${fieldKey}-indexed'])[self.${interpolatorKey}] = value`, { value: "any" }, true, {}); + return getField.compiled ? new ComputedField(getField, setField?.compiled ? setField : undefined) : undefined; + } +} + +export namespace ComputedField { + let useComputed = true; + export function DisableComputedFields() { + useComputed = false; + } + + export function EnableComputedFields() { + useComputed = true; + } + + export const undefined = "__undefined"; + + export function WithoutComputed(fn: () => T) { + DisableComputedFields(); + try { + return fn(); + } finally { + EnableComputedFields(); + } + } + + export function initPlugin() { + Plugins.addGetterPlugin((doc, _, value) => { + if (useComputed && value instanceof ComputedField) { + return { value: value._valueOutsideReaction(doc), shouldReturn: true }; + } + }); + } +} \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 61dcd6a0e23384e68a7d7f2f9e0143741f5cbf56 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 15 May 2020 17:36:39 -0400 Subject: moving toward a proper slide transition system --- src/client/views/DocumentDecorations.tsx | 2 +- src/client/views/MainView.tsx | 5 +- .../views/collections/CollectionCarouselView.tsx | 5 +- .../CollectionFreeFormLayoutEngines.tsx | 4 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 118 ++++++++++----------- .../views/nodes/CollectionFreeFormDocumentView.tsx | 58 +++++++++- src/fields/ScriptField.ts | 8 +- 7 files changed, 128 insertions(+), 72 deletions(-) (limited to 'src/fields/ScriptField.ts') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index fc7c16296..6639f1cce 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -483,7 +483,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
{`${this.selectionTitle}`}
- + ; bounds.x = Math.max(0, bounds.x - this._resizeBorderWidth / 2) + this._resizeBorderWidth / 2; bounds.y = Math.max(0, bounds.y - this._resizeBorderWidth / 2 - this._titleHeight) + this._resizeBorderWidth / 2 + this._titleHeight; diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 978cf7868..f58313f06 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -1,6 +1,6 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { - faTrashAlt, faAngleRight, faBell, faTrash, faCamera, faExpand, faCaretDown, faCaretRight, faCaretSquareDown, faCaretSquareRight, faArrowsAltH, faPlus, faMinus, + faTrashAlt, faAngleRight, faBell, faTrash, faCamera, faExpand, faCaretDown, faCaretLeft, faCaretRight, faCaretSquareDown, faCaretSquareRight, faArrowsAltH, faPlus, faMinus, faTerminal, faToggleOn, faFile as fileSolid, faExternalLinkAlt, faLocationArrow, faSearch, faFileDownload, faStop, faCalculator, faWindowMaximize, faAddressCard, faQuestionCircle, faArrowLeft, faArrowRight, faArrowDown, faArrowUp, faBolt, faBullseye, faCaretUp, faCat, faCheck, faChevronRight, faClipboard, faClone, faCloudUploadAlt, faCommentAlt, faCompressArrowsAlt, faCut, faEllipsisV, faEraser, faExclamation, faFileAlt, faFileAudio, faFilePdf, faFilm, faFilter, faFont, faGlobeAsia, faHighlighter, @@ -121,6 +121,8 @@ export class MainView extends React.Component { library.add(faCamera); library.add(faExpand); library.add(faCaretDown); + library.add(faCaretUp); + library.add(faCaretLeft); library.add(faCaretRight); library.add(faCaretSquareDown); library.add(faCaretSquareRight); @@ -168,7 +170,6 @@ export class MainView extends React.Component { library.add(faThumbtack); library.add(faLongArrowAltRight); library.add(faCheck); - library.add(faCaretUp); library.add(faFilter); library.add(faBullseye); library.add(faArrowLeft); diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx index 39bb9bc23..f65a89422 100644 --- a/src/client/views/collections/CollectionCarouselView.tsx +++ b/src/client/views/collections/CollectionCarouselView.tsx @@ -9,7 +9,6 @@ import { DragManager } from '../../util/DragManager'; import { ContentFittingDocumentView } from '../nodes/ContentFittingDocumentView'; import "./CollectionCarouselView.scss"; import { CollectionSubView } from './CollectionSubView'; -import { faCaretLeft, faCaretRight } from '@fortawesome/free-solid-svg-icons'; import { Doc } from '../../../fields/Doc'; import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox'; import { ContextMenu } from '../ContextMenu'; @@ -76,10 +75,10 @@ export class CollectionCarouselView extends CollectionSubView(CarouselDocument) @computed get buttons() { return <>
- +
- +
; } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx index 3860ce2d7..a4fd5384f 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx @@ -25,6 +25,7 @@ export interface ViewDefBounds { fontSize?: number; highlight?: boolean; color?: string; + opacity?: number; replica?: string; pair?: { layout: Doc, data?: Doc }; } @@ -37,6 +38,7 @@ export interface PoolData { width?: number; height?: number; color?: string; + opacity?: number; transition?: string; highlight?: boolean; replica: string; @@ -416,7 +418,7 @@ function normalizeResults( height: newPosRaw.height! * scale, pair: ele[1].pair }; - poolData.set(newPos.pair.layout[Id] + (newPos.replica || ""), { transition: "transform 1s", ...newPos }); + poolData.set(newPos.pair.layout[Id] + (newPos.replica || ""), { transition: "all 1s", ...newPos }); } }); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index bf679309c..751ee03d2 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -46,6 +46,7 @@ import React = require("react"); import { CollectionViewType } from "../CollectionView"; import { Timeline } from "../../animationtimeline/Timeline"; import { SnappingManager } from "../../../util/SnappingManager"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; library.add(faEye as any, faTable, faPaintBrush, faExpandArrowsAlt, faCompressArrowsAlt, faCompass, faUpload, faBraille, faChalkboard, faFileUpload); @@ -53,6 +54,7 @@ export const panZoomSchema = createSchema({ _panX: "number", _panY: "number", scale: "number", + timecode: "number", arrangeScript: ScriptField, arrangeInit: ScriptField, useClusters: "boolean", @@ -124,15 +126,8 @@ export class CollectionFreeFormView extends CollectionSubView { - const timecode = Cast(this.props.Document.timecode, "number", null); - if (timecode !== undefined) { - ((newBox instanceof Doc) ? [newBox] : newBox).map(doc => { - doc["x-indexed"] = new List(numberRange(timecode + 1).map(i => NumCast(doc.x))); - doc["y-indexed"] = new List(numberRange(timecode + 1).map(i => NumCast(doc.y))); - doc.timecode = ComputedField.MakeFunction("collection.timecode", {}, { collection: this.props.Document }); - doc.x = ComputedField.MakeInterpolated("x", "timecode"); - doc.y = ComputedField.MakeInterpolated("y", "timecode"); - }); + if (this.Document.timecode !== undefined) { + CollectionFreeFormDocumentView.setupKeyframes((newBox instanceof Doc) ? [newBox] : newBox, this.Document.timecode, this.props.Document); } if (newBox instanceof Doc) { @@ -145,6 +140,25 @@ export class CollectionFreeFormView extends CollectionSubView { + if (this.props.Document.timecode === undefined) { + this.props.Document.timecode = 0; + CollectionFreeFormDocumentView.setupKeyframes(this.childDocs, 0, this.props.Document); + } + const timecode = NumCast(this.props.Document.timecode); + CollectionFreeFormDocumentView.updateKeyframe(this.childDocs, timecode); + this.props.Document.timecode = Math.max(0, timecode + 1); + } + @undoBatch + @action + prevKeyframe = (): void => { + CollectionFreeFormDocumentView.gotoKeyframe(this.childDocs.slice()); + this.props.Document.timecode = Math.max(0, NumCast(this.props.Document.timecode) - 1); + } + private selectDocuments = (docs: Doc[]) => { SelectionManager.DeselectAll(); docs.map(doc => DocumentManager.Instance.getDocumentView(doc)).map(dv => dv && SelectionManager.SelectDoc(dv, true)); @@ -185,8 +199,12 @@ export class CollectionFreeFormView extends CollectionSubView { - if (this.props.Document.timecode === undefined) { - this.childDocs.map(doc => { - this.props.Document.timecode = 0; - doc["x-indexed"] = new List([NumCast(doc.x)]); - doc["y-indexed"] = new List([NumCast(doc.y)]); - doc.timecode = ComputedField.MakeFunction("collection.timecode", {}, { collection: this.props.Document }); - doc.x = ComputedField.MakeInterpolated("x", "timecode"); - doc.y = ComputedField.MakeInterpolated("y", "timecode"); - }); - } - const timecode = NumCast(this.props.Document.timecode); - this.childDocs.map(doc => { - const xindexed = Cast(doc['x-indexed'], listSpec("number"), null); - const yindexed = Cast(doc['y-indexed'], listSpec("number"), null); - xindexed.length <= timecode + 1 && xindexed.push(NumCast(doc.x)); - yindexed.length <= timecode + 1 && yindexed.push(NumCast(doc.y)); - }); - this.childDocs.map(doc => doc.transition = "transform 1s"); - this.props.Document.timecode = Math.max(0, timecode + 1); - setTimeout(() => this.childDocs.map(doc => doc.transition = undefined), 1010); - } - @undoBatch - @action - backupInterpolated = (): void => { - this.childDocs.map(doc => doc.transition = "transform 1s"); - this.props.Document.timecode = Math.max(0, NumCast(this.props.Document.timecode) - 1); - setTimeout(() => this.childDocs.map(doc => doc.transition = undefined), 1010); - } - - private thumbIdentifier?: number; onContextMenu = (e: React.MouseEvent) => { @@ -1185,8 +1175,8 @@ export class CollectionFreeFormView extends CollectionSubView 0 ? this.placeholder : this.marqueeView} - + {this.isAnnotationOverlay ? (null) : + <> +
+ +
+
+ {NumCast(this.props.Document.timecode)} +
+
+ +
+ }
{ x: number, y: number, zIndex?: number, highlight?: boolean, z: number, transition?: string } | undefined; + dataProvider?: (doc: Doc, replica: string) => { x: number, y: number, zIndex?: number, opacity?: number, highlight?: boolean, z: number, transition?: string } | undefined; sizeProvider?: (doc: Doc, replica: string) => { width: number, height: number } | undefined; zIndex?: number; highlight?: boolean; @@ -35,6 +40,7 @@ export class CollectionFreeFormDocumentView extends DocComponent (i <= time && x !== undefined) || p === undefined ? x : p, undefined as any as number), + y: Cast(doc["y-indexed"], listSpec("number"), []).reduce((p, y, i) => (i <= time && y !== undefined) || p === undefined ? y : p, undefined as any as number), + opacity: Cast(doc["opacity-indexed"], listSpec("number"), []).reduce((p, o, i) => i <= time || p === undefined ? o : p, undefined as any as number), + }); + } + + public static setValues(timecode: number, d: Doc, x?: number, y?: number, opacity?: number) { + Cast(d["x-indexed"], listSpec("number"), [])[timecode] = x as any as number; + Cast(d["y-indexed"], listSpec("number"), null)[timecode] = y as any as number; + Cast(d["opacity-indexed"], listSpec("number"), null)[timecode] = opacity as any as number; + } + public static updateKeyframe(docs: Doc[], timecode: number) { + docs.forEach(doc => { + const xindexed = Cast(doc['x-indexed'], listSpec("number"), null); + const yindexed = Cast(doc['y-indexed'], listSpec("number"), null); + const opacityindexed = Cast(doc['opacity-indexed'], listSpec("number"), null); + xindexed.length <= timecode + 1 && xindexed.push(undefined as any as number); + yindexed.length <= timecode + 1 && yindexed.push(undefined as any as number); + opacityindexed.length <= timecode + 1 && opacityindexed.push(undefined as any as number); + doc.transition = "all 1s"; + }); + setTimeout(() => docs.forEach(doc => doc.transition = undefined), 1010); + } + + public static gotoKeyframe(docs: Doc[]) { + docs.forEach(doc => doc.transition = "all 1s"); + setTimeout(() => docs.forEach(doc => doc.transition = undefined), 1010); + } + + public static setupKeyframes(docs: Doc[], timecode: number, collection: Doc) { + docs.forEach(doc => { + doc["x-indexed"] = new List(numberRange(timecode).map(i => undefined) as any as number[]); + doc["y-indexed"] = new List(numberRange(timecode).map(i => undefined) as any as number[]); + doc["opacity-indexed"] = new List(numberRange(timecode).map(i => 0)); + (doc["x-indexed"] as any).push(NumCast(doc.x)); + (doc["y-indexed"] as any).push(NumCast(doc.y)); + (doc["opacity-indexed"] as any).push(NumCast(doc.opacity, 1)); + doc.timecode = ComputedField.MakeFunction("collection.timecode", {}, { collection }); + doc.x = ComputedField.MakeInterpolated("x", "timecode"); + doc.y = ComputedField.MakeInterpolated("y", "timecode"); + doc.opacity = ComputedField.MakeInterpolated("opacity", "timecode"); + }); + } + nudge = (x: number, y: number) => { this.props.Document.x = NumCast(this.props.Document.x) + x; this.props.Document.y = NumCast(this.props.Document.y) + y; @@ -79,7 +132,7 @@ export class CollectionFreeFormDocumentView extends DocComponent (i <= index && x !== undefined) || p === undefined ? x : p, undefined as any) +}); + export namespace ComputedField { let useComputed = true; export function DisableComputedFields() { -- cgit v1.2.3-70-g09d2