diff options
author | Fawn <fangrui_tong@brown.edu> | 2020-01-09 15:52:05 -0500 |
---|---|---|
committer | Fawn <fangrui_tong@brown.edu> | 2020-01-09 15:52:05 -0500 |
commit | 9a8d2a903b10568686cc66c849fba21b1ab75be2 (patch) | |
tree | ea0bf48e4f47c72f9eeab3cbd00a5f1494abbb34 /src | |
parent | e0a8d325d601d305a166c1683dccfcc67e91fe95 (diff) | |
parent | 540bda7295f6ee7c2eed848598de6f5df74b2723 (diff) |
pull and merge with master
Diffstat (limited to 'src')
38 files changed, 2157 insertions, 1204 deletions
diff --git a/src/Utils.ts b/src/Utils.ts index 2b15ad0f2..04fe6750b 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -4,7 +4,6 @@ import { Socket } from 'socket.io'; import { Message } from './server/Message'; export namespace Utils { - export const DRAG_THRESHOLD = 4; export function GenerateGuid(): string { diff --git a/src/client/DocServer.ts b/src/client/DocServer.ts index 47c63bfb7..ed7fbd7ba 100644 --- a/src/client/DocServer.ts +++ b/src/client/DocServer.ts @@ -82,7 +82,9 @@ export namespace DocServer { Utils.AddServerHandler(_socket, MessageStore.UpdateField, respondToUpdate); Utils.AddServerHandler(_socket, MessageStore.DeleteField, respondToDelete); Utils.AddServerHandler(_socket, MessageStore.DeleteFields, respondToDelete); - Utils.AddServerHandler(_socket, MessageStore.ConnectionTerminated, () => alert("Your connection to the server has been terminated.")); + Utils.AddServerHandler(_socket, MessageStore.ConnectionTerminated, () => { + alert("Your connection to the server has been terminated."); + }); } function errorFunc(): never { diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 304eccc02..e149963b9 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -429,7 +429,7 @@ export namespace Docs { return InstanceFromProto(Prototypes.get(DocumentType.TEXT), "", options); } - export function InkDocument(color: string, tool: number, strokeWidth: number, points: { x: number, y: number }[], options: DocumentOptions = {}) { + export function InkDocument(color: string, tool: number, strokeWidth: number, points: { X: number, Y: number }[], options: DocumentOptions = {}) { const doc = InstanceFromProto(Prototypes.get(DocumentType.INK), new InkField(points), options); doc.color = color; doc.strokeWidth = strokeWidth; diff --git a/src/client/util/InteractionUtils.ts b/src/client/util/InteractionUtils.ts index 0c3de66ed..2e4e8c7ca 100644 --- a/src/client/util/InteractionUtils.ts +++ b/src/client/util/InteractionUtils.ts @@ -8,6 +8,17 @@ export namespace InteractionUtils { const REACT_POINTER_PEN_BUTTON = 0; const ERASER_BUTTON = 5; + export function GetMyTargetTouches(e: TouchEvent | React.TouchEvent, prevPoints: Map<number, React.Touch>): React.Touch[] { + const myTouches = new Array<React.Touch>(); + for (let i = 0; i < e.targetTouches.length; i++) { + const pt = e.targetTouches.item(i); + if (pt && prevPoints.has(pt.identifier)) { + myTouches.push(pt); + } + } + return myTouches; + } + export function IsType(e: PointerEvent | React.PointerEvent, type: string): boolean { switch (type) { // pen and eraser are both pointer type 'pen', but pen is button 0 and eraser is button 5. -syip2 @@ -79,6 +90,20 @@ export namespace InteractionUtils { return 0; } + export function IsDragging(oldTouches: Map<number, React.Touch>, newTouches: React.Touch[], leniency: number): boolean { + for (const touch of newTouches) { + if (touch) { + const oldTouch = oldTouches.get(touch.identifier); + if (oldTouch) { + if (TwoPointEuclidist(touch, oldTouch) >= leniency) { + return true; + } + } + } + } + return false; + } + // These might not be very useful anymore, but I'll leave them here for now -syip2 { @@ -134,20 +159,5 @@ export namespace InteractionUtils { // return { type: undefined }; // } // } - - // export function IsDragging(oldTouches: Map<number, React.Touch>, newTouches: TouchList, leniency: number): boolean { - // for (let i = 0; i < newTouches.length; i++) { - // let touch = newTouches.item(i); - // if (touch) { - // let oldTouch = oldTouches.get(touch.identifier); - // if (oldTouch) { - // if (TwoPointEuclidist(touch, oldTouch) >= leniency) { - // return true; - // } - // } - // } - // } - // return false; - // } } }
\ No newline at end of file diff --git a/src/client/util/ProsemirrorExampleTransfer.ts b/src/client/util/ProsemirrorExampleTransfer.ts index b879ca7aa..c028dbf8b 100644 --- a/src/client/util/ProsemirrorExampleTransfer.ts +++ b/src/client/util/ProsemirrorExampleTransfer.ts @@ -111,8 +111,6 @@ export default function buildKeymap<S extends Schema<any>>(schema: S, mapKeys?: return true; }); - bind("Mod-s", TooltipTextMenu.insertSummarizer); - bind("Tab", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => { const ref = state.selection; const range = ref.$from.blockRange(ref.$to); diff --git a/src/client/util/RichTextMenu.tsx b/src/client/util/RichTextMenu.tsx index 454afe3b7..e367cf350 100644 --- a/src/client/util/RichTextMenu.tsx +++ b/src/client/util/RichTextMenu.tsx @@ -154,8 +154,6 @@ export default class RichTextMenu extends AntimodeMenu { const activeFamilies = active && active.get("families"); const activeSizes = active && active.get("sizes"); - console.log("active families", activeFamilies); - console.log("other active families", this.activeFontFamilyOnSelection()); this.activeFontFamily = !activeFamilies || activeFamilies.length === 0 ? "Arial" : activeFamilies.length === 1 ? String(activeFamilies[0]) : "various"; this.activeFontSize = !activeSizes || activeSizes.length === 0 ? "13pt" : activeSizes.length === 1 ? String(activeSizes[0]) + "pt" : "various"; @@ -185,26 +183,10 @@ export default class RichTextMenu extends AntimodeMenu { } } - activeFontFamilyOnSelection() { - if (!this.view) return; - - //current selection - const state = this.view.state; - const activeFamilies: string[] = []; - const pos = this.view.state.selection.$from; - const ref_node: ProsNode | null = this.reference_node(pos); - if (ref_node && ref_node !== this.view.state.doc && ref_node.isText) { - ref_node.marks.forEach(m => m.type === state.schema.marks.pFontFamily && activeFamilies.push(m.attrs.family)); - } - return activeFamilies; - } - // finds font sizes and families in selection getActiveFontStylesOnSelection() { if (!this.view) return; - console.log("\nget active font styles"); - const activeFamilies: string[] = []; const activeSizes: string[] = []; const state = this.view.state; @@ -212,7 +194,6 @@ export default class RichTextMenu extends AntimodeMenu { const ref_node = this.reference_node(pos); if (ref_node && ref_node !== this.view.state.doc && ref_node.isText) { ref_node.marks.forEach(m => { - console.log("attribute", m.attrs); m.type === state.schema.marks.pFontFamily && activeFamilies.push(m.attrs.family); m.type === state.schema.marks.pFontSize && activeSizes.push(String(m.attrs.fontSize) + "pt"); }); diff --git a/src/client/util/RichTextRules.ts b/src/client/util/RichTextRules.ts index c980a8003..29b378299 100644 --- a/src/client/util/RichTextRules.ts +++ b/src/client/util/RichTextRules.ts @@ -233,19 +233,20 @@ export const inpRules = { new RegExp(/%\(/), (state, match, start, end) => { const node = (state.doc.resolve(start) as any).nodeAfter; - const sm = state.storedMarks || undefined; + const sm = state.storedMarks || []; const mark = state.schema.marks.summarizeInclusive.create(); + sm.push(mark); const selected = state.tr.setSelection(new TextSelection(state.doc.resolve(start), state.doc.resolve(end))).addMark(start, end, mark); const content = selected.selection.content(); - const replaced = node ? selected.replaceRangeWith(start, start, - schema.nodes.summary.create({ visibility: true, text: content, textslice: content.toJSON() })).setStoredMarks([...node.marks, ...(sm ? sm : [])]) : + const replaced = node ? selected.replaceRangeWith(start, end, + schema.nodes.summary.create({ visibility: true, text: content, textslice: content.toJSON() })) : state.tr; - return replaced.setSelection(new TextSelection(replaced.doc.resolve(end + 1))); + return replaced.setSelection(new TextSelection(replaced.doc.resolve(end + 1))).setStoredMarks([...node.marks, ...sm]); }), new InputRule( new RegExp(/%\)/), (state, match, start, end) => { - return state.tr.removeStoredMark(state.schema.marks.summarizeInclusive.create()); + return state.tr.deleteRange(start, end).removeStoredMark(state.schema.marks.summarizeInclusive.create()); }), new InputRule( new RegExp(/%f$/), diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index 2a5b348d2..ef90a7294 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -283,7 +283,7 @@ export const marks: { [index: string]: MarkSpec } = { inclusive: false, parseDOM: [{ tag: "a[href]", getAttrs(dom: any) { - return { href: dom.getAttribute("href"), location: dom.getAttribute("location"), title: dom.getAttribute("title") }; + return { href: dom.getAttribute("href"), location: dom.getAttribute("location"), title: dom.getAttribute("title"), targetId: dom.getAttribute("id") }; } }], toDOM(node: any) { diff --git a/src/client/util/TooltipTextMenu.scss b/src/client/util/TooltipTextMenu.scss index 8310a0da6..2a38fe118 100644 --- a/src/client/util/TooltipTextMenu.scss +++ b/src/client/util/TooltipTextMenu.scss @@ -149,7 +149,7 @@ } svg { - fill: white; + fill: inherit; width: 18px; height: 18px; } @@ -181,7 +181,7 @@ } } -#colorPicker { +.colorPicker { position: relative; svg { diff --git a/src/client/util/TooltipTextMenu.tsx b/src/client/util/TooltipTextMenu.tsx index 2c4d08b82..8177593c2 100644 --- a/src/client/util/TooltipTextMenu.tsx +++ b/src/client/util/TooltipTextMenu.tsx @@ -4,7 +4,6 @@ import { wrapInList } from 'prosemirror-schema-list'; import { EditorState, NodeSelection, TextSelection } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; import { Doc, Field, Opt } from "../../new_fields/Doc"; -import { Id } from "../../new_fields/FieldSymbols"; import { Utils } from "../../Utils"; import { DocServer } from "../DocServer"; import { FieldViewProps } from "../views/nodes/FieldView"; @@ -17,8 +16,7 @@ import { updateBullets } from './ProsemirrorExampleTransfer'; import { DocumentDecorations } from '../views/DocumentDecorations'; import { SelectionManager } from './SelectionManager'; import { PastelSchemaPalette, DarkPastelSchemaPalette } from '../../new_fields/SchemaHeaderField'; -const { toggleMark, setBlockType } = require("prosemirror-commands"); -const { openPrompt, TextField } = require("./ProsemirrorCopy/prompt.js"); +const { toggleMark } = require("prosemirror-commands"); // deprecated in favor of richtextmenu @@ -32,10 +30,7 @@ export class TooltipTextMenu { private fontStyles: Mark[] = []; private fontSizes: Mark[] = []; - private listTypes: (NodeType | any)[] = []; - private listTypeToIcon: Map<NodeType | any, string> = new Map(); - private _activeMarks: Mark[] = []; - private _marksToDoms: Map<Mark, HTMLSpanElement> = new Map(); + private _marksToDoms: Map<MarkType, HTMLSpanElement> = new Map(); private _collapsed: boolean = false; // editor doms @@ -45,19 +40,18 @@ export class TooltipTextMenu { // editor button doms private colorDom?: Node; private colorDropdownDom?: Node; + private linkDom?: Node; private highighterDom?: Node; private highlighterDropdownDom?: Node; - private linkEditor?: HTMLDivElement; - private linkDrag?: HTMLImageElement; - private _linkDropdownDom?: Node; + private linkDropdownDom?: Node; private _brushdom?: Node; private _brushDropdownDom?: Node; private fontSizeDom?: Node; private fontStyleDom?: Node; - private listTypeBtnDom?: Node; private basicTools?: HTMLElement; - + static createDiv(className: string) { const div = document.createElement("div"); div.className = className; return div; } + static createSpan(className: string) { const div = document.createElement("span"); div.className = className; return div; } constructor(view: EditorView) { this.view = view; @@ -65,59 +59,55 @@ export class TooltipTextMenu { this.initTooltip(view); // initialize the wrapper - this.wrapper = document.createElement("div"); - this.wrapper.className = "wrapper"; + this.wrapper = TooltipTextMenu.createDiv("wrapper"); this.wrapper.appendChild(this.tooltip); - // initialize the dragger -- appends it to the wrapper - this.createDragger(); - TooltipTextMenu.Toolbar = this.wrapper; } private async initTooltip(view: EditorView) { - // initialize tooltip dom - this.tooltip = document.createElement("div"); - this.tooltip.className = "tooltipMenu"; - this.basicTools = document.createElement("div"); - this.basicTools.className = "basic-tools"; - - // init buttons to the tooltip -- paths to svgs are obtained from fontawesome - const items = [ - { command: toggleMark(schema.marks.strong), dom: this.svgIcon("strong", "Bold", "M333.49 238a122 122 0 0 0 27-65.21C367.87 96.49 308 32 233.42 32H34a16 16 0 0 0-16 16v48a16 16 0 0 0 16 16h31.87v288H34a16 16 0 0 0-16 16v48a16 16 0 0 0 16 16h209.32c70.8 0 134.14-51.75 141-122.4 4.74-48.45-16.39-92.06-50.83-119.6zM145.66 112h87.76a48 48 0 0 1 0 96h-87.76zm87.76 288h-87.76V288h87.76a56 56 0 0 1 0 112z") }, - { command: toggleMark(schema.marks.em), dom: this.svgIcon("em", "Italic", "M320 48v32a16 16 0 0 1-16 16h-62.76l-80 320H208a16 16 0 0 1 16 16v32a16 16 0 0 1-16 16H16a16 16 0 0 1-16-16v-32a16 16 0 0 1 16-16h62.76l80-320H112a16 16 0 0 1-16-16V48a16 16 0 0 1 16-16h192a16 16 0 0 1 16 16z") }, - { command: toggleMark(schema.marks.underline), dom: this.svgIcon("underline", "Underline", "M32 64h32v160c0 88.22 71.78 160 160 160s160-71.78 160-160V64h32a16 16 0 0 0 16-16V16a16 16 0 0 0-16-16H272a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h32v160a80 80 0 0 1-160 0V64h32a16 16 0 0 0 16-16V16a16 16 0 0 0-16-16H32a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16zm400 384H16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16z") }, - { command: toggleMark(schema.marks.strikethrough), dom: this.svgIcon("strikethrough", "Strikethrough", "M496 224H293.9l-87.17-26.83A43.55 43.55 0 0 1 219.55 112h66.79A49.89 49.89 0 0 1 331 139.58a16 16 0 0 0 21.46 7.15l42.94-21.47a16 16 0 0 0 7.16-21.46l-.53-1A128 128 0 0 0 287.51 32h-68a123.68 123.68 0 0 0-123 135.64c2 20.89 10.1 39.83 21.78 56.36H16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h480a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zm-180.24 96A43 43 0 0 1 336 356.45 43.59 43.59 0 0 1 292.45 400h-66.79A49.89 49.89 0 0 1 181 372.42a16 16 0 0 0-21.46-7.15l-42.94 21.47a16 16 0 0 0-7.16 21.46l.53 1A128 128 0 0 0 224.49 480h68a123.68 123.68 0 0 0 123-135.64 114.25 114.25 0 0 0-5.34-24.36z") }, - { command: toggleMark(schema.marks.superscript), dom: this.svgIcon("superscript", "Superscript", "M496 160h-16V16a16 16 0 0 0-16-16h-48a16 16 0 0 0-14.29 8.83l-16 32A16 16 0 0 0 400 64h16v96h-16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h96a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zM336 64h-67a16 16 0 0 0-13.14 6.87l-79.9 115-79.9-115A16 16 0 0 0 83 64H16A16 16 0 0 0 0 80v48a16 16 0 0 0 16 16h33.48l77.81 112-77.81 112H16a16 16 0 0 0-16 16v48a16 16 0 0 0 16 16h67a16 16 0 0 0 13.14-6.87l79.9-115 79.9 115A16 16 0 0 0 269 448h67a16 16 0 0 0 16-16v-48a16 16 0 0 0-16-16h-33.48l-77.81-112 77.81-112H336a16 16 0 0 0 16-16V80a16 16 0 0 0-16-16z") }, - { command: toggleMark(schema.marks.subscript), dom: this.svgIcon("subscript", "Subscript", "M496 448h-16V304a16 16 0 0 0-16-16h-48a16 16 0 0 0-14.29 8.83l-16 32A16 16 0 0 0 400 352h16v96h-16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h96a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zM336 64h-67a16 16 0 0 0-13.14 6.87l-79.9 115-79.9-115A16 16 0 0 0 83 64H16A16 16 0 0 0 0 80v48a16 16 0 0 0 16 16h33.48l77.81 112-77.81 112H16a16 16 0 0 0-16 16v48a16 16 0 0 0 16 16h67a16 16 0 0 0 13.14-6.87l79.9-115 79.9 115A16 16 0 0 0 269 448h67a16 16 0 0 0 16-16v-48a16 16 0 0 0-16-16h-33.48l-77.81-112 77.81-112H336a16 16 0 0 0 16-16V80a16 16 0 0 0-16-16z") }, + const self = this; + this.tooltip = TooltipTextMenu.createDiv("tooltipMenu"); + this.basicTools = TooltipTextMenu.createDiv("basic-tools"); + + const svgIcon = (name: string, title: string = name, dpath: string) => { + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("viewBox", "-100 -100 650 650"); + const path = document.createElementNS('http://www.w3.org/2000/svg', "path"); + path.setAttributeNS(null, "d", dpath); + svg.appendChild(path); + + const span = TooltipTextMenu.createSpan(name + " menuicon"); + span.title = title; + span.appendChild(svg); + + return span; + }; + + const basicItems = [ // init basicItems in minimized toolbar -- paths to svgs are obtained from fontawesome + { mark: schema.marks.strong, dom: svgIcon("strong", "Bold", "M333.49 238a122 122 0 0 0 27-65.21C367.87 96.49 308 32 233.42 32H34a16 16 0 0 0-16 16v48a16 16 0 0 0 16 16h31.87v288H34a16 16 0 0 0-16 16v48a16 16 0 0 0 16 16h209.32c70.8 0 134.14-51.75 141-122.4 4.74-48.45-16.39-92.06-50.83-119.6zM145.66 112h87.76a48 48 0 0 1 0 96h-87.76zm87.76 288h-87.76V288h87.76a56 56 0 0 1 0 112z") }, + { mark: schema.marks.em, dom: svgIcon("em", "Italic", "M320 48v32a16 16 0 0 1-16 16h-62.76l-80 320H208a16 16 0 0 1 16 16v32a16 16 0 0 1-16 16H16a16 16 0 0 1-16-16v-32a16 16 0 0 1 16-16h62.76l80-320H112a16 16 0 0 1-16-16V48a16 16 0 0 1 16-16h192a16 16 0 0 1 16 16z") }, + { mark: schema.marks.underline, dom: svgIcon("underline", "Underline", "M32 64h32v160c0 88.22 71.78 160 160 160s160-71.78 160-160V64h32a16 16 0 0 0 16-16V16a16 16 0 0 0-16-16H272a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h32v160a80 80 0 0 1-160 0V64h32a16 16 0 0 0 16-16V16a16 16 0 0 0-16-16H32a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16zm400 384H16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h416a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16z") }, + ]; + const items = [ // init items in full size toolbar + { mark: schema.marks.strikethrough, dom: svgIcon("strikethrough", "Strikethrough", "M496 224H293.9l-87.17-26.83A43.55 43.55 0 0 1 219.55 112h66.79A49.89 49.89 0 0 1 331 139.58a16 16 0 0 0 21.46 7.15l42.94-21.47a16 16 0 0 0 7.16-21.46l-.53-1A128 128 0 0 0 287.51 32h-68a123.68 123.68 0 0 0-123 135.64c2 20.89 10.1 39.83 21.78 56.36H16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h480a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zm-180.24 96A43 43 0 0 1 336 356.45 43.59 43.59 0 0 1 292.45 400h-66.79A49.89 49.89 0 0 1 181 372.42a16 16 0 0 0-21.46-7.15l-42.94 21.47a16 16 0 0 0-7.16 21.46l.53 1A128 128 0 0 0 224.49 480h68a123.68 123.68 0 0 0 123-135.64 114.25 114.25 0 0 0-5.34-24.36z") }, + { mark: schema.marks.superscript, dom: svgIcon("superscript", "Superscript", "M496 160h-16V16a16 16 0 0 0-16-16h-48a16 16 0 0 0-14.29 8.83l-16 32A16 16 0 0 0 400 64h16v96h-16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h96a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zM336 64h-67a16 16 0 0 0-13.14 6.87l-79.9 115-79.9-115A16 16 0 0 0 83 64H16A16 16 0 0 0 0 80v48a16 16 0 0 0 16 16h33.48l77.81 112-77.81 112H16a16 16 0 0 0-16 16v48a16 16 0 0 0 16 16h67a16 16 0 0 0 13.14-6.87l79.9-115 79.9 115A16 16 0 0 0 269 448h67a16 16 0 0 0 16-16v-48a16 16 0 0 0-16-16h-33.48l-77.81-112 77.81-112H336a16 16 0 0 0 16-16V80a16 16 0 0 0-16-16z") }, + { mark: schema.marks.subscript, dom: svgIcon("subscript", "Subscript", "M496 448h-16V304a16 16 0 0 0-16-16h-48a16 16 0 0 0-14.29 8.83l-16 32A16 16 0 0 0 400 352h16v96h-16a16 16 0 0 0-16 16v32a16 16 0 0 0 16 16h96a16 16 0 0 0 16-16v-32a16 16 0 0 0-16-16zM336 64h-67a16 16 0 0 0-13.14 6.87l-79.9 115-79.9-115A16 16 0 0 0 83 64H16A16 16 0 0 0 0 80v48a16 16 0 0 0 16 16h33.48l77.81 112-77.81 112H16a16 16 0 0 0-16 16v48a16 16 0 0 0 16 16h67a16 16 0 0 0 13.14-6.87l79.9-115 79.9 115A16 16 0 0 0 269 448h67a16 16 0 0 0 16-16v-48a16 16 0 0 0-16-16h-33.48l-77.81-112 77.81-112H336a16 16 0 0 0 16-16V80a16 16 0 0 0-16-16z") }, ]; - // add menu items - this._marksToDoms = new Map(); - items.forEach(({ dom, command }) => { + basicItems.map(({ dom, mark }) => this.basicTools?.appendChild(dom.cloneNode(true))); + basicItems.concat(items).forEach(({ dom, mark }) => { this.tooltip.appendChild(dom); - switch (dom.title) { - case "Bold": - this._marksToDoms.set(schema.mark(schema.marks.strong), dom); - this.basicTools && this.basicTools.appendChild(dom.cloneNode(true)); - break; - case "Italic": - this._marksToDoms.set(schema.mark(schema.marks.em), dom); - this.basicTools && this.basicTools.appendChild(dom.cloneNode(true)); - break; - case "Underline": - this._marksToDoms.set(schema.mark(schema.marks.underline), dom); - this.basicTools && this.basicTools.appendChild(dom.cloneNode(true)); - break; - } + this._marksToDoms.set(mark, dom); //pointer down handler to activate button effects dom.addEventListener("pointerdown", e => { - e.preventDefault(); this.view.focus(); if (dom.contains(e.target as Node)) { + e.preventDefault(); e.stopPropagation(); - command(this.view.state, this.view.dispatch, this.view); + toggleMark(mark)(this.view.state, this.view.dispatch, this.view); + this.updateHighlightStateOfButtons(); } }); }); @@ -135,46 +125,12 @@ export class TooltipTextMenu { this.tooltip.appendChild(this.colorDropdownDom); // link menu - this.updateLinkMenu(); - const dropdown = await this.createLinkDropdown(); - this._linkDropdownDom = dropdown.render(this.view).dom; - this.tooltip.appendChild(this._linkDropdownDom); + this.linkDom = this.createLinkTool().render(this.view).dom; + this.linkDropdownDom = this.createLinkDropdown("").render(this.view).dom; + this.tooltip.appendChild(this.linkDom); + this.tooltip.appendChild(this.linkDropdownDom); // list of font styles - this.initFontStyles(); - - // font sizes - this.initFontSizes(); - - // list types - this.initListTypes(); - - // init brush tool - this._brushdom = this.createBrush().render(this.view).dom; - this.tooltip.appendChild(this._brushdom); - this._brushDropdownDom = this.createBrushDropdown().render(this.view).dom; - this.tooltip.appendChild(this._brushDropdownDom); - - // star - this.tooltip.appendChild(this.createSummarizer().render(this.view).dom); - - // list types dropdown - this.updateListItemDropdown(":", this.listTypeBtnDom); - - await this.updateFromDash(view, undefined, undefined); - } - - initFontStyles() { - this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Times New Roman" })); - this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Arial" })); - this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Georgia" })); - this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Comic Sans MS" })); - this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Tahoma" })); - this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Impact" })); - this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Crimson Text" })); - } - - initFontSizes() { this.fontSizes.push(schema.marks.pFontSize.create({ fontSize: 7 })); this.fontSizes.push(schema.marks.pFontSize.create({ fontSize: 8 })); this.fontSizes.push(schema.marks.pFontSize.create({ fontSize: 9 })); @@ -188,56 +144,89 @@ export class TooltipTextMenu { this.fontSizes.push(schema.marks.pFontSize.create({ fontSize: 32 })); this.fontSizes.push(schema.marks.pFontSize.create({ fontSize: 48 })); this.fontSizes.push(schema.marks.pFontSize.create({ fontSize: 72 })); - } - initListTypes() { - this.listTypeToIcon = new Map(); - //this.listTypeToIcon.set(schema.nodes.bullet_list, ":"); - this.listTypeToIcon.set(schema.nodes.ordered_list.create({ mapStyle: "bullet" }), ":"); - this.listTypeToIcon.set(schema.nodes.ordered_list.create({ mapStyle: "decimal" }), "1.1)"); - this.listTypeToIcon.set(schema.nodes.ordered_list.create({ mapStyle: "multi" }), "1.A)"); - // this.listTypeToIcon.set(schema.nodes.bullet_list, "⬜"); - this.listTypes = Array.from(this.listTypeToIcon.keys()); - } + // font sizes + this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Times New Roman" })); + this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Arial" })); + this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Georgia" })); + this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Comic Sans MS" })); + this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Tahoma" })); + this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Impact" })); + this.fontStyles.push(schema.marks.pFontFamily.create({ family: "Crimson Text" })); - // creates dragger element that allows dragging and collapsing (on double click) - // of editor and appends it to the wrapper - createDragger() { - const draggerWrapper = document.createElement("div"); - draggerWrapper.className = "dragger-wrapper"; - const dragger = document.createElement("div"); - dragger.className = "dragger"; + // init brush tool + this._brushdom = this.createBrushTool().render(this.view).dom; + this.tooltip.appendChild(this._brushdom); + this._brushDropdownDom = this.createBrushDropdown().render(this.view).dom; + this.tooltip.appendChild(this._brushDropdownDom); + + // summarizer tool + const summarizer = new MenuItem({ + title: "Summarize", + label: "Summarize", + icon: icons.join, + css: "fill:white;", + class: "menuicon", + execEvent: "", + run: (state, dispatch) => TooltipTextMenu.insertSummarizer(state, dispatch) + }); + this.tooltip.appendChild(summarizer.render(this.view).dom); - const line1 = document.createElement("span"); - line1.className = "dragger-line"; - const line2 = document.createElement("span"); - line2.className = "dragger-line"; - const line3 = document.createElement("span"); - line3.className = "dragger-line"; + // list types dropdown + const listDropdownTypes = [{ mapStyle: "bullet", label: ":" }, { mapStyle: "decimal", label: "1.1" }, { mapStyle: "multi", label: "A.1" }, { label: "X" }]; + const listTypes = new Dropdown(listDropdownTypes.map(({ mapStyle, label }) => + new MenuItem({ + title: "Set Bullet Style", + label: label, + execEvent: "", + class: "dropdown-item", + css: "color: black; width: 40px;", + enable() { return true; }, + run() { + const marks = self.view.state.storedMarks || (view.state.selection.$to.parentOffset && view.state.selection.$from.marks()); + if (!wrapInList(schema.nodes.ordered_list)(view.state, (tx2: any) => { + const tx3 = updateBullets(tx2, schema, mapStyle); + marks && tx3.ensureMarks([...marks]); + marks && tx3.setStoredMarks([...marks]); + + view.dispatch(tx2); + })) { + const tx2 = view.state.tr; + const tx3 = updateBullets(tx2, schema, mapStyle); + marks && tx3.ensureMarks([...marks]); + marks && tx3.setStoredMarks([...marks]); + + view.dispatch(tx3); + } + } + })), { label: ":", css: "color:black; width: 40px;" }); + this.tooltip.appendChild(listTypes.render(this.view).dom); - dragger.appendChild(line1); - dragger.appendChild(line2); - dragger.appendChild(line3); + await this.updateFromDash(view, undefined, undefined); + const draggerWrapper = TooltipTextMenu.createDiv("dragger-wrapper"); + const dragger = TooltipTextMenu.createDiv("dragger"); + dragger.appendChild(TooltipTextMenu.createSpan("dragger-line")); + dragger.appendChild(TooltipTextMenu.createSpan("dragger-line")); + dragger.appendChild(TooltipTextMenu.createSpan("dragger-line")); draggerWrapper.appendChild(dragger); - this.wrapper.appendChild(draggerWrapper); - this.dragElement(draggerWrapper); + this.setupDragElementInteractions(draggerWrapper); } - dragElement(elmnt: HTMLElement) { + setupDragElementInteractions(elmnt: HTMLElement) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (elmnt) { // if present, the header is where you move the DIV from: - elmnt.onpointerdown = dragMouseDown; + elmnt.onpointerdown = dragPointerDown; elmnt.ondblclick = onClick; } const self = this; - function dragMouseDown(e: PointerEvent) { + function dragPointerDown(e: PointerEvent) { e = e || window.event; - //e.preventDefault(); + e.preventDefault(); // get the mouse cursor position at startup: pos3 = e.clientX; pos4 = e.clientY; @@ -286,9 +275,28 @@ export class TooltipTextMenu { updateFontSizeDropdown(label: string) { //font SIZES const fontSizeBtns: MenuItem[] = []; - this.fontSizes.forEach(mark => { - fontSizeBtns.push(this.dropdownFontSizeBtn(String(mark.attrs.fontSize), "color: black; width: 50px;", mark, this.view, this.changeToFontSize)); - }); + const self = this; + this.fontSizes.forEach(mark => + fontSizeBtns.push(new MenuItem({ + title: "Set Font Size", + label: String(mark.attrs.fontSize), + execEvent: "", + class: "dropdown-item", + css: "color: black; width: 50px;", + enable() { return true; }, + run() { + const size = mark.attrs.fontSize; + if (size) { self.updateFontSizeDropdown(String(size) + " pt"); } + if (self.editorProps) { + const ruleProvider = self.editorProps.ruleProvider; + const heading = NumCast(self.editorProps.Document.heading); + if (ruleProvider && heading) { + ruleProvider["ruleSize_" + heading] = size; + } + } + TooltipTextMenu.setMark(self.view.state.schema.marks.pFontSize.create({ fontSize: size }), self.view.state, self.view.dispatch); + } + }))); const newfontSizeDom = (new Dropdown(fontSizeBtns, { label: label, css: "color:black; min-width: 60px;" }) as MenuItem).render(this.view).dom; if (this.fontSizeDom) { @@ -304,9 +312,28 @@ export class TooltipTextMenu { updateFontStyleDropdown(label: string) { //font STYLES const fontBtns: MenuItem[] = []; - this.fontStyles.forEach((mark) => { - fontBtns.push(this.dropdownFontFamilyBtn(mark.attrs.family, "color: black; font-family: " + mark.attrs.family + ", sans-serif; width: 125px;", mark, this.view, this.changeToFontFamily)); - }); + const self = this; + this.fontStyles.forEach(mark => + fontBtns.push(new MenuItem({ + title: "Set Font Family", + label: mark.attrs.family, + execEvent: "", + class: "dropdown-item", + css: "color: black; font-family: " + mark.attrs.family + ", sans-serif; width: 125px;", + enable() { return true; }, + run() { + const fontName = mark.attrs.family; + if (fontName) { self.updateFontStyleDropdown(fontName); } + if (self.editorProps) { + const ruleProvider = self.editorProps.ruleProvider; + const heading = NumCast(self.editorProps.Document.heading); + if (ruleProvider && heading) { + ruleProvider["ruleFont_" + heading] = fontName; + } + } + TooltipTextMenu.setMark(self.view.state.schema.marks.pFontFamily.create({ family: fontName }), self.view.state, self.view.dispatch); + } + }))); const newfontStyleDom = (new Dropdown(fontBtns, { label: label, css: "color:black; width: 125px;" }) as MenuItem).render(this.view).dom; if (this.fontStyleDom) { @@ -317,20 +344,6 @@ export class TooltipTextMenu { } this.fontStyleDom = newfontStyleDom; } - - updateLinkMenu() { - this.linkEditor = document.createElement("div"); - this.linkEditor.className = "ProseMirror-icon menuicon"; - this.linkDrag = document.createElement("img"); - this.linkDrag.src = "https://seogurusnyc.com/wp-content/uploads/2016/12/link-1.png"; - this.linkDrag.style.width = "15px"; - this.linkDrag.style.height = "15px"; - this.linkDrag.title = "Click to set link target"; - this.linkDrag.id = "link-btn"; - this.linkEditor.appendChild(this.linkDrag); - this.tooltip.appendChild(this.linkEditor); - } - async getTextLinkTargetTitle() { const node = this.view.state.selection.$from.nodeAfter; const link = node && node.marks.find(m => m.type.name === "link"); @@ -364,8 +377,21 @@ export class TooltipTextMenu { } } - async createLinkDropdown() { - const targetTitle = await this.getTextLinkTargetTitle(); + // LINK TOOL + createLinkTool(active: boolean = false) { + return new MenuItem({ + title: "Link tool", + label: "Link tool", + icon: icons.link, + css: "fill:white;", + class: active ? "menuicon-active" : "menuicon", + execEvent: "", + run: async (state, dispatch) => { }, + active: (state) => true + }); + } + + createLinkDropdown(targetTitle: string) { const input = document.createElement("input"); // menu item for input for hyperlink url @@ -409,9 +435,22 @@ export class TooltipTextMenu { return button; }, enable() { return false; }, - run: (state, dispatch, view, event) => { + run: async (state, dispatch, view, event) => { event.stopPropagation(); - this.makeLinkToURL(input.value, "onRight"); + let node = this.view.state.selection.$from.nodeAfter; + let link = this.view.state.schema.mark(this.view.state.schema.marks.link, { href: input.value, location: "onRight" }); + this.view.dispatch(this.view.state.tr.removeMark(this.view.state.selection.from, this.view.state.selection.to, this.view.state.schema.marks.link)); + this.view.dispatch(this.view.state.tr.addMark(this.view.state.selection.from, this.view.state.selection.to, link)); + node = this.view.state.selection.$from.nodeAfter; + link = node && node.marks.find(m => m.type.name === "link"); + + // update link menu + const linkDom = self.createLinkTool(true).render(self.view).dom; + const linkDropdownDom = self.createLinkDropdown(await self.getTextLinkTargetTitle()).render(self.view).dom; + self.linkDom && self.tooltip.replaceChild(linkDom, self.linkDom); + self.linkDropdownDom && self.tooltip.replaceChild(linkDropdownDom, self.linkDropdownDom); + self.linkDom = linkDom; + self.linkDropdownDom = linkDropdownDom; } }); @@ -433,155 +472,55 @@ export class TooltipTextMenu { }, enable() { return true; }, async run() { - self.deleteLink(); - // update link dropdown - const dropdown = await self.createLinkDropdown(); - const newLinkDropdowndom = dropdown.render(self.view).dom; - self._linkDropdownDom && self.tooltip.replaceChild(newLinkDropdowndom, self._linkDropdownDom); - self._linkDropdownDom = newLinkDropdowndom; - } - }); - - - const linkDropdown = new Dropdown(targetTitle ? [linkInfo, linkApply, deleteLink] : [linkInfo, linkApply], { class: "buttonSettings-dropdown" }) as MenuItem; - return linkDropdown; - } - - // makeLinkWithState = (state: EditorState, target: string, location: string) => { - // let link = state.schema.mark(state.schema.marks.link, { href: target, location: location }); - // } - - makeLink = (linkDocId: string, title: string, location: string, targetDocId: string): string => { - const link = this.view.state.schema.marks.link.create({ href: Utils.prepend("/doc/" + linkDocId), title: title, location: location, targetId: targetDocId }); - this.view.dispatch(this.view.state.tr.removeMark(this.view.state.selection.from, this.view.state.selection.to, this.view.state.schema.marks.link). - addMark(this.view.state.selection.from, this.view.state.selection.to, link)); - const node = this.view.state.selection.$from.nodeAfter; - if (node && node.text) { - return node.text; - } - return ""; - } - - makeLinkToURL = (target: String, lcoation: string) => { - let node = this.view.state.selection.$from.nodeAfter; - let link = this.view.state.schema.mark(this.view.state.schema.marks.link, { href: target, location: location }); - this.view.dispatch(this.view.state.tr.removeMark(this.view.state.selection.from, this.view.state.selection.to, this.view.state.schema.marks.link)); - this.view.dispatch(this.view.state.tr.addMark(this.view.state.selection.from, this.view.state.selection.to, link)); - node = this.view.state.selection.$from.nodeAfter; - link = node && node.marks.find(m => m.type.name === "link"); - } - - deleteLink = () => { - const node = this.view.state.selection.$from.nodeAfter; - const link = node && node.marks.find(m => m.type === this.view.state.schema.marks.link); - const href = link!.attrs.href; - if (href) { - if (href.indexOf(Utils.prepend("/doc/")) === 0) { - const linkclicked = href.replace(Utils.prepend("/doc/"), "").split("?")[0]; - if (linkclicked) { - DocServer.GetRefField(linkclicked).then(async linkDoc => { + // delete the link + const node = self.view.state.selection.$from.nodeAfter; + const link = node && node.marks.find(m => m.type === self.view.state.schema.marks.link); + const href = link!.attrs.href; + if (href?.indexOf(Utils.prepend("/doc/")) === 0) { + const linkclicked = href.replace(Utils.prepend("/doc/"), "").split("?")[0]; + linkclicked && DocServer.GetRefField(linkclicked).then(async linkDoc => { if (linkDoc instanceof Doc) { LinkManager.Instance.deleteLink(linkDoc); - this.view.dispatch(this.view.state.tr.removeMark(this.view.state.selection.from, this.view.state.selection.to, this.view.state.schema.marks.link)); + self.view.dispatch(self.view.state.tr.removeMark(self.view.state.selection.from, self.view.state.selection.to, self.view.state.schema.marks.link)); } }); } + // update link menu + const linkDom = self.createLinkTool(false).render(self.view).dom; + const linkDropdownDom = self.createLinkDropdown("").render(self.view).dom; + self.linkDom && self.tooltip.replaceChild(linkDom, self.linkDom); + self.linkDropdownDom && self.tooltip.replaceChild(linkDropdownDom, self.linkDropdownDom); + self.linkDom = linkDom; + self.linkDropdownDom = linkDropdownDom; } - } - } - - createLink() { - const markType = schema.marks.link; - return new MenuItem({ - title: "Add or remove link", - label: "Add or remove link", - execEvent: "", - icon: icons.link, - css: "color:white;", - class: "menuicon", - enable(state) { return !state.selection.empty; }, - run: (state, dispatch, view) => { - // to remove link - let curLink = ""; - if (this.markActive(state, markType)) { - - const { from, $from, to, empty } = state.selection; - const node = state.doc.nodeAt(from); - node && node.marks.map(m => { - m.type === markType && (curLink = m.attrs.href); - }); - //toggleMark(markType)(state, dispatch); - //return true; - } - // to create link - openPrompt({ - title: "Create a link", - fields: { - href: new TextField({ - value: curLink, - label: "Link Target", - required: true - }), - title: new TextField({ label: "Title" }) - }, - callback(attrs: any) { - toggleMark(markType, attrs)(view.state, view.dispatch); - view.focus(); - }, - flyout_top: 0, - flyout_left: 0 - }); - } - }); - } - - //will display a remove-list-type button if selection is in list, otherwise will show list type dropdown - updateListItemDropdown(label: string, listTypeBtn: any) { - //remove old btn - if (listTypeBtn) { this.tooltip.removeChild(listTypeBtn); } - - //Make a dropdown of all list types - const toAdd: MenuItem[] = []; - this.listTypeToIcon.forEach((icon, type) => { - toAdd.push(this.dropdownBulletBtn(icon, "color: black; width: 40px;", type, this.view, this.listTypes, this.changeBulletType)); }); - //option to remove the list formatting - toAdd.push(this.dropdownBulletBtn("X", "color: black; width: 40px;", undefined, this.view, this.listTypes, this.changeBulletType)); - listTypeBtn = (new Dropdown(toAdd, { label: label, css: "color:black; width: 40px;" }) as MenuItem).render(this.view).dom; - - //add this new button and return it - this.tooltip.appendChild(listTypeBtn); - return listTypeBtn; + return new Dropdown(targetTitle ? [linkInfo, linkApply, deleteLink] : [linkInfo, linkApply], { class: "buttonSettings-dropdown" }) as MenuItem; } - createSummarizer() { - return new MenuItem({ - title: "Summarize", - label: "Summarize", - icon: icons.join, - css: "color:white;", - class: "menuicon", - execEvent: "", - run: (state, dispatch) => TooltipTextMenu.insertSummarizer(state, dispatch) - }); + public MakeLinkToSelection = (linkDocId: string, title: string, location: string, targetDocId: string): string => { + const link = this.view.state.schema.marks.link.create({ href: Utils.prepend("/doc/" + linkDocId), title: title, location: location, targetId: targetDocId }); + this.view.dispatch(this.view.state.tr.removeMark(this.view.state.selection.from, this.view.state.selection.to, this.view.state.schema.marks.link). + addMark(this.view.state.selection.from, this.view.state.selection.to, link)); + return this.view.state.selection.$from.nodeAfter?.text || ""; } - public static insertSummarizer(state: EditorState<any>, dispatch: any) { - if (state.selection.empty) return false; - const mark = state.schema.marks.summarize.create(); - const tr = state.tr; - tr.addMark(state.selection.from, state.selection.to, mark); - const content = tr.selection.content(); - const newNode = state.schema.nodes.summary.create({ visibility: false, text: content, textslice: content.toJSON() }); - dispatch && dispatch(tr.replaceSelectionWith(newNode).removeMark(tr.selection.from - 1, tr.selection.from, mark)); - return true; + // SUMMARIZER TOOL + static insertSummarizer(state: EditorState<any>, dispatch: any) { + if (!state.selection.empty) { + const mark = state.schema.marks.summarize.create(); + const tr = state.tr.addMark(state.selection.from, state.selection.to, mark); + const content = tr.selection.content(); + const newNode = state.schema.nodes.summary.create({ visibility: false, text: content, textslice: content.toJSON() }); + dispatch?.(tr.replaceSelectionWith(newNode).removeMark(tr.selection.from - 1, tr.selection.from, mark)); + } } + // HIGHLIGHTER TOOL createHighlightTool() { return new MenuItem({ title: "Highlight", - css: "color:white;", + css: "fill:white;", class: "menuicon", execEvent: "", render() { @@ -591,12 +530,10 @@ export class TooltipTextMenu { path.setAttributeNS(null, "d", "M0 479.98L99.92 512l35.45-35.45-67.04-67.04L0 479.98zm124.61-240.01a36.592 36.592 0 0 0-10.79 38.1l13.05 42.83-50.93 50.94 96.23 96.23 50.86-50.86 42.74 13.08c13.73 4.2 28.65-.01 38.15-10.78l35.55-41.64-173.34-173.34-41.52 35.44zm403.31-160.7l-63.2-63.2c-20.49-20.49-53.38-21.52-75.12-2.35L190.55 183.68l169.77 169.78L530.27 154.4c19.18-21.74 18.15-54.63-2.35-75.13z"); svg.appendChild(path); - const color = document.createElement("div"); - color.className = "buttonColor"; + const color = TooltipTextMenu.createDiv("buttonColor"); color.style.backgroundColor = TooltipTextMenuManager.Instance.highlighter.toString(); - const wrapper = document.createElement("div"); - wrapper.id = "colorPicker"; + const wrapper = TooltipTextMenu.createDiv("colorPicker"); wrapper.appendChild(svg); wrapper.appendChild(color); return wrapper; @@ -605,10 +542,10 @@ export class TooltipTextMenu { }); } - public static insertHighlight(color: String, state: EditorState<any>, dispatch: any) { - if (state.selection.empty) return false; - - toggleMark(state.schema.marks.marker, { highlight: color })(state, dispatch); + static insertHighlight(color: String, state: EditorState<any>, dispatch: any) { + if (!state.selection.empty) { + toggleMark(state.schema.marks.marker, { highlight: color })(state, dispatch); + } } createHighlightDropdown() { @@ -623,8 +560,7 @@ export class TooltipTextMenu { const p = document.createElement("p"); p.textContent = "Change highlight:"; - const colorsWrapper = document.createElement("div"); - colorsWrapper.className = "colorPicker-wrapper"; + const colorsWrapper = TooltipTextMenu.createDiv("colorPicker-wrapper"); const colors = [ PastelSchemaPalette.get("pink2"), @@ -673,14 +609,14 @@ export class TooltipTextMenu { } }); - const colorDropdown = new Dropdown([colors], { class: "buttonSettings-dropdown" }) as MenuItem; - return colorDropdown; + return new Dropdown([colors], { class: "buttonSettings-dropdown" }) as MenuItem; } + // COLOR TOOL createColorTool() { return new MenuItem({ title: "Color", - css: "color:white;", + css: "fill:white;", class: "menuicon", execEvent: "", render() { @@ -690,27 +626,25 @@ export class TooltipTextMenu { path.setAttributeNS(null, "d", "M204.3 5C104.9 24.4 24.8 104.3 5.2 203.4c-37 187 131.7 326.4 258.8 306.7 41.2-6.4 61.4-54.6 42.5-91.7-23.1-45.4 9.9-98.4 60.9-98.4h79.7c35.8 0 64.8-29.6 64.9-65.3C511.5 97.1 368.1-26.9 204.3 5zM96 320c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm32-128c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128-64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128 64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32z"); svg.appendChild(path); - const color = document.createElement("div"); - color.className = "buttonColor"; + const color = TooltipTextMenu.createDiv("buttonColor"); color.style.backgroundColor = TooltipTextMenuManager.Instance.color.toString(); - const wrapper = document.createElement("div"); - wrapper.id = "colorPicker"; + const wrapper = TooltipTextMenu.createDiv("colorPicker"); wrapper.appendChild(svg); wrapper.appendChild(color); return wrapper; }, - run: (state, dispatch) => this.insertColor(TooltipTextMenuManager.Instance.color, state, dispatch) + run: (state, dispatch) => TooltipTextMenu.insertColor(TooltipTextMenuManager.Instance.color, state, dispatch) }); } - public insertColor(color: String, state: EditorState<any>, dispatch: any) { + static insertColor(color: String, state: EditorState<any>, dispatch: any) { const colorMark = state.schema.mark(state.schema.marks.pFontColor, { color: color }); if (state.selection.empty) { dispatch(state.tr.addStoredMark(colorMark)); - return false; + } else { + this.setMark(colorMark, state, dispatch); } - this.setMark(colorMark, state, dispatch); } createColorDropdown() { @@ -725,8 +659,7 @@ export class TooltipTextMenu { const p = document.createElement("p"); p.textContent = "Change color:"; - const colorsWrapper = document.createElement("div"); - colorsWrapper.className = "colorPicker-wrapper"; + const colorsWrapper = TooltipTextMenu.createDiv("colorPicker-wrapper"); const colors = [ DarkPastelSchemaPalette.get("pink2"), @@ -749,7 +682,7 @@ export class TooltipTextMenu { button.onclick = e => { TooltipTextMenuManager.Instance.color = color; - self.insertColor(TooltipTextMenuManager.Instance.color, self.view.state, self.view.dispatch); + TooltipTextMenu.insertColor(TooltipTextMenuManager.Instance.color, self.view.state, self.view.dispatch); // update color menu const colorDom = self.createColorTool().render(self.view).dom; @@ -775,7 +708,8 @@ export class TooltipTextMenu { return new Dropdown([colors], { class: "buttonSettings-dropdown" }) as MenuItem; } - createBrush(active: boolean = false) { + // BRUSH TOOL + createBrushTool(active: boolean = false) { const icon = { height: 32, width: 32, path: "M30.828 1.172c-1.562-1.562-4.095-1.562-5.657 0l-5.379 5.379-3.793-3.793-4.243 4.243 3.326 3.326-14.754 14.754c-0.252 0.252-0.358 0.592-0.322 0.921h-0.008v5c0 0.552 0.448 1 1 1h5c0 0 0.083 0 0.125 0 0.288 0 0.576-0.11 0.795-0.329l14.754-14.754 3.326 3.326 4.243-4.243-3.793-3.793 5.379-5.379c1.562-1.562 1.562-4.095 0-5.657zM5.409 30h-3.409v-3.409l14.674-14.674 3.409 3.409-14.674 14.674z" @@ -785,7 +719,7 @@ export class TooltipTextMenu { title: "Brush tool", label: "Brush tool", icon: icon, - css: "color:white;", + css: "fill:white;", class: active ? "menuicon-active" : "menuicon", execEvent: "", run: (state, dispatch) => { @@ -802,15 +736,17 @@ export class TooltipTextMenu { brush_function(state: EditorState<any>, dispatch: any) { if (TooltipTextMenuManager.Instance._brushIsEmpty) { - const selected_marks = this.getMarksInSelection(this.view.state); - if (this._brushdom) { - if (selected_marks.size >= 0) { - TooltipTextMenuManager.Instance._brushMarks = selected_marks; - const newbrush = this.createBrush(true).render(this.view).dom; - this.tooltip.replaceChild(newbrush, this._brushdom); - this._brushdom = newbrush; - TooltipTextMenuManager.Instance._brushIsEmpty = !TooltipTextMenuManager.Instance._brushIsEmpty; - } + // get marks in the selection + const selected_marks = new Set<Mark>(); + const { from, to } = state.selection as TextSelection; + state.doc.nodesBetween(from, to, (node) => node.marks?.forEach(m => selected_marks.add(m))); + + if (this._brushdom && selected_marks.size >= 0) { + TooltipTextMenuManager.Instance._brushMarks = selected_marks; + const newbrush = this.createBrushTool(true).render(this.view).dom; + this.tooltip.replaceChild(newbrush, this._brushdom); + this._brushdom = newbrush; + TooltipTextMenuManager.Instance._brushIsEmpty = !TooltipTextMenuManager.Instance._brushIsEmpty; } } else { @@ -820,12 +756,12 @@ export class TooltipTextMenu { if (TooltipTextMenuManager.Instance._brushMarks && to - from > 0) { this.view.dispatch(this.view.state.tr.removeMark(from, to)); Array.from(TooltipTextMenuManager.Instance._brushMarks).filter(m => m.type !== schema.marks.user_mark).forEach((mark: Mark) => { - this.setMark(mark, this.view.state, this.view.dispatch); + TooltipTextMenu.setMark(mark, this.view.state, this.view.dispatch); }); } } else { - const newbrush = this.createBrush(false).render(this.view).dom; + const newbrush = this.createBrushTool(false).render(this.view).dom; this.tooltip.replaceChild(newbrush, this._brushdom); this._brushdom = newbrush; TooltipTextMenuManager.Instance._brushIsEmpty = !TooltipTextMenuManager.Instance._brushIsEmpty; @@ -837,17 +773,12 @@ export class TooltipTextMenu { createBrushDropdown(active: boolean = false) { let label = "Stored marks: "; if (TooltipTextMenuManager.Instance._brushMarks && TooltipTextMenuManager.Instance._brushMarks.size > 0) { - TooltipTextMenuManager.Instance._brushMarks.forEach((mark: Mark) => { - const markType = mark.type; - label += markType.name; - label += ", "; - }); + TooltipTextMenuManager.Instance._brushMarks.forEach((mark: Mark) => label += mark.type.name + ", "); label = label.substring(0, label.length - 2); } else { label = "No marks are currently stored"; } - const brushInfo = new MenuItem({ title: "", label: label, @@ -904,7 +835,7 @@ export class TooltipTextMenu { // update brush tool // TODO: this probably isn't very clean - const newBrushdom = self.createBrush().render(self.view).dom; + const newBrushdom = self.createBrushTool().render(self.view).dom; self._brushdom && self.tooltip.replaceChild(newBrushdom, self._brushdom); self._brushdom = newBrushdom; const newBrushDropdowndom = self.createBrushDropdown().render(self.view).dom; @@ -917,7 +848,7 @@ export class TooltipTextMenu { return new Dropdown(hasMarks ? [brushInfo, clearBrush] : [brushInfo], { class: "buttonSettings-dropdown" }) as MenuItem; } - setMark = (mark: Mark, state: EditorState<any>, dispatch: any) => { + static setMark = (mark: Mark, state: EditorState<any>, dispatch: any) => { if (mark) { const node = (state.selection as NodeSelection).node; if (node?.type === schema.nodes.ordered_list) { @@ -938,182 +869,7 @@ export class TooltipTextMenu { } } - changeToFontFamily = (mark: Mark, view: EditorView) => { - const fontName = mark.attrs.family; - if (fontName) { this.updateFontStyleDropdown(fontName); } - if (this.editorProps) { - const ruleProvider = this.editorProps.ruleProvider; - const heading = NumCast(this.editorProps.Document.heading); - if (ruleProvider && heading) { - ruleProvider["ruleFont_" + heading] = fontName; - } - } - this.setMark(view.state.schema.marks.pFontFamily.create({ family: fontName }), view.state, view.dispatch); - } - - changeToFontSize = (mark: Mark, view: EditorView) => { - const size = mark.attrs.fontSize; - if (size) { this.updateFontSizeDropdown(String(size) + " pt"); } - if (this.editorProps) { - const ruleProvider = this.editorProps.ruleProvider; - const heading = NumCast(this.editorProps.Document.heading); - if (ruleProvider && heading) { - ruleProvider["ruleSize_" + heading] = size; - } - } - this.setMark(view.state.schema.marks.pFontSize.create({ fontSize: size }), view.state, view.dispatch); - } - - //remove all node typeand apply the passed-in one to the selected text - changeBulletType = (nodeType: NodeType | undefined) => { - //remove oldif (nodeType) { //add new - const view = this.view; - if (nodeType === schema.nodes.bullet_list) { - wrapInList(nodeType)(view.state, view.dispatch); - } else { - const marks = view.state.storedMarks || (view.state.selection.$to.parentOffset && view.state.selection.$from.marks()); - if (!wrapInList(schema.nodes.ordered_list)(view.state, (tx2: any) => { - const tx3 = updateBullets(tx2, schema, nodeType && (nodeType as any).attrs.mapStyle); - marks && tx3.ensureMarks([...marks]); - marks && tx3.setStoredMarks([...marks]); - - view.dispatch(tx2); - })) { - const tx2 = view.state.tr; - const tx3 = updateBullets(tx2, schema, nodeType && (nodeType as any).attrs.mapStyle); - marks && tx3.ensureMarks([...marks]); - marks && tx3.setStoredMarks([...marks]); - - view.dispatch(tx3); - } - } - } - - //makes a button for the drop down FOR MARKS - //css is the style you want applied to the button - dropdownFontFamilyBtn(label: string, css: string, mark: Mark, view: EditorView, changeFontFamily: (mark: Mark<any>, view: EditorView) => any) { - return new MenuItem({ - title: "Set Font Family", - label: label, - execEvent: "", - class: "dropdown-item", - css: css, - enable() { return true; }, - run() { changeFontFamily(mark, view); } - }); - } - //makes a button for the drop down FOR MARKS - //css is the style you want applied to the button - dropdownFontSizeBtn(label: string, css: string, mark: Mark, view: EditorView, changeFontSize: (markType: Mark<any>, view: EditorView) => any) { - return new MenuItem({ - title: "Set Font Size", - label: label, - execEvent: "", - class: "dropdown-item", - css: css, - enable() { return true; }, - run() { changeFontSize(mark, view); } - }); - } - - //makes a button for the drop down FOR NODE TYPES - //css is the style you want applied to the button - dropdownBulletBtn(label: string, css: string, nodeType: NodeType | undefined, view: EditorView, groupNodes: NodeType[], changeToNodeInGroup: (nodeType: NodeType<any> | undefined, view: EditorView, groupNodes: NodeType[]) => any) { - return new MenuItem({ - title: "Set Bullet Style", - label: label, - execEvent: "", - class: "dropdown-item", - css: css, - enable() { return true; }, - run() { changeToNodeInGroup(nodeType, view, groupNodes); } - }); - } - - markActive = function (state: EditorState<any>, type: MarkType<Schema<string, string>>) { - const { from, $from, to, empty } = state.selection; - if (empty) return type.isInSet(state.storedMarks || $from.marks()); - else return state.doc.rangeHasMark(from, to, type); - }; - - // Helper function to create menu icons - icon(text: string, name: string, title: string = name) { - const span = document.createElement("span"); - span.className = name + " menuicon"; - span.title = title; - span.textContent = text; - span.style.color = "white"; - return span; - } - - svgIcon(name: string, title: string = name, dpath: string) { - const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); - svg.setAttribute("viewBox", "-100 -100 650 650"); - const path = document.createElementNS('http://www.w3.org/2000/svg', "path"); - path.setAttributeNS(null, "d", dpath); - svg.appendChild(path); - - const span = document.createElement("span"); - span.className = name + " menuicon"; - span.title = title; - span.appendChild(svg); - - return span; - } - - //method for checking whether node can be inserted - canInsert(state: EditorState, nodeType: NodeType<Schema<string, string>>) { - const $from = state.selection.$from; - for (let d = $from.depth; d >= 0; d--) { - const index = $from.index(d); - if ($from.node(d).canReplaceWith(index, index, nodeType)) return true; - } - return false; - } - - - //adapted this method - use it to check if block has a tag (ie bulleting) - blockActive(type: NodeType<Schema<string, string>>, state: EditorState) { - const attrs = {}; - - if (state.selection instanceof NodeSelection) { - const sel: NodeSelection = state.selection; - const $from = sel.$from; - const to = sel.to; - const node = sel.node; - - if (node) { - return node.hasMarkup(type, attrs); - } - - return to <= $from.end() && $from.parent.hasMarkup(type, attrs); - } - } - - // Create an icon for a heading at the given level - heading(level: number) { - return { - command: setBlockType(schema.nodes.heading, { level }), - dom: this.icon("H" + level, "heading") - }; - } - - getMarksInSelection(state: EditorState<any>) { - const found = new Set<Mark>(); - const { from, to } = state.selection as TextSelection; - state.doc.nodesBetween(from, to, (node) => node.marks?.forEach(m => found.add(m))); - return found; - } - - reset_mark_doms() { - const iterator = this._marksToDoms.values(); - let next = iterator.next(); - while (!next.done) { - next.value.style.color = "white"; - next = iterator.next(); - } - } - + // called by Prosemirror update(view: EditorView, lastState: EditorState | undefined) { this.updateFromDash(view, lastState, this.editorProps); } //updates the tooltip menu when the selection changes public async updateFromDash(view: EditorView, lastState: EditorState | undefined, props: any) { @@ -1122,58 +878,45 @@ export class TooltipTextMenu { return; } this.view = view; - const state = view.state; DocumentDecorations.Instance.showTextBar(); props && (this.editorProps = props); - // Don't do anything if the document/selection didn't change - if (lastState && lastState.doc.eq(state.doc) && - lastState.selection.eq(state.selection)) return; - - this.reset_mark_doms(); - - // update link dropdown - const linkDropdown = await this.createLinkDropdown(); - const newLinkDropdowndom = linkDropdown.render(this.view).dom; - this._linkDropdownDom && this.tooltip.replaceChild(newLinkDropdowndom, this._linkDropdownDom); - this._linkDropdownDom = newLinkDropdowndom; - - //UPDATE FONT STYLE DROPDOWN - const activeStyles = this.activeFontFamilyOnSelection(); - if (activeStyles !== undefined) { - if (activeStyles.length === 1) { - console.log("updating font style dropdown", activeStyles[0]); - activeStyles[0] && this.updateFontStyleDropdown(activeStyles[0]); - } else this.updateFontStyleDropdown(activeStyles.length ? "various" : "default"); - } - //UPDATE FONT SIZE DROPDOWN - const activeSizes = this.activeFontSizeOnSelection(); - if (activeSizes !== undefined) { - if (activeSizes.length === 1) { //if there's only one active font size - activeSizes[0] && this.updateFontSizeDropdown(String(activeSizes[0]) + " pt"); - } else this.updateFontSizeDropdown(activeSizes.length ? "various" : "default"); + // Don't do anything if the document/selection didn't change + if (!lastState || !lastState.doc.eq(view.state.doc) || !lastState.selection.eq(view.state.selection)) { + + // UPDATE LINK DROPDOWN + const linkTarget = await this.getTextLinkTargetTitle(); + const linkDom = this.createLinkTool(linkTarget ? true : false).render(this.view).dom; + const linkDropdownDom = this.createLinkDropdown(linkTarget).render(this.view).dom; + this.linkDom && this.tooltip.replaceChild(linkDom, this.linkDom); + this.linkDropdownDom && this.tooltip.replaceChild(linkDropdownDom, this.linkDropdownDom); + this.linkDom = linkDom; + this.linkDropdownDom = linkDropdownDom; + + //UPDATE FONT STYLE DROPDOWN + const activeStyles = this.activeFontFamilyOnSelection(); + this.updateFontStyleDropdown(activeStyles.length === 1 ? activeStyles[0] : activeStyles.length ? "various" : "default"); + + //UPDATE FONT SIZE DROPDOWN + const activeSizes = this.activeFontSizeOnSelection(); + this.updateFontSizeDropdown(activeSizes.length === 1 ? String(activeSizes[0]) + " pt" : activeSizes.length ? "various" : "default"); + + //UPDATE ALL OTHER BUTTONS + this.updateHighlightStateOfButtons(); } - - this.update_mark_doms(); } - update_mark_doms() { - this.reset_mark_doms(); - this._activeMarks.forEach((mark) => { - if (this._marksToDoms.has(mark)) { - const dom = this._marksToDoms.get(mark); - if (dom) dom.style.color = "greenyellow"; - } - }); + + updateHighlightStateOfButtons() { + Array.from(this._marksToDoms.values()).forEach(val => val.style.fill = "white"); + this.activeMarksOnSelection().filter(mark => this._marksToDoms.has(mark)).forEach(mark => + this._marksToDoms.get(mark)!.style.fill = "greenyellow"); // keeps brush tool highlighted if active when switching between textboxes - if (!TooltipTextMenuManager.Instance._brushIsEmpty) { - if (this._brushdom) { - const newbrush = this.createBrush(true).render(this.view).dom; - this.tooltip.replaceChild(newbrush, this._brushdom); - this._brushdom = newbrush; - } + if (!TooltipTextMenuManager.Instance._brushIsEmpty && this._brushdom) { + const newbrush = this.createBrushTool(true).render(this.view).dom; + this.tooltip.replaceChild(newbrush, this._brushdom); + this._brushdom = newbrush; } - } //finds fontSize at start of selection @@ -1201,24 +944,21 @@ export class TooltipTextMenu { return activeFamilies; } //finds all active marks on selection in given group - activeMarksOnSelection(markGroup: MarkType[]) { + activeMarksOnSelection() { + const markGroup = Array.from(this._marksToDoms.keys()); + if (this.view.state.storedMarks) return this.view.state.storedMarks.map(mark => mark.type); //current selection const { empty, ranges, $to } = this.view.state.selection as TextSelection; const state = this.view.state; - const dispatch = this.view.dispatch; - let activeMarks: MarkType[]; + let activeMarks: MarkType[] = []; if (!empty) { activeMarks = markGroup.filter(mark => { const has = false; for (let i = 0; !has && i < ranges.length; i++) { - const { $from, $to } = ranges[i]; - return state.doc.rangeHasMark($from.pos, $to.pos, mark); + return state.doc.rangeHasMark(ranges[i].$from.pos, ranges[i].$to.pos, mark); } return false; }); - - const refnode = this.reference_node($to); - this._activeMarks = refnode.marks; } else { const pos = this.view.state.selection.$from; @@ -1229,7 +969,6 @@ export class TooltipTextMenu { else { return []; } - this._activeMarks = ref_node.marks; activeMarks = markGroup.filter(mark_type => { if (mark_type === state.schema.marks.pFontSize) { return ref_node.marks.some(m => m.type.name === state.schema.marks.pFontSize.name); @@ -1238,10 +977,6 @@ export class TooltipTextMenu { return ref_node.marks.includes(mark); }); } - else { - return []; - } - } return activeMarks; } diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index 0ef842275..202bfe400 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -119,7 +119,7 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | const anchor2Title = linkDoc.anchor2 instanceof Doc ? StrCast(linkDoc.anchor2.title) : "-untitled-"; if (linkDoc.anchor2 instanceof Doc) { - const text = FormattedTextBox.ToolTipTextMenu.makeLink(linkDoc[Id], anchor2Title, e.ctrlKey ? "onRight" : "inTab", linkDoc.anchor2[Id]); + const text = FormattedTextBox.ToolTipTextMenu.MakeLinkToSelection(linkDoc[Id], anchor2Title, e.ctrlKey ? "onRight" : "inTab", linkDoc.anchor2[Id]); proto.title = text === "" ? proto.title : text + " to " + linkDoc.anchor2.title; // TODO open to more descriptive descriptions of following in text link } } diff --git a/src/client/views/InkingStroke.tsx b/src/client/views/InkingStroke.tsx index 7cee84fc5..a413eebc9 100644 --- a/src/client/views/InkingStroke.tsx +++ b/src/client/views/InkingStroke.tsx @@ -13,8 +13,8 @@ import React = require("react"); type InkDocument = makeInterface<[typeof documentSchema]>; const InkDocument = makeInterface(documentSchema); -export function CreatePolyline(points: { x: number, y: number }[], left: number, top: number, color?: string, width?: number) { - const pts = points.reduce((acc: string, pt: { x: number, y: number }) => acc + `${pt.x - left},${pt.y - top} `, ""); +export function CreatePolyline(points: { X: number, Y: number }[], left: number, top: number, color?: string, width?: number) { + const pts = points.reduce((acc: string, pt: { X: number, Y: number }) => acc + `${pt.X - left},${pt.Y - top} `, ""); return ( <polyline points={pts} @@ -36,8 +36,8 @@ export class InkingStroke extends DocExtendableComponent<FieldViewProps, InkDocu render() { const data: InkData = Cast(this.Document.data, InkField)?.inkData ?? []; - const xs = data.map(p => p.x); - const ys = data.map(p => p.y); + const xs = data.map(p => p.X); + const ys = data.map(p => p.Y); const left = Math.min(...xs); const top = Math.min(...ys); const right = Math.max(...xs); @@ -53,7 +53,7 @@ export class InkingStroke extends DocExtendableComponent<FieldViewProps, InkDocu transform: `translate(${left}px, ${top}px) scale(${scaleX}, ${scaleY})`, mixBlendMode: this.Document.tool === InkTool.Highlighter ? "multiply" : "unset", pointerEvents: "all" - }} onTouchStart={this.onTouchStart}> + }}> {points} </svg> ); diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 9a0b7b7a2..305966160 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -387,7 +387,7 @@ export class MainView extends React.Component { getScale={returnOne}> </DocumentView> </div> - <div style={{ position: "relative", height: `calc(100% - ${this._buttonBarHeight}px)`, width: "100%", overflow: "auto" }}> + <div className="mainView-contentArea" style={{ position: "relative", height: `calc(100% - ${this._buttonBarHeight}px)`, width: "100%", overflow: "visible" }}> <DocumentView Document={sidebarContent} DataDoc={undefined} diff --git a/src/client/views/Touchable.tsx b/src/client/views/Touchable.tsx index 183d3e4e8..251cd41e5 100644 --- a/src/client/views/Touchable.tsx +++ b/src/client/views/Touchable.tsx @@ -2,7 +2,11 @@ import * as React from 'react'; import { action } from 'mobx'; import { InteractionUtils } from '../util/InteractionUtils'; +const HOLD_DURATION = 1000; + export abstract class Touchable<T = {}> extends React.Component<T> { + private holdTimer: NodeJS.Timeout | undefined; + protected _touchDrag: boolean = false; protected prevPoints: Map<number, React.Touch> = new Map<number, React.Touch>(); @@ -18,26 +22,24 @@ export abstract class Touchable<T = {}> extends React.Component<T> { protected onTouchStart = (e: React.TouchEvent): void => { for (let i = 0; i < e.targetTouches.length; i++) { const pt: any = e.targetTouches.item(i); - // pen is also a touch, but with a radius of 0.5 (at least with the surface pens). i doubt anyone's fingers are 2 pixels wide, + // pen is also a touch, but with a radius of 0.5 (at least with the surface pens) // and this seems to be the only way of differentiating pen and touch on touch events - if (pt.radiusX > 2 && pt.radiusY > 2) { + if (pt.radiusX > 0.5 && pt.radiusY > 0.5) { this.prevPoints.set(pt.identifier, pt); } } if (this.prevPoints.size) { - switch (e.targetTouches.length) { + switch (this.prevPoints.size) { case 1: this.handle1PointerDown(e); + e.persist(); + this.holdTimer = setTimeout(() => this.handle1PointerHoldStart(e), HOLD_DURATION); break; case 2: this.handle2PointersDown(e); + break; } - - document.removeEventListener("touchmove", this.onTouch); - document.addEventListener("touchmove", this.onTouch); - document.removeEventListener("touchend", this.onTouchEnd); - document.addEventListener("touchend", this.onTouchEnd); } } @@ -46,10 +48,15 @@ export abstract class Touchable<T = {}> extends React.Component<T> { */ @action protected onTouch = (e: TouchEvent): void => { + const myTouches = InteractionUtils.GetMyTargetTouches(e, this.prevPoints); + // if we're not actually moving a lot, don't consider it as dragging yet - // if (!InteractionUtils.IsDragging(this.prevPoints, e.targetTouches, 5) && !this._touchDrag) return; + if (!InteractionUtils.IsDragging(this.prevPoints, myTouches, 5) && !this._touchDrag) return; this._touchDrag = true; - switch (e.targetTouches.length) { + if (this.holdTimer) { + clearTimeout(this.holdTimer); + } + switch (myTouches.length) { case 1: this.handle1PointerMove(e); break; @@ -64,32 +71,36 @@ export abstract class Touchable<T = {}> extends React.Component<T> { if (this.prevPoints.has(pt.identifier)) { this.prevPoints.set(pt.identifier, pt); } - else { - this.prevPoints.set(pt.identifier, pt); - } } } } @action protected onTouchEnd = (e: TouchEvent): void => { - this._touchDrag = false; - e.stopPropagation(); - + // console.log(InteractionUtils.GetMyTargetTouches(e, this.prevPoints).length + " up"); // remove all the touches associated with the event - for (let i = 0; i < e.targetTouches.length; i++) { - const pt = e.targetTouches.item(i); + for (let i = 0; i < e.changedTouches.length; i++) { + const pt = e.changedTouches.item(i); if (pt) { if (this.prevPoints.has(pt.identifier)) { this.prevPoints.delete(pt.identifier); } } } + if (this.holdTimer) { + clearTimeout(this.holdTimer); + } + this._touchDrag = false; + e.stopPropagation(); + - if (e.targetTouches.length === 0) { - this.prevPoints.clear(); + // if (e.targetTouches.length === 0) { + // this.prevPoints.clear(); + // } + + if (this.prevPoints.size === 0) { + this.cleanUpInteractions(); } - this.cleanUpInteractions(); } cleanUpInteractions = (): void => { @@ -107,6 +118,23 @@ export abstract class Touchable<T = {}> extends React.Component<T> { e.preventDefault(); } - handle1PointerDown = (e: React.TouchEvent): any => { }; - handle2PointersDown = (e: React.TouchEvent): any => { }; + handle1PointerDown = (e: React.TouchEvent): any => { + document.removeEventListener("touchmove", this.onTouch); + document.addEventListener("touchmove", this.onTouch); + document.removeEventListener("touchend", this.onTouchEnd); + document.addEventListener("touchend", this.onTouchEnd); + } + + handle2PointersDown = (e: React.TouchEvent): any => { + document.removeEventListener("touchmove", this.onTouch); + document.addEventListener("touchmove", this.onTouch); + document.removeEventListener("touchend", this.onTouchEnd); + document.addEventListener("touchend", this.onTouchEnd); + } + + handle1PointerHoldStart = (e: React.TouchEvent): any => { + console.log("Hold"); + e.stopPropagation(); + e.preventDefault(); + } }
\ No newline at end of file diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 232722f48..151b84c50 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -32,6 +32,7 @@ import React = require("react"); import { ButtonSelector } from './ParentDocumentSelector'; import { DocumentType } from '../../documents/DocumentTypes'; import { ComputedField } from '../../../new_fields/ScriptField'; +import { InteractionUtils } from '../../util/InteractionUtils'; import { TraceMobx } from '../../../new_fields/util'; library.add(faFile); const _global = (window /* browser */ || global /* node */) as any; @@ -478,6 +479,28 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp this.AddTab(stack, Docs.Create.FreeformDocument([], { width: this.props.PanelWidth(), height: this.props.PanelHeight(), title: "Untitled Collection" }), undefined); } }); + + // starter code for bezel to add new pane + // stack.element.on("touchstart", (e: TouchEvent) => { + // if (e.targetTouches.length === 2) { + // let pt1 = e.targetTouches.item(0); + // let pt2 = e.targetTouches.item(1); + // let threshold = 40 * window.devicePixelRatio; + // if (pt1 && pt2 && InteractionUtils.TwoPointEuclidist(pt1, pt2) < threshold) { + // let edgeThreshold = 30 * window.devicePixelRatio; + // let center = InteractionUtils.CenterPoint([pt1, pt2]); + // let stackRect: DOMRect = stack.element.getBoundingClientRect(); + // let nearLeft = center.X - stackRect.x < edgeThreshold; + // let nearTop = center.Y - stackRect.y < edgeThreshold; + // let nearRight = stackRect.right - center.X < edgeThreshold; + // let nearBottom = stackRect.bottom - center.Y < edgeThreshold; + // let ns = [nearLeft, nearTop, nearRight, nearBottom].filter(n => n); + // if (ns.length === 1) { + + // } + // } + // } + // }); stack.header.controlsContainer.find('.lm_close') //get the close icon .off('click') //unbind the current click handler .click(action(async function () { diff --git a/src/client/views/collections/ParentDocumentSelector.tsx b/src/client/views/collections/ParentDocumentSelector.tsx index 422d01cee..24aa6ddfa 100644 --- a/src/client/views/collections/ParentDocumentSelector.tsx +++ b/src/client/views/collections/ParentDocumentSelector.tsx @@ -11,7 +11,7 @@ import { CollectionViewType } from "./CollectionView"; import { DocumentButtonBar } from "../DocumentButtonBar"; import { DocumentManager } from "../../util/DocumentManager"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { faEdit } from "@fortawesome/free-solid-svg-icons"; +import { faEdit, faChevronCircleUp } from "@fortawesome/free-solid-svg-icons"; import { library } from "@fortawesome/fontawesome-svg-core"; import { MetadataEntryMenu } from "../MetadataEntryMenu"; import { DocumentView } from "../nodes/DocumentView"; @@ -86,11 +86,11 @@ export class ParentDocSelector extends React.Component<SelectorProps> { <SelectorContextMenu {...this.props} /> </div> ); - return <div title="Drag(create link) Tap(view links)" onPointerDown={e => e.stopPropagation()} className="parentDocumentSelector-linkFlyout"> - <Flyout anchorPoint={anchorPoints.RIGHT_TOP} + return <div title="Tap to View Contexts/Metadata" onPointerDown={e => e.stopPropagation()} className="parentDocumentSelector-linkFlyout"> + <Flyout anchorPoint={anchorPoints.LEFT_TOP} content={flyout}> <span className="parentDocumentSelector-button" > - <p>^</p> + <FontAwesomeIcon icon={faChevronCircleUp} size={"lg"} /> </span> </Flyout> </div>; @@ -124,7 +124,7 @@ export class ButtonSelector extends React.Component<{ Document: Doc, Stack: any </div> ); return <span title="Tap for menu" onPointerDown={e => e.stopPropagation()} className="buttonSelector"> - <Flyout anchorPoint={anchorPoints.RIGHT_TOP} content={flyout} stylesheet={this.customStylesheet}> + <Flyout anchorPoint={anchorPoints.LEFT_TOP} content={flyout} stylesheet={this.customStylesheet}> <FontAwesomeIcon icon={faEdit} size={"sm"} /> </Flyout> </span>; diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx index 059393142..b8fbaef5c 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx @@ -8,6 +8,7 @@ import v5 = require("uuid/v5"); import { DocumentType } from "../../../documents/DocumentTypes"; import { observable, action, reaction, IReactionDisposer } from "mobx"; import { StrCast } from "../../../../new_fields/Types"; +import { Id } from "../../../../new_fields/FieldSymbols"; export interface CollectionFreeFormLinkViewProps { A: DocumentView; @@ -21,7 +22,7 @@ export class CollectionFreeFormLinkView extends React.Component<CollectionFreeFo _anchorDisposer: IReactionDisposer | undefined; @action componentDidMount() { - this._anchorDisposer = reaction(() => [this.props.A.props.ScreenToLocalTransform(), this.props.B.props.ScreenToLocalTransform()], + this._anchorDisposer = reaction(() => [this.props.A.props.ScreenToLocalTransform(), this.props.B.props.ScreenToLocalTransform(), this.props.A.isSelected() || Doc.IsBrushed(this.props.A.props.Document), this.props.A.isSelected() || Doc.IsBrushed(this.props.A.props.Document)], action(() => { setTimeout(action(() => this._opacity = 1), 0); // since the render code depends on querying the Dom through getBoudndingClientRect, we need to delay triggering render() setTimeout(action(() => this._opacity = 0.05), 750); // this will unhighlight the link line. @@ -41,10 +42,36 @@ export class CollectionFreeFormLinkView extends React.Component<CollectionFreeFo apt.point.x, apt.point.y); const afield = StrCast(this.props.A.props.Document[StrCast(this.props.A.props.layoutKey, "layout")]).indexOf("anchor1") === -1 ? "anchor2" : "anchor1"; const bfield = afield === "anchor1" ? "anchor2" : "anchor1"; - this.props.A.props.Document[afield + "_x"] = (apt.point.x - abounds.left) / abounds.width * 100; - this.props.A.props.Document[afield + "_y"] = (apt.point.y - abounds.top) / abounds.height * 100; - this.props.A.props.Document[bfield + "_x"] = (bpt.point.x - bbounds.left) / bbounds.width * 100; - this.props.A.props.Document[bfield + "_y"] = (bpt.point.y - bbounds.top) / bbounds.height * 100; + + // really hacky stuff to make the DocuLinkBox display where we want it to: + // if there's an element in the DOM with the id of the opposite anchor, then that DOM element is a hyperlink source for the current anchor and we want to place our link box at it's top right + // otherwise, we just use the computed nearest point on the document boundary to the target Document + const targetAhyperlink = window.document.getElementById((this.props.LinkDocs[0][afield] as Doc)[Id]); + const targetBhyperlink = window.document.getElementById((this.props.LinkDocs[0][bfield] as Doc)[Id]); + if (!targetBhyperlink) { + this.props.A.props.Document[afield + "_x"] = (apt.point.x - abounds.left) / abounds.width * 100; + this.props.A.props.Document[afield + "_y"] = (apt.point.y - abounds.top) / abounds.height * 100; + } else { + setTimeout(() => { + (this.props.A.props.Document[(this.props.A.props as any).fieldKey] as Doc); + const m = targetBhyperlink.getBoundingClientRect(); + const mp = this.props.A.props.ScreenToLocalTransform().transformPoint(m.right, m.top + 5); + this.props.A.props.Document[afield + "_x"] = mp[0] / this.props.A.props.PanelWidth() * 100; + this.props.A.props.Document[afield + "_y"] = mp[1] / this.props.A.props.PanelHeight() * 100; + }, 0); + } + if (!targetAhyperlink) { + this.props.A.props.Document[bfield + "_x"] = (bpt.point.x - bbounds.left) / bbounds.width * 100; + this.props.A.props.Document[bfield + "_y"] = (bpt.point.y - bbounds.top) / bbounds.height * 100; + } else { + setTimeout(() => { + (this.props.B.props.Document[(this.props.B.props as any).fieldKey] as Doc); + const m = targetAhyperlink.getBoundingClientRect(); + const mp = this.props.B.props.ScreenToLocalTransform().transformPoint(m.right, m.top + 5); + this.props.B.props.Document[afield + "_x"] = mp[0] / this.props.B.props.PanelWidth() * 100; + this.props.B.props.Document[afield + "_y"] = mp[1] / this.props.B.props.PanelHeight() * 100; + }, 0); + } }) , { fireImmediately: true }); } @@ -66,11 +93,11 @@ export class CollectionFreeFormLinkView extends React.Component<CollectionFreeFo apt.point.x, apt.point.y); const pt1 = [apt.point.x, apt.point.y]; const pt2 = [bpt.point.x, bpt.point.y]; - let aActive = this.props.A.isSelected() || Doc.IsBrushed(this.props.A.props.Document); - let bActive = this.props.A.isSelected() || Doc.IsBrushed(this.props.A.props.Document); + const aActive = this.props.A.isSelected() || Doc.IsBrushed(this.props.A.props.Document); + const bActive = this.props.A.isSelected() || Doc.IsBrushed(this.props.A.props.Document); return !aActive && !bActive ? (null) : <line key="linkLine" className="collectionfreeformlinkview-linkLine" - style={{ opacity: this._opacity }} + style={{ opacity: this._opacity, strokeDasharray: "2 2" }} x1={`${pt1[0]}`} y1={`${pt1[1]}`} x2={`${pt2[0]}`} y2={`${pt2[1]}`} />; } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 6af29171e..eb5a074bb 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -41,6 +41,8 @@ import { MarqueeView } from "./MarqueeView"; import React = require("react"); import { computedFn } from "mobx-utils"; import { TraceMobx } from "../../../../new_fields/util"; +import { GestureUtils } from "../../../../pen-gestures/GestureUtils"; +import { LinkManager } from "../../../util/LinkManager"; import { CognitiveServices } from "../../../cognitive_services/CognitiveServices"; library.add(faEye as any, faTable, faPaintBrush, faExpandArrowsAlt, faCompressArrowsAlt, faCompass, faUpload, faBraille, faChalkboard, faFileUpload); @@ -270,7 +272,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { return clusterColor; } - @observable private _points: { x: number, y: number }[] = []; + @observable private _points: { X: number, Y: number }[] = []; @action onPointerDown = (e: React.PointerEvent): void => { @@ -286,7 +288,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { e.stopPropagation(); e.preventDefault(); const point = this.getTransform().transformPoint(e.pageX, e.pageY); - this._points.push({ x: point[0], y: point[1] }); + this._points.push({ X: point[0], Y: point[1] }); } // if not using a pen and in no ink mode else if (InkingControl.Instance.selectedTool === InkTool.None) { @@ -325,6 +327,28 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { const pt = e.targetTouches.item(0); if (pt) { this._hitCluster = this.props.Document.useCluster ? this.pickCluster(this.getTransform().transformPoint(pt.clientX, pt.clientY)) !== -1 : false; + if (!e.shiftKey && !e.altKey && !e.ctrlKey && this.props.active(true)) { + document.removeEventListener("touchmove", this.onTouch); + document.addEventListener("touchmove", this.onTouch); + document.removeEventListener("touchend", this.onTouchEnd); + document.addEventListener("touchend", this.onTouchEnd); + if (InkingControl.Instance.selectedTool === InkTool.Highlighter || InkingControl.Instance.selectedTool === InkTool.Pen) { + e.stopPropagation(); + e.preventDefault(); + const point = this.getTransform().transformPoint(pt.pageX, pt.pageY); + this._points.push({ X: point[0], Y: point[1] }); + } + else if (InkingControl.Instance.selectedTool === InkTool.None) { + this._lastX = pt.pageX; + this._lastY = pt.pageY; + e.stopPropagation(); + e.preventDefault(); + } + else { + e.stopPropagation(); + e.preventDefault(); + } + } } } @@ -334,10 +358,65 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { if (this._points.length > 1) { const B = this.svgBounds; - const points = this._points.map(p => ({ x: p.x - B.left, y: p.y - B.top })); - const inkDoc = Docs.Create.InkDocument(InkingControl.Instance.selectedColor, InkingControl.Instance.selectedTool, parseInt(InkingControl.Instance.selectedWidth), points, { width: B.width, height: B.height, x: B.left, y: B.top }); - this.addDocument(inkDoc); - this._points = []; + const points = this._points.map(p => ({ X: p.X - B.left, Y: p.Y - B.top })); + + const result = GestureUtils.GestureRecognizer.Recognize(new Array(points)); + let actionPerformed = false; + if (result && result.Score > 0.7) { + switch (result.Name) { + case GestureUtils.Gestures.Box: + const bounds = { x: Math.min(...this._points.map(p => p.X)), r: Math.max(...this._points.map(p => p.X)), y: Math.min(...this._points.map(p => p.Y)), b: Math.max(...this._points.map(p => p.Y)) }; + const sel = this.getActiveDocuments().filter(doc => { + const l = NumCast(doc.x); + const r = l + doc[WidthSym](); + const t = NumCast(doc.y); + const b = t + doc[HeightSym](); + const pass = !(bounds.x > r || bounds.r < l || bounds.y > b || bounds.b < t); + if (pass) { + doc.x = l - B.left - B.width / 2; + doc.y = t - B.top - B.height / 2; + } + return pass; + }); + this.addDocument(Docs.Create.FreeformDocument(sel, { x: B.left, y: B.top, width: B.width, height: B.height, panX: 0, panY: 0 })); + sel.forEach(d => this.props.removeDocument(d)); + actionPerformed = true; + break; + case GestureUtils.Gestures.Line: + const ep1 = this._points[0]; + const ep2 = this._points[this._points.length - 1]; + let d1: Doc | undefined; + let d2: Doc | undefined; + this.getActiveDocuments().map(doc => { + const l = NumCast(doc.x); + const r = l + doc[WidthSym](); + const t = NumCast(doc.y); + const b = t + doc[HeightSym](); + if (!d1 && l < ep1.X && r > ep1.X && t < ep1.Y && b > ep1.Y) { + d1 = doc; + } + else if (!d2 && l < ep2.X && r > ep2.X && t < ep2.Y && b > ep2.Y) { + d2 = doc; + } + }); + if (d1 && d2) { + if (!LinkManager.Instance.doesLinkExist(d1, d2)) { + DocUtils.MakeLink({ doc: d1 }, { doc: d2 }); + actionPerformed = true; + } + } + break; + } + if (actionPerformed) { + this._points = []; + } + } + + if (!actionPerformed) { + const inkDoc = Docs.Create.InkDocument(InkingControl.Instance.selectedColor, InkingControl.Instance.selectedTool, parseInt(InkingControl.Instance.selectedWidth), points, { width: B.width, height: B.height, x: B.left, y: B.top }); + this.addDocument(inkDoc); + this._points = []; + } } document.removeEventListener("pointermove", this.onPointerMove); @@ -396,7 +475,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { const selectedTool = InkingControl.Instance.selectedTool; if (selectedTool === InkTool.Highlighter || selectedTool === InkTool.Pen || InteractionUtils.IsType(e, InteractionUtils.PENTYPE)) { const point = this.getTransform().transformPoint(e.clientX, e.clientY); - this._points.push({ x: point[0], y: point[1] }); + this._points.push({ X: point[0], Y: point[1] }); } else if (selectedTool === InkTool.None) { if (this._hitCluster && this.tryDragCluster(e)) { @@ -416,7 +495,8 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { handle1PointerMove = (e: TouchEvent) => { // panning a workspace if (!e.cancelBubble) { - const pt = e.targetTouches.item(0); + const myTouches = InteractionUtils.GetMyTargetTouches(e, this.prevPoints); + const pt = myTouches[0]; if (pt) { if (InkingControl.Instance.selectedTool === InkTool.None) { if (this._hitCluster && this.tryDragCluster(e)) { @@ -430,7 +510,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { } else if (InkingControl.Instance.selectedTool !== InkTool.Eraser && InkingControl.Instance.selectedTool !== InkTool.Scrubber) { const point = this.getTransform().transformPoint(pt.clientX, pt.clientY); - this._points.push({ x: point[0], y: point[1] }); + this._points.push({ X: point[0], Y: point[1] }); } } e.stopPropagation(); @@ -441,9 +521,9 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { handle2PointersMove = (e: TouchEvent) => { // pinch zooming if (!e.cancelBubble) { - const pt1: Touch | null = e.targetTouches.item(0); - const pt2: Touch | null = e.targetTouches.item(1); - if (!pt1 || !pt2) return; + const myTouches = InteractionUtils.GetMyTargetTouches(e, this.prevPoints); + const pt1 = myTouches[0]; + const pt2 = myTouches[1]; if (this.prevPoints.size === 2) { const oldPoint1 = this.prevPoints.get(pt1.identifier); @@ -462,8 +542,8 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { const rawDelta = (dir * (d1 + d2)); // this floors and ceils the delta value to prevent jitteriness - const delta = Math.sign(rawDelta) * Math.min(Math.abs(rawDelta), 16); - this.zoom(centerX, centerY, delta); + const delta = Math.sign(rawDelta) * Math.min(Math.abs(rawDelta), 8); + this.zoom(centerX, centerY, delta * window.devicePixelRatio); this.prevPoints.set(pt1.identifier, pt1); this.prevPoints.set(pt2.identifier, pt2); } @@ -478,20 +558,28 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { } } } + e.stopPropagation(); + e.preventDefault(); } - e.stopPropagation(); - e.preventDefault(); } + @action handle2PointersDown = (e: React.TouchEvent) => { - const pt1: React.Touch | null = e.targetTouches.item(0); - const pt2: React.Touch | null = e.targetTouches.item(1); - if (!pt1 || !pt2) return; + if (!e.nativeEvent.cancelBubble && this.props.active(true)) { + const pt1: React.Touch | null = e.targetTouches.item(0); + const pt2: React.Touch | null = e.targetTouches.item(1); + if (!pt1 || !pt2) return; - const centerX = Math.min(pt1.clientX, pt2.clientX) + Math.abs(pt2.clientX - pt1.clientX) / 2; - const centerY = Math.min(pt1.clientY, pt2.clientY) + Math.abs(pt2.clientY - pt1.clientY) / 2; - this._lastX = centerX; - this._lastY = centerY; + const centerX = Math.min(pt1.clientX, pt2.clientX) + Math.abs(pt2.clientX - pt1.clientX) / 2; + const centerY = Math.min(pt1.clientY, pt2.clientY) + Math.abs(pt2.clientY - pt1.clientY) / 2; + this._lastX = centerX; + this._lastY = centerY; + document.removeEventListener("touchmove", this.onTouch); + document.addEventListener("touchmove", this.onTouch); + document.removeEventListener("touchend", this.onTouchEnd); + document.addEventListener("touchend", this.onTouchEnd); + e.stopPropagation(); + } } cleanUpInteractions = () => { @@ -855,8 +943,8 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { } @computed get svgBounds() { - const xs = this._points.map(p => p.x); - const ys = this._points.map(p => p.y); + const xs = this._points.map(p => p.X); + const ys = this._points.map(p => p.Y); const right = Math.max(...xs); const left = Math.min(...xs); const bottom = Math.max(...ys); @@ -872,7 +960,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { const B = this.svgBounds; return ( - <svg width={B.width} height={B.height} style={{ transform: `translate(${B.left}px, ${B.top}px)` }}> + <svg width={B.width} height={B.height} style={{ transform: `translate(${B.left}px, ${B.top}px)`, position: "absolute", zIndex: 30000 }}> {CreatePolyline(this._points, B.left, B.top)} </svg> ); @@ -950,7 +1038,7 @@ class CollectionFreeFormViewPannableContents extends React.Component<CollectionF const panx = -this.props.panX(); const pany = -this.props.panY(); const zoom = this.props.zoomScaling(); - return <div className={freeformclass} style={{ transform: `translate(${cenx}px, ${ceny}px) scale(${zoom}) translate(${panx}px, ${pany}px)` }}> + return <div className={freeformclass} style={{ touchAction: "none", borderRadius: "inherit", transform: `translate(${cenx}px, ${ceny}px) scale(${zoom}) translate(${panx}px, ${pany}px)` }}> {this.props.children()} </div>; } diff --git a/src/client/views/nodes/DocuLinkBox.tsx b/src/client/views/nodes/DocuLinkBox.tsx index d17b2e498..0d4d50c59 100644 --- a/src/client/views/nodes/DocuLinkBox.tsx +++ b/src/client/views/nodes/DocuLinkBox.tsx @@ -68,25 +68,11 @@ export class DocuLinkBox extends DocComponent<FieldViewProps, DocLinkSchema>(Doc } render() { - const anchorDoc = Cast(this.props.Document[this.props.fieldKey], Doc); - let anchorScale = anchorDoc instanceof Doc && anchorDoc.type === DocumentType.PDFANNO ? 0.33 : 1; - let y = NumCast(this.props.Document[this.props.fieldKey + "_y"], 100); - let x = NumCast(this.props.Document[this.props.fieldKey + "_x"], 100); + const x = NumCast(this.props.Document[this.props.fieldKey + "_x"], 100); + const y = NumCast(this.props.Document[this.props.fieldKey + "_y"], 100); const c = StrCast(this.props.Document.backgroundColor, "lightblue"); const anchor = this.props.fieldKey === "anchor1" ? "anchor2" : "anchor1"; - - // really hacky stuff to make the link box display at the top right of hypertext link in a formatted text box. somehow, this should get moved into the hyperlink itself... - const other = window.document.getElementById((this.props.Document[anchor] as Doc)[Id]); - if (other) { - (this.props.Document[this.props.fieldKey] as Doc)?.data; // ugh .. assumes that 'data' is the field used to store the text - setTimeout(() => { - let m = other.getBoundingClientRect(); - let mp = this.props.ScreenToLocalTransform().transformPoint(m.right - 5, m.top + 5); - this.props.Document[this.props.fieldKey + "_x"] = mp[0] / this.props.PanelWidth() * 100; - this.props.Document[this.props.fieldKey + "_y"] = mp[1] / this.props.PanelHeight() * 100; - }, 0); - anchorScale = 0.15; - } + const anchorScale = (x === 0 || x === 100 || y === 0 || y === 100) ? 1 : .15; const timecode = this.props.Document[anchor + "Timecode"]; const targetTitle = StrCast((this.props.Document[anchor]! as Doc).title) + (timecode !== undefined ? ":" + timecode : ""); diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 63c17b1f6..10d2e2b3e 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -4,7 +4,7 @@ import { action, computed, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; import * as rp from "request-promise"; import { Doc, DocListCast, DocListCastAsync, Opt } from "../../../new_fields/Doc"; -import { Document } from '../../../new_fields/documentSchemas'; +import { Document, PositionDocument } from '../../../new_fields/documentSchemas'; import { Id } from '../../../new_fields/FieldSymbols'; import { listSpec } from "../../../new_fields/Schema"; import { ScriptField } from '../../../new_fields/ScriptField'; @@ -236,28 +236,166 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu } } + handle1PointerDown = (e: React.TouchEvent) => { + if (!e.nativeEvent.cancelBubble) { + const touch = InteractionUtils.GetMyTargetTouches(e, this.prevPoints)[0]; + this._downX = touch.clientX; + this._downY = touch.clientY; + this._hitTemplateDrag = false; + for (let element = (e.target as any); element && !this._hitTemplateDrag; element = element.parentElement) { + if (element.className && element.className.toString() === "collectionViewBaseChrome-collapse") { + this._hitTemplateDrag = true; + } + } + if ((this.active || this.Document.onDragStart || this.Document.onClick) && !e.ctrlKey && !this.Document.lockedPosition && !this.Document.inOverlay) e.stopPropagation(); + document.removeEventListener("touchmove", this.onTouch); + document.addEventListener("touchmove", this.onTouch); + document.removeEventListener("touchend", this.onTouchEnd); + document.addEventListener("touchend", this.onTouchEnd); + if ((e.nativeEvent as any).formattedHandled) e.stopPropagation(); + } + } + + handle1PointerMove = (e: TouchEvent) => { + if ((e as any).formattedHandled) { e.stopPropagation; return; } + if (e.cancelBubble && this.active) { + document.removeEventListener("touchmove", this.onTouch); + } + else if (!e.cancelBubble && (SelectionManager.IsSelected(this, true) || this.props.parentActive(true) || this.Document.onDragStart || this.Document.onClick) && !this.Document.lockedPosition && !this.Document.inOverlay) { + const touch = InteractionUtils.GetMyTargetTouches(e, this.prevPoints)[0]; + if (Math.abs(this._downX - touch.clientX) > 3 || Math.abs(this._downY - touch.clientY) > 3) { + if (!e.altKey && (!this.topMost || this.Document.onDragStart || this.Document.onClick)) { + document.removeEventListener("touchmove", this.onTouch); + document.removeEventListener("touchend", this.onTouchEnd); + this.startDragging(this._downX, this._downY, this.Document.dropAction ? this.Document.dropAction as any : e.ctrlKey || e.altKey ? "alias" : undefined, this._hitTemplateDrag); + } + } + e.stopPropagation(); // doesn't actually stop propagation since all our listeners are listening to events on 'document' however it does mark the event as cancelBubble=true which we test for in the move event handlers + e.preventDefault(); + + } + } + + handle2PointersDown = (e: React.TouchEvent) => { + if (!e.nativeEvent.cancelBubble && !this.isSelected()) { + e.stopPropagation(); + e.preventDefault(); + + document.removeEventListener("touchmove", this.onTouch); + document.addEventListener("touchmove", this.onTouch); + document.removeEventListener("touchend", this.onTouchEnd); + document.addEventListener("touchend", this.onTouchEnd); + } + } + + @action + handle2PointersMove = (e: TouchEvent) => { + const myTouches = InteractionUtils.GetMyTargetTouches(e, this.prevPoints); + const pt1 = myTouches[0]; + const pt2 = myTouches[1]; + const oldPoint1 = this.prevPoints.get(pt1.identifier); + const oldPoint2 = this.prevPoints.get(pt2.identifier); + const pinching = InteractionUtils.Pinning(pt1, pt2, oldPoint1!, oldPoint2!); + if (pinching !== 0 && oldPoint1 && oldPoint2) { + // let dX = (Math.min(pt1.clientX, pt2.clientX) - Math.min(oldPoint1.clientX, oldPoint2.clientX)); + // let dY = (Math.min(pt1.clientY, pt2.clientY) - Math.min(oldPoint1.clientY, oldPoint2.clientY)); + // let dX = Math.sign(Math.abs(pt1.clientX - oldPoint1.clientX) - Math.abs(pt2.clientX - oldPoint2.clientX)); + // let dY = Math.sign(Math.abs(pt1.clientY - oldPoint1.clientY) - Math.abs(pt2.clientY - oldPoint2.clientY)); + // let dW = -dX; + // let dH = -dY; + const dW = (Math.abs(pt1.clientX - pt2.clientX) - Math.abs(oldPoint1.clientX - oldPoint2.clientX)); + const dH = (Math.abs(pt1.clientY - pt2.clientY) - Math.abs(oldPoint1.clientY - oldPoint2.clientY)); + const dX = -1 * Math.sign(dW); + const dY = -1 * Math.sign(dH); + + if (dX !== 0 || dY !== 0 || dW !== 0 || dH !== 0) { + const doc = PositionDocument(this.props.Document); + const layoutDoc = PositionDocument(Doc.Layout(this.props.Document)); + let nwidth = layoutDoc.nativeWidth || 0; + let nheight = layoutDoc.nativeHeight || 0; + const width = (layoutDoc.width || 0); + const height = (layoutDoc.height || (nheight / nwidth * width)); + const scale = this.props.ScreenToLocalTransform().Scale * this.props.ContentScaling(); + const actualdW = Math.max(width + (dW * scale), 20); + const actualdH = Math.max(height + (dH * scale), 20); + doc.x = (doc.x || 0) + dX * (actualdW - width); + doc.y = (doc.y || 0) + dY * (actualdH - height); + const fixedAspect = e.ctrlKey || (!layoutDoc.ignoreAspect && nwidth && nheight); + if (fixedAspect && e.ctrlKey && layoutDoc.ignoreAspect) { + layoutDoc.ignoreAspect = false; + layoutDoc.nativeWidth = nwidth = layoutDoc.width || 0; + layoutDoc.nativeHeight = nheight = layoutDoc.height || 0; + } + if (fixedAspect && (!nwidth || !nheight)) { + layoutDoc.nativeWidth = nwidth = layoutDoc.width || 0; + layoutDoc.nativeHeight = nheight = layoutDoc.height || 0; + } + if (nwidth > 0 && nheight > 0 && !layoutDoc.ignoreAspect) { + if (Math.abs(dW) > Math.abs(dH)) { + if (!fixedAspect) { + layoutDoc.nativeWidth = actualdW / (layoutDoc.width || 1) * (layoutDoc.nativeWidth || 0); + } + layoutDoc.width = actualdW; + if (fixedAspect && !layoutDoc.fitWidth) layoutDoc.height = nheight / nwidth * layoutDoc.width; + else layoutDoc.height = actualdH; + } + else { + if (!fixedAspect) { + layoutDoc.nativeHeight = actualdH / (layoutDoc.height || 1) * (doc.nativeHeight || 0); + } + layoutDoc.height = actualdH; + if (fixedAspect && !layoutDoc.fitWidth) layoutDoc.width = nwidth / nheight * layoutDoc.height; + else layoutDoc.width = actualdW; + } + } else { + dW && (layoutDoc.width = actualdW); + dH && (layoutDoc.height = actualdH); + dH && layoutDoc.autoHeight && (layoutDoc.autoHeight = false); + } + } + // let newWidth = Math.max(Math.abs(oldPoint1!.clientX - oldPoint2!.clientX), Math.abs(pt1.clientX - pt2.clientX)) + // this.props.Document.width = newWidth; + e.stopPropagation(); + e.preventDefault(); + } + } + onPointerDown = (e: React.PointerEvent): void => { - if ((e.nativeEvent.cancelBubble && (e.button === 0 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE))) - // return if we're inking, and not selecting a button document - || (InkingControl.Instance.selectedTool !== InkTool.None && !this.Document.onClick) - // return if using pen or eraser - || InteractionUtils.IsType(e, InteractionUtils.PENTYPE) || InteractionUtils.IsType(e, InteractionUtils.ERASERTYPE)) return; - this._downX = e.clientX; - this._downY = e.clientY; - this._hitTemplateDrag = false; - // this whole section needs to move somewhere else. We're trying to initiate a special "template" drag where - // this document is the template and we apply it to whatever we drop it on. - for (let element = (e.target as any); element && !this._hitTemplateDrag; element = element.parentElement) { - if (element.className && element.className.toString() === "collectionViewBaseChrome-collapse") { - this._hitTemplateDrag = true; + // console.log(e.button) + // console.log(e.nativeEvent) + // continue if the event hasn't been canceled AND we are using a moues or this is has an onClick or onDragStart function (meaning it is a button document) + if (!InteractionUtils.IsType(e, InteractionUtils.MOUSETYPE)) { + if (!InteractionUtils.IsType(e, InteractionUtils.PENTYPE)) { + e.stopPropagation(); } + return; + } + if ((!e.nativeEvent.cancelBubble || this.Document.onClick || this.Document.onDragStart)) { + // if ((e.nativeEvent.cancelBubble && (e.button === 0 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE))) + // // return if we're inking, and not selecting a button document + // || (InkingControl.Instance.selectedTool !== InkTool.None && !this.Document.onClick) + // // return if using pen or eraser + // || InteractionUtils.IsType(e, InteractionUtils.PENTYPE) || InteractionUtils.IsType(e, InteractionUtils.ERASERTYPE)) { + // return; + // } + + this._downX = e.clientX; + this._downY = e.clientY; + this._hitTemplateDrag = false; + // this whole section needs to move somewhere else. We're trying to initiate a special "template" drag where + // this document is the template and we apply it to whatever we drop it on. + for (let element = (e.target as any); element && !this._hitTemplateDrag; element = element.parentElement) { + if (element.className && element.className.toString() === "collectionViewBaseChrome-collapse") { + this._hitTemplateDrag = true; + } + } + if ((this.active || this.Document.onDragStart || this.Document.onClick) && !e.ctrlKey && (e.button === 0 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE)) && !this.Document.lockedPosition && !this.Document.inOverlay) e.stopPropagation(); // events stop at the lowest document that is active. if right dragging, we let it go through though to allow for context menu clicks. PointerMove callbacks should remove themselves if the move event gets stopPropagated by a lower-level handler (e.g, marquee drag); + document.removeEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + document.addEventListener("pointermove", this.onPointerMove); + document.addEventListener("pointerup", this.onPointerUp); + if ((e.nativeEvent as any).formattedHandled) { e.stopPropagation(); } } - if ((this.active || this.Document.onDragStart || this.Document.onClick) && !e.ctrlKey && (e.button === 0 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE)) && !this.Document.lockedPosition && !this.Document.inOverlay) e.stopPropagation(); // events stop at the lowest document that is active. if right dragging, we let it go through though to allow for context menu clicks. PointerMove callbacks should remove themselves if the move event gets stopPropagated by a lower-level handler (e.g, marquee drag); - document.removeEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp); - document.addEventListener("pointermove", this.onPointerMove); - document.addEventListener("pointerup", this.onPointerUp); - if ((e.nativeEvent as any).formattedHandled) { e.stopPropagation(); } } onPointerMove = (e: PointerEvent): void => { @@ -445,6 +583,11 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu @action onContextMenu = async (e: React.MouseEvent): Promise<void> => { + // the touch onContextMenu is button 0, the pointer onContextMenu is button 2 + if (e.button === 0) { + e.preventDefault(); + return; + } e.persist(); e.stopPropagation(); if (Math.abs(this._downX - e.clientX) > 3 || Math.abs(this._downY - e.clientY) > 3 || @@ -707,21 +850,6 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu return (this.Document.isBackground && !this.isSelected()) || (this.Document.type === DocumentType.INK && InkingControl.Instance.selectedTool !== InkTool.None); } - @action - handle2PointersMove = (e: TouchEvent) => { - const pt1 = e.targetTouches.item(0); - const pt2 = e.targetTouches.item(1); - if (pt1 && pt2 && this.prevPoints.has(pt1.identifier) && this.prevPoints.has(pt2.identifier)) { - const oldPoint1 = this.prevPoints.get(pt1.identifier); - const oldPoint2 = this.prevPoints.get(pt2.identifier); - const pinching = InteractionUtils.Pinning(pt1, pt2, oldPoint1!, oldPoint2!); - if (pinching !== 0) { - const newWidth = Math.max(Math.abs(oldPoint1!.clientX - oldPoint2!.clientX), Math.abs(pt1.clientX - pt2.clientX)); - this.props.Document.width = newWidth; - } - } - } - render() { if (!(this.props.Document instanceof Doc)) return (null); const ruleColor = this.props.ruleProvider ? StrCast(this.props.ruleProvider["ruleColor_" + this.Document.heading]) : undefined; @@ -742,7 +870,8 @@ export class DocumentView extends DocComponent<DocumentViewProps, Document>(Docu const highlightColors = ["transparent", "maroon", "maroon", "yellow", "magenta", "cyan", "orange"]; const highlightStyles = ["solid", "dashed", "solid", "solid", "solid", "solid", "solid"]; - const highlighting = fullDegree && this.layoutDoc.type !== DocumentType.FONTICON && this.layoutDoc.viewType !== CollectionViewType.Linear; + let highlighting = fullDegree && this.layoutDoc.type !== DocumentType.FONTICON && this.layoutDoc.viewType !== CollectionViewType.Linear; + highlighting = highlighting && this.props.focus !== emptyFunction; // bcz: hack to turn off highlighting onsidebar panel documents. need to flag a document as not highlightable in a more direct way return <div className={`documentView-node${this.topMost ? "-topmost" : ""}`} ref={this._mainCont} onKeyDown={this.onKeyDown} onDrop={this.onDrop} onContextMenu={this.onContextMenu} onPointerDown={this.onPointerDown} onClick={this.onClick} onPointerEnter={e => Doc.BrushDoc(this.props.Document)} onPointerLeave={e => Doc.UnBrushDoc(this.props.Document)} diff --git a/src/client/views/nodes/FormattedTextBox.scss b/src/client/views/nodes/FormattedTextBox.scss index a344a50b3..c203ca0c3 100644 --- a/src/client/views/nodes/FormattedTextBox.scss +++ b/src/client/views/nodes/FormattedTextBox.scss @@ -11,6 +11,7 @@ } .formattedTextBox-cont { + touch-action: none; cursor: text; background: inherit; padding: 0; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index df055a2ab..8e28cf928 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -1161,7 +1161,6 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & onPointerUp={this.onPointerUp} onPointerDown={this.onPointerDown} onMouseUp={this.onMouseUp} - onTouchStart={this.onTouchStart} onWheel={this.onPointerWheel} onPointerEnter={action(() => this._entered = true)} onPointerLeave={action(() => this._entered = false)} diff --git a/src/client/views/search/SearchBox.scss b/src/client/views/search/SearchBox.scss index 4eb992d36..0825580b7 100644 --- a/src/client/views/search/SearchBox.scss +++ b/src/client/views/search/SearchBox.scss @@ -70,8 +70,7 @@ display: flex; flex-direction: column; height: 100%; - overflow: hidden; - overflow-y: auto; + overflow: visible; .no-result { width: 500px; diff --git a/src/client/views/search/SearchBox.tsx b/src/client/views/search/SearchBox.tsx index 2f28ebf76..dd1ac7421 100644 --- a/src/client/views/search/SearchBox.tsx +++ b/src/client/views/search/SearchBox.tsx @@ -353,7 +353,8 @@ export class SearchBox extends React.Component { </div> <div className="searchBox-results" onScroll={this.resultsScrolled} style={{ display: this._resultsOpen ? "flex" : "none", - height: this.resFull ? "auto" : this.resultHeight, overflow: this.resFull ? "auto" : "visible" + height: this.resFull ? "auto" : this.resultHeight, + overflow: "visibile" // this.resFull ? "auto" : "visible" }} ref={this.resultsRef}> {this._visibleElements} </div> diff --git a/src/client/views/search/SearchItem.scss b/src/client/views/search/SearchItem.scss index 82ff96700..469f062b2 100644 --- a/src/client/views/search/SearchItem.scss +++ b/src/client/views/search/SearchItem.scss @@ -1,22 +1,14 @@ @import "../globalCssVariables"; -.search-overview { +.searchItem-overview { display: flex; flex-direction: reverse; justify-content: flex-end; z-index: 0; } -.link-count { - background: black; - border-radius: 20px; - color: white; - width: 15px; - text-align: center; - margin-top: 5px; -} .searchBox-placeholder, -.search-overview .search-item { +.searchItem-overview .searchItem { width: 100%; background: $light-color-secondary; border-color: $intermediate-color; @@ -26,19 +18,19 @@ max-height: 150px; height: auto; z-index: 0; - display: inline-block; - overflow: auto; + display: flex; + overflow: visible; - .main-search-info { + .searchItem-body { display: flex; flex-direction: row; width: 100%; - .search-title-container { + .searchItem-title-container { width: 100%; overflow: hidden; - .search-title { + .searchItem-title { text-transform: uppercase; text-align: left; width: 100%; @@ -46,75 +38,28 @@ } } - .search-info { + .searchItem-info { display: flex; justify-content: flex-end; - .link-container.item { - margin-left: auto; - margin-right: auto; - height: 26px; - width: 26px; - border-radius: 13px; - background: $dark-color; - color: $light-color-secondary; - display: flex; - justify-content: center; - align-items: center; - -webkit-transition: all 0.2s ease-in-out; - -moz-transition: all 0.2s ease-in-out; - -o-transition: all 0.2s ease-in-out; - transition: all 0.2s ease-in-out; - transform-origin: top right; - overflow: hidden; - position: relative; - - - .link-extended { - // display: none; - visibility: hidden; - opacity: 0; - position: relative; - z-index: 500; - overflow: hidden; - -webkit-transition: opacity 0.2s ease-in-out .2s, visibility 0s linear 0s; - -moz-transition: opacity 0.2s ease-in-out .2s, visibility 0s linear 0s; - -o-transition: opacity 0.2s ease-in-out .2s, visibility 0s linear 0s; - transition: opacity 0.2s ease-in-out .2s, visibility 0s linear 0s; - // transition-delay: 1s; - } - - } - - .link-container.item:hover { - width: 70px; - } - - .link-container.item:hover .link-count { - opacity: 0; - } - - .link-container.item:hover .link-extended { - opacity: 1; - visibility: visible; - // display: inline; - } - .icon-icons { width: 50px } .icon-live { width: 175px; + height: 0px; } + .icon-icons { + height:auto; + } .icon-icons, .icon-live { - height: auto; margin: auto; - overflow: hidden; + overflow: visible; - .search-type { + .searchItem-type { display: inline-block; width: 100%; position: absolute; @@ -133,11 +78,11 @@ } } - .search-type:hover+.search-label { + .searchItem-type:hover+.searchItem-label { opacity: 1; } - .search-label { + .searchItem-label { font-size: 10; position: relative; right: 0px; @@ -151,8 +96,6 @@ } .icon-live:hover { - height: 175px; - .pdfBox-cont { img { width: 100% !important; @@ -161,42 +104,44 @@ } } - .search-info:hover { + .searchItem-info:hover { width: 60%; } } } -.search-item:hover~.searchBox-instances, +.searchItem:hover~.searchBox-instances, .searchBox-instances:hover, .searchBox-instances:active { opacity: 1; background: $lighter-alt-accent; - width:150px } -.search-item:hover { +.searchItem:hover { transition: all 0.2s; background: $lighter-alt-accent; } -.search-highlighting { +.searchItem-highlighting { overflow: hidden; text-overflow: ellipsis; white-space: pre; } .searchBox-instances { - float: left; opacity: 1; - width: 0px; + width:40px; + height:40px; + background: gray; transition: all 0.2s ease; color: black; overflow: hidden; + right:-100; + display:inline-block; } -.search-overview:hover { +.searchItem-overview:hover { z-index: 1; } diff --git a/src/client/views/search/SearchItem.tsx b/src/client/views/search/SearchItem.tsx index 673cb7937..32ba5d19d 100644 --- a/src/client/views/search/SearchItem.tsx +++ b/src/client/views/search/SearchItem.tsx @@ -17,11 +17,11 @@ import { SEARCH_THUMBNAIL_SIZE } from "../../views/globalCssVariables.scss"; import { CollectionViewType } from "../collections/CollectionView"; import { CollectionDockingView } from "../collections/CollectionDockingView"; import { ContextMenu } from "../ContextMenu"; -import { DocumentView } from "../nodes/DocumentView"; import { SearchBox } from "./SearchBox"; import "./SearchItem.scss"; import "./SelectorContextMenu.scss"; import { ContentFittingDocumentView } from "../nodes/ContentFittingDocumentView"; +import { ButtonSelector, ParentDocSelector } from "../collections/ParentDocumentSelector"; export interface SearchItemProps { doc: Doc; @@ -188,24 +188,12 @@ export class SearchItem extends React.Component<SearchItemProps> { layoutresult.indexOf(DocumentType.HIST) !== -1 ? faChartBar : layoutresult.indexOf(DocumentType.WEB) !== -1 ? faGlobeAsia : faCaretUp; - return <div onPointerDown={action(() => { this._useIcons = false; this._displayDim = Number(SEARCH_THUMBNAIL_SIZE); })} > + return <div onClick={action(() => { this._useIcons = false; this._displayDim = Number(SEARCH_THUMBNAIL_SIZE); })} > <FontAwesomeIcon icon={button} size="2x" /> </div>; } collectionRef = React.createRef<HTMLDivElement>(); - startDocDrag = () => { - const doc = this.props.doc; - const isProto = Doc.GetT(doc, "isPrototype", "boolean", true); - if (isProto) { - return Doc.MakeDelegate(doc); - } else { - return Doc.MakeAlias(doc); - } - } - - @computed - get linkCount() { return DocListCast(this.props.doc.links).length; } @action pointerDown = (e: React.PointerEvent) => { e.preventDefault(); e.button === 0 && SearchBox.Instance.openSearch(e); } @@ -258,43 +246,62 @@ export class SearchItem extends React.Component<SearchItemProps> { ContextMenu.Instance.displayMenu(e.clientX, e.clientY); } + _downX = 0; + _downY = 0; + _target: any; onPointerDown = (e: React.PointerEvent<HTMLDivElement>) => { + this._downX = e.clientX; + this._downY = e.clientY; e.stopPropagation(); - const doc = Doc.IsPrototype(this.props.doc) ? Doc.MakeDelegate(this.props.doc) : this.props.doc; - DragManager.StartDocumentDrag([e.currentTarget], new DragManager.DocumentDragData([doc]), e.clientX, e.clientY); + this._target = e.currentTarget; + document.removeEventListener("pointermove", this.onPointerMoved); + document.removeEventListener("pointerup", this.onPointerUp); + document.addEventListener("pointermove", this.onPointerMoved); + document.addEventListener("pointerup", this.onPointerUp); + } + onPointerMoved = (e: PointerEvent) => { + if (Math.abs(e.clientX - this._downX) > Utils.DRAG_THRESHOLD || + Math.abs(e.clientY - this._downY) > Utils.DRAG_THRESHOLD) { + console.log("DRAGGIGNG"); + document.removeEventListener("pointermove", this.onPointerMoved); + document.removeEventListener("pointerup", this.onPointerUp); + const doc = Doc.IsPrototype(this.props.doc) ? Doc.MakeDelegate(this.props.doc) : this.props.doc; + DragManager.StartDocumentDrag([this._target], new DragManager.DocumentDragData([doc]), e.clientX, e.clientY); + } + } + onPointerUp = (e: PointerEvent) => { + document.removeEventListener("pointermove", this.onPointerMoved); + document.removeEventListener("pointerup", this.onPointerUp); + } + + @computed + get contextButton() { + return <ParentDocSelector Views={DocumentManager.Instance.DocumentViews} Document={this.props.doc} addDocTab={(doc, data, where) => CollectionDockingView.AddRightSplit(doc, data)} />; } render() { const doc1 = Cast(this.props.doc.anchor1, Doc); const doc2 = Cast(this.props.doc.anchor2, Doc); - return ( - <div className="search-overview" onPointerDown={this.pointerDown} onContextMenu={this.onContextMenu}> - <div className="search-item" onPointerDown={this.nextHighlight} onPointerEnter={this.highlightDoc} onPointerLeave={this.unHighlightDoc} id="result" - onClick={this.onClick}> - <div className="main-search-info"> - <div title="Drag as document" onPointerDown={this.onPointerDown} style={{ marginRight: "7px" }}> <FontAwesomeIcon icon="file" size="lg" /> - <div className="link-container item"> - <div className="link-count" title={`${this.linkCount + " links"}`}>{this.linkCount}</div> - </div> - </div> - <div className="search-title-container"> - <div className="search-title">{StrCast(this.props.doc.title)}</div> - <div className="search-highlighting">{this.props.highlighting.length ? "Matched fields:" + this.props.highlighting.join(", ") : this.props.lines.length ? this.props.lines[0] : ""}</div> - {this.props.lines.filter((m, i) => i).map((l, i) => <div id={i.toString()} className="search-highlighting">`${l}`</div>)} - </div> - <div className="search-info" style={{ width: this._useIcons ? "15%" : "100%" }}> - <div className={`icon-${this._useIcons ? "icons" : "live"}`}> - <div className="search-type" title="Click to Preview">{this.DocumentIcon()}</div> - <div className="search-label">{this.props.doc.type ? this.props.doc.type : "Other"}</div> - </div> - </div> + return <div className="searchItem-overview" onPointerDown={this.pointerDown} onContextMenu={this.onContextMenu}> + <div className="searchItem" onPointerDown={this.nextHighlight} onPointerEnter={this.highlightDoc} onPointerLeave={this.unHighlightDoc}> + <div className="searchItem-body" onClick={this.onClick}> + <div className="searchItem-title-container"> + <div className="searchItem-title">{StrCast(this.props.doc.title)}</div> + <div className="searchItem-highlighting">{this.props.highlighting.length ? "Matched fields:" + this.props.highlighting.join(", ") : this.props.lines.length ? this.props.lines[0] : ""}</div> + {this.props.lines.filter((m, i) => i).map((l, i) => <div id={i.toString()} className="searchItem-highlighting">`${l}`</div>)} </div> </div> - <div className="searchBox-instances"> + <div className="searchItem-info" style={{ width: this._useIcons ? "30px" : "100%" }}> + <div className={`icon-${this._useIcons ? "icons" : "live"}`}> + <div className="searchItem-type" title="Click to Preview" onPointerDown={this.onPointerDown}>{this.DocumentIcon()}</div> + <div className="searchItem-label">{this.props.doc.type ? this.props.doc.type : "Other"}</div> + </div> + </div> + <div className="searchItem-context" title="Drag as document"> {(doc1 instanceof Doc && doc2 instanceof Doc) && this.props.doc.type === DocumentType.LINK ? <LinkContextMenu doc1={doc1} doc2={doc2} /> : - <SelectorContextMenu {...this.props} />} + this.contextButton} </div> </div> - ); + </div>; } }
\ No newline at end of file diff --git a/src/new_fields/InkField.ts b/src/new_fields/InkField.ts index 2d8bb582a..83d631958 100644 --- a/src/new_fields/InkField.ts +++ b/src/new_fields/InkField.ts @@ -13,14 +13,14 @@ export enum InkTool { } export interface PointData { - x: number; - y: number; + X: number; + Y: number; } export type InkData = Array<PointData>; const pointSchema = createSimpleSchema({ - x: true, y: true + X: true, Y: true }); const strokeDataSchema = createSimpleSchema({ diff --git a/src/pen-gestures/GestureUtils.ts b/src/pen-gestures/GestureUtils.ts new file mode 100644 index 000000000..59a85b66b --- /dev/null +++ b/src/pen-gestures/GestureUtils.ts @@ -0,0 +1,28 @@ +import { NDollarRecognizer } from "./ndollar"; +import { Type } from "typescript"; +import { InkField } from "../new_fields/InkField"; +import { Docs } from "../client/documents/Documents"; +import { Doc, WidthSym, HeightSym } from "../new_fields/Doc"; +import { NumCast } from "../new_fields/Types"; +import { CollectionFreeFormView } from "../client/views/collections/collectionFreeForm/CollectionFreeFormView"; + +export namespace GestureUtils { + namespace GestureDataTypes { + export type BoxData = Array<Doc>; + } + + export enum Gestures { + Box = "box", + Line = "line" + } + + export const GestureRecognizer = new NDollarRecognizer(false); + + export function GestureOptions(name: string, gestureData?: any): (params: {}) => any { + switch (name) { + case Gestures.Box: + break; + } + throw new Error("This means that you're trying to do something with the gesture that hasn't been defined yet. Define it in GestureUtils.ts"); + } +}
\ No newline at end of file diff --git a/src/pen-gestures/ndollar.ts b/src/pen-gestures/ndollar.ts new file mode 100644 index 000000000..872c524d6 --- /dev/null +++ b/src/pen-gestures/ndollar.ts @@ -0,0 +1,533 @@ +import { GestureUtils } from "./GestureUtils"; + +/** + * The $N Multistroke Recognizer (JavaScript version) + * Converted to TypeScript -syip2 + * + * Lisa Anthony, Ph.D. + * UMBC + * Information Systems Department + * 1000 Hilltop Circle + * Baltimore, MD 21250 + * lanthony@umbc.edu + * + * Jacob O. Wobbrock, Ph.D. + * The Information School + * University of Washington + * Seattle, WA 98195-2840 + * wobbrock@uw.edu + * + * The academic publications for the $N recognizer, and what should be + * used to cite it, are: + * + * Anthony, L. and Wobbrock, J.O. (2010). A lightweight multistroke + * recognizer for user interface prototypes. Proceedings of Graphics + * Interface (GI '10). Ottawa, Ontario (May 31-June 2, 2010). Toronto, + * Ontario: Canadian Information Processing Society, pp. 245-252. + * https://dl.acm.org/citation.cfm?id=1839258 + * + * Anthony, L. and Wobbrock, J.O. (2012). $N-Protractor: A fast and + * accurate multistroke recognizer. Proceedings of Graphics Interface + * (GI '12). Toronto, Ontario (May 28-30, 2012). Toronto, Ontario: + * Canadian Information Processing Society, pp. 117-120. + * https://dl.acm.org/citation.cfm?id=2305296 + * + * The Protractor enhancement was separately published by Yang Li and programmed + * here by Jacob O. Wobbrock and Lisa Anthony: + * + * Li, Y. (2010). Protractor: A fast and accurate gesture + * recognizer. Proceedings of the ACM Conference on Human + * Factors in Computing Systems (CHI '10). Atlanta, Georgia + * (April 10-15, 2010). New York: ACM Press, pp. 2169-2172. + * https://dl.acm.org/citation.cfm?id=1753654 + * + * This software is distributed under the "New BSD License" agreement: + * + * Copyright (C) 2007-2011, Jacob O. Wobbrock and Lisa Anthony. + * All rights reserved. Last updated July 14, 2018. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the names of UMBC nor the University of Washington, + * nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Lisa Anthony OR Jacob O. Wobbrock + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. +**/ + +// +// Point class +// +export class Point { + constructor(public X: number, public Y: number) { } +} + +// +// Rectangle class +// +export class Rectangle { + constructor(public X: number, public Y: number, public Width: number, public Height: number) { } +} + +// +// Unistroke class: a unistroke template +// +export class Unistroke { + public Points: Point[]; + public StartUnitVector: Point; + public Vector: number[]; + + constructor(public Name: string, useBoundedRotationInvariance: boolean, points: Point[]) { + this.Points = Resample(points, NumPoints); + const radians = IndicativeAngle(this.Points); + this.Points = RotateBy(this.Points, -radians); + this.Points = ScaleDimTo(this.Points, SquareSize, OneDThreshold); + if (useBoundedRotationInvariance) { + this.Points = RotateBy(this.Points, +radians); // restore + } + this.Points = TranslateTo(this.Points, Origin); + this.StartUnitVector = CalcStartUnitVector(this.Points, StartAngleIndex); + this.Vector = Vectorize(this.Points, useBoundedRotationInvariance); // for Protractor + } +} +// +// Multistroke class: a container for unistrokes +// +export class Multistroke { + public NumStrokes: number; + public Unistrokes: Unistroke[]; + + constructor(public Name: string, useBoundedRotationInvariance: boolean, strokes: any[]) // constructor + { + this.NumStrokes = strokes.length; // number of individual strokes + + const order = new Array(strokes.length); // array of integer indices + for (var i = 0; i < strokes.length; i++) { + order[i] = i; // initialize + } + const orders = new Array(); // array of integer arrays + HeapPermute(strokes.length, order, /*out*/ orders); + + const unistrokes = MakeUnistrokes(strokes, orders); // returns array of point arrays + this.Unistrokes = new Array(unistrokes.length); // unistrokes for this multistroke + for (var j = 0; j < unistrokes.length; j++) { + this.Unistrokes[j] = new Unistroke(this.Name, useBoundedRotationInvariance, unistrokes[j]); + } + } +} + +// +// Result class +// +export class Result { + constructor(public Name: string, public Score: any, public Time: any) { } +} + +// +// NDollarRecognizer constants +// +const NumMultistrokes = 2; +const NumPoints = 96; +const SquareSize = 250.0; +const OneDThreshold = 0.25; // customize to desired gesture set (usually 0.20 - 0.35) +const Origin = new Point(0, 0); +const Diagonal = Math.sqrt(SquareSize * SquareSize + SquareSize * SquareSize); +const HalfDiagonal = 0.5 * Diagonal; +const AngleRange = Deg2Rad(45.0); +const AnglePrecision = Deg2Rad(2.0); +const Phi = 0.5 * (-1.0 + Math.sqrt(5.0)); // Golden Ratio +const StartAngleIndex = (NumPoints / 8); // eighth of gesture length +const AngleSimilarityThreshold = Deg2Rad(30.0); + +// +// NDollarRecognizer class +// +export class NDollarRecognizer { + public Multistrokes: Multistroke[]; + + constructor(useBoundedRotationInvariance: boolean) // constructor + { + // + // one predefined multistroke for each multistroke type + // + this.Multistrokes = new Array(NumMultistrokes); + this.Multistrokes[0] = new Multistroke(GestureUtils.Gestures.Box, useBoundedRotationInvariance, new Array( + new Array(new Point(30, 146), new Point(30, 222), new Point(106, 225), new Point(106, 146), new Point(30, 146)) + )); + this.Multistrokes[1] = new Multistroke(GestureUtils.Gestures.Line, useBoundedRotationInvariance, new Array( + new Array(new Point(12, 347), new Point(119, 347)) + )); + + // + // PREDEFINED STROKES + // + + // this.Multistrokes[0] = new Multistroke("T", useBoundedRotationInvariance, new Array( + // new Array(new Point(30, 7), new Point(103, 7)), + // new Array(new Point(66, 7), new Point(66, 87)) + // )); + // this.Multistrokes[1] = new Multistroke("N", useBoundedRotationInvariance, new Array( + // new Array(new Point(177, 92), new Point(177, 2)), + // new Array(new Point(182, 1), new Point(246, 95)), + // new Array(new Point(247, 87), new Point(247, 1)) + // )); + // this.Multistrokes[2] = new Multistroke("D", useBoundedRotationInvariance, new Array( + // new Array(new Point(345, 9), new Point(345, 87)), + // new Array(new Point(351, 8), new Point(363, 8), new Point(372, 9), new Point(380, 11), new Point(386, 14), new Point(391, 17), new Point(394, 22), new Point(397, 28), new Point(399, 34), new Point(400, 42), new Point(400, 50), new Point(400, 56), new Point(399, 61), new Point(397, 66), new Point(394, 70), new Point(391, 74), new Point(386, 78), new Point(382, 81), new Point(377, 83), new Point(372, 85), new Point(367, 87), new Point(360, 87), new Point(355, 88), new Point(349, 87)) + // )); + // this.Multistrokes[3] = new Multistroke("P", useBoundedRotationInvariance, new Array( + // new Array(new Point(507, 8), new Point(507, 87)), + // new Array(new Point(513, 7), new Point(528, 7), new Point(537, 8), new Point(544, 10), new Point(550, 12), new Point(555, 15), new Point(558, 18), new Point(560, 22), new Point(561, 27), new Point(562, 33), new Point(561, 37), new Point(559, 42), new Point(556, 45), new Point(550, 48), new Point(544, 51), new Point(538, 53), new Point(532, 54), new Point(525, 55), new Point(519, 55), new Point(513, 55), new Point(510, 55)) + // )); + // this.Multistrokes[4] = new Multistroke("X", useBoundedRotationInvariance, new Array( + // new Array(new Point(30, 146), new Point(106, 222)), + // new Array(new Point(30, 225), new Point(106, 146)) + // )); + // this.Multistrokes[5] = new Multistroke("H", useBoundedRotationInvariance, new Array( + // new Array(new Point(188, 137), new Point(188, 225)), + // new Array(new Point(188, 180), new Point(241, 180)), + // new Array(new Point(241, 137), new Point(241, 225)) + // )); + // this.Multistrokes[6] = new Multistroke("I", useBoundedRotationInvariance, new Array( + // new Array(new Point(371, 149), new Point(371, 221)), + // new Array(new Point(341, 149), new Point(401, 149)), + // new Array(new Point(341, 221), new Point(401, 221)) + // )); + // this.Multistrokes[7] = new Multistroke("exclamation", useBoundedRotationInvariance, new Array( + // new Array(new Point(526, 142), new Point(526, 204)), + // new Array(new Point(526, 221)) + // )); + // this.Multistrokes[9] = new Multistroke("five-point star", useBoundedRotationInvariance, new Array( + // new Array(new Point(177, 396), new Point(223, 299), new Point(262, 396), new Point(168, 332), new Point(278, 332), new Point(184, 397)) + // )); + // this.Multistrokes[10] = new Multistroke("null", useBoundedRotationInvariance, new Array( + // new Array(new Point(382, 310), new Point(377, 308), new Point(373, 307), new Point(366, 307), new Point(360, 310), new Point(356, 313), new Point(353, 316), new Point(349, 321), new Point(347, 326), new Point(344, 331), new Point(342, 337), new Point(341, 343), new Point(341, 350), new Point(341, 358), new Point(342, 362), new Point(344, 366), new Point(347, 370), new Point(351, 374), new Point(356, 379), new Point(361, 382), new Point(368, 385), new Point(374, 387), new Point(381, 387), new Point(390, 387), new Point(397, 385), new Point(404, 382), new Point(408, 378), new Point(412, 373), new Point(416, 367), new Point(418, 361), new Point(419, 353), new Point(418, 346), new Point(417, 341), new Point(416, 336), new Point(413, 331), new Point(410, 326), new Point(404, 320), new Point(400, 317), new Point(393, 313), new Point(392, 312)), + // new Array(new Point(418, 309), new Point(337, 390)) + // )); + // this.Multistrokes[11] = new Multistroke("arrowhead", useBoundedRotationInvariance, new Array( + // new Array(new Point(506, 349), new Point(574, 349)), + // new Array(new Point(525, 306), new Point(584, 349), new Point(525, 388)) + // )); + // this.Multistrokes[12] = new Multistroke("pitchfork", useBoundedRotationInvariance, new Array( + // new Array(new Point(38, 470), new Point(36, 476), new Point(36, 482), new Point(37, 489), new Point(39, 496), new Point(42, 500), new Point(46, 503), new Point(50, 507), new Point(56, 509), new Point(63, 509), new Point(70, 508), new Point(75, 506), new Point(79, 503), new Point(82, 499), new Point(85, 493), new Point(87, 487), new Point(88, 480), new Point(88, 474), new Point(87, 468)), + // new Array(new Point(62, 464), new Point(62, 571)) + // )); + // this.Multistrokes[13] = new Multistroke("six-point star", useBoundedRotationInvariance, new Array( + // new Array(new Point(177, 554), new Point(223, 476), new Point(268, 554), new Point(183, 554)), + // new Array(new Point(177, 490), new Point(223, 568), new Point(268, 490), new Point(183, 490)) + // )); + // this.Multistrokes[14] = new Multistroke("asterisk", useBoundedRotationInvariance, new Array( + // new Array(new Point(325, 499), new Point(417, 557)), + // new Array(new Point(417, 499), new Point(325, 557)), + // new Array(new Point(371, 486), new Point(371, 571)) + // )); + // this.Multistrokes[15] = new Multistroke("half-note", useBoundedRotationInvariance, new Array( + // new Array(new Point(546, 465), new Point(546, 531)), + // new Array(new Point(540, 530), new Point(536, 529), new Point(533, 528), new Point(529, 529), new Point(524, 530), new Point(520, 532), new Point(515, 535), new Point(511, 539), new Point(508, 545), new Point(506, 548), new Point(506, 554), new Point(509, 558), new Point(512, 561), new Point(517, 564), new Point(521, 564), new Point(527, 563), new Point(531, 560), new Point(535, 557), new Point(538, 553), new Point(542, 548), new Point(544, 544), new Point(546, 540), new Point(546, 536)) + // )); + // + // The $N Gesture Recognizer API begins here -- 3 methods: Recognize(), AddGesture(), and DeleteUserGestures() + // + } + + Recognize = (strokes: any[], useBoundedRotationInvariance: boolean = false, requireSameNoOfStrokes: boolean = false, useProtractor: boolean = true) => { + const t0 = Date.now(); + const points = CombineStrokes(strokes); // make one connected unistroke from the given strokes + const candidate = new Unistroke("", useBoundedRotationInvariance, points); + + var u = -1; + var b = +Infinity; + for (var i = 0; i < this.Multistrokes.length; i++) // for each multistroke template + { + if (!requireSameNoOfStrokes || strokes.length === this.Multistrokes[i].NumStrokes) // optional -- only attempt match when same # of component strokes + { + for (var j = 0; j < this.Multistrokes[i].Unistrokes.length; j++) // for each unistroke within this multistroke + { + if (AngleBetweenUnitVectors(candidate.StartUnitVector, this.Multistrokes[i].Unistrokes[j].StartUnitVector) <= AngleSimilarityThreshold) // strokes start in the same direction + { + var d; + if (useProtractor) { + d = OptimalCosineDistance(this.Multistrokes[i].Unistrokes[j].Vector, candidate.Vector); // Protractor + } + else { + d = DistanceAtBestAngle(candidate.Points, this.Multistrokes[i].Unistrokes[j], -AngleRange, +AngleRange, AnglePrecision); // Golden Section Search (original $N) + } + if (d < b) { + b = d; // best (least) distance + u = i; // multistroke owner of unistroke + } + } + } + } + } + const t1 = Date.now(); + return (u === -1) ? null : new Result(this.Multistrokes[u].Name, useProtractor ? (1.0 - b) : (1.0 - b / HalfDiagonal), t1 - t0); + } + + AddGesture = (name: string, useBoundedRotationInvariance: boolean, strokes: any[]) => { + this.Multistrokes[this.Multistrokes.length] = new Multistroke(name, useBoundedRotationInvariance, strokes); + var num = 0; + for (var i = 0; i < this.Multistrokes.length; i++) { + if (this.Multistrokes[i].Name === name) { + num++; + } + } + return num; + } + + DeleteUserGestures = () => { + this.Multistrokes.length = NumMultistrokes; // clear any beyond the original set + return NumMultistrokes; + } +} + + +// +// Private helper functions from here on down +// +function HeapPermute(n: number, order: any[], /*out*/ orders: any[]) { + if (n === 1) { + orders[orders.length] = order.slice(); // append copy + } else { + for (var i = 0; i < n; i++) { + HeapPermute(n - 1, order, orders); + if (n % 2 === 1) { // swap 0, n-1 + const tmp = order[0]; + order[0] = order[n - 1]; + order[n - 1] = tmp; + } else { // swap i, n-1 + const tmp = order[i]; + order[i] = order[n - 1]; + order[n - 1] = tmp; + } + } + } +} + +function MakeUnistrokes(strokes: any, orders: any) { + const unistrokes = new Array(); // array of point arrays + for (var r = 0; r < orders.length; r++) { + for (var b = 0; b < Math.pow(2, orders[r].length); b++) // use b's bits for directions + { + const unistroke = new Array(); // array of points + for (var i = 0; i < orders[r].length; i++) { + var pts; + if (((b >> i) & 1) === 1) {// is b's bit at index i on? + pts = strokes[orders[r][i]].slice().reverse(); // copy and reverse + } + else { + pts = strokes[orders[r][i]].slice(); // copy + } + for (var p = 0; p < pts.length; p++) { + unistroke[unistroke.length] = pts[p]; // append points + } + } + unistrokes[unistrokes.length] = unistroke; // add one unistroke to set + } + } + return unistrokes; +} + +function CombineStrokes(strokes: any) { + const points = new Array(); + for (var s = 0; s < strokes.length; s++) { + for (var p = 0; p < strokes[s].length; p++) { + points[points.length] = new Point(strokes[s][p].X, strokes[s][p].Y); + } + } + return points; +} +function Resample(points: any, n: any) { + const I = PathLength(points) / (n - 1); // interval length + var D = 0.0; + const newpoints = new Array(points[0]); + for (var i = 1; i < points.length; i++) { + const d = Distance(points[i - 1], points[i]); + if ((D + d) >= I) { + const qx = points[i - 1].X + ((I - D) / d) * (points[i].X - points[i - 1].X); + const qy = points[i - 1].Y + ((I - D) / d) * (points[i].Y - points[i - 1].Y); + const q = new Point(qx, qy); + newpoints[newpoints.length] = q; // append new point 'q' + points.splice(i, 0, q); // insert 'q' at position i in points s.t. 'q' will be the next i + D = 0.0; + } + else D += d; + } + if (newpoints.length === n - 1) {// sometimes we fall a rounding-error short of adding the last point, so add it if so + newpoints[newpoints.length] = new Point(points[points.length - 1].X, points[points.length - 1].Y); + } + return newpoints; +} +function IndicativeAngle(points: any) { + const c = Centroid(points); + return Math.atan2(c.Y - points[0].Y, c.X - points[0].X); +} +function RotateBy(points: any, radians: any) // rotates points around centroid +{ + const c = Centroid(points); + const cos = Math.cos(radians); + const sin = Math.sin(radians); + const newpoints = new Array(); + for (var i = 0; i < points.length; i++) { + const qx = (points[i].X - c.X) * cos - (points[i].Y - c.Y) * sin + c.X; + const qy = (points[i].X - c.X) * sin + (points[i].Y - c.Y) * cos + c.Y; + newpoints[newpoints.length] = new Point(qx, qy); + } + return newpoints; +} +function ScaleDimTo(points: any, size: any, ratio1D: any) // scales bbox uniformly for 1D, non-uniformly for 2D +{ + const B = BoundingBox(points); + const uniformly = Math.min(B.Width / B.Height, B.Height / B.Width) <= ratio1D; // 1D or 2D gesture test + const newpoints = new Array(); + for (var i = 0; i < points.length; i++) { + const qx = uniformly ? points[i].X * (size / Math.max(B.Width, B.Height)) : points[i].X * (size / B.Width); + const qy = uniformly ? points[i].Y * (size / Math.max(B.Width, B.Height)) : points[i].Y * (size / B.Height); + newpoints[newpoints.length] = new Point(qx, qy); + } + return newpoints; +} +function TranslateTo(points: any, pt: any) // translates points' centroid +{ + const c = Centroid(points); + const newpoints = new Array(); + for (var i = 0; i < points.length; i++) { + const qx = points[i].X + pt.X - c.X; + const qy = points[i].Y + pt.Y - c.Y; + newpoints[newpoints.length] = new Point(qx, qy); + } + return newpoints; +} +function Vectorize(points: any, useBoundedRotationInvariance: any) // for Protractor +{ + var cos = 1.0; + var sin = 0.0; + if (useBoundedRotationInvariance) { + const iAngle = Math.atan2(points[0].Y, points[0].X); + const baseOrientation = (Math.PI / 4.0) * Math.floor((iAngle + Math.PI / 8.0) / (Math.PI / 4.0)); + cos = Math.cos(baseOrientation - iAngle); + sin = Math.sin(baseOrientation - iAngle); + } + var sum = 0.0; + const vector = new Array<number>(); + for (var i = 0; i < points.length; i++) { + const newX = points[i].X * cos - points[i].Y * sin; + const newY = points[i].Y * cos + points[i].X * sin; + vector[vector.length] = newX; + vector[vector.length] = newY; + sum += newX * newX + newY * newY; + } + const magnitude = Math.sqrt(sum); + for (var i = 0; i < vector.length; i++) { + vector[i] /= magnitude; + } + return vector; +} +function OptimalCosineDistance(v1: any, v2: any) // for Protractor +{ + var a = 0.0; + var b = 0.0; + for (var i = 0; i < v1.length; i += 2) { + a += v1[i] * v2[i] + v1[i + 1] * v2[i + 1]; + b += v1[i] * v2[i + 1] - v1[i + 1] * v2[i]; + } + const angle = Math.atan(b / a); + return Math.acos(a * Math.cos(angle) + b * Math.sin(angle)); +} +function DistanceAtBestAngle(points: any, T: any, a: any, b: any, threshold: any) { + var x1 = Phi * a + (1.0 - Phi) * b; + var f1 = DistanceAtAngle(points, T, x1); + var x2 = (1.0 - Phi) * a + Phi * b; + var f2 = DistanceAtAngle(points, T, x2); + while (Math.abs(b - a) > threshold) { + if (f1 < f2) { + b = x2; + x2 = x1; + f2 = f1; + x1 = Phi * a + (1.0 - Phi) * b; + f1 = DistanceAtAngle(points, T, x1); + } else { + a = x1; + x1 = x2; + f1 = f2; + x2 = (1.0 - Phi) * a + Phi * b; + f2 = DistanceAtAngle(points, T, x2); + } + } + return Math.min(f1, f2); +} +function DistanceAtAngle(points: any, T: any, radians: any) { + const newpoints = RotateBy(points, radians); + return PathDistance(newpoints, T.Points); +} +function Centroid(points: any) { + var x = 0.0, y = 0.0; + for (var i = 0; i < points.length; i++) { + x += points[i].X; + y += points[i].Y; + } + x /= points.length; + y /= points.length; + return new Point(x, y); +} +function BoundingBox(points: any) { + var minX = +Infinity, maxX = -Infinity, minY = +Infinity, maxY = -Infinity; + for (var i = 0; i < points.length; i++) { + minX = Math.min(minX, points[i].X); + minY = Math.min(minY, points[i].Y); + maxX = Math.max(maxX, points[i].X); + maxY = Math.max(maxY, points[i].Y); + } + return new Rectangle(minX, minY, maxX - minX, maxY - minY); +} +function PathDistance(pts1: any, pts2: any) // average distance between corresponding points in two paths +{ + var d = 0.0; + for (var i = 0; i < pts1.length; i++) {// assumes pts1.length == pts2.length + d += Distance(pts1[i], pts2[i]); + } + return d / pts1.length; +} +function PathLength(points: any) // length traversed by a point path +{ + var d = 0.0; + for (var i = 1; i < points.length; i++) { + d += Distance(points[i - 1], points[i]); + } + return d; +} +function Distance(p1: any, p2: any) // distance between two points +{ + const dx = p2.X - p1.X; + const dy = p2.Y - p1.Y; + return Math.sqrt(dx * dx + dy * dy); +} +function CalcStartUnitVector(points: any, index: any) // start angle from points[0] to points[index] normalized as a unit vector +{ + const v = new Point(points[index].X - points[0].X, points[index].Y - points[0].Y); + const len = Math.sqrt(v.X * v.X + v.Y * v.Y); + return new Point(v.X / len, v.Y / len); +} +function AngleBetweenUnitVectors(v1: any, v2: any) // gives acute angle between unit vectors from (0,0) to v1, and (0,0) to v2 +{ + const n = (v1.X * v2.X + v1.Y * v2.Y); + const c = Math.max(-1.0, Math.min(1.0, n)); // ensure [-1,+1] + return Math.acos(c); // arc cosine of the vector dot product +} +function Deg2Rad(d: any) { return (d * Math.PI / 180.0); }
\ No newline at end of file diff --git a/src/server/ActionUtilities.ts b/src/server/ActionUtilities.ts index 30aed32e6..a93566fb1 100644 --- a/src/server/ActionUtilities.ts +++ b/src/server/ActionUtilities.ts @@ -118,25 +118,34 @@ export namespace Email { } }); + export interface DispatchFailure { + recipient: string; + error: Error; + } + export async function dispatchAll(recipients: string[], subject: string, content: string) { - const failures: string[] = []; + const failures: DispatchFailure[] = []; await Promise.all(recipients.map(async (recipient: string) => { - if (!await Email.dispatch(recipient, subject, content)) { - failures.push(recipient); + let error: Error | null; + if ((error = await Email.dispatch(recipient, subject, content)) !== null) { + failures.push({ + recipient, + error + }); } })); - return failures; + return failures.length ? failures : undefined; } - export async function dispatch(recipient: string, subject: string, content: string): Promise<boolean> { + export async function dispatch(recipient: string, subject: string, content: string): Promise<Error | null> { const mailOptions = { to: recipient, from: 'brownptcdash@gmail.com', subject, text: `Hello ${recipient.split("@")[0]},\n\n${content}` } as MailOptions; - return new Promise<boolean>(resolve => { - smtpTransport.sendMail(mailOptions, (dispatchError: Error | null) => resolve(dispatchError === null)); + return new Promise<Error | null>(resolve => { + smtpTransport.sendMail(mailOptions, resolve); }); } diff --git a/src/server/ApiManagers/SearchManager.ts b/src/server/ApiManagers/SearchManager.ts index c1c908088..4ce12f9f3 100644 --- a/src/server/ApiManagers/SearchManager.ts +++ b/src/server/ApiManagers/SearchManager.ts @@ -4,11 +4,11 @@ import { Search } from "../Search"; const findInFiles = require('find-in-files'); import * as path from 'path'; import { pathToDirectory, Directory } from "./UploadManager"; -import { command_line } from "../ActionUtilities"; -import request = require('request-promise'); -import { red } from "colors"; +import { red, cyan, yellow } from "colors"; import RouteSubscriber from "../RouteSubscriber"; -import { execSync } from "child_process"; +import { exec } from "child_process"; +import { onWindows } from ".."; +import { get } from "request-promise"; export class SearchManager extends ApiManager { @@ -69,15 +69,23 @@ export class SearchManager extends ApiManager { export namespace SolrManager { + const command = onWindows ? "solr.cmd" : "solr"; + export async function SetRunning(status: boolean): Promise<boolean> { const args = status ? "start" : "stop -p 8983"; + console.log(`solr management: trying to ${args}`); + exec(`${command} ${args}`, { cwd: "./solr-8.3.1/bin" }, (error, stdout, stderr) => { + if (error) { + console.log(red(`solr management error: unable to ${args} server`)); + console.log(red(error.message)); + } + console.log(cyan(stdout)); + console.log(yellow(stderr)); + }); try { - console.log(`Solr management: trying to ${args}`); - console.log(execSync(`./solr.cmd ${args}`, { cwd: "./solr-8.3.1/bin" })); + await get("http://localhost:8983"); return true; - } catch (e) { - console.log(red(`Solr management error: unable to ${args}`)); - console.log(e); + } catch { return false; } } diff --git a/src/server/DashSession.ts b/src/server/DashSession.ts new file mode 100644 index 000000000..a0e00adda --- /dev/null +++ b/src/server/DashSession.ts @@ -0,0 +1,73 @@ +import { Session } from "./Session/session"; +import { Email } from "./ActionUtilities"; +import { red, yellow, green } from "colors"; +import { get } from "request-promise"; +import { Utils } from "../Utils"; +import { WebSocket } from "./Websocket/Websocket"; +import { MessageStore } from "./Message"; +import { launchServer, onWindows } from "."; + +/** +* If we're the monitor (master) thread, we should launch the monitor logic for the session. +* Otherwise, we must be on a worker thread that was spawned *by* the monitor (master) thread, and thus +* our job should be to run the server. +*/ +export class DashSessionAgent extends Session.AppliedSessionAgent { + + private readonly notificationRecipients = ["samuel_wilkins@brown.edu"]; + private readonly signature = "-Dash Server Session Manager"; + + protected async launchMonitor() { + const monitor = Session.Monitor.Create({ + key: async key => { + // this sends a pseudorandomly generated guid to the configuration's recipients, allowing them alone + // to kill the server via the /kill/:key route + const content = `The key for this session (started @ ${new Date().toUTCString()}) is ${key}.\n\n${this.signature}`; + const failures = await Email.dispatchAll(this.notificationRecipients, "Server Termination Key", content); + if (failures) { + failures.map(({ recipient, error: { message } }) => monitor.mainLog(red(`dispatch failure @ ${recipient} (${yellow(message)})`))); + return false; + } + return true; + }, + crash: async ({ name, message, stack }) => { + const body = [ + "You, as a Dash Administrator, are being notified of a server crash event. Here's what we know:", + `name:\n${name}`, + `message:\n${message}`, + `stack:\n${stack}`, + "The server is already restarting itself, but if you're concerned, use the Remote Desktop Connection to monitor progress.", + ].join("\n\n"); + const content = `${body}\n\n${this.signature}`; + const failures = await Email.dispatchAll(this.notificationRecipients, "Dash Web Server Crash", content); + if (failures) { + failures.map(({ recipient, error: { message } }) => monitor.mainLog(red(`dispatch failure @ ${recipient} (${yellow(message)})`))); + return false; + } + return true; + } + }); + monitor.addReplCommand("pull", [], () => monitor.exec("git pull")); + monitor.addReplCommand("solr", [/start|stop/], async args => { + const command = `${onWindows ? "solr.cmd" : "solr"} ${args[0] === "start" ? "start" : "stop -p 8983"}`; + await monitor.exec(command, { cwd: "./solr-8.3.1/bin" }); + try { + await get("http://localhost:8983"); + monitor.mainLog(green("successfully connected to 8983 after running solr initialization")); + } catch { + monitor.mainLog(red("unable to connect at 8983 after running solr initialization")); + } + }); + return monitor; + } + + protected async launchServerWorker() { + const worker = Session.ServerWorker.Create(launchServer); // server initialization delegated to worker + worker.addExitHandler(() => { + const { _socket } = WebSocket; + _socket && Utils.Emit(_socket, MessageStore.ConnectionTerminated, "Manual"); + }); + return worker; + } + +}
\ No newline at end of file diff --git a/src/server/Session/session.ts b/src/server/Session/session.ts index cf2231b1f..6967ece52 100644 --- a/src/server/Session/session.ts +++ b/src/server/Session/session.ts @@ -1,338 +1,675 @@ -import { red, cyan, green, yellow, magenta, blue } from "colors"; -import { on, fork, setupMaster, Worker } from "cluster"; -import { execSync } from "child_process"; +import { red, cyan, green, yellow, magenta, blue, white, Color, grey, gray, black } from "colors"; +import { on, fork, setupMaster, Worker, isMaster, isWorker } from "cluster"; import { get } from "request-promise"; import { Utils } from "../../Utils"; import Repl, { ReplAction } from "../repl"; import { readFileSync } from "fs"; import { validate, ValidationError } from "jsonschema"; import { configurationSchema } from "./session_config_schema"; - -const onWindows = process.platform === "win32"; +import { exec, ExecOptions } from "child_process"; /** - * This namespace relies on NodeJS's cluster module, which allows a parent (master) process to share - * code with its children (workers). A simple `isMaster` flag indicates who is trying to access - * the code, and thus determines the functionality that actually gets invoked (checked by the caller, not internally). - * - * Think of the master thread as a factory, and the workers as the helpers that actually run the server. - * - * So, when we run `npm start`, given the appropriate check, initializeMaster() is called in the parent process - * This will spawn off its own child process (by default, mirrors the execution path of its parent), - * in which initializeWorker() is invoked. - */ + * This namespace relies on NodeJS's cluster module, which allows a parent (master) process to share + * code with its children (workers). A simple `isMaster` flag indicates who is trying to access + * the code, and thus determines the functionality that actually gets invoked (checked by the caller, not internally). + * + * Think of the master thread as a factory, and the workers as the helpers that actually run the server. + * + * So, when we run `npm start`, given the appropriate check, initializeMaster() is called in the parent process + * This will spawn off its own child process (by default, mirrors the execution path of its parent), + * in which initializeWorker() is invoked. + */ export namespace Session { + type ColorLabel = "yellow" | "red" | "cyan" | "green" | "blue" | "magenta" | "grey" | "gray" | "white" | "black"; + const colorMapping: Map<ColorLabel, Color> = new Map([ + ["yellow", yellow], + ["red", red], + ["cyan", cyan], + ["green", green], + ["blue", blue], + ["magenta", magenta], + ["grey", grey], + ["gray", gray], + ["white", white], + ["black", black] + ]); + + export abstract class AppliedSessionAgent { + + // the following two methods allow the developer to create a custom + // session and use the built in customization options for each thread + protected abstract async launchMonitor(): Promise<Session.Monitor>; + protected abstract async launchServerWorker(): Promise<Session.ServerWorker>; + + private launched = false; + + public killSession = (reason: string, graceful = true, errorCode = 0) => { + const target = isMaster ? this.sessionMonitor : this.serverWorker; + target.killSession(reason, graceful, errorCode); + } + + private sessionMonitorRef: Session.Monitor | undefined; + public get sessionMonitor(): Session.Monitor { + if (!isMaster) { + this.serverWorker.sendMonitorAction("kill", { + graceful: false, + reason: "Cannot access the session monitor directly from the server worker thread.", + errorCode: 1 + }); + throw new Error(); + } + return this.sessionMonitorRef!; + } + + private serverWorkerRef: Session.ServerWorker | undefined; + public get serverWorker(): Session.ServerWorker { + if (isMaster) { + throw new Error("Cannot access the server worker directly from the session monitor thread"); + } + return this.serverWorkerRef!; + } + + public async launch(): Promise<void> { + if (!this.launched) { + this.launched = true; + if (isMaster) { + this.sessionMonitorRef = await this.launchMonitor(); + } else { + this.serverWorkerRef = await this.launchServerWorker(); + } + } else { + throw new Error("Cannot launch a session thread more than once per process."); + } + } + + } + + interface Identifier { + text: string; + color: ColorLabel; + } + + interface Identifiers { + master: Identifier; + worker: Identifier; + exec: Identifier; + } + interface Configuration { showServerOutput: boolean; - masterIdentifier: string; - workerIdentifier: string; + identifiers: Identifiers; ports: { [description: string]: number }; - pollingRoute: string; - pollingIntervalSeconds: number; - [key: string]: any; + polling: { + route: string; + intervalSeconds: number; + failureTolerance: number; + }; } - const defaultConfiguration: Configuration = { + const defaultConfig: Configuration = { showServerOutput: false, - masterIdentifier: yellow("__monitor__:"), - workerIdentifier: magenta("__server__:"), + identifiers: { + master: { + text: "__monitor__", + color: "yellow" + }, + worker: { + text: "__server__", + color: "magenta" + }, + exec: { + text: "__exec__", + color: "green" + } + }, ports: { server: 3000 }, - pollingRoute: "/", - pollingIntervalSeconds: 30 + polling: { + route: "/", + intervalSeconds: 30, + failureTolerance: 0 + } }; - interface MasterExtensions { - addReplCommand: (basename: string, argPatterns: (RegExp | string)[], action: ReplAction) => void; - addChildMessageHandler: (message: string, handler: ActionHandler) => void; - } + export type ExitHandler = (reason: Error | null) => void | Promise<void>; - export interface NotifierHooks { - key?: (key: string) => boolean | Promise<boolean>; - crash?: (error: Error) => boolean | Promise<boolean>; - } + export namespace Monitor { - export interface SessionAction { - message: string; - args: any; - } + export interface NotifierHooks { + key?: (key: string) => (boolean | Promise<boolean>); + crash?: (error: Error) => (boolean | Promise<boolean>); + } + + export interface Action { + message: string; + args: any; + } + + export type ServerMessageHandler = (action: Action) => void | Promise<void>; - export type ExitHandler = (error: Error) => void | Promise<void>; - export type ActionHandler = (action: SessionAction) => void | Promise<void>; - export interface EmailTemplate { - subject: string; - body: string; } - function loadAndValidateConfiguration(): any { - try { - const configuration: Configuration = JSON.parse(readFileSync('./session.config.json', 'utf8')); - const options = { - throwError: true, - allowUnknownAttributes: false - }; - // ensure all necessary and no excess information is specified by the configuration file - validate(configuration, configurationSchema, options); - let formatMaster = true; - let formatWorker = true; - Object.keys(defaultConfiguration).forEach(property => { - if (!configuration[property]) { - if (property === "masterIdentifier") { - formatMaster = false; - } else if (property === "workerIdentifier") { - formatWorker = false; + /** + * Validates and reads the configuration file, accordingly builds a child process factory + * and spawns off an initial process that will respawn as predecessors die. + */ + export class Monitor { + + private static count = 0; + private exitHandlers: ExitHandler[] = []; + private readonly notifiers: Monitor.NotifierHooks | undefined; + private readonly config: Configuration; + private onMessage: { [message: string]: Monitor.ServerMessageHandler[] | undefined } = {}; + private activeWorker: Worker | undefined; + private key: string | undefined; + private repl: Repl; + + public static Create(notifiers?: Monitor.NotifierHooks) { + if (isWorker) { + process.send?.({ + action: { + message: "kill", + args: { + reason: "cannot create a monitor on the worker process.", + graceful: false, + errorCode: 1 + } } - configuration[property] = defaultConfiguration[property]; - } - }); - if (formatMaster) { - configuration.masterIdentifier = yellow(configuration.masterIdentifier + ":"); - } - if (formatWorker) { - configuration.workerIdentifier = magenta(configuration.workerIdentifier + ":"); + }); + process.exit(1); + } else if (++Monitor.count > 1) { + console.error(red("cannot create more than one monitor.")); + process.exit(1); + } else { + return new Monitor(notifiers); } - return configuration; - } catch (error) { - if (error instanceof ValidationError) { - console.log(red("\nSession configuration failed.")); - console.log("The given session.config.json configuration file is invalid."); - console.log(`${error.instance}: ${error.stack}`); - process.exit(0); - } else if (error.code === "ENOENT" && error.path === "./session.config.json") { - console.log(cyan("Loading default session parameters...")); - console.log("Consider including a session.config.json configuration file in your project root for customization."); - return defaultConfiguration; + } + + /** + * Kill this session and its active child + * server process, either gracefully (may wait + * indefinitely, but at least allows active networking + * requests to complete) or immediately. + */ + public killSession = async (reason: string, graceful = true, errorCode = 0) => { + this.mainLog(cyan(`exiting session ${graceful ? "clean" : "immediate"}ly`)); + this.mainLog(`reason: ${(red(reason))}`); + await this.executeExitHandlers(null); + this.killActiveWorker(graceful); + process.exit(errorCode); + } + + /** + * Execute the list of functions registered to be called + * whenever the process exits. + */ + public addExitHandler = (handler: ExitHandler) => this.exitHandlers.push(handler); + + /** + * Extend the default repl by adding in custom commands + * that can invoke application logic external to this module + */ + public addReplCommand = (basename: string, argPatterns: (RegExp | string)[], action: ReplAction) => { + this.repl.registerCommand(basename, argPatterns, action); + } + + public exec = (command: string, options?: ExecOptions) => { + return new Promise<void>(resolve => { + exec(command, { ...options, encoding: "utf8" }, (error, stdout, stderr) => { + if (error) { + this.execLog(red(`unable to execute ${white(command)}`)); + error.message.split("\n").forEach(line => line.length && this.execLog(red(`(error) ${line}`))); + } else { + let outLines: string[], errorLines: string[]; + if ((outLines = stdout.split("\n").filter(line => line.length)).length) { + outLines.forEach(line => line.length && this.execLog(cyan(`(stdout) ${line}`))); + } + if ((errorLines = stderr.split("\n").filter(line => line.length)).length) { + errorLines.forEach(line => line.length && this.execLog(yellow(`(stderr) ${line}`))); + } + } + resolve(); + }); + }); + } + + /** + * Add a listener at this message. When the monitor process + * receives a message, it will invoke all registered functions. + */ + public addServerMessageListener = (message: string, handler: Monitor.ServerMessageHandler) => { + const handlers = this.onMessage[message]; + if (handlers) { + handlers.push(handler); } else { - console.log(red("\nSession configuration failed.")); - console.log("The following unknown error occurred during configuration."); - console.log(error.stack); - process.exit(0); + this.onMessage[message] = [handler]; } } - } - function timestamp() { - return blue(`[${new Date().toUTCString()}]`); - } + /** + * Unregister a given listener at this message. + */ + public removeServerMessageListener = (message: string, handler: Monitor.ServerMessageHandler) => { + const handlers = this.onMessage[message]; + if (handlers) { + const index = handlers.indexOf(handler); + if (index > -1) { + handlers.splice(index, 1); + } + } + } - /** - * Validates and reads the configuration file, accordingly builds a child process factory - * and spawns off an initial process that will respawn as predecessors die. - */ - export async function initializeMonitorThread(notifiers?: NotifierHooks): Promise<MasterExtensions> { - let activeWorker: Worker; - const childMessageHandlers: { [message: string]: (action: SessionAction, args: any) => void } = {}; - - // read in configuration .json file only once, in the master thread - // pass down any variables the pertinent to the child processes as environment variables - const { - masterIdentifier, - workerIdentifier, - ports, - pollingRoute, - showServerOutput, - pollingIntervalSeconds - } = loadAndValidateConfiguration(); - - const masterLog = (...optionalParams: any[]) => console.log(timestamp(), masterIdentifier, ...optionalParams); - - // this sends a pseudorandomly generated guid to the configuration's recipients, allowing them alone - // to kill the server via the /kill/:key route - let key: string | undefined; - if (notifiers && notifiers.key) { - key = Utils.GenerateGuid(); - const success = await notifiers.key(key); - const statement = success ? green("distributed session key to recipients") : red("distribution of session key failed"); - masterLog(statement); + /** + * Unregister all listeners at this message. + */ + public clearServerMessageListeners = (message: string) => this.onMessage[message] = undefined; + + private constructor(notifiers?: Monitor.NotifierHooks) { + this.notifiers = notifiers; + + console.log(this.timestamp(), cyan("initializing session...")); + + this.config = this.loadAndValidateConfiguration(); + + this.initializeSessionKey(); + // determines whether or not we see the compilation / initialization / runtime output of each child server process + const output = this.config.showServerOutput ? "inherit" : "ignore"; + setupMaster({ stdio: ["ignore", output, output, "ipc"] }); + + // handle exceptions in the master thread - there shouldn't be many of these + // the IPC (inter process communication) channel closed exception can't seem + // to be caught in a try catch, and is inconsequential, so it is ignored + process.on("uncaughtException", ({ message, stack }): void => { + if (message !== "Channel closed") { + this.mainLog(red(message)); + if (stack) { + this.mainLog(`uncaught exception\n${red(stack)}`); + } + } + }); + + // a helpful cluster event called on the master thread each time a child process exits + on("exit", ({ process: { pid } }, code, signal) => { + const prompt = `server worker with process id ${pid} has exited with code ${code}${signal === null ? "" : `, having encountered signal ${signal}`}.`; + this.mainLog(cyan(prompt)); + // to make this a robust, continuous session, every time a child process dies, we immediately spawn a new one + this.spawn(); + }); + + this.repl = this.initializeRepl(); + this.spawn(); + } + + /** + * Generates a blue UTC string associated with the time + * of invocation. + */ + private timestamp = () => blue(`[${new Date().toUTCString()}]`); + + /** + * A formatted, identified and timestamped log in color + */ + public mainLog = (...optionalParams: any[]) => { + console.log(this.timestamp(), this.config.identifiers.master.text, ...optionalParams); + } + + /** + * A formatted, identified and timestamped log in color for non- + */ + private execLog = (...optionalParams: any[]) => { + console.log(this.timestamp(), this.config.identifiers.exec.text, ...optionalParams); + } + + /** + * If the caller has indicated an interest + * in being notified of this feature, creates + * a GUID for this session that can, for example, + * be used as authentication for killing the server + * (checked externally). + */ + private initializeSessionKey = async (): Promise<void> => { + if (this.notifiers?.key) { + this.key = Utils.GenerateGuid(); + const success = await this.notifiers.key(this.key); + const statement = success ? green("distributed session key to recipients") : red("distribution of session key failed"); + this.mainLog(statement); + } } - // handle exceptions in the master thread - there shouldn't be many of these - // the IPC (inter process communication) channel closed exception can't seem - // to be caught in a try catch, and is inconsequential, so it is ignored - process.on("uncaughtException", ({ message, stack }) => { - if (message !== "Channel closed") { - masterLog(red(message)); - if (stack) { - masterLog(`uncaught exception\n${red(stack)}`); + /** + * At any arbitrary layer of nesting within the configuration objects, any single value that + * is not specified by the configuration is given the default counterpart. If, within an object, + * one peer is given by configuration and two are not, the one is preserved while the two are given + * the default value. + */ + private assign = (defaultObject: any, specifiedObject: any, collector: any) => { + Array.from(new Set([...Object.keys(defaultObject), ...Object.keys(specifiedObject)])).map(property => { + let defaultValue: any, specifiedValue: any; + if (specifiedValue = specifiedObject[property]) { + if (typeof specifiedValue === "object" && typeof (defaultValue = defaultObject[property]) === "object") { + this.assign(defaultValue, specifiedValue, collector[property] = {}); + } else { + collector[property] = specifiedValue; + } + } else { + collector[property] = defaultObject[property]; + } + }); + } + + /** + * Reads in configuration .json file only once, in the master thread + * and pass down any variables the pertinent to the child processes as environment variables. + */ + private loadAndValidateConfiguration = (): Configuration => { + let config: Configuration; + try { + console.log(this.timestamp(), cyan("validating configuration...")); + config = JSON.parse(readFileSync('./session.config.json', 'utf8')); + const options = { + throwError: true, + allowUnknownAttributes: false + }; + // ensure all necessary and no excess information is specified by the configuration file + validate(config, configurationSchema, options); + const results: any = {}; + this.assign(defaultConfig, config, results); + config = results; + } catch (error) { + if (error instanceof ValidationError) { + console.log(red("\nSession configuration failed.")); + console.log("The given session.config.json configuration file is invalid."); + console.log(`${error.instance}: ${error.stack}`); + process.exit(0); + } else if (error.code === "ENOENT" && error.path === "./session.config.json") { + console.log(cyan("Loading default session parameters...")); + console.log("Consider including a session.config.json configuration file in your project root for customization."); + config = { ...defaultConfig }; + } else { + console.log(red("\nSession configuration failed.")); + console.log("The following unknown error occurred during configuration."); + console.log(error.stack); + process.exit(0); } + } finally { + const { identifiers } = config!; + Object.keys(identifiers).forEach(key => { + const resolved = key as keyof Identifiers; + const { text, color } = identifiers[resolved]; + identifiers[resolved].text = (colorMapping.get(color) || white)(`${text}:`); + }); + return config!; } - }); + } - // determines whether or not we see the compilation / initialization / runtime output of each child server process - setupMaster({ silent: !showServerOutput }); + /** + * Builds the repl that allows the following commands to be typed into stdin of the master thread. + */ + private initializeRepl = (): Repl => { + const repl = new Repl({ identifier: () => `${this.timestamp()} ${this.config.identifiers.master.text}` }); + const boolean = /true|false/; + const number = /\d+/; + const letters = /[a-zA-Z]+/; + repl.registerCommand("exit", [/clean|force/], args => this.killSession("manual exit requested by repl", args[0] === "clean", 0)); + repl.registerCommand("restart", [/clean|force/], args => this.killActiveWorker(args[0] === "clean")); + repl.registerCommand("set", [letters, "port", number, boolean], args => this.setPort(args[0], Number(args[2]), args[3] === "true")); + repl.registerCommand("set", [/polling/, number, boolean], args => { + const newPollingIntervalSeconds = Math.floor(Number(args[2])); + if (newPollingIntervalSeconds < 0) { + this.mainLog(red("the polling interval must be a non-negative integer")); + } else { + if (newPollingIntervalSeconds !== this.config.polling.intervalSeconds) { + this.config.polling.intervalSeconds = newPollingIntervalSeconds; + if (args[3] === "true") { + this.activeWorker?.send({ newPollingIntervalSeconds }); + } + } + } + }); + return repl; + } - // attempts to kills the active worker ungracefully - const tryKillActiveWorker = (graceful = false): boolean => { - if (activeWorker && !activeWorker.isDead()) { + private executeExitHandlers = async (reason: Error | null) => Promise.all(this.exitHandlers.map(handler => handler(reason))); + + /** + * Attempts to kill the active worker gracefully, unless otherwise specified. + */ + private killActiveWorker = (graceful = true): void => { + if (this.activeWorker && !this.activeWorker.isDead()) { if (graceful) { - activeWorker.kill(); + this.activeWorker.send({ manualExit: true }); } else { - activeWorker.process.kill(); + this.activeWorker.process.kill(); } - return true; } - return false; - }; - - const restart = () => { - // indicate to the worker that we are 'expecting' this restart - activeWorker.send({ setResponsiveness: false }); - tryKillActiveWorker(); - }; + } - const setPort = (port: string, value: number, immediateRestart: boolean) => { + /** + * Allows the caller to set the port at which the target (be it the server, + * the websocket, some other custom port) is listening. If an immediate restart + * is specified, this monitor will kill the active child and re-launch the server + * at the port. Otherwise, the updated port won't be used until / unless the child + * dies on its own and triggers a restart. + */ + private setPort = (port: "server" | "socket" | string, value: number, immediateRestart: boolean): void => { if (value > 1023 && value < 65536) { - ports[port] = value; + this.config.ports[port] = value; if (immediateRestart) { - restart(); + this.killActiveWorker(); } } else { - masterLog(red(`${port} is an invalid port number`)); + this.mainLog(red(`${port} is an invalid port number`)); } - }; + } - // kills the current active worker and proceeds to spawn a new worker, - // feeding in configuration information as environment variables - const spawn = (): void => { - tryKillActiveWorker(); - activeWorker = fork({ - pollingRoute, + /** + * Kills the current active worker and proceeds to spawn a new worker, + * feeding in configuration information as environment variables. + */ + private spawn = (): void => { + const { + polling: { + route, + failureTolerance, + intervalSeconds + }, + ports + } = this.config; + this.killActiveWorker(); + this.activeWorker = fork({ + pollingRoute: route, + pollingFailureTolerance: failureTolerance, serverPort: ports.server, socketPort: ports.socket, - pollingIntervalSeconds, - session_key: key + pollingIntervalSeconds: intervalSeconds, + session_key: this.key }); - masterLog(`spawned new server worker with process id ${activeWorker.process.pid}`); + this.mainLog(cyan(`spawned new server worker with process id ${this.activeWorker.process.pid}`)); // an IPC message handler that executes actions on the master thread when prompted by the active worker - activeWorker.on("message", async ({ lifecycle, action }) => { + this.activeWorker.on("message", async ({ lifecycle, action }) => { if (action) { - const { message, args } = action as SessionAction; - console.log(timestamp(), `${workerIdentifier} action requested (${cyan(message)})`); + const { message, args } = action as Monitor.Action; + console.log(this.timestamp(), `${this.config.identifiers.worker.text} action requested (${cyan(message)})`); switch (message) { case "kill": - masterLog(red("an authorized user has manually ended the server session")); - tryKillActiveWorker(true); - process.exit(0); + const { reason, graceful, errorCode } = args; + this.killSession(reason, graceful, errorCode); + break; case "notify_crash": - if (notifiers && notifiers.crash) { + if (this.notifiers?.crash) { const { error } = args; - const success = await notifiers.crash(error); + const success = await this.notifiers.crash(error); const statement = success ? green("distributed crash notification to recipients") : red("distribution of crash notification failed"); - masterLog(statement); + this.mainLog(statement); } + break; case "set_port": const { port, value, immediateRestart } = args; - setPort(port, value, immediateRestart); - default: - const handler = childMessageHandlers[message]; - if (handler) { - handler(action, args); - } + this.setPort(port, value, immediateRestart); + break; } - } else if (lifecycle) { - console.log(timestamp(), `${workerIdentifier} lifecycle phase (${lifecycle})`); + const handlers = this.onMessage[message]; + if (handlers) { + handlers.forEach(handler => handler({ message, args })); + } + } + if (lifecycle) { + console.log(this.timestamp(), `${this.config.identifiers.worker.text} lifecycle phase (${lifecycle})`); } }); - }; + } - // a helpful cluster event called on the master thread each time a child process exits - on("exit", ({ process: { pid } }, code, signal) => { - const prompt = `server worker with process id ${pid} has exited with code ${code}${signal === null ? "" : `, having encountered signal ${signal}`}.`; - masterLog(cyan(prompt)); - // to make this a robust, continuous session, every time a child process dies, we immediately spawn a new one - spawn(); - }); - - // builds the repl that allows the following commands to be typed into stdin of the master thread - const repl = new Repl({ identifier: () => `${timestamp()} ${masterIdentifier}` }); - repl.registerCommand("exit", [], () => execSync(onWindows ? "taskkill /f /im node.exe" : "killall -9 node")); - repl.registerCommand("restart", [], restart); - repl.registerCommand("set", [/[a-zA-Z]+/, "port", /\d+/, /true|false/], args => setPort(args[0], Number(args[2]), args[3] === "true")); - // finally, set things in motion by spawning off the first child (server) process - spawn(); - - // returned to allow the caller to add custom commands - return { - addReplCommand: repl.registerCommand, - addChildMessageHandler: (message: string, handler: ActionHandler) => { childMessageHandlers[message] = handler; } - }; } /** * Effectively, each worker repairs the connection to the server by reintroducing a consistent state * if its predecessor has died. It itself also polls the server heartbeat, and exits with a notification * email if the server encounters an uncaught exception or if the server cannot be reached. - * @param work the function specifying the work to be done by each worker thread */ - export async function initializeWorkerThread(work: Function): Promise<(handler: ExitHandler) => void> { - let shouldServerBeResponsive = false; - const exitHandlers: ExitHandler[] = []; - - // notify master thread (which will log update in the console) of initialization via IPC - process.send?.({ lifecycle: green("compiling and initializing...") }); + export class ServerWorker { + + private static count = 0; + private shouldServerBeResponsive = false; + private exitHandlers: ExitHandler[] = []; + private pollingFailureCount = 0; + private pollingIntervalSeconds: number; + private pollingFailureTolerance: number; + private pollTarget: string; + private serverPort: number; + + public static Create(work: Function) { + if (isMaster) { + console.error(red("cannot create a worker on the monitor process.")); + process.exit(1); + } else if (++ServerWorker.count > 1) { + process.send?.({ + action: { + message: "kill", args: { + reason: "cannot create more than one worker on a given worker process.", + graceful: false, + errorCode: 1 + } + } + }); + process.exit(1); + } else { + return new ServerWorker(work); + } + } - // updates the local value of listening to the value sent from master - process.on("message", ({ setResponsiveness }) => shouldServerBeResponsive = setResponsiveness); + /** + * Allows developers to invoke application specific logic + * by hooking into the exiting of the server process. + */ + public addExitHandler = (handler: ExitHandler) => this.exitHandlers.push(handler); + + /** + * Kill the session monitor (parent process) from this + * server worker (child process). This will also kill + * this process (child process). + */ + public killSession = (reason: string, graceful = true, errorCode = 0) => this.sendMonitorAction("kill", { reason, graceful, errorCode }); + + /** + * A convenience wrapper to tell the session monitor (parent process) + * to carry out the action with the specified message and arguments. + */ + public sendMonitorAction = (message: string, args?: any) => process.send!({ action: { message, args } }); + + private constructor(work: Function) { + this.lifecycleNotification(green(`initializing process... (${white(`${process.execPath} ${process.execArgv.join(" ")}`)})`)); + + const { pollingRoute, serverPort, pollingIntervalSeconds, pollingFailureTolerance } = process.env; + this.serverPort = Number(serverPort); + this.pollingIntervalSeconds = Number(pollingIntervalSeconds); + this.pollingFailureTolerance = Number(pollingFailureTolerance); + this.pollTarget = `http://localhost:${serverPort}${pollingRoute}`; + + this.configureProcess(); + work(); + this.pollServer(); + } - // called whenever the process has a reason to terminate, either through an uncaught exception - // in the process (potentially inconsistent state) or the server cannot be reached - const activeExit = async (error: Error): Promise<void> => { - if (!shouldServerBeResponsive) { - return; - } - shouldServerBeResponsive = false; - // communicates via IPC to the master thread that it should dispatch a crash notification email - process.send?.({ - action: { - message: "notify_crash", - args: { error } + /** + * Set up message and uncaught exception handlers for this + * server process. + */ + private configureProcess = () => { + // updates the local values of variables to the those sent from master + process.on("message", async ({ newPollingIntervalSeconds, manualExit }) => { + if (newPollingIntervalSeconds !== undefined) { + this.pollingIntervalSeconds = newPollingIntervalSeconds; + } + if (manualExit !== undefined) { + await this.executeExitHandlers(null); + process.exit(0); } }); - await Promise.all(exitHandlers.map(handler => handler(error))); + + // one reason to exit, as the process might be in an inconsistent state after such an exception + process.on('uncaughtException', this.proactiveUnplannedExit); + process.on('unhandledRejection', this.proactiveUnplannedExit); + } + + /** + * Execute the list of functions registered to be called + * whenever the process exits. + */ + private executeExitHandlers = async (reason: Error | null) => Promise.all(this.exitHandlers.map(handler => handler(reason))); + + /** + * Notify master thread (which will log update in the console) of initialization via IPC. + */ + public lifecycleNotification = (event: string) => process.send?.({ lifecycle: event }); + + /** + * Called whenever the process has a reason to terminate, either through an uncaught exception + * in the process (potentially inconsistent state) or the server cannot be reached. + */ + private proactiveUnplannedExit = async (error: any): Promise<void> => { + this.shouldServerBeResponsive = false; + // communicates via IPC to the master thread that it should dispatch a crash notification email + this.sendMonitorAction("notify_crash", { error }); + await this.executeExitHandlers(error); // notify master thread (which will log update in the console) of crash event via IPC - process.send?.({ lifecycle: red(`crash event detected @ ${new Date().toUTCString()}`) }); - process.send?.({ lifecycle: red(error.message) }); + this.lifecycleNotification(red(`crash event detected @ ${new Date().toUTCString()}`)); + this.lifecycleNotification(red(error.message || error)); process.exit(1); - }; + } - // one reason to exit, as the process might be in an inconsistent state after such an exception - process.on('uncaughtException', activeExit); - - const { - pollingIntervalSeconds, - pollingRoute, - serverPort - } = process.env; - // this monitors the health of the server by submitting a get request to whatever port / route specified - // by the configuration every n seconds, where n is also given by the configuration. - const pollTarget = `http://localhost:${serverPort}${pollingRoute}`; - const pollServer = async (): Promise<void> => { + /** + * This monitors the health of the server by submitting a get request to whatever port / route specified + * by the configuration every n seconds, where n is also given by the configuration. + */ + private pollServer = async (): Promise<void> => { await new Promise<void>(resolve => { setTimeout(async () => { try { - await get(pollTarget); - if (!shouldServerBeResponsive) { - // notify master thread (which will log update in the console) via IPC that the server is up and running - process.send?.({ lifecycle: green(`listening on ${serverPort}...`) }); + await get(this.pollTarget); + if (!this.shouldServerBeResponsive) { + // notify monitor thread that the server is up and running + this.lifecycleNotification(green(`listening on ${this.serverPort}...`)); } - shouldServerBeResponsive = true; + this.shouldServerBeResponsive = true; resolve(); } catch (error) { // if we expect the server to be unavailable, i.e. during compilation, // the listening variable is false, activeExit will return early and the child // process will continue - activeExit(error); + if (this.shouldServerBeResponsive) { + if (++this.pollingFailureCount > this.pollingFailureTolerance) { + this.proactiveUnplannedExit(error); + } else { + this.lifecycleNotification(yellow(`the server has encountered ${this.pollingFailureCount} of ${this.pollingFailureTolerance} tolerable failures`)); + } + } } - }, 1000 * Number(pollingIntervalSeconds)); + }, 1000 * this.pollingIntervalSeconds); }); // controlled, asynchronous infinite recursion achieves a persistent poll that does not submit a new request until the previous has completed - pollServer(); - }; - - work(); - pollServer(); // begin polling + this.pollServer(); + } - return (handler: ExitHandler) => exitHandlers.push(handler); } }
\ No newline at end of file diff --git a/src/server/Session/session_config_schema.ts b/src/server/Session/session_config_schema.ts index 76af04b9f..e32cf8c6a 100644 --- a/src/server/Session/session_config_schema.ts +++ b/src/server/Session/session_config_schema.ts @@ -1,35 +1,67 @@ import { Schema } from "jsonschema"; +const colorPattern = /black|red|green|yellow|blue|magenta|cyan|white|gray|grey/; + +const identifierProperties: Schema = { + type: "object", + properties: { + text: { + type: "string", + minLength: 1 + }, + color: { + type: "string", + pattern: colorPattern + } + } +}; + +const portProperties: Schema = { + type: "number", + minimum: 1024, + maximum: 65535 +}; + export const configurationSchema: Schema = { id: "/configuration", type: "object", properties: { + showServerOutput: { type: "boolean" }, ports: { type: "object", properties: { - server: { type: "number", minimum: 1024, maximum: 65535 }, - socket: { type: "number", minimum: 1024, maximum: 65535 } + server: portProperties, + socket: portProperties }, required: ["server"], additionalProperties: true }, - pollingRoute: { - type: "string", - pattern: /\/[a-zA-Z]*/g - }, - masterIdentifier: { - type: "string", - minLength: 1 + identifiers: { + type: "object", + properties: { + master: identifierProperties, + worker: identifierProperties, + exec: identifierProperties + } }, - workerIdentifier: { - type: "string", - minLength: 1 + polling: { + type: "object", + additionalProperties: false, + properties: { + intervalSeconds: { + type: "number", + minimum: 1, + maximum: 86400 + }, + route: { + type: "string", + pattern: /\/[a-zA-Z]*/g + }, + failureTolerance: { + type: "number", + minimum: 0, + } + } }, - showServerOutput: { type: "boolean" }, - pollingIntervalSeconds: { - type: "number", - minimum: 1, - maximum: 86400 - } } };
\ No newline at end of file diff --git a/src/server/index.ts b/src/server/index.ts index 5e411aa3a..6b3dfd614 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -3,10 +3,9 @@ import { GoogleApiServerUtils } from "./apis/google/GoogleApiServerUtils"; import * as mobileDetect from 'mobile-detect'; import * as path from 'path'; import { Database } from './database'; -const serverPort = 4321; import { DashUploadUtils } from './DashUploadUtils'; import RouteSubscriber from './RouteSubscriber'; -import initializeServer from './server_Initialization'; +import initializeServer from './server_initialization'; import RouteManager, { Method, _success, _permission_denied, _error, _invalid, PublicHandler } from './RouteManager'; import * as qs from 'query-string'; import UtilManager from './ApiManagers/UtilManager'; @@ -22,13 +21,12 @@ import { log_execution, Email } from "./ActionUtilities"; import GeneralGoogleManager from "./ApiManagers/GeneralGoogleManager"; import GooglePhotosManager from "./ApiManagers/GooglePhotosManager"; import { Logger } from "./ProcessFactory"; -import { yellow } from "colors"; +import { yellow, red } from "colors"; import { Session } from "./Session/session"; -import { isMaster } from "cluster"; -import { execSync } from "child_process"; -import { Utils } from "../Utils"; -import { MessageStore } from "./Message"; +import { DashSessionAgent } from "./DashSession"; +export const onWindows = process.platform === "win32"; +export let sessionAgent: Session.AppliedSessionAgent; export const publicDirectory = path.resolve(__dirname, "public"); export const filesDirectory = path.resolve(publicDirectory, "files"); @@ -96,7 +94,9 @@ function routeSetter({ isRelease, addSupervisedRoute, logRegistrationOutcome }: secureHandler: ({ req, res }) => { if (req.params.key === process.env.session_key) { res.send("<img src='https://media.giphy.com/media/NGIfqtcS81qi4/giphy.gif' style='width:100%;height:100%;'/>"); - process.send!({ action: { message: "kill" } }); + setTimeout(() => { + sessionAgent.killSession("an authorized user has manually ended the server session via the /kill route", false); + }, 5000); } else { res.redirect("/home"); } @@ -136,7 +136,7 @@ function routeSetter({ isRelease, addSupervisedRoute, logRegistrationOutcome }: * however, this becomes the logic invoked by a single worker thread spawned by * the main monitor (master) thread. */ -async function launchServer() { +export async function launchServer() { await log_execution({ startMessage: "\nstarting execution of preliminary functions", endMessage: "completed preliminary functions\n", @@ -146,51 +146,13 @@ async function launchServer() { } /** - * If we're the monitor (master) thread, we should launch the monitor logic for the session. - * Otherwise, we must be on a worker thread that was spawned *by* the monitor (master) thread, and thus - * our job should be to run the server. - */ -async function launchMonitoredSession() { - if (isMaster) { - const recipients = ["samuel_wilkins@brown.edu"]; - const signature = "-Dash Server Session Manager"; - const customizer = await Session.initializeMonitorThread({ - key: async (key: string) => { - const content = `The key for this session (started @ ${new Date().toUTCString()}) is ${key}.\n\n${signature}`; - const failures = await Email.dispatchAll(recipients, "Server Termination Key", content); - return failures.length === 0; - }, - crash: async (error: Error) => { - const subject = "Dash Web Server Crash"; - const { name, message, stack } = error; - const body = [ - "You, as a Dash Administrator, are being notified of a server crash event. Here's what we know:", - `name:\n${name}`, - `message:\n${message}`, - `stack:\n${stack}`, - "The server is already restarting itself, but if you're concerned, use the Remote Desktop Connection to monitor progress.", - ].join("\n\n"); - const content = `${body}\n\n${signature}`; - const failures = await Email.dispatchAll(recipients, subject, content); - return failures.length === 0; - } - }); - customizer.addReplCommand("pull", [], () => execSync("git pull", { stdio: ["ignore", "inherit", "inherit"] })); - customizer.addReplCommand("solr", [/start|stop/g], args => SolrManager.SetRunning(args[0] === "start")); - } else { - const addExitHandler = await Session.initializeWorkerThread(launchServer); // server initialization delegated to worker - addExitHandler(() => Utils.Emit(WebSocket._socket, MessageStore.ConnectionTerminated, "Manual")); - } -} - -/** * If you're in development mode, you won't need to run a session. * The session spawns off new server processes each time an error is encountered, and doesn't * log the output of the server process, so it's not ideal for development. * So, the 'else' clause is exactly what we've always run when executing npm start. */ if (process.env.RELEASE) { - launchMonitoredSession(); + (sessionAgent = new DashSessionAgent()).launch(); } else { launchServer(); }
\ No newline at end of file diff --git a/src/server/repl.ts b/src/server/repl.ts index bd00e48cd..ad55b6aaa 100644 --- a/src/server/repl.ts +++ b/src/server/repl.ts @@ -3,7 +3,7 @@ import { red, green, white } from "colors"; export interface Configuration { identifier: () => string | string; - onInvalid?: (culprit?: string) => string | string; + onInvalid?: (command: string, validCommand: boolean) => string | string; onValid?: (success?: string) => string | string; isCaseSensitive?: boolean; } @@ -16,8 +16,8 @@ export interface Registration { export default class Repl { private identifier: () => string | string; - private onInvalid: (culprit?: string) => string | string; - private onValid: (success: string) => string | string; + private onInvalid: ((command: string, validCommand: boolean) => string) | string; + private onValid: ((success: string) => string) | string; private isCaseSensitive: boolean; private commandMap = new Map<string, Registration[]>(); public interface: Interface; @@ -34,18 +34,24 @@ export default class Repl { private resolvedIdentifier = () => typeof this.identifier === "string" ? this.identifier : this.identifier(); - private usage = () => { - const resolved = this.keys; - if (resolved) { - return resolved; - } - const members: string[] = []; - const keys = this.commandMap.keys(); - let next: IteratorResult<string>; - while (!(next = keys.next()).done) { - members.push(next.value); + private usage = (command: string, validCommand: boolean) => { + if (validCommand) { + const formatted = white(command); + const patterns = green(this.commandMap.get(command)!.map(({ argPatterns }) => `${formatted} ${argPatterns.join(" ")}`).join('\n')); + return `${this.resolvedIdentifier()}\nthe given arguments do not match any registered patterns for ${formatted}\nthe list of valid argument patterns is given by:\n${patterns}`; + } else { + const resolved = this.keys; + if (resolved) { + return resolved; + } + const members: string[] = []; + const keys = this.commandMap.keys(); + let next: IteratorResult<string>; + while (!(next = keys.next()).done) { + members.push(next.value); + } + return `${this.resolvedIdentifier()} commands: { ${members.sort().join(", ")} }`; } - return `${this.resolvedIdentifier()} commands: { ${members.sort().join(", ")} }`; } private success = (command: string) => `${this.resolvedIdentifier()} completed execution of ${white(command)}`; @@ -61,8 +67,8 @@ export default class Repl { } } - private invalid = (culprit?: string) => { - console.log(red(typeof this.onInvalid === "string" ? this.onInvalid : this.onInvalid(culprit))); + private invalid = (command: string, validCommand: boolean) => { + console.log(red(typeof this.onInvalid === "string" ? this.onInvalid : this.onInvalid(command, validCommand))); this.busy = false; } @@ -83,7 +89,7 @@ export default class Repl { } const [command, ...args] = line.split(/\s+/g); if (!command) { - return this.invalid(); + return this.invalid(command, false); } const registered = this.commandMap.get(command); if (registered) { @@ -91,25 +97,32 @@ export default class Repl { const candidates = registered.filter(({ argPatterns: { length: count } }) => count === length); for (const { argPatterns, action } of candidates) { const parsed: string[] = []; - let matched = false; + let matched = true; if (length) { for (let i = 0; i < length; i++) { let matches: RegExpExecArray | null; if ((matches = argPatterns[i].exec(args[i])) === null) { + matched = false; break; } parsed.push(matches[0]); } - matched = true; } if (!length || matched) { - await action(parsed); - this.valid(`${command} ${parsed.join(" ")}`); + const result = action(parsed); + const resolve = () => this.valid(`${command} ${parsed.join(" ")}`); + if (result instanceof Promise) { + result.then(resolve); + } else { + resolve(); + } return; } } + this.invalid(command, true); + } else { + this.invalid(command, false); } - this.invalid(command); } }
\ No newline at end of file diff --git a/src/server/server_Initialization.ts b/src/server/server_Initialization.ts index 0f502e8fb..cbe070293 100644 --- a/src/server/server_Initialization.ts +++ b/src/server/server_Initialization.ts @@ -22,7 +22,7 @@ import { publicDirectory } from '.'; import { logPort, } from './ActionUtilities'; import { timeMap } from './ApiManagers/UserManager'; import { blue, yellow } from 'colors'; -var cors = require('cors'); +import * as cors from "cors"; /* RouteSetter is a wrapper around the server that prevents the server from being exposed. */ @@ -33,13 +33,11 @@ export default async function InitializeServer(routeSetter: RouteSetter) { const app = buildWithMiddleware(express()); app.use(express.static(publicDirectory, { - setHeaders: (res, path) => { - res.setHeader("Access-Control-Allow-Origin", "*"); - } + setHeaders: res => res.setHeader("Access-Control-Allow-Origin", "*") })); app.use("/images", express.static(publicDirectory)); const corsOptions = { - origin: function (origin: any, callback: any) { + origin: function (_origin: any, callback: any) { callback(null, true); } }; diff --git a/src/typings/index.d.ts b/src/typings/index.d.ts index 887f96734..cc68e8a4d 100644 --- a/src/typings/index.d.ts +++ b/src/typings/index.d.ts @@ -4,6 +4,7 @@ declare module 'googlephotos'; declare module 'react-image-lightbox-with-rotate'; declare module 'kill-port'; declare module 'ipc-event-emitter'; +declare module 'cors'; declare module '@react-pdf/renderer' { import * as React from 'react'; |