aboutsummaryrefslogtreecommitdiff
path: root/src/client/util
diff options
context:
space:
mode:
Diffstat (limited to 'src/client/util')
-rw-r--r--src/client/util/DictationManager.ts10
-rw-r--r--src/client/util/DocumentManager.ts173
-rw-r--r--src/client/util/DragManager.ts91
-rw-r--r--src/client/util/DropConverter.ts45
-rw-r--r--src/client/util/History.ts6
-rw-r--r--src/client/util/Import & Export/DirectoryImportBox.tsx21
-rw-r--r--src/client/util/Import & Export/ImageUtils.ts5
-rw-r--r--src/client/util/InteractionUtils.tsx64
-rw-r--r--src/client/util/KeyCodes.ts136
-rw-r--r--src/client/util/LinkManager.ts54
-rw-r--r--src/client/util/ParagraphNodeSpec.ts143
-rw-r--r--src/client/util/ProsemirrorExampleTransfer.ts191
-rw-r--r--src/client/util/RichTextMenu.scss121
-rw-r--r--src/client/util/RichTextMenu.tsx860
-rw-r--r--src/client/util/RichTextRules.ts295
-rw-r--r--src/client/util/RichTextSchema.tsx1144
-rw-r--r--src/client/util/Scripting.ts30
-rw-r--r--src/client/util/SearchUtil.ts35
-rw-r--r--src/client/util/SelectionManager.ts13
-rw-r--r--src/client/util/SettingsManager.scss2
-rw-r--r--src/client/util/SharingManager.tsx2
-rw-r--r--src/client/util/prosemirrorPatches.js139
-rw-r--r--src/client/util/type_decls.d2
23 files changed, 475 insertions, 3107 deletions
diff --git a/src/client/util/DictationManager.ts b/src/client/util/DictationManager.ts
index 3394cb93d..b3295ece0 100644
--- a/src/client/util/DictationManager.ts
+++ b/src/client/util/DictationManager.ts
@@ -10,7 +10,6 @@ import { CollectionViewType } from "../views/collections/CollectionView";
import { Cast, CastCtor } from "../../new_fields/Types";
import { listSpec } from "../../new_fields/Schema";
import { AudioField, ImageField } from "../../new_fields/URLField";
-import { HistogramField } from "../northstar/dash-fields/HistogramField";
import { Utils } from "../../Utils";
import { RichTextField } from "../../new_fields/RichTextField";
import { DictationOverlay } from "../views/DictationOverlay";
@@ -282,9 +281,8 @@ export namespace DictationManager {
[DocumentType.COL, listSpec(Doc)],
[DocumentType.AUDIO, AudioField],
[DocumentType.IMG, ImageField],
- [DocumentType.HIST, HistogramField],
[DocumentType.IMPORT, listSpec(Doc)],
- [DocumentType.TEXT, "string"]
+ [DocumentType.RTF, "string"]
]);
const tryCast = (view: DocumentView, type: DocumentType) => {
@@ -326,7 +324,7 @@ export namespace DictationManager {
["open fields", {
action: (target: DocumentView) => {
const kvp = Docs.Create.KVPDocument(target.props.Document, { _width: 300, _height: 300 });
- target.props.addDocTab(kvp, target.props.DataDoc, "onRight");
+ target.props.addDocTab(kvp, "onRight");
}
}],
@@ -340,7 +338,7 @@ export namespace DictationManager {
const proseMirrorState = `{"doc":{"type":"doc","content":[{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"type":"text","text":"${prompt}"}]}]}]}]},"selection":{"type":"text","anchor":${anchor},"head":${head}}}`;
proto.data = new RichTextField(proseMirrorState);
proto.backgroundColor = "#eeffff";
- target.props.addDocTab(newBox, proto, "onRight");
+ target.props.addDocTab(newBox, "onRight");
}
}]
@@ -377,7 +375,7 @@ export namespace DictationManager {
{
expression: /view as (freeform|stacking|masonry|schema|tree)/g,
action: (target: DocumentView, matches: RegExpExecArray) => {
- const mode = CollectionViewType.valueOf(matches[1]);
+ const mode = matches[1];
mode && (target.props.Document._viewType = mode);
},
restrictTo: [DocumentType.COL]
diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts
index 60bb25272..4683e77a8 100644
--- a/src/client/util/DocumentManager.ts
+++ b/src/client/util/DocumentManager.ts
@@ -1,16 +1,16 @@
import { action, computed, observable } from 'mobx';
-import { Doc, DocListCastAsync, DocListCast } from '../../new_fields/Doc';
+import { Doc, DocListCastAsync, DocListCast, Opt } from '../../new_fields/Doc';
import { Id } from '../../new_fields/FieldSymbols';
-import { List } from '../../new_fields/List';
import { Cast, NumCast, StrCast } from '../../new_fields/Types';
import { CollectionDockingView } from '../views/collections/CollectionDockingView';
import { CollectionView } from '../views/collections/CollectionView';
-import { DocumentView } from '../views/nodes/DocumentView';
+import { DocumentView, DocFocusFunc } from '../views/nodes/DocumentView';
import { LinkManager } from './LinkManager';
import { Scripting } from './Scripting';
import { SelectionManager } from './SelectionManager';
import { DocumentType } from '../documents/DocumentTypes';
+export type CreateViewFunc = (doc: Doc, followLinkLocation: string, finished?: () => void) => void;
export class DocumentManager {
@@ -28,7 +28,6 @@ export class DocumentManager {
//private constructor so no other class can create a nodemanager
private constructor() {
- // this.DocumentViews = new Array<DocumentView>();
}
//gets all views
@@ -55,7 +54,7 @@ export class DocumentManager {
}
public getDocumentViewById(id: string, preferredCollection?: CollectionView): DocumentView | undefined {
-
+ if (!id) return undefined;
let toReturn: DocumentView | undefined;
const passes = preferredCollection ? [preferredCollection, undefined] : [undefined];
@@ -85,17 +84,20 @@ export class DocumentManager {
return this.getDocumentViewById(toFind[Id], preferredCollection);
}
- public getFirstDocumentView(toFind: Doc): DocumentView | undefined {
- const views = this.getDocumentViews(toFind);
- return views.length ? views[0] : undefined;
+ public getFirstDocumentView = (toFind: Doc, originatingDoc: Opt<Doc> = undefined): DocumentView | undefined => {
+ return this.getDocumentViews(toFind)?.find(view => view.props.Document !== originatingDoc);
}
public getDocumentViews(toFind: Doc): DocumentView[] {
const toReturn: DocumentView[] = [];
+ const docViews = DocumentManager.Instance.DocumentViews;
- DocumentManager.Instance.DocumentViews.map(view =>
- view.props.Document.presBox === undefined && view.props.Document === toFind && toReturn.push(view));
- DocumentManager.Instance.DocumentViews.map(view =>
- view.props.Document.presBox === undefined && view.props.Document !== toFind && Doc.AreProtosEqual(view.props.Document, toFind) && toReturn.push(view));
+ // heuristic to return the "best" documents first:
+ // choose an exact match over an alias match
+ // choose documents that have a PanelWidth() over those that don't (the treeview documents have no panelWidth)
+ docViews.map(view => !view.props.Document.presBox && view.props.PanelWidth() > 1 && view.props.Document === toFind && toReturn.push(view));
+ docViews.map(view => !view.props.Document.presBox && view.props.PanelWidth() <= 1 && view.props.Document === toFind && toReturn.push(view));
+ docViews.map(view => !view.props.Document.presBox && view.props.PanelWidth() > 1 && view.props.Document !== toFind && Doc.AreProtosEqual(view.props.Document, toFind) && toReturn.push(view));
+ docViews.map(view => !view.props.Document.presBox && view.props.PanelWidth() <= 1 && view.props.Document !== toFind && Doc.AreProtosEqual(view.props.Document, toFind) && toReturn.push(view));
return toReturn;
}
@@ -127,99 +129,116 @@ export class DocumentManager {
return pairs;
}
- public jumpToDocument = async (targetDoc: Doc, willZoom: boolean, dockFunc?: (doc: Doc) => void, docContext?: Doc, linkId?: string, closeContextIfNotFound: boolean = false): Promise<void> => {
+ static addRightSplit = (doc: Doc, finished?: () => void) => {
+ CollectionDockingView.AddRightSplit(doc);
+ finished?.();
+ }
+ public jumpToDocument = async (
+ targetDoc: Doc,
+ willZoom: boolean,
+ createViewFunc = DocumentManager.addRightSplit,
+ docContext?: Doc,
+ linkId?: string,
+ closeContextIfNotFound: boolean = false,
+ originatingDoc: Opt<Doc> = undefined,
+ finished?: () => void
+ ): Promise<void> => {
+ const getFirstDocView = DocumentManager.Instance.getFirstDocumentView;
+ const focusAndFinish = () => { finished?.(); return false; };
const highlight = () => {
- const finalDocView = DocumentManager.Instance.getFirstDocumentView(targetDoc);
- finalDocView && (finalDocView.Document.scrollToLinkID = linkId);
- finalDocView && Doc.linkFollowHighlight(finalDocView.props.Document);
+ const finalDocView = getFirstDocView(targetDoc);
+ if (finalDocView) {
+ finalDocView.layoutDoc.scrollToLinkID = linkId;
+ Doc.linkFollowHighlight(finalDocView.props.Document);
+ }
};
- const docView = DocumentManager.Instance.getFirstDocumentView(targetDoc);
- let annotatedDoc = await Cast(docView?.props.Document.annotationOn, Doc);
+ const docView = getFirstDocView(targetDoc, originatingDoc);
+ let annotatedDoc = await Cast(targetDoc.annotationOn, Doc);
if (annotatedDoc) {
- const first = DocumentManager.Instance.getFirstDocumentView(annotatedDoc);
- if (first) annotatedDoc = first.props.Document;
+ const first = getFirstDocView(annotatedDoc);
+ if (first) {
+ annotatedDoc = first.props.Document;
+ if (docView) {
+ docView.props.focus(annotatedDoc, false);
+ }
+ }
}
if (docView) { // we have a docView already and aren't forced to create a new one ... just focus on the document. TODO move into view if necessary otherwise just highlight?
- docView.props.focus(docView.props.Document, willZoom);
+ docView.props.focus(docView.props.Document, willZoom, undefined, focusAndFinish);
highlight();
} else {
const contextDocs = docContext ? await DocListCastAsync(docContext.data) : undefined;
- const contextDoc = contextDocs && contextDocs.find(doc => Doc.AreProtosEqual(doc, targetDoc)) ? docContext : undefined;
- const targetDocContext = (annotatedDoc ? annotatedDoc : contextDoc);
+ const contextDoc = contextDocs?.find(doc => Doc.AreProtosEqual(doc, targetDoc)) ? docContext : undefined;
+ const targetDocContext = annotatedDoc || contextDoc;
if (!targetDocContext) { // we don't have a view and there's no context specified ... create a new view of the target using the dockFunc or default
- (dockFunc || CollectionDockingView.AddRightSplit)(Doc.BrushDoc(Doc.MakeAlias(targetDoc)), undefined);
+ createViewFunc(Doc.BrushDoc(targetDoc), finished); // bcz: should we use this?: Doc.MakeAlias(targetDoc)));
highlight();
- } else {
- const targetDocContextView = DocumentManager.Instance.getFirstDocumentView(targetDocContext);
+ } else { // otherwise try to get a view of the context of the target
+ const targetDocContextView = getFirstDocView(targetDocContext);
targetDocContext.scrollY = 0; // this will force PDFs to activate and load their annotations / allow scrolling
- if (targetDocContextView) { // we have a context view and aren't forced to create a new one ... focus on the context
+ if (targetDocContextView) { // we found a context view and aren't forced to create a new one ... focus on the context first..
targetDocContext.panTransformType = "Ease";
targetDocContextView.props.focus(targetDocContextView.props.Document, willZoom);
// now find the target document within the context
- setTimeout(() => {
- const retryDocView = DocumentManager.Instance.getDocumentView(targetDoc);
- if (retryDocView) {
- retryDocView.props.focus(targetDoc, willZoom); // focus on the target if it now exists in the context
- } else {
- if (closeContextIfNotFound && targetDocContextView.props.removeDocument) targetDocContextView.props.removeDocument(targetDocContextView.props.Document);
- targetDoc.layout && (dockFunc || CollectionDockingView.AddRightSplit)(Doc.BrushDoc(Doc.MakeAlias(targetDoc)), undefined); // otherwise create a new view of the target
- }
- highlight();
- }, 0);
+ if (targetDoc.displayTimecode) { // if the target has a timecode, it should show up once the (presumed) video context scrubs to the display timecode;
+ targetDocContext.currentTimecode = targetDoc.displayTimecode;
+ finished?.();
+ } else { // no timecode means we need to find the context view and focus on our target
+ setTimeout(() => {
+ const retryDocView = getFirstDocView(targetDoc); // test again for the target view snce we presumably created the context above by focusing on it
+ if (retryDocView) { // we found the target in the context
+ retryDocView.props.focus(targetDoc, willZoom, undefined, focusAndFinish); // focus on the target in the context
+ } else { // we didn't find the target, so it must have moved out of the context. Go back to just creating it.
+ if (closeContextIfNotFound) targetDocContextView.props.removeDocument?.(targetDocContextView.props.Document);
+ targetDoc.layout && createViewFunc(Doc.BrushDoc(targetDoc), finished); // create a new view of the target
+ }
+ highlight();
+ }, 0);
+ }
} else { // there's no context view so we need to create one first and try again
- (dockFunc || CollectionDockingView.AddRightSplit)(targetDocContext, undefined);
+ createViewFunc(targetDocContext); // so first we create the target, but don't pass finished because we still need to create the target
setTimeout(() => {
- const finalDocView = DocumentManager.Instance.getFirstDocumentView(targetDoc);
- const finalDocContextView = DocumentManager.Instance.getFirstDocumentView(targetDocContext);
+ const finalDocView = getFirstDocView(targetDoc);
+ const finalDocContextView = getFirstDocView(targetDocContext);
setTimeout(() => // if not, wait a bit to see if the context can be loaded (e.g., a PDF). wait interval heurisitic tries to guess how we're animating based on what's just become visible
- this.jumpToDocument(targetDoc, willZoom, dockFunc, undefined, linkId, true), finalDocView ? 0 : finalDocContextView ? 250 : 2000); // so call jump to doc again and if the doc isn't found, it will be created.
+ this.jumpToDocument(targetDoc, willZoom, createViewFunc, undefined, linkId, true, undefined, finished), // pass true this time for closeContextIfNotFound
+ finalDocView ? 0 : finalDocContextView ? 250 : 2000); // so call jump to doc again and if the doc isn't found, it will be created.
}, 0);
}
}
}
}
- public async FollowLink(link: Doc | undefined, doc: Doc, focus: (doc: Doc, maxLocation: string) => void, zoom: boolean = false, reverse: boolean = false, currentContext?: Doc) {
+ public async FollowLink(link: Opt<Doc>, doc: Doc, createViewFunc: CreateViewFunc, zoom = false, currentContext?: Doc, finished?: () => void, traverseBacklink?: boolean) {
const linkDocs = link ? [link] : DocListCast(doc.links);
SelectionManager.DeselectAll();
- const firstDocs = linkDocs.filter(linkDoc => Doc.AreProtosEqual(linkDoc.anchor1 as Doc, doc));
- const secondDocs = linkDocs.filter(linkDoc => Doc.AreProtosEqual(linkDoc.anchor2 as Doc, doc));
- const firstDocWithoutView = firstDocs.find(d => DocumentManager.Instance.getDocumentViews(d.anchor2 as Doc).length === 0);
- const secondDocWithoutView = secondDocs.find(d => DocumentManager.Instance.getDocumentViews(d.anchor1 as Doc).length === 0);
- const first = firstDocWithoutView ? [firstDocWithoutView] : firstDocs;
- const second = secondDocWithoutView ? [secondDocWithoutView] : secondDocs;
- const linkDoc = first.length ? first[0] : second.length ? second[0] : undefined;
- const linkFollowDocs = first.length ? [await first[0].anchor2 as Doc, await first[0].anchor1 as Doc] : second.length ? [await second[0].anchor1 as Doc, await second[0].anchor2 as Doc] : undefined;
- const linkFollowDocContexts = first.length ? [await first[0].anchor2Context as Doc, await first[0].anchor1Context as Doc] : second.length ? [await second[0].anchor1Context as Doc, await second[0].anchor2Context as Doc] : [undefined, undefined];
- const linkFollowTimecodes = first.length ? [NumCast(first[0].anchor2Timecode), NumCast(first[0].anchor1Timecode)] : second.length ? [NumCast(second[0].anchor1Timecode), NumCast(second[0].anchor2Timecode)] : [undefined, undefined];
- if (linkFollowDocs && linkDoc) {
- const maxLocation = StrCast(linkFollowDocs[0].maximizeLocation, "inTab");
- const targetContext = !Doc.AreProtosEqual(linkFollowDocContexts[reverse ? 1 : 0], currentContext) ? linkFollowDocContexts[reverse ? 1 : 0] : undefined;
- const target = linkFollowDocs[reverse ? 1 : 0];
- target.currentTimecode !== undefined && (target.currentTimecode = linkFollowTimecodes[reverse ? 1 : 0]);
- DocumentManager.Instance.jumpToDocument(linkFollowDocs[reverse ? 1 : 0], zoom, (doc: Doc) => focus(doc, maxLocation), targetContext, linkDoc[Id]);
- } else if (link) {
- DocumentManager.Instance.jumpToDocument(link, zoom, (doc: Doc) => focus(doc, "onRight"), undefined, undefined);
- }
- }
-
- @action
- zoomIntoScale = (docDelegate: Doc, scale: number) => {
- const docView = DocumentManager.Instance.getDocumentView(Doc.GetProto(docDelegate));
- docView && docView.props.zoomToScale(scale);
- }
-
- getScaleOfDocView = (docDelegate: Doc) => {
- const doc = Doc.GetProto(docDelegate);
-
- const docView = DocumentManager.Instance.getDocumentView(doc);
- if (docView) {
- return docView.props.getScale();
+ const firstDocs = linkDocs.filter(linkDoc => Doc.AreProtosEqual(linkDoc.anchor1 as Doc, doc)); // link docs where 'doc' is anchor1
+ const secondDocs = linkDocs.filter(linkDoc => Doc.AreProtosEqual(linkDoc.anchor2 as Doc, doc)); // link docs where 'doc' is anchor2
+ const fwdLinkWithoutTargetView = firstDocs.find(d => DocumentManager.Instance.getDocumentViews(d.anchor2 as Doc).length === 0);
+ const backLinkWithoutTargetView = secondDocs.find(d => DocumentManager.Instance.getDocumentViews(d.anchor1 as Doc).length === 0);
+ const linkWithoutTargetDoc = traverseBacklink === undefined ? fwdLinkWithoutTargetView || backLinkWithoutTargetView : traverseBacklink ? backLinkWithoutTargetView : fwdLinkWithoutTargetView;
+ const linkDocList = linkWithoutTargetDoc ? [linkWithoutTargetDoc] : (traverseBacklink === undefined ? firstDocs.concat(secondDocs) : traverseBacklink ? secondDocs : firstDocs);
+ const linkDoc = linkDocList.length && linkDocList[0];
+ if (linkDoc) {
+ const target = (doc === linkDoc.anchor1 ? linkDoc.anchor2 : doc === linkDoc.anchor2 ? linkDoc.anchor1 :
+ (Doc.AreProtosEqual(doc, linkDoc.anchor1 as Doc) ? linkDoc.anchor2 : linkDoc.anchor1)) as Doc;
+ const targetTimecode = (doc === linkDoc.anchor1 ? Cast(linkDoc.anchor2_timecode, "number") :
+ doc === linkDoc.anchor2 ? Cast(linkDoc.anchor1_timecode, "number") :
+ (Doc.AreProtosEqual(doc, linkDoc.anchor1 as Doc) ? Cast(linkDoc.anchor2_timecode, "number") : Cast(linkDoc.anchor1_timecode, "number")));
+ if (target) {
+ const containerDoc = (await Cast(target.annotationOn, Doc)) || target;
+ containerDoc.currentTimecode = targetTimecode;
+ const targetContext = await target?.context as Doc;
+ const targetNavContext = !Doc.AreProtosEqual(targetContext, currentContext) ? targetContext : undefined;
+ DocumentManager.Instance.jumpToDocument(target, zoom, (doc, finished) => createViewFunc(doc, StrCast(linkDoc.followLinkLocation, "onRight"), finished), targetNavContext, linkDoc[Id], undefined, doc, finished);
+ } else {
+ finished?.();
+ }
} else {
- return 1;
+ finished?.();
}
}
}
-Scripting.addGlobal(function focus(doc: any) { DocumentManager.Instance.getDocumentViews(Doc.GetProto(doc)).map(view => view.props.focus(doc, true)); }); \ No newline at end of file
+Scripting.addGlobal(function DocFocus(doc: any) { DocumentManager.Instance.getDocumentViews(Doc.GetProto(doc)).map(view => view.props.focus(doc, true)); }); \ No newline at end of file
diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts
index e572f0fcb..35694a6bd 100644
--- a/src/client/util/DragManager.ts
+++ b/src/client/util/DragManager.ts
@@ -1,5 +1,5 @@
import { Doc, Field, DocListCast } from "../../new_fields/Doc";
-import { Cast, ScriptCast } from "../../new_fields/Types";
+import { Cast, ScriptCast, StrCast } from "../../new_fields/Types";
import { emptyFunction } from "../../Utils";
import { CollectionDockingView } from "../views/collections/CollectionDockingView";
import * as globalCssVariables from "../views/globalCssVariables.scss";
@@ -7,15 +7,19 @@ import { DocumentManager } from "./DocumentManager";
import { LinkManager } from "./LinkManager";
import { SelectionManager } from "./SelectionManager";
import { SchemaHeaderField } from "../../new_fields/SchemaHeaderField";
-import { Docs } from "../documents/Documents";
+import { Docs, DocUtils } from "../documents/Documents";
import { ScriptField } from "../../new_fields/ScriptField";
import { List } from "../../new_fields/List";
import { PrefetchProxy } from "../../new_fields/Proxy";
import { listSpec } from "../../new_fields/Schema";
import { Scripting } from "./Scripting";
import { convertDropDataToButtons } from "./DropConverter";
+import { AudioBox } from "../views/nodes/AudioBox";
+import { DateField } from "../../new_fields/DateField";
+import { DocumentView } from "../views/nodes/DocumentView";
+import { UndoManager } from "./UndoManager";
-export type dropActionType = "alias" | "copy" | undefined;
+export type dropActionType = "alias" | "copy" | "move" | undefined; // undefined = move
export function SetupDrag(
_reference: React.RefObject<HTMLElement>,
docFunc: () => Doc | Promise<Doc> | undefined,
@@ -79,6 +83,7 @@ export namespace DragManager {
}
export let AbortDrag: () => void = emptyFunction;
export type MoveFunction = (document: Doc, targetCollection: Doc | undefined, addDocument: (document: Doc) => boolean) => boolean;
+ export type RemoveFunction = (document: Doc) => boolean;
export interface DragDropDisposer { (): void; }
export interface DragOptions {
@@ -130,11 +135,12 @@ export namespace DragManager {
dontHideOnDrop?: boolean;
offset: number[];
dropAction: dropActionType;
+ removeDropProperties?: string[];
userDropAction: dropActionType;
embedDoc?: boolean;
moveDocument?: MoveFunction;
+ removeDocument?: RemoveFunction;
isSelectionMove?: boolean; // indicates that an explicitly selected Document is being dragged. this will suppress onDragStart scripts
- applyAsTemplate?: boolean;
}
export class LinkDragData {
constructor(linkSourceDoc: Doc) {
@@ -144,6 +150,7 @@ export namespace DragManager {
linkSourceDocument: Doc;
dontClearTextBox?: boolean;
linkDocument?: Doc;
+ linkDropCallback?: (data: LinkDragData) => void;
}
export class ColumnDragData {
constructor(colKey: SchemaHeaderField) {
@@ -172,7 +179,8 @@ export namespace DragManager {
export function MakeDropTarget(
element: HTMLElement,
- dropFunc: (e: Event, de: DropEvent) => void
+ dropFunc: (e: Event, de: DropEvent) => void,
+ doc?: Doc
): DragDropDisposer {
if ("canDrop" in element.dataset) {
throw new Error(
@@ -181,26 +189,39 @@ export namespace DragManager {
}
element.dataset.canDrop = "true";
const handler = (e: Event) => dropFunc(e, (e as CustomEvent<DropEvent>).detail);
+ const preDropHandler = (e: Event) => {
+ const de = (e as CustomEvent<DropEvent>).detail;
+ if (de.complete.docDragData && doc?.targetDropAction) {
+ de.complete.docDragData.dropAction = StrCast(doc.targetDropAction) as dropActionType;
+ }
+ };
element.addEventListener("dashOnDrop", handler);
+ doc && element.addEventListener("dashPreDrop", preDropHandler);
return () => {
element.removeEventListener("dashOnDrop", handler);
+ doc && element.removeEventListener("dashPreDrop", preDropHandler);
delete element.dataset.canDrop;
};
}
// drag a document and drop it (or make an alias/copy on drop)
export function StartDocumentDrag(eles: HTMLElement[], dragData: DocumentDragData, downX: number, downY: number, options?: DragOptions) {
+ const addAudioTag = (dropDoc: any) => {
+ dropDoc && !dropDoc.creationDate && (dropDoc.creationDate = new DateField);
+ dropDoc instanceof Doc && AudioBox.ActiveRecordings.map(d => DocUtils.MakeLink({ doc: dropDoc }, { doc: d }, "audio link", "audio timeline"));
+ return dropDoc;
+ };
+ const batch = UndoManager.StartBatch("dragging");
const finishDrag = (e: DragCompleteEvent) => {
e.docDragData && (e.docDragData.droppedDocuments =
- dragData.draggedDocuments.map(d => !dragData.isSelectionMove && !dragData.userDropAction && ScriptCast(d.onDragStart) ? ScriptCast(d.onDragStart).script.run({ this: d }).result :
+ dragData.draggedDocuments.map(d => !dragData.isSelectionMove && !dragData.userDropAction && ScriptCast(d.onDragStart) ? addAudioTag(ScriptCast(d.onDragStart).script.run({ this: d }).result) :
dragData.userDropAction === "alias" || (!dragData.userDropAction && dragData.dropAction === "alias") ? Doc.MakeAlias(d) :
- dragData.userDropAction === "copy" || (!dragData.userDropAction && dragData.dropAction === "copy") ? Doc.MakeCopy(d, true) : d)
+ dragData.userDropAction === "copy" || (!dragData.userDropAction && dragData.dropAction === "copy") ? Doc.MakeClone(d) : d)
);
e.docDragData?.droppedDocuments.forEach((drop: Doc, i: number) =>
- Cast(dragData.draggedDocuments[i].removeDropProperties, listSpec("string"), []).map(prop => {
- drop[prop] = undefined;
- })
+ (dragData?.removeDropProperties || []).concat(Cast(dragData.draggedDocuments[i].removeDropProperties, listSpec("string"), [])).map(prop => drop[prop] = undefined)
);
+ batch.end();
};
dragData.draggedDocuments.map(d => d.dragFactory); // does this help? trying to make sure the dragFactory Doc is loaded
StartDrag(eles, dragData, downX, downY, options, finishDrag);
@@ -209,18 +230,17 @@ export namespace DragManager {
// drag a button template and drop a new button
export function StartButtonDrag(eles: HTMLElement[], script: string, title: string, vars: { [name: string]: Field }, params: string[], initialize: (button: Doc) => void, downX: number, downY: number, options?: DragOptions) {
const finishDrag = (e: DragCompleteEvent) => {
- const bd = Docs.Create.ButtonDocument({ _width: 150, _height: 50, title: title });
- bd.onClick = ScriptField.MakeScript(script);
- params.map(p => Object.keys(vars).indexOf(p) !== -1 && (Doc.GetProto(bd)[p] = new PrefetchProxy(vars[p] as Doc)));
- initialize && initialize(bd);
- bd.buttonParams = new List<string>(params);
+ const bd = Docs.Create.ButtonDocument({ _width: 150, _height: 50, title, onClick: ScriptField.MakeScript(script) });
+ params.map(p => Object.keys(vars).indexOf(p) !== -1 && (Doc.GetProto(bd)[p] = new PrefetchProxy(vars[p] as Doc))); // copy all "captured" arguments into document parameterfields
+ initialize?.(bd);
+ Doc.GetProto(bd)["onClick-paramFieldKeys"] = new List<string>(params);
e.docDragData && (e.docDragData.droppedDocuments = [bd]);
};
StartDrag(eles, new DragManager.DocumentDragData([]), downX, downY, options, finishDrag);
}
// drag links and drop link targets (aliasing them if needed)
- export async function StartLinkTargetsDrag(dragEle: HTMLElement, downX: number, downY: number, sourceDoc: Doc, specificLinks?: Doc[]) {
+ export async function StartLinkTargetsDrag(dragEle: HTMLElement, docView: DocumentView, downX: number, downY: number, sourceDoc: Doc, specificLinks?: Doc[]) {
const draggedDocs = (specificLinks ? specificLinks : DocListCast(sourceDoc.links)).map(link => LinkManager.Instance.getOppositeAnchor(link, sourceDoc)).filter(l => l) as Doc[];
if (draggedDocs.length) {
@@ -232,12 +252,11 @@ export namespace DragManager {
const dragData = new DragManager.DocumentDragData(moddrag.length ? moddrag : draggedDocs);
dragData.moveDocument = (doc: Doc, targetCollection: Doc | undefined, addDocument: (doc: Doc) => boolean): boolean => {
- const document = SelectionManager.SelectedDocuments()[0];
- document && document.props.removeDocument && document.props.removeDocument(doc);
+ docView.props.removeDocument?.(doc);
addDocument(doc);
return true;
};
- const containingView = SelectionManager.SelectedDocuments()[0] ? SelectionManager.SelectedDocuments()[0].props.ContainingCollectionView : undefined;
+ const containingView = docView.props.ContainingCollectionView;
const finishDrag = (e: DragCompleteEvent) =>
e.docDragData && (e.docDragData.droppedDocuments =
dragData.draggedDocuments.reduce((droppedDocs, d) => {
@@ -269,6 +288,10 @@ export namespace DragManager {
StartDrag([ele], dragData, downX, downY, options);
}
+ export function StartImgDrag(ele: HTMLElement, downX: number, downY: number) {
+ StartDrag([ele], {}, downX, downY);
+ }
+
function StartDrag(eles: HTMLElement[], dragData: { [id: string]: any }, downX: number, downY: number, options?: DragOptions, finishDrag?: (dropData: DragCompleteEvent) => void) {
eles = eles.filter(e => e);
if (!dragDiv) {
@@ -339,12 +362,17 @@ export namespace DragManager {
let lastX = downX;
let lastY = downY;
+ let alias = "alias";
const moveHandler = (e: PointerEvent) => {
e.preventDefault(); // required or dragging text menu link item ends up dragging the link button as native drag/drop
if (dragData instanceof DocumentDragData) {
- dragData.userDropAction = e.ctrlKey ? "alias" : undefined;
+ dragData.userDropAction = e.ctrlKey && e.altKey ? "copy" : e.ctrlKey ? "alias" : undefined;
}
if (e.shiftKey && CollectionDockingView.Instance && dragData.droppedDocuments.length === 1) {
+ !dragData.dropAction && (dragData.dropAction = alias);
+ if (dragData.dropAction === "move") {
+ dragData.removeDocument?.(dragData.draggedDocuments[0]);
+ }
AbortDrag();
finishDrag?.(new DragCompleteEvent(true, dragData));
CollectionDockingView.Instance.StartOtherDrag({
@@ -354,7 +382,7 @@ export namespace DragManager {
button: 0
}, dragData.droppedDocuments);
}
- //TODO: Why can't we use e.movementX and e.movementY?
+ alias = "move";
const moveX = e.pageX - lastX;
const moveY = e.pageY - lastY;
lastX = e.pageX;
@@ -383,8 +411,8 @@ export namespace DragManager {
hideDragShowOriginalElements();
dispatchDrag(eles, e, dragData, options, finishDrag);
SelectionManager.SetIsDragging(false);
- options?.dragComplete?.(new DragCompleteEvent(false, dragData));
endDrag();
+ options?.dragComplete?.(new DragCompleteEvent(false, dragData));
};
document.addEventListener("pointermove", moveHandler, true);
document.addEventListener("pointerup", upHandler);
@@ -392,20 +420,35 @@ export namespace DragManager {
function dispatchDrag(dragEles: HTMLElement[], e: PointerEvent, dragData: { [index: string]: any }, options?: DragOptions, finishDrag?: (e: DragCompleteEvent) => void) {
const removed = dragData.dontHideOnDrop ? [] : dragEles.map(dragEle => {
- const ret = { ele: dragEle, w: dragEle.style.width, h: dragEle.style.height };
+ const ret = { ele: dragEle, w: dragEle.style.width, h: dragEle.style.height, o: dragEle.style.overflow };
dragEle.style.width = "0";
dragEle.style.height = "0";
+ dragEle.style.overflow = "hidden";
return ret;
});
const target = document.elementFromPoint(e.x, e.y);
removed.map(r => {
r.ele.style.width = r.w;
r.ele.style.height = r.h;
+ r.ele.style.overflow = r.o;
});
if (target) {
const complete = new DragCompleteEvent(false, dragData);
+ target.dispatchEvent(
+ new CustomEvent<DropEvent>("dashPreDrop", {
+ bubbles: true,
+ detail: {
+ x: e.x,
+ y: e.y,
+ complete: complete,
+ shiftKey: e.shiftKey,
+ altKey: e.altKey,
+ metaKey: e.metaKey,
+ ctrlKey: e.ctrlKey
+ }
+ })
+ );
finishDrag?.(complete);
-
target.dispatchEvent(
new CustomEvent<DropEvent>("dashOnDrop", {
bubbles: true,
diff --git a/src/client/util/DropConverter.ts b/src/client/util/DropConverter.ts
index d0f1d86cb..60a6bbb3c 100644
--- a/src/client/util/DropConverter.ts
+++ b/src/client/util/DropConverter.ts
@@ -1,5 +1,5 @@
import { DragManager } from "./DragManager";
-import { Doc, DocListCast } from "../../new_fields/Doc";
+import { Doc, DocListCast, Opt } from "../../new_fields/Doc";
import { DocumentType } from "../documents/DocumentTypes";
import { ObjectField } from "../../new_fields/ObjectField";
import { StrCast } from "../../new_fields/Types";
@@ -8,39 +8,64 @@ import { ScriptField, ComputedField } from "../../new_fields/ScriptField";
import { RichTextField } from "../../new_fields/RichTextField";
import { ImageField } from "../../new_fields/URLField";
-export function makeTemplate(doc: Doc): boolean {
+//
+// converts 'doc' into a template that can be used to render other documents.
+// the title of doc is used to determine which field is being templated, so
+// passing a value for 'rename' allows the doc to be given a meangingful name
+// after it has been converted to
+export function makeTemplate(doc: Doc, first: boolean = true, rename: Opt<string> = undefined): boolean {
const layoutDoc = doc.layout instanceof Doc && doc.layout.isTemplateForField ? doc.layout : doc;
+ if (layoutDoc.layout instanceof Doc) { // its already a template
+ return true;
+ }
const layout = StrCast(layoutDoc.layout).match(/fieldKey={'[^']*'}/)![0];
const fieldKey = layout.replace("fieldKey={'", "").replace(/'}$/, "");
const docs = DocListCast(layoutDoc[fieldKey]);
let any = false;
docs.forEach(d => {
if (!StrCast(d.title).startsWith("-")) {
- any = Doc.MakeMetadataFieldTemplate(d, Doc.GetProto(layoutDoc)) || any;
+ const params = StrCast(d.title).match(/\(([a-zA-Z0-9._\-]*)\)/)?.[1].replace("()", "");
+ if (params) {
+ any = makeTemplate(d, false) || any;
+ d.PARAMS = params;
+ } else {
+ any = Doc.MakeMetadataFieldTemplate(d, Doc.GetProto(layoutDoc)) || any;
+ }
} else if (d.type === DocumentType.COL || d.data instanceof RichTextField) {
- any = makeTemplate(d) || any;
+ any = makeTemplate(d, false) || any;
}
});
+ if (first) {
+ if (docs.length) { // bcz: feels hacky : if the root level document has items, it's not a field template, but we still want its caption to be a textTemplate
+ if (doc.caption instanceof RichTextField && !doc.caption.Empty()) {
+ doc["caption-textTemplate"] = ComputedField.MakeFunction(`copyField(this.caption)`);
+ }
+ } else {
+ any = Doc.MakeMetadataFieldTemplate(doc, Doc.GetProto(layoutDoc)) || any;
+ }
+ }
if (layoutDoc[fieldKey] instanceof RichTextField || layoutDoc[fieldKey] instanceof ImageField) {
if (!StrCast(layoutDoc.title).startsWith("-")) {
any = Doc.MakeMetadataFieldTemplate(layoutDoc, Doc.GetProto(layoutDoc));
}
}
+ rename && (doc.title = rename);
return any;
}
export function convertDropDataToButtons(data: DragManager.DocumentDragData) {
data && data.draggedDocuments.map((doc, i) => {
let dbox = doc;
// bcz: isButtonBar is intended to allow a collection of linear buttons to be dropped and nested into another collection of buttons... it's not being used yet, and isn't very elegant
- if (!doc.onDragStart && !doc.onClick && !doc.isButtonBar) {
+ if (!doc.onDragStart && !doc.isButtonBar) {
const layoutDoc = doc.layout instanceof Doc && doc.layout.isTemplateForField ? doc.layout : doc;
- if (layoutDoc.type === DocumentType.COL || layoutDoc.type === DocumentType.TEXT || layoutDoc.type === DocumentType.IMG) {
- makeTemplate(layoutDoc);
- } else {
- (layoutDoc.layout instanceof Doc) && !data.userDropAction;
+ if (layoutDoc.type !== DocumentType.FONTICON) {
+ !layoutDoc.isTemplateDoc && makeTemplate(layoutDoc);
}
layoutDoc.isTemplateDoc = true;
- dbox = Docs.Create.FontIconDocument({ _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, backgroundColor: StrCast(doc.backgroundColor), title: "Custom", icon: layoutDoc.isTemplateDoc ? "font" : "bolt" });
+ dbox = Docs.Create.FontIconDocument({
+ _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100,
+ backgroundColor: StrCast(doc.backgroundColor), title: StrCast(layoutDoc.title), icon: layoutDoc.isTemplateDoc ? "font" : "bolt"
+ });
dbox.dragFactory = layoutDoc;
dbox.removeDropProperties = doc.removeDropProperties instanceof ObjectField ? ObjectField.MakeCopy(doc.removeDropProperties) : undefined;
dbox.onDragStart = ScriptField.MakeFunction('getCopy(this.dragFactory, true)');
diff --git a/src/client/util/History.ts b/src/client/util/History.ts
index 545e8acb4..2c53d7e52 100644
--- a/src/client/util/History.ts
+++ b/src/client/util/History.ts
@@ -40,8 +40,12 @@ export namespace HistoryUtil {
// }
}
+ let _lastStatePush = 0;
export function pushState(state: ParsedUrl) {
- history.pushState(state, "", createUrl(state));
+ if (Date.now() - _lastStatePush > 1000) {
+ history.pushState(state, "", createUrl(state));
+ }
+ _lastStatePush = Date.now();
}
export function replaceState(state: ParsedUrl) {
diff --git a/src/client/util/Import & Export/DirectoryImportBox.tsx b/src/client/util/Import & Export/DirectoryImportBox.tsx
index 071015193..438904688 100644
--- a/src/client/util/Import & Export/DirectoryImportBox.tsx
+++ b/src/client/util/Import & Export/DirectoryImportBox.tsx
@@ -22,7 +22,7 @@ import "./DirectoryImportBox.scss";
import { Networking } from "../../Network";
import { BatchedArray } from "array-batcher";
import * as path from 'path';
-import { AcceptibleMedia } from "../../../server/SharedMediaTypes";
+import { AcceptibleMedia, Upload } from "../../../server/SharedMediaTypes";
const unsupported = ["text/html", "text/plain"];
@@ -107,25 +107,26 @@ export default class DirectoryImportBox extends React.Component<FieldViewProps>
runInAction(() => this.phase = `Internal: uploading ${this.quota - this.completed} files to Dash...`);
const batched = BatchedArray.from(validated, { batchSize: 15 });
- const uploads = await batched.batchedMapAsync<any>(async (batch, collector) => {
- const formData = new FormData();
-
+ const uploads = await batched.batchedMapAsync<Upload.FileResponse<Upload.ImageInformation>>(async (batch, collector) => {
batch.forEach(file => {
sizes.push(file.size);
modifiedDates.push(file.lastModified);
- formData.append(Utils.GenerateGuid(), file);
});
-
- collector.push(...(await Networking.PostFormDataToServer("/uploadFormData", formData)));
+ collector.push(...(await Networking.UploadFilesToServer<Upload.ImageInformation>(batch)));
runInAction(() => this.completed += batch.length);
});
- await Promise.all(uploads.map(async ({ name, type, clientAccessPath, exifData }) => {
- const path = Utils.prepend(clientAccessPath);
+ await Promise.all(uploads.map(async response => {
+ const { source: { type }, result } = response;
+ if (result instanceof Error) {
+ return;
+ }
+ const { accessPaths, exifData } = result;
+ const path = Utils.prepend(accessPaths.agnostic.client);
const document = await Docs.Get.DocumentFromType(type, path, { _width: 300, title: name });
const { data, error } = exifData;
if (document) {
- Doc.GetProto(document).exif = error || Docs.Get.DocumentHierarchyFromJson(data);
+ Doc.GetProto(document).exif = error || Docs.Get.FromJson({ data });
docs.push(document);
}
}));
diff --git a/src/client/util/Import & Export/ImageUtils.ts b/src/client/util/Import & Export/ImageUtils.ts
index ff909cc6b..c8d1530b3 100644
--- a/src/client/util/Import & Export/ImageUtils.ts
+++ b/src/client/util/Import & Export/ImageUtils.ts
@@ -20,11 +20,12 @@ export namespace ImageUtils {
nativeHeight,
exifData: { error, data }
} = await Networking.PostToServer("/inspectImage", { source });
- document.exif = error || Docs.Get.DocumentHierarchyFromJson(data);
+ document.exif = error || Docs.Get.FromJson({ data });
const proto = Doc.GetProto(document);
proto["data-nativeWidth"] = nativeWidth;
proto["data-nativeHeight"] = nativeHeight;
- proto.contentSize = contentSize;
+ proto["data-path"] = source;
+ proto.contentSize = contentSize ? contentSize : undefined;
return data !== undefined;
};
diff --git a/src/client/util/InteractionUtils.tsx b/src/client/util/InteractionUtils.tsx
index 7194feb2e..b1f136430 100644
--- a/src/client/util/InteractionUtils.tsx
+++ b/src/client/util/InteractionUtils.tsx
@@ -1,3 +1,5 @@
+import React = require("react");
+
export namespace InteractionUtils {
export const MOUSETYPE = "mouse";
export const TOUCHTYPE = "touch";
@@ -8,24 +10,9 @@ export namespace InteractionUtils {
const REACT_POINTER_PEN_BUTTON = 0;
const ERASER_BUTTON = 5;
- 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}
- style={{
- fill: "none",
- stroke: color,
- strokeWidth: width
- }}
- />
- );
- }
-
export class MultiTouchEvent<T extends React.TouchEvent | TouchEvent> {
constructor(
readonly fingers: number,
- // readonly points: T extends React.TouchEvent ? React.TouchList : TouchList,
readonly targetTouches: T extends React.TouchEvent ? React.Touch[] : Touch[],
readonly touches: T extends React.TouchEvent ? React.Touch[] : Touch[],
readonly changedTouches: T extends React.TouchEvent ? React.Touch[] : Touch[],
@@ -35,9 +22,14 @@ export namespace InteractionUtils {
export interface MultiTouchEventDisposer { (): void; }
+ /**
+ *
+ * @param element - element to turn into a touch target
+ * @param startFunc - event handler, typically Touchable.onTouchStart (classes that inherit touchable can pass in this.onTouchStart)
+ */
export function MakeMultiTouchTarget(
element: HTMLElement,
- startFunc: (e: Event, me: MultiTouchEvent<React.TouchEvent>) => void,
+ startFunc: (e: Event, me: MultiTouchEvent<React.TouchEvent>) => void
): MultiTouchEventDisposer {
const onMultiTouchStartHandler = (e: Event) => startFunc(e, (e as CustomEvent<MultiTouchEvent<React.TouchEvent>>).detail);
// const onMultiTouchMoveHandler = moveFunc ? (e: Event) => moveFunc(e, (e as CustomEvent<MultiTouchEvent<TouchEvent>>).detail) : undefined;
@@ -60,6 +52,22 @@ export namespace InteractionUtils {
};
}
+ /**
+ * Turns an element onto a target for touch hold handling.
+ * @param element - element to add events to
+ * @param func - function to add to the event
+ */
+ export function MakeHoldTouchTarget(
+ element: HTMLElement,
+ func: (e: Event, me: MultiTouchEvent<React.TouchEvent>) => void
+ ): MultiTouchEventDisposer {
+ const handler = (e: Event) => func(e, (e as CustomEvent<MultiTouchEvent<React.TouchEvent>>).detail);
+ element.addEventListener("dashOnTouchHoldStart", handler);
+ return () => {
+ element.removeEventListener("dashOnTouchHoldStart", handler);
+ };
+ }
+
export function GetMyTargetTouches(mte: InteractionUtils.MultiTouchEvent<React.TouchEvent | TouchEvent>, prevPoints: Map<number, React.Touch>, ignorePen: boolean): React.Touch[] {
const myTouches = new Array<React.Touch>();
for (const pt of mte.touches) {
@@ -79,6 +87,25 @@ export namespace InteractionUtils {
return myTouches;
}
+ 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}
+ style={{
+ fill: "none",
+ stroke: color,
+ strokeWidth: width
+ }}
+ />
+ );
+ }
+
+ /**
+ * Returns whether or not the pointer event passed in is of the type passed in
+ * @param e - pointer event. this event could be from a mouse, a pen, or a finger
+ * @param type - InteractionUtils.(PENTYPE | ERASERTYPE | MOUSETYPE | TOUCHTYPE)
+ */
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
@@ -91,6 +118,11 @@ export namespace InteractionUtils {
}
}
+ /**
+ * Returns euclidean distance between two points
+ * @param pt1
+ * @param pt2
+ */
export function TwoPointEuclidist(pt1: React.Touch, pt2: React.Touch): number {
return Math.sqrt(Math.pow(pt1.clientX - pt2.clientX, 2) + Math.pow(pt1.clientY - pt2.clientY, 2));
}
diff --git a/src/client/util/KeyCodes.ts b/src/client/util/KeyCodes.ts
new file mode 100644
index 000000000..cacb72a57
--- /dev/null
+++ b/src/client/util/KeyCodes.ts
@@ -0,0 +1,136 @@
+/**
+ * Class contains the keycodes for keys on your keyboard.
+ *
+ * Useful for auto completion:
+ *
+ * ```
+ * switch (event.key)
+ * {
+ * case KeyCode.UP:
+ * {
+ * // Up key pressed
+ * break;
+ * }
+ * case KeyCode.DOWN:
+ * {
+ * // Down key pressed
+ * break;
+ * }
+ * case KeyCode.LEFT:
+ * {
+ * // Left key pressed
+ * break;
+ * }
+ * case KeyCode.RIGHT:
+ * {
+ * // Right key pressed
+ * break;
+ * }
+ * default:
+ * {
+ * // ignore
+ * break;
+ * }
+ * }
+ * ```
+ */
+export class KeyCodes {
+ public static TAB: number = 9;
+ public static CAPS_LOCK: number = 20;
+ public static SHIFT: number = 16;
+ public static CONTROL: number = 17;
+ public static SPACE: number = 32;
+ public static DOWN: number = 40;
+ public static UP: number = 38;
+ public static LEFT: number = 37;
+ public static RIGHT: number = 39;
+ public static ESCAPE: number = 27;
+ public static F1: number = 112;
+ public static F2: number = 113;
+ public static F3: number = 114;
+ public static F4: number = 115;
+ public static F5: number = 116;
+ public static F6: number = 117;
+ public static F7: number = 118;
+ public static F8: number = 119;
+ public static F9: number = 120;
+ public static F10: number = 121;
+ public static F11: number = 122;
+ public static F12: number = 123;
+ public static INSERT: number = 45;
+ public static HOME: number = 36;
+ public static PAGE_UP: number = 33;
+ public static PAGE_DOWN: number = 34;
+ public static DELETE: number = 46;
+ public static END: number = 35;
+ public static ENTER: number = 13;
+ public static BACKSPACE: number = 8;
+ public static NUMPAD_0: number = 96;
+ public static NUMPAD_1: number = 97;
+ public static NUMPAD_2: number = 98;
+ public static NUMPAD_3: number = 99;
+ public static NUMPAD_4: number = 100;
+ public static NUMPAD_5: number = 101;
+ public static NUMPAD_6: number = 102;
+ public static NUMPAD_7: number = 103;
+ public static NUMPAD_8: number = 104;
+ public static NUMPAD_9: number = 105;
+ public static NUMPAD_DIVIDE: number = 111;
+ public static NUMPAD_ADD: number = 107;
+ public static NUMPAD_ENTER: number = 13;
+ public static NUMPAD_DECIMAL: number = 110;
+ public static NUMPAD_SUBTRACT: number = 109;
+ public static NUMPAD_MULTIPLY: number = 106;
+ public static SEMICOLON: number = 186;
+ public static EQUAL: number = 187;
+ public static COMMA: number = 188;
+ public static MINUS: number = 189;
+ public static PERIOD: number = 190;
+ public static SLASH: number = 191;
+ public static BACKQUOTE: number = 192;
+ public static LEFTBRACKET: number = 219;
+ public static BACKSLASH: number = 220;
+ public static RIGHTBRACKET: number = 221;
+ public static QUOTE: number = 222;
+ public static ALT: number = 18;
+ public static COMMAND: number = 15;
+ public static NUMPAD: number = 21;
+ public static A: number = 65;
+ public static B: number = 66;
+ public static C: number = 67;
+ public static D: number = 68;
+ public static E: number = 69;
+ public static F: number = 70;
+ public static G: number = 71;
+ public static H: number = 72;
+ public static I: number = 73;
+ public static J: number = 74;
+ public static K: number = 75;
+ public static L: number = 76;
+ public static M: number = 77;
+ public static N: number = 78;
+ public static O: number = 79;
+ public static P: number = 80;
+ public static Q: number = 81;
+ public static R: number = 82;
+ public static S: number = 83;
+ public static T: number = 84;
+ public static U: number = 85;
+ public static V: number = 86;
+ public static W: number = 87;
+ public static X: number = 88;
+ public static Y: number = 89;
+ public static Z: number = 90;
+ public static NUM_0: number = 48;
+ public static NUM_1: number = 49;
+ public static NUM_2: number = 50;
+ public static NUM_3: number = 51;
+ public static NUM_4: number = 52;
+ public static NUM_5: number = 53;
+ public static NUM_6: number = 54;
+ public static NUM_7: number = 55;
+ public static NUM_8: number = 56;
+ public static NUM_9: number = 57;
+ public static SUBSTRACT: number = 189;
+ public static ADD: number = 187;
+} \ No newline at end of file
diff --git a/src/client/util/LinkManager.ts b/src/client/util/LinkManager.ts
index 5f3667acc..e236c7f47 100644
--- a/src/client/util/LinkManager.ts
+++ b/src/client/util/LinkManager.ts
@@ -40,7 +40,7 @@ export class LinkManager {
public getAllLinks(): Doc[] {
const ldoc = LinkManager.Instance.LinkManagerDoc;
if (ldoc) {
- const docs = DocListCast(ldoc.allLinks);
+ const docs = DocListCast(ldoc.data);
return docs;
}
return [];
@@ -50,7 +50,7 @@ export class LinkManager {
const linkList = LinkManager.Instance.getAllLinks();
linkList.push(linkDoc);
if (LinkManager.Instance.LinkManagerDoc) {
- LinkManager.Instance.LinkManagerDoc.allLinks = new List<Doc>(linkList);
+ LinkManager.Instance.LinkManagerDoc.data = new List<Doc>(linkList);
return true;
}
return false;
@@ -62,7 +62,7 @@ export class LinkManager {
if (index > -1) {
linkList.splice(index, 1);
if (LinkManager.Instance.LinkManagerDoc) {
- LinkManager.Instance.LinkManagerDoc.allLinks = new List<Doc>(linkList);
+ LinkManager.Instance.LinkManagerDoc.data = new List<Doc>(linkList);
return true;
}
}
@@ -135,35 +135,13 @@ export class LinkManager {
return DocListCast(linkDoc.anchor2Groups);
}
}
-
- // sets the groups of the given anchor in the given link
- public setAnchorGroups(linkDoc: Doc, anchor: Doc, groups: Doc[]) {
- if (Doc.AreProtosEqual(anchor, Cast(linkDoc.anchor1, Doc, null))) {
- linkDoc.anchor1Groups = new List<Doc>(groups);
- } else {
- linkDoc.anchor2Groups = new List<Doc>(groups);
- }
- }
-
public addGroupToAnchor(linkDoc: Doc, anchor: Doc, groupDoc: Doc, replace: boolean = false) {
- const groups = LinkManager.Instance.getAnchorGroups(linkDoc, anchor);
- const index = groups.findIndex(gDoc => {
- return StrCast(groupDoc.type).toUpperCase() === StrCast(gDoc.type).toUpperCase();
- });
- if (index > -1 && replace) {
- groups[index] = groupDoc;
- }
- if (index === -1) {
- groups.push(groupDoc);
- }
- LinkManager.Instance.setAnchorGroups(linkDoc, anchor, groups);
+ Doc.GetProto(linkDoc).linkRelationship = groupDoc.linkRelationship;
}
// removes group doc of given group type only from given anchor on given link
public removeGroupFromAnchor(linkDoc: Doc, anchor: Doc, groupType: string) {
- const groups = LinkManager.Instance.getAnchorGroups(linkDoc, anchor);
- const newGroups = groups.filter(groupDoc => StrCast(groupDoc.type).toUpperCase() !== groupType.toUpperCase());
- LinkManager.Instance.setAnchorGroups(linkDoc, anchor, newGroups);
+ Doc.GetProto(linkDoc).linkRelationship = "-ungrouped-";
}
// returns map of group type to anchor's links in that group type
@@ -171,19 +149,10 @@ export class LinkManager {
const related = this.getAllRelatedLinks(anchor);
const anchorGroups = new Map<string, Array<Doc>>();
related.forEach(link => {
- const groups = LinkManager.Instance.getAnchorGroups(link, anchor);
-
- if (groups.length > 0) {
- groups.forEach(groupDoc => {
- const groupType = StrCast(groupDoc.type);
- if (groupType === "") {
- const group = anchorGroups.get("*");
- anchorGroups.set("*", group ? [...group, link] : [link]);
- } else {
- const group = anchorGroups.get(groupType);
- anchorGroups.set(groupType, group ? [...group, link] : [link]);
- }
- });
+ if (!link.linkRelationship || link?.linkRelationship !== "-ungrouped-") {
+ const group = anchorGroups.get(StrCast(link.linkRelationship));
+ anchorGroups.set(StrCast(link.linkRelationship), group ? [...group, link] : [link]);
+
} else {
// if link is in no groups then put it in default group
const group = anchorGroups.get("*");
@@ -215,10 +184,7 @@ export class LinkManager {
const md: Doc[] = [];
const allLinks = LinkManager.Instance.getAllLinks();
allLinks.forEach(linkDoc => {
- const anchor1Groups = LinkManager.Instance.getAnchorGroups(linkDoc, Cast(linkDoc.anchor1, Doc, null));
- const anchor2Groups = LinkManager.Instance.getAnchorGroups(linkDoc, Cast(linkDoc.anchor2, Doc, null));
- anchor1Groups.forEach(groupDoc => { if (StrCast(groupDoc.type).toUpperCase() === groupType.toUpperCase()) { const meta = Cast(groupDoc.metadata, Doc, null); meta && md.push(meta); } });
- anchor2Groups.forEach(groupDoc => { if (StrCast(groupDoc.type).toUpperCase() === groupType.toUpperCase()) { const meta = Cast(groupDoc.metadata, Doc, null); meta && md.push(meta); } });
+ if (StrCast(linkDoc.linkRelationship).toUpperCase() === groupType.toUpperCase()) { md.push(linkDoc); }
});
return md;
}
diff --git a/src/client/util/ParagraphNodeSpec.ts b/src/client/util/ParagraphNodeSpec.ts
deleted file mode 100644
index 0a3b68217..000000000
--- a/src/client/util/ParagraphNodeSpec.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import clamp from './clamp';
-import convertToCSSPTValue from './convertToCSSPTValue';
-import toCSSLineSpacing from './toCSSLineSpacing';
-import { Node, DOMOutputSpec } from 'prosemirror-model';
-
-//import type { NodeSpec } from './Types';
-type NodeSpec = {
- attrs?: { [key: string]: any },
- content?: string,
- draggable?: boolean,
- group?: string,
- inline?: boolean,
- name?: string,
- parseDOM?: Array<any>,
- toDOM?: (node: any) => DOMOutputSpec,
-};
-
-// This assumes that every 36pt maps to one indent level.
-export const INDENT_MARGIN_PT_SIZE = 36;
-export const MIN_INDENT_LEVEL = 0;
-export const MAX_INDENT_LEVEL = 7;
-export const ATTRIBUTE_INDENT = 'data-indent';
-
-export const EMPTY_CSS_VALUE = new Set(['', '0%', '0pt', '0px']);
-
-const ALIGN_PATTERN = /(left|right|center|justify)/;
-
-// https://github.com/ProseMirror/prosemirror-schema-basic/blob/master/src/schema-basic.js
-// :: NodeSpec A plain paragraph textblock. Represented in the DOM
-// as a `<p>` element.
-const ParagraphNodeSpec: NodeSpec = {
- attrs: {
- align: { default: null },
- color: { default: null },
- id: { default: null },
- indent: { default: null },
- inset: { default: null },
- lineSpacing: { default: null },
- // TODO: Add UI to let user edit / clear padding.
- paddingBottom: { default: null },
- // TODO: Add UI to let user edit / clear padding.
- paddingTop: { default: null },
- },
- content: 'inline*',
- group: 'block',
- parseDOM: [{ tag: 'p', getAttrs }],
- toDOM,
-};
-
-function getAttrs(dom: HTMLElement): Object {
- const {
- lineHeight,
- textAlign,
- marginLeft,
- paddingTop,
- paddingBottom,
- } = dom.style;
-
- let align = dom.getAttribute('align') || textAlign || '';
- align = ALIGN_PATTERN.test(align) ? align : "";
-
- let indent = parseInt(dom.getAttribute(ATTRIBUTE_INDENT) || "", 10);
-
- if (!indent && marginLeft) {
- indent = convertMarginLeftToIndentValue(marginLeft);
- }
-
- indent = indent || MIN_INDENT_LEVEL;
-
- const lineSpacing = lineHeight ? toCSSLineSpacing(lineHeight) : null;
-
- const id = dom.getAttribute('id') || '';
- return { align, indent, lineSpacing, paddingTop, paddingBottom, id };
-}
-
-function toDOM(node: Node): DOMOutputSpec {
- const {
- align,
- indent,
- inset,
- lineSpacing,
- paddingTop,
- paddingBottom,
- id,
- } = node.attrs;
- const attrs: { [key: string]: any } | null = {};
-
- let style = '';
- if (align && align !== 'left') {
- style += `text-align: ${align};`;
- }
-
- if (lineSpacing) {
- const cssLineSpacing = toCSSLineSpacing(lineSpacing);
- style +=
- `line-height: ${cssLineSpacing};` +
- // This creates the local css variable `--czi-content-line-height`
- // that its children may apply.
- `--czi-content-line-height: ${cssLineSpacing}`;
- }
-
- if (paddingTop && !EMPTY_CSS_VALUE.has(paddingTop)) {
- style += `padding-top: ${paddingTop};`;
- }
-
- if (paddingBottom && !EMPTY_CSS_VALUE.has(paddingBottom)) {
- style += `padding-bottom: ${paddingBottom};`;
- }
-
- if (indent) {
- style += `text-indent: ${indent}; padding-left: ${indent < 0 ? -indent : undefined};`;
- }
-
- if (inset) {
- style += `margin-left: ${inset}; margin-right: ${inset};`;
- }
-
- style && (attrs.style = style);
-
- if (indent) {
- attrs[ATTRIBUTE_INDENT] = String(indent);
- }
-
- if (id) {
- attrs.id = id;
- }
-
- return ['p', attrs, 0];
-}
-
-export const toParagraphDOM = toDOM;
-export const getParagraphNodeAttrs = getAttrs;
-
-export function convertMarginLeftToIndentValue(marginLeft: string): number {
- const ptValue = convertToCSSPTValue(marginLeft);
- return clamp(
- MIN_INDENT_LEVEL,
- Math.floor(ptValue / INDENT_MARGIN_PT_SIZE),
- MAX_INDENT_LEVEL
- );
-}
-
-export default ParagraphNodeSpec; \ No newline at end of file
diff --git a/src/client/util/ProsemirrorExampleTransfer.ts b/src/client/util/ProsemirrorExampleTransfer.ts
deleted file mode 100644
index da3815181..000000000
--- a/src/client/util/ProsemirrorExampleTransfer.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-import { chainCommands, exitCode, joinDown, joinUp, lift, selectParentNode, setBlockType, splitBlockKeepMarks, toggleMark, wrapIn } from "prosemirror-commands";
-import { redo, undo } from "prosemirror-history";
-import { undoInputRule } from "prosemirror-inputrules";
-import { Schema } from "prosemirror-model";
-import { liftListItem, sinkListItem } from "./prosemirrorPatches.js";
-import { splitListItem, wrapInList, } from "prosemirror-schema-list";
-import { EditorState, Transaction, TextSelection } from "prosemirror-state";
-import { SelectionManager } from "./SelectionManager";
-
-const mac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
-
-export type KeyMap = { [key: string]: any };
-
-export let updateBullets = (tx2: Transaction, schema: Schema, mapStyle?: string) => {
- let fontSize: number | undefined = undefined;
- tx2.doc.descendants((node: any, offset: any, index: any) => {
- if (node.type === schema.nodes.ordered_list || node.type === schema.nodes.list_item) {
- const path = (tx2.doc.resolve(offset) as any).path;
- let depth = Array.from(path).reduce((p: number, c: any) => p + (c.hasOwnProperty("type") && c.type === schema.nodes.ordered_list ? 1 : 0), 0);
- if (node.type === schema.nodes.ordered_list) depth++;
- fontSize = depth === 1 && node.attrs.setFontSize ? Number(node.attrs.setFontSize) : fontSize;
- const fsize = fontSize && node.type === schema.nodes.ordered_list ? Math.max(6, fontSize - (depth - 1) * 4) : undefined;
- tx2.setNodeMarkup(offset, node.type, { ...node.attrs, mapStyle: mapStyle ? mapStyle : node.attrs.mapStyle, bulletStyle: depth, inheritedFontSize: fsize }, node.marks);
- }
- });
- return tx2;
-};
-export default function buildKeymap<S extends Schema<any>>(schema: S, mapKeys?: KeyMap): KeyMap {
- const keys: { [key: string]: any } = {};
-
- function bind(key: string, cmd: any) {
- if (mapKeys) {
- const mapped = mapKeys[key];
- if (mapped === false) return;
- if (mapped) key = mapped;
- }
- keys[key] = cmd;
- }
-
- bind("Mod-z", undo);
- bind("Shift-Mod-z", redo);
- bind("Backspace", undoInputRule);
-
- !mac && bind("Mod-y", redo);
-
- bind("Alt-ArrowUp", joinUp);
- bind("Alt-ArrowDown", joinDown);
- bind("Mod-BracketLeft", lift);
- bind("Escape", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => {
- dispatch(state.tr.setSelection(TextSelection.create(state.doc, state.selection.from, state.selection.from)));
- (document.activeElement as any).blur?.();
- SelectionManager.DeselectAll();
- });
-
- bind("Mod-b", toggleMark(schema.marks.strong));
- bind("Mod-B", toggleMark(schema.marks.strong));
-
- bind("Mod-e", toggleMark(schema.marks.em));
- bind("Mod-E", toggleMark(schema.marks.em));
-
- bind("Mod-u", toggleMark(schema.marks.underline));
- bind("Mod-U", toggleMark(schema.marks.underline));
-
- bind("Mod-`", toggleMark(schema.marks.code));
-
- bind("Ctrl-.", wrapInList(schema.nodes.bullet_list));
-
- bind("Ctrl-n", wrapInList(schema.nodes.ordered_list));
-
- bind("Ctrl->", wrapIn(schema.nodes.blockquote));
-
- // bind("^", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => {
- // let newNode = schema.nodes.footnote.create({});
- // if (dispatch && state.selection.from === state.selection.to) {
- // let tr = state.tr;
- // tr.replaceSelectionWith(newNode); // replace insertion with a footnote.
- // dispatch(tr.setSelection(new NodeSelection( // select the footnote node to open its display
- // tr.doc.resolve( // get the location of the footnote node by subtracting the nodesize of the footnote from the current insertion point anchor (which will be immediately after the footnote node)
- // tr.selection.anchor - tr.selection.$anchor.nodeBefore!.nodeSize))));
- // return true;
- // }
- // return false;
- // });
-
-
- const cmd = chainCommands(exitCode, (state, dispatch) => {
- if (dispatch) {
- dispatch(state.tr.replaceSelectionWith(schema.nodes.hard_break.create()).scrollIntoView());
- return true;
- }
- return false;
- });
- bind("Mod-Enter", cmd);
- bind("Shift-Enter", cmd);
- mac && bind("Ctrl-Enter", cmd);
-
-
- bind("Shift-Ctrl-0", setBlockType(schema.nodes.paragraph));
-
- bind("Shift-Ctrl-\\", setBlockType(schema.nodes.code_block));
-
- for (let i = 1; i <= 6; i++) {
- bind("Shift-Ctrl-" + i, setBlockType(schema.nodes.heading, { level: i }));
- }
-
- const hr = schema.nodes.horizontal_rule;
- bind("Mod-_", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => {
- dispatch(state.tr.replaceSelectionWith(hr.create()).scrollIntoView());
- return true;
- });
-
- bind("Tab", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => {
- const ref = state.selection;
- const range = ref.$from.blockRange(ref.$to);
- const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());
- if (!sinkListItem(schema.nodes.list_item)(state, (tx2: Transaction) => {
- const tx3 = updateBullets(tx2, schema);
- marks && tx3.ensureMarks([...marks]);
- marks && tx3.setStoredMarks([...marks]);
- dispatch(tx3);
- })) { // couldn't sink into an existing list, so wrap in a new one
- const newstate = state.applyTransaction(state.tr.setSelection(TextSelection.create(state.doc, range!.start, range!.end)));
- if (!wrapInList(schema.nodes.ordered_list)(newstate.state, (tx2: Transaction) => {
- const tx3 = updateBullets(tx2, schema);
- // when promoting to a list, assume list will format things so don't copy the stored marks.
- marks && tx3.ensureMarks([...marks]);
- marks && tx3.setStoredMarks([...marks]);
- dispatch(tx3);
- })) {
- console.log("bullet promote fail");
- }
- }
- });
-
- bind("Shift-Tab", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => {
- const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());
-
- if (!liftListItem(schema.nodes.list_item)(state.tr, (tx2: Transaction) => {
- const tx3 = updateBullets(tx2, schema);
- marks && tx3.ensureMarks([...marks]);
- marks && tx3.setStoredMarks([...marks]);
- dispatch(tx3);
- })) {
- console.log("bullet demote fail");
- }
- });
-
- const splitMetadata = (marks: any, tx: Transaction) => {
- marks && tx.ensureMarks(marks.filter((val: any) => val.type !== schema.marks.metadata && val.type !== schema.marks.metadataKey && val.type !== schema.marks.metadataVal));
- marks && tx.setStoredMarks(marks.filter((val: any) => val.type !== schema.marks.metadata && val.type !== schema.marks.metadataKey && val.type !== schema.marks.metadataVal));
- return tx;
- };
- bind("Enter", (state: EditorState<S>, dispatch: (tx: Transaction<Schema<any, any>>) => void) => {
- const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());
- if (!splitListItem(schema.nodes.list_item)(state, dispatch)) {
- if (!splitBlockKeepMarks(state, (tx3: Transaction) => {
- splitMetadata(marks, tx3);
- if (!liftListItem(schema.nodes.list_item)(tx3, dispatch as ((tx: Transaction<Schema<any, any>>) => void))) {
- dispatch(tx3);
- }
- })) {
- return false;
- }
- }
- return true;
- });
- bind("Space", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => {
- const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks());
- dispatch(splitMetadata(marks, state.tr));
- return false;
- });
- bind(":", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => {
- const range = state.selection.$from.blockRange(state.selection.$to, (node: any) => {
- return !node.marks || !node.marks.find((m: any) => m.type === schema.marks.metadata);
- });
- const path = (state.doc.resolve(state.selection.from - 1) as any).path;
- const spaceSeparator = path[path.length - 3].childCount > 1 ? 0 : -1;
- const textsel = TextSelection.create(state.doc, range!.end - path[path.length - 3].lastChild.nodeSize + spaceSeparator, range!.end);
- const text = range ? state.doc.textBetween(textsel.from, textsel.to) : "";
- let whitespace = text.length - 1;
- for (; whitespace >= 0 && text[whitespace] !== " "; whitespace--) { }
- if (text.endsWith(":")) {
- dispatch(state.tr.addMark(textsel.from + whitespace + 1, textsel.to, schema.marks.metadata.create() as any).
- addMark(textsel.from + whitespace + 1, textsel.to - 2, schema.marks.metadataKey.create() as any));
- }
- return false;
- });
-
-
- return keys;
-}
diff --git a/src/client/util/RichTextMenu.scss b/src/client/util/RichTextMenu.scss
deleted file mode 100644
index 43cc23ecd..000000000
--- a/src/client/util/RichTextMenu.scss
+++ /dev/null
@@ -1,121 +0,0 @@
-@import "../views/globalCssVariables";
-
-.button-dropdown-wrapper {
- position: relative;
-
- .dropdown-button {
- width: 15px;
- padding-left: 5px;
- padding-right: 5px;
- }
-
- .dropdown-button-combined {
- width: 50px;
- display: flex;
- justify-content: space-between;
-
- svg:nth-child(2) {
- margin-top: 2px;
- }
- }
-
- .dropdown {
- position: absolute;
- top: 35px;
- left: 0;
- background-color: #323232;
- color: $light-color-secondary;
- border: 1px solid #4d4d4d;
- border-radius: 0 6px 6px 6px;
- box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.25);
- min-width: 150px;
- padding: 5px;
- font-size: 12px;
- z-index: 10001;
-
- button {
- background-color: #323232;
- border: 1px solid black;
- border-radius: 1px;
- padding: 6px;
- margin: 5px 0;
- font-size: 10px;
-
- &:hover {
- background-color: black;
- }
-
- &:last-child {
- margin-bottom: 0;
- }
- }
- }
-
- input {
- color: black;
- }
-}
-
-.link-menu {
- .divider {
- background-color: white;
- height: 1px;
- width: 100%;
- }
-}
-
-.color-preview-button {
- .color-preview {
- width: 100%;
- height: 3px;
- margin-top: 3px;
- }
-}
-
-.color-wrapper {
- display: flex;
- flex-wrap: wrap;
- justify-content: space-between;
-
- button.color-button {
- width: 20px;
- height: 20px;
- border-radius: 15px !important;
- margin: 3px;
- border: 2px solid transparent !important;
- padding: 3px;
-
- &.active {
- border: 2px solid white !important;
- }
- }
-}
-
-select {
- background-color: #323232;
- color: white;
- border: 1px solid black;
- // border-top: none;
- // border-bottom: none;
- font-size: 12px;
- height: 100%;
- margin-right: 3px;
-
- &:focus,
- &:hover {
- background-color: black;
- }
-
- &::-ms-expand {
- color: white;
- }
-}
-
-.row-2 {
- display: flex;
- justify-content: space-between;
-
- >div {
- display: flex;
- }
-} \ No newline at end of file
diff --git a/src/client/util/RichTextMenu.tsx b/src/client/util/RichTextMenu.tsx
deleted file mode 100644
index e07efe056..000000000
--- a/src/client/util/RichTextMenu.tsx
+++ /dev/null
@@ -1,860 +0,0 @@
-import React = require("react");
-import AntimodeMenu from "../views/AntimodeMenu";
-import { observable, action, } from "mobx";
-import { observer } from "mobx-react";
-import { Mark, MarkType, Node as ProsNode, NodeType, ResolvedPos, Schema } from "prosemirror-model";
-import { schema } from "./RichTextSchema";
-import { EditorView } from "prosemirror-view";
-import { EditorState, NodeSelection, TextSelection } from "prosemirror-state";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { IconProp, library } from '@fortawesome/fontawesome-svg-core';
-import { faBold, faItalic, faUnderline, faStrikethrough, faSubscript, faSuperscript, faIndent, faEyeDropper, faCaretDown, faPalette, faHighlighter, faLink, faPaintRoller, faSleigh } from "@fortawesome/free-solid-svg-icons";
-import { MenuItem, Dropdown } from "prosemirror-menu";
-import { updateBullets } from "./ProsemirrorExampleTransfer";
-import { FieldViewProps } from "../views/nodes/FieldView";
-import { NumCast, Cast, StrCast } from "../../new_fields/Types";
-import { FormattedTextBoxProps } from "../views/nodes/FormattedTextBox";
-import { unimplementedFunction, Utils } from "../../Utils";
-import { wrapInList } from "prosemirror-schema-list";
-import { PastelSchemaPalette, DarkPastelSchemaPalette } from '../../new_fields/SchemaHeaderField';
-import "./RichTextMenu.scss";
-import { DocServer } from "../DocServer";
-import { Doc } from "../../new_fields/Doc";
-import { SelectionManager } from "./SelectionManager";
-import { LinkManager } from "./LinkManager";
-const { toggleMark, setBlockType } = require("prosemirror-commands");
-
-library.add(faBold, faItalic, faUnderline, faStrikethrough, faSuperscript, faSubscript, faIndent, faEyeDropper, faCaretDown, faPalette, faHighlighter, faLink, faPaintRoller);
-
-@observer
-export default class RichTextMenu extends AntimodeMenu {
- static Instance: RichTextMenu;
- public overMenu: boolean = false; // kind of hacky way to prevent selects not being selectable
-
- private view?: EditorView;
- public editorProps: FieldViewProps & FormattedTextBoxProps | undefined;
-
- public _brushMap: Map<string, Set<Mark>> = new Map();
- private fontSizeOptions: { mark: Mark | null, title: string, label: string, command: any, hidden?: boolean, style?: {} }[];
- private fontFamilyOptions: { mark: Mark | null, title: string, label: string, command: any, hidden?: boolean, style?: {} }[];
- private listTypeOptions: { node: NodeType | any | null, title: string, label: string, command: any, style?: {} }[];
- private fontColors: (string | undefined)[];
- private highlightColors: (string | undefined)[];
-
- @observable private boldActive: boolean = false;
- @observable private italicsActive: boolean = false;
- @observable private underlineActive: boolean = false;
- @observable private strikethroughActive: boolean = false;
- @observable private subscriptActive: boolean = false;
- @observable private superscriptActive: boolean = false;
-
- @observable private activeFontSize: string = "";
- @observable private activeFontFamily: string = "";
- @observable private activeListType: string = "";
-
- @observable private brushIsEmpty: boolean = true;
- @observable private brushMarks: Set<Mark> = new Set();
- @observable private showBrushDropdown: boolean = false;
-
- @observable private activeFontColor: string = "black";
- @observable private showColorDropdown: boolean = false;
-
- @observable private activeHighlightColor: string = "transparent";
- @observable private showHighlightDropdown: boolean = false;
-
- @observable private currentLink: string | undefined = "";
- @observable private showLinkDropdown: boolean = false;
-
- constructor(props: Readonly<{}>) {
- super(props);
- RichTextMenu.Instance = this;
- this._canFade = false;
-
- this.fontSizeOptions = [
- { mark: schema.marks.pFontSize.create({ fontSize: 7 }), title: "Set font size", label: "7pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 8 }), title: "Set font size", label: "8pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 9 }), title: "Set font size", label: "9pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 10 }), title: "Set font size", label: "10pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 12 }), title: "Set font size", label: "12pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 14 }), title: "Set font size", label: "14pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 16 }), title: "Set font size", label: "16pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 18 }), title: "Set font size", label: "18pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 20 }), title: "Set font size", label: "20pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 24 }), title: "Set font size", label: "24pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 32 }), title: "Set font size", label: "32pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 48 }), title: "Set font size", label: "48pt", command: this.changeFontSize },
- { mark: schema.marks.pFontSize.create({ fontSize: 72 }), title: "Set font size", label: "72pt", command: this.changeFontSize },
- { mark: null, title: "", label: "various", command: unimplementedFunction, hidden: true },
- { mark: null, title: "", label: "13pt", command: unimplementedFunction, hidden: true }, // this is here because the default size is 13, but there is no actual 13pt option
- ];
-
- this.fontFamilyOptions = [
- { mark: schema.marks.pFontFamily.create({ family: "Times New Roman" }), title: "Set font family", label: "Times New Roman", command: this.changeFontFamily, style: { fontFamily: "Times New Roman" } },
- { mark: schema.marks.pFontFamily.create({ family: "Arial" }), title: "Set font family", label: "Arial", command: this.changeFontFamily, style: { fontFamily: "Arial" } },
- { mark: schema.marks.pFontFamily.create({ family: "Georgia" }), title: "Set font family", label: "Georgia", command: this.changeFontFamily, style: { fontFamily: "Georgia" } },
- { mark: schema.marks.pFontFamily.create({ family: "Comic Sans MS" }), title: "Set font family", label: "Comic Sans MS", command: this.changeFontFamily, style: { fontFamily: "Comic Sans MS" } },
- { mark: schema.marks.pFontFamily.create({ family: "Tahoma" }), title: "Set font family", label: "Tahoma", command: this.changeFontFamily, style: { fontFamily: "Tahoma" } },
- { mark: schema.marks.pFontFamily.create({ family: "Impact" }), title: "Set font family", label: "Impact", command: this.changeFontFamily, style: { fontFamily: "Impact" } },
- { mark: schema.marks.pFontFamily.create({ family: "Crimson Text" }), title: "Set font family", label: "Crimson Text", command: this.changeFontFamily, style: { fontFamily: "Crimson Text" } },
- { mark: null, title: "", label: "various", command: unimplementedFunction, hidden: true },
- // { mark: null, title: "", label: "default", command: unimplementedFunction, hidden: true },
- ];
-
- this.listTypeOptions = [
- { node: schema.nodes.ordered_list.create({ mapStyle: "bullet" }), title: "Set list type", label: ":", command: this.changeListType },
- { node: schema.nodes.ordered_list.create({ mapStyle: "decimal" }), title: "Set list type", label: "1.1", command: this.changeListType },
- { node: schema.nodes.ordered_list.create({ mapStyle: "multi" }), title: "Set list type", label: "1.A", command: this.changeListType },
- { node: undefined, title: "Set list type", label: "Remove", command: this.changeListType },
- ];
-
- this.fontColors = [
- DarkPastelSchemaPalette.get("pink2"),
- DarkPastelSchemaPalette.get("purple4"),
- DarkPastelSchemaPalette.get("bluegreen1"),
- DarkPastelSchemaPalette.get("yellow4"),
- DarkPastelSchemaPalette.get("red2"),
- DarkPastelSchemaPalette.get("bluegreen7"),
- DarkPastelSchemaPalette.get("bluegreen5"),
- DarkPastelSchemaPalette.get("orange1"),
- "#757472",
- "#000"
- ];
-
- this.highlightColors = [
- PastelSchemaPalette.get("pink2"),
- PastelSchemaPalette.get("purple4"),
- PastelSchemaPalette.get("bluegreen1"),
- PastelSchemaPalette.get("yellow4"),
- PastelSchemaPalette.get("red2"),
- PastelSchemaPalette.get("bluegreen7"),
- PastelSchemaPalette.get("bluegreen5"),
- PastelSchemaPalette.get("orange1"),
- "white",
- "transparent"
- ];
- }
-
- @action
- changeView(view: EditorView) {
- this.view = view;
- }
-
- update(view: EditorView, lastState: EditorState | undefined) {
- this.updateFromDash(view, lastState, this.editorProps);
- }
-
-
- public MakeLinkToSelection = (linkDocId: string, title: string, location: string, targetDocId: string): string => {
- if (this.view) {
- 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 || "";
- }
- return "";
- }
-
- @action
- public async updateFromDash(view: EditorView, lastState: EditorState | undefined, props: any) {
- if (!view) {
- console.log("no editor? why?");
- return;
- }
- this.view = view;
- const state = view.state;
- 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;
-
- // update active marks
- const activeMarks = this.getActiveMarksOnSelection();
- this.setActiveMarkButtons(activeMarks);
-
- // update active font family and size
- const active = this.getActiveFontStylesOnSelection();
- const activeFamilies = active && active.get("families");
- const activeSizes = active && active.get("sizes");
-
- 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";
-
- // update link in current selection
- const targetTitle = await this.getTextLinkTargetTitle();
- this.setCurrentLink(targetTitle);
- }
-
- setMark = (mark: Mark, state: EditorState<any>, dispatch: any) => {
- if (mark) {
- const node = (state.selection as NodeSelection).node;
- if (node?.type === schema.nodes.ordered_list) {
- let attrs = node.attrs;
- if (mark.type === schema.marks.pFontFamily) attrs = { ...attrs, setFontFamily: mark.attrs.family };
- if (mark.type === schema.marks.pFontSize) attrs = { ...attrs, setFontSize: mark.attrs.fontSize };
- if (mark.type === schema.marks.pFontColor) attrs = { ...attrs, setFontColor: mark.attrs.color };
- const tr = updateBullets(state.tr.setNodeMarkup(state.selection.from, node.type, attrs), state.schema);
- dispatch(tr.setSelection(new NodeSelection(tr.doc.resolve(state.selection.from))));
- } else {
- toggleMark(mark.type, mark.attrs)(state, (tx: any) => {
- const { from, $from, to, empty } = tx.selection;
- if (!tx.doc.rangeHasMark(from, to, mark.type)) {
- toggleMark(mark.type, mark.attrs)({ tr: tx, doc: tx.doc, selection: tx.selection, storedMarks: tx.storedMarks }, dispatch);
- } else dispatch(tx);
- });
- }
- }
- }
-
- // finds font sizes and families in selection
- getActiveFontStylesOnSelection() {
- if (!this.view) return;
-
- const activeFamilies: string[] = [];
- const activeSizes: string[] = [];
- const state = this.view.state;
- const pos = this.view.state.selection.$from;
- const ref_node = 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);
- m.type === state.schema.marks.pFontSize && activeSizes.push(String(m.attrs.fontSize) + "pt");
- });
- }
-
- const styles = new Map<String, String[]>();
- styles.set("families", activeFamilies);
- styles.set("sizes", activeSizes);
- return styles;
- }
-
- 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;
- }
-
- //finds all active marks on selection in given group
- getActiveMarksOnSelection() {
- if (!this.view) return;
-
- const markGroup = [schema.marks.strong, schema.marks.em, schema.marks.underline, schema.marks.strikethrough, schema.marks.superscript, schema.marks.subscript];
- 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;
- let activeMarks: MarkType[] = [];
- if (!empty) {
- activeMarks = markGroup.filter(mark => {
- const has = false;
- for (let i = 0; !has && i < ranges.length; i++) {
- return state.doc.rangeHasMark(ranges[i].$from.pos, ranges[i].$to.pos, mark);
- }
- return false;
- });
- }
- else {
- const pos = this.view.state.selection.$from;
- const ref_node: ProsNode | null = this.reference_node(pos);
- if (ref_node !== null && ref_node !== this.view.state.doc) {
- if (ref_node.isText) {
- }
- else {
- return [];
- }
- 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);
- }
- const mark = state.schema.mark(mark_type);
- return ref_node.marks.includes(mark);
- });
- }
- }
- return activeMarks;
- }
-
- destroy() {
- }
-
- @action
- setActiveMarkButtons(activeMarks: MarkType[] | undefined) {
- if (!activeMarks) return;
-
- this.boldActive = false;
- this.italicsActive = false;
- this.underlineActive = false;
- this.strikethroughActive = false;
- this.subscriptActive = false;
- this.superscriptActive = false;
-
- activeMarks.forEach(mark => {
- switch (mark.name) {
- case "strong": this.boldActive = true; break;
- case "em": this.italicsActive = true; break;
- case "underline": this.underlineActive = true; break;
- case "strikethrough": this.strikethroughActive = true; break;
- case "subscript": this.subscriptActive = true; break;
- case "superscript": this.superscriptActive = true; break;
- }
- });
- }
-
- createButton(faIcon: string, title: string, isActive: boolean = false, command?: any, onclick?: any) {
- const self = this;
- function onClick(e: React.PointerEvent) {
- e.preventDefault();
- e.stopPropagation();
- self.view && self.view.focus();
- self.view && command && command(self.view.state, self.view.dispatch, self.view);
- self.view && onclick && onclick(self.view.state, self.view.dispatch, self.view);
- self.setActiveMarkButtons(self.getActiveMarksOnSelection());
- }
-
- return (
- <button className={"antimodeMenu-button" + (isActive ? " active" : "")} key={title} title={title} onPointerDown={onClick}>
- <FontAwesomeIcon icon={faIcon as IconProp} size="lg" />
- </button>
- );
- }
-
- createMarksDropdown(activeOption: string, options: { mark: Mark | null, title: string, label: string, command: (mark: Mark, view: EditorView) => void, hidden?: boolean, style?: {} }[], key: string): JSX.Element {
- const items = options.map(({ title, label, hidden, style }) => {
- if (hidden) {
- return label === activeOption ?
- <option value={label} title={title} key={label} style={style ? style : {}} selected hidden>{label}</option> :
- <option value={label} title={title} key={label} style={style ? style : {}} hidden>{label}</option>;
- }
- return label === activeOption ?
- <option value={label} title={title} key={label} style={style ? style : {}} selected>{label}</option> :
- <option value={label} title={title} key={label} style={style ? style : {}}>{label}</option>;
- });
-
- const self = this;
- function onChange(e: React.ChangeEvent<HTMLSelectElement>) {
- e.stopPropagation();
- e.preventDefault();
- options.forEach(({ label, mark, command }) => {
- if (e.target.value === label) {
- self.view && mark && command(mark, self.view);
- }
- });
- }
- return <select onChange={onChange} key={key}>{items}</select>;
- }
-
- createNodesDropdown(activeOption: string, options: { node: NodeType | any | null, title: string, label: string, command: (node: NodeType | any) => void, hidden?: boolean, style?: {} }[], key: string): JSX.Element {
- const items = options.map(({ title, label, hidden, style }) => {
- if (hidden) {
- return label === activeOption ?
- <option value={label} title={title} key={label} style={style ? style : {}} selected hidden>{label}</option> :
- <option value={label} title={title} key={label} style={style ? style : {}} hidden>{label}</option>;
- }
- return label === activeOption ?
- <option value={label} title={title} key={label} style={style ? style : {}} selected>{label}</option> :
- <option value={label} title={title} key={label} style={style ? style : {}}>{label}</option>;
- });
-
- const self = this;
- function onChange(val: string) {
- options.forEach(({ label, node, command }) => {
- if (val === label) {
- self.view && node && command(node);
- }
- });
- }
- return <select onChange={e => onChange(e.target.value)} key={key}>{items}</select>;
- }
-
- changeFontSize = (mark: Mark, view: EditorView) => {
- this.setMark(view.state.schema.marks.pFontSize.create({ fontSize: mark.attrs.fontSize }), view.state, view.dispatch);
- }
-
- changeFontFamily = (mark: Mark, view: EditorView) => {
- this.setMark(view.state.schema.marks.pFontFamily.create({ family: mark.attrs.family }), view.state, view.dispatch);
- }
-
- // TODO: remove doesn't work
- //remove all node type and apply the passed-in one to the selected text
- changeListType = (nodeType: NodeType | undefined) => {
- if (!this.view) return;
-
- if (nodeType === schema.nodes.bullet_list) {
- wrapInList(nodeType)(this.view.state, this.view.dispatch);
- } else {
- const marks = this.view.state.storedMarks || (this.view.state.selection.$to.parentOffset && this.view.state.selection.$from.marks());
- if (!wrapInList(schema.nodes.ordered_list)(this.view.state, (tx2: any) => {
- const tx3 = updateBullets(tx2, schema, nodeType && (nodeType as any).attrs.mapStyle);
- marks && tx3.ensureMarks([...marks]);
- marks && tx3.setStoredMarks([...marks]);
-
- this.view!.dispatch(tx2);
- })) {
- const tx2 = this.view.state.tr;
- const tx3 = updateBullets(tx2, schema, nodeType && (nodeType as any).attrs.mapStyle);
- marks && tx3.ensureMarks([...marks]);
- marks && tx3.setStoredMarks([...marks]);
-
- this.view.dispatch(tx3);
- }
- }
- }
-
- 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;
- }
-
- @action toggleBrushDropdown() { this.showBrushDropdown = !this.showBrushDropdown; }
-
- // todo: add brushes to brushMap to save with a style name
- onBrushNameKeyPress = (e: React.KeyboardEvent) => {
- if (e.key === "Enter") {
- RichTextMenu.Instance.brushMarks && RichTextMenu.Instance._brushMap.set(this._brushNameRef.current!.value, RichTextMenu.Instance.brushMarks);
- this._brushNameRef.current!.style.background = "lightGray";
- }
- }
- _brushNameRef = React.createRef<HTMLInputElement>();
-
- createBrushButton() {
- const self = this;
- function onBrushClick(e: React.PointerEvent) {
- e.preventDefault();
- e.stopPropagation();
- self.view && self.view.focus();
- self.view && self.fillBrush(self.view.state, self.view.dispatch);
- }
-
- let label = "Stored marks: ";
- if (this.brushMarks && this.brushMarks.size > 0) {
- this.brushMarks.forEach((mark: Mark) => {
- const markType = mark.type;
- label += markType.name;
- label += ", ";
- });
- label = label.substring(0, label.length - 2);
- } else {
- label = "No marks are currently stored";
- }
-
- const button =
- <button className="antimodeMenu-button" title="" onPointerDown={onBrushClick} style={this.brushMarks && this.brushMarks.size > 0 ? { backgroundColor: "121212" } : {}}>
- <FontAwesomeIcon icon="paint-roller" size="lg" style={{ transition: "transform 0.1s", transform: this.brushMarks && this.brushMarks.size > 0 ? "rotate(45deg)" : "" }} />
- </button>;
-
- const dropdownContent =
- <div className="dropdown">
- <p>{label}</p>
- <button onPointerDown={this.clearBrush}>Clear brush</button>
- <input placeholder="-brush name-" ref={this._brushNameRef} onKeyPress={this.onBrushNameKeyPress}></input>
- </div>;
-
- return (
- <ButtonDropdown view={this.view} key={"brush dropdown"} button={button} dropdownContent={dropdownContent} />
- );
- }
-
- @action
- clearBrush() {
- RichTextMenu.Instance.brushIsEmpty = true;
- RichTextMenu.Instance.brushMarks = new Set();
- }
-
- @action
- fillBrush(state: EditorState<any>, dispatch: any) {
- if (!this.view) return;
-
- if (this.brushIsEmpty) {
- const selected_marks = this.getMarksInSelection(this.view.state);
- if (selected_marks.size >= 0) {
- this.brushMarks = selected_marks;
- this.brushIsEmpty = !this.brushIsEmpty;
- }
- }
- else {
- const { from, to, $from } = this.view.state.selection;
- if (!this.view.state.selection.empty && $from && $from.nodeAfter) {
- if (this.brushMarks && to - from > 0) {
- this.view.dispatch(this.view.state.tr.removeMark(from, to));
- Array.from(this.brushMarks).filter(m => m.type !== schema.marks.user_mark).forEach((mark: Mark) => {
- this.setMark(mark, this.view!.state, this.view!.dispatch);
- });
- }
- }
- else {
- this.brushIsEmpty = !this.brushIsEmpty;
- }
- }
- }
-
- @action toggleColorDropdown() { this.showColorDropdown = !this.showColorDropdown; }
- @action setActiveColor(color: string) { this.activeFontColor = color; }
-
- createColorButton() {
- const self = this;
- function onColorClick(e: React.PointerEvent) {
- e.preventDefault();
- e.stopPropagation();
- self.view && self.view.focus();
- self.view && self.insertColor(self.activeFontColor, self.view.state, self.view.dispatch);
- }
- function changeColor(e: React.PointerEvent, color: string) {
- e.preventDefault();
- e.stopPropagation();
- self.view && self.view.focus();
- self.setActiveColor(color);
- self.view && self.insertColor(self.activeFontColor, self.view.state, self.view.dispatch);
- }
-
- const button =
- <button className="antimodeMenu-button color-preview-button" title="" onPointerDown={onColorClick}>
- <FontAwesomeIcon icon="palette" size="lg" />
- <div className="color-preview" style={{ backgroundColor: this.activeFontColor }}></div>
- </button>;
-
- const dropdownContent =
- <div className="dropdown" >
- <p>Change font color:</p>
- <div className="color-wrapper">
- {this.fontColors.map(color => {
- if (color) {
- return this.activeFontColor === color ?
- <button className="color-button active" key={"active" + color} style={{ backgroundColor: color }} onPointerDown={e => changeColor(e, color)}></button> :
- <button className="color-button" key={"other" + color} style={{ backgroundColor: color }} onPointerDown={e => changeColor(e, color)}></button>;
- }
- })}
- </div>
- </div>;
-
- return (
- <ButtonDropdown view={this.view} key={"color dropdown"} button={button} dropdownContent={dropdownContent} />
- );
- }
-
- public 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;
- }
- this.setMark(colorMark, state, dispatch);
- }
-
- @action toggleHighlightDropdown() { this.showHighlightDropdown = !this.showHighlightDropdown; }
- @action setActiveHighlight(color: string) { this.activeHighlightColor = color; }
-
- createHighlighterButton() {
- const self = this;
- function onHighlightClick(e: React.PointerEvent) {
- e.preventDefault();
- e.stopPropagation();
- self.view && self.view.focus();
- self.view && self.insertHighlight(self.activeHighlightColor, self.view.state, self.view.dispatch);
- }
- function changeHighlight(e: React.PointerEvent, color: string) {
- e.preventDefault();
- e.stopPropagation();
- self.view && self.view.focus();
- self.setActiveHighlight(color);
- self.view && self.insertHighlight(self.activeHighlightColor, self.view.state, self.view.dispatch);
- }
-
- const button =
- <button className="antimodeMenu-button color-preview-button" title="" key="highilghter-button" onPointerDown={onHighlightClick}>
- <FontAwesomeIcon icon="highlighter" size="lg" />
- <div className="color-preview" style={{ backgroundColor: this.activeHighlightColor }}></div>
- </button>;
-
- const dropdownContent =
- <div className="dropdown">
- <p>Change highlight color:</p>
- <div className="color-wrapper">
- {this.highlightColors.map(color => {
- if (color) {
- return this.activeHighlightColor === color ?
- <button className="color-button active" key={`active ${color}`} style={{ backgroundColor: color }} onPointerDown={e => changeHighlight(e, color)}>{color === "transparent" ? "X" : ""}</button> :
- <button className="color-button" key={`inactive ${color}`} style={{ backgroundColor: color }} onPointerDown={e => changeHighlight(e, color)}>{color === "transparent" ? "X" : ""}</button>;
- }
- })}
- </div>
- </div>;
-
- return (
- <ButtonDropdown view={this.view} key={"highlighter"} button={button} dropdownContent={dropdownContent} />
- );
- }
-
- insertHighlight(color: String, state: EditorState<any>, dispatch: any) {
- if (state.selection.empty) return false;
- toggleMark(state.schema.marks.marker, { highlight: color })(state, dispatch);
- }
-
- @action toggleLinkDropdown() { this.showLinkDropdown = !this.showLinkDropdown; }
- @action setCurrentLink(link: string) { this.currentLink = link; }
-
- createLinkButton() {
- const self = this;
-
- function onLinkChange(e: React.ChangeEvent<HTMLInputElement>) {
- self.setCurrentLink(e.target.value);
- }
-
- const link = this.currentLink ? this.currentLink : "";
-
- const button = <FontAwesomeIcon icon="link" size="lg" />;
-
- const dropdownContent =
- <div className="dropdown link-menu">
- <p>Linked to:</p>
- <input value={link} placeholder="Enter URL" onChange={onLinkChange} />
- <button className="make-button" onPointerDown={e => this.makeLinkToURL(link, "onRight")}>Apply hyperlink</button>
- <div className="divider"></div>
- <button className="remove-button" onPointerDown={e => this.deleteLink()}>Remove link</button>
- </div>;
-
- return (
- <ButtonDropdown view={this.view} key={"link button"} button={button} dropdownContent={dropdownContent} openDropdownOnButton={true} />
- );
- }
-
- async getTextLinkTargetTitle() {
- if (!this.view) return;
-
- const node = this.view.state.selection.$from.nodeAfter;
- const link = node && node.marks.find(m => m.type.name === "link");
- if (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) {
- const linkDoc = await DocServer.GetRefField(linkclicked);
- if (linkDoc instanceof Doc) {
- const anchor1 = await Cast(linkDoc.anchor1, Doc);
- const anchor2 = await Cast(linkDoc.anchor2, Doc);
- const currentDoc = SelectionManager.SelectedDocuments().length && SelectionManager.SelectedDocuments()[0].props.Document;
- if (currentDoc && anchor1 && anchor2) {
- if (Doc.AreProtosEqual(currentDoc, anchor1)) {
- return StrCast(anchor2.title);
- }
- if (Doc.AreProtosEqual(currentDoc, anchor2)) {
- return StrCast(anchor1.title);
- }
- }
- }
- }
- } else {
- return href;
- }
- } else {
- return link.attrs.title;
- }
- }
- }
-
- // TODO: should check for valid URL
- makeLinkToURL = (target: String, lcoation: string) => {
- if (!this.view) return;
-
- 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 = () => {
- if (!this.view) return;
-
- 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 => {
- 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));
- }
- });
- }
- } else {
- if (node) {
- const { tr, schema, selection } = this.view.state;
- const extension = this.linkExtend(selection.$anchor, href);
- this.view.dispatch(tr.removeMark(extension.from, extension.to, schema.marks.link));
- }
- }
- }
- }
-
- linkExtend($start: ResolvedPos, href: string) {
- const mark = this.view!.state.schema.marks.link;
-
- let startIndex = $start.index();
- let endIndex = $start.indexAfter();
-
- while (startIndex > 0 && $start.parent.child(startIndex - 1).marks.filter(m => m.type === mark && m.attrs.href === href).length) startIndex--;
- while (endIndex < $start.parent.childCount && $start.parent.child(endIndex).marks.filter(m => m.type === mark && m.attrs.href === href).length) endIndex++;
-
- let startPos = $start.start();
- let endPos = startPos;
- for (let i = 0; i < endIndex; i++) {
- const size = $start.parent.child(i).nodeSize;
- if (i < startIndex) startPos += size;
- endPos += size;
- }
- return { from: startPos, to: endPos };
- }
-
- reference_node(pos: ResolvedPos<any>): ProsNode | null {
- if (!this.view) return null;
-
- let ref_node: ProsNode = this.view.state.doc;
- if (pos.nodeBefore !== null && pos.nodeBefore !== undefined) {
- ref_node = pos.nodeBefore;
- }
- else if (pos.nodeAfter !== null && pos.nodeAfter !== undefined) {
- ref_node = pos.nodeAfter;
- }
- else if (pos.pos > 0) {
- let skip = false;
- for (let i: number = pos.pos - 1; i > 0; i--) {
- this.view.state.doc.nodesBetween(i, pos.pos, (node: ProsNode) => {
- if (node.isLeaf && !skip) {
- ref_node = node;
- skip = true;
- }
-
- });
- }
- }
- if (!ref_node.isLeaf && ref_node.childCount > 0) {
- ref_node = ref_node.child(0);
- }
- return ref_node;
- }
-
- @action onPointerEnter(e: React.PointerEvent) { RichTextMenu.Instance.overMenu = true; }
- @action onPointerLeave(e: React.PointerEvent) { RichTextMenu.Instance.overMenu = false; }
-
- @action
- toggleMenuPin = (e: React.MouseEvent) => {
- this.Pinned = !this.Pinned;
- if (!this.Pinned) {
- this.fadeOut(true);
- }
- }
-
- render() {
-
- const row1 = <div className="antimodeMenu-row" key="row1">{[
- this.createButton("bold", "Bold", this.boldActive, toggleMark(schema.marks.strong)),
- this.createButton("italic", "Italic", this.italicsActive, toggleMark(schema.marks.em)),
- this.createButton("underline", "Underline", this.underlineActive, toggleMark(schema.marks.underline)),
- this.createButton("strikethrough", "Strikethrough", this.strikethroughActive, toggleMark(schema.marks.strikethrough)),
- this.createButton("superscript", "Superscript", this.superscriptActive, toggleMark(schema.marks.superscript)),
- this.createButton("subscript", "Subscript", this.subscriptActive, toggleMark(schema.marks.subscript)),
- this.createColorButton(),
- this.createHighlighterButton(),
- this.createLinkButton(),
- this.createBrushButton(),
- this.createButton("indent", "Summarize", undefined, this.insertSummarizer),
- ]}</div>;
-
- const row2 = <div className="antimodeMenu-row row-2" key="antimodemenu row2">
- <div key="row">
- {[this.createMarksDropdown(this.activeFontSize, this.fontSizeOptions, "font size"),
- this.createMarksDropdown(this.activeFontFamily, this.fontFamilyOptions, "font family"),
- this.createNodesDropdown(this.activeListType, this.listTypeOptions, "nodes")]}
- </div>
- <div key="button">
- <button className="antimodeMenu-button" key="pin menu" title="Pin menu" onClick={this.toggleMenuPin} style={this.Pinned ? { backgroundColor: "#121212" } : {}}>
- <FontAwesomeIcon icon="thumbtack" size="lg" style={{ transition: "transform 0.1s", transform: this.Pinned ? "rotate(45deg)" : "" }} />
- </button>
- {this.getDragger()}
- </div>
- </div>;
-
- return (
- <div className="richTextMenu" onPointerEnter={this.onPointerEnter} onPointerLeave={this.onPointerLeave}>
- {this.getElementWithRows([row1, row2], 2, false)}
- </div>
- );
- }
-}
-
-interface ButtonDropdownProps {
- view?: EditorView;
- button: JSX.Element;
- dropdownContent: JSX.Element;
- openDropdownOnButton?: boolean;
-}
-
-@observer
-class ButtonDropdown extends React.Component<ButtonDropdownProps> {
-
- @observable private showDropdown: boolean = false;
- private ref: HTMLDivElement | null = null;
-
- componentDidMount() {
- document.addEventListener("pointerdown", this.onBlur);
- }
-
- componentWillUnmount() {
- document.removeEventListener("pointerdown", this.onBlur);
- }
-
- @action
- setShowDropdown(show: boolean) {
- this.showDropdown = show;
- }
- @action
- toggleDropdown() {
- this.showDropdown = !this.showDropdown;
- }
-
- onDropdownClick = (e: React.PointerEvent) => {
- e.preventDefault();
- e.stopPropagation();
- this.props.view && this.props.view.focus();
- this.toggleDropdown();
- }
-
- onBlur = (e: PointerEvent) => {
- setTimeout(() => {
- if (this.ref !== null && !this.ref.contains(e.target as Node)) {
- this.setShowDropdown(false);
- }
- }, 0);
- }
-
- render() {
- return (
- <div className="button-dropdown-wrapper" ref={node => this.ref = node}>
- {this.props.openDropdownOnButton ?
- <button className="antimodeMenu-button dropdown-button-combined" onPointerDown={this.onDropdownClick}>
- {this.props.button}
- <FontAwesomeIcon icon="caret-down" size="sm" />
- </button> :
- <>
- {this.props.button}
- <button className="dropdown-button antimodeMenu-button" key="antimodebutton" onPointerDown={this.onDropdownClick}>
- <FontAwesomeIcon icon="caret-down" size="sm" />
- </button>
- </>}
-
- {this.showDropdown ? this.props.dropdownContent : (null)}
- </div>
- );
- }
-} \ No newline at end of file
diff --git a/src/client/util/RichTextRules.ts b/src/client/util/RichTextRules.ts
deleted file mode 100644
index 3b30b5b3f..000000000
--- a/src/client/util/RichTextRules.ts
+++ /dev/null
@@ -1,295 +0,0 @@
-import { textblockTypeInputRule, smartQuotes, emDash, ellipsis, InputRule } from "prosemirror-inputrules";
-import { schema } from "./RichTextSchema";
-import { wrappingInputRule } from "./prosemirrorPatches";
-import { NodeSelection, TextSelection } from "prosemirror-state";
-import { StrCast, Cast, NumCast } from "../../new_fields/Types";
-import { Doc, DataSym } from "../../new_fields/Doc";
-import { FormattedTextBox } from "../views/nodes/FormattedTextBox";
-import { Docs, DocUtils } from "../documents/Documents";
-import { Id } from "../../new_fields/FieldSymbols";
-import { DocServer } from "../DocServer";
-import { returnFalse, Utils } from "../../Utils";
-import RichTextMenu from "./RichTextMenu";
-import { RichTextField } from "../../new_fields/RichTextField";
-import { ComputedField } from "../../new_fields/ScriptField";
-
-export const inpRules = {
- rules: [
- ...smartQuotes,
- ellipsis,
- emDash,
-
- // > blockquote
- wrappingInputRule(/^\s*>\s$/, schema.nodes.blockquote),
-
- // 1. ordered list
- wrappingInputRule(
- /^1\.\s$/,
- schema.nodes.ordered_list,
- () => {
- return ({ mapStyle: "decimal", bulletStyle: 1 });
- },
- (match: any, node: any) => {
- return node.childCount + node.attrs.order === +match[1];
- },
- (type: any) => ({ type: type, attrs: { mapStyle: "decimal", bulletStyle: 1 } })
- ),
- // a. alphabbetical list
- wrappingInputRule(
- /^a\.\s$/,
- schema.nodes.ordered_list,
- // match => {
- () => {
- return ({ mapStyle: "alpha", bulletStyle: 1 });
- // return ({ order: +match[1] })
- },
- (match: any, node: any) => {
- return node.childCount + node.attrs.order === +match[1];
- },
- (type: any) => ({ type: type, attrs: { mapStyle: "alpha", bulletStyle: 1 } })
- ),
-
- // * bullet list
- wrappingInputRule(/^\s*([-+*])\s$/, schema.nodes.bullet_list),
-
- // ``` code block
- textblockTypeInputRule(/^```$/, schema.nodes.code_block),
-
- // # heading
- textblockTypeInputRule(
- new RegExp(/^(#{1,6})\s$/),
- schema.nodes.heading,
- match => {
- return ({ level: match[1].length });
- }
- ),
-
- // set the font size using #<font-size>
- new InputRule(
- new RegExp(/%([0-9]+)\s$/),
- (state, match, start, end) => {
- const size = Number(match[1]);
- return state.tr.deleteRange(start, end).addStoredMark(schema.marks.pFontSize.create({ fontSize: size }));
- }),
-
- // create a text display of a metadata field on this or another document, or create a hyperlink portal to another document [[ <fieldKey> : <Doc>]] // [[:Doc]] => hyperlink [[fieldKey]] => show field [[fieldKey:Doc]] => show field of doc
- new InputRule(
- new RegExp(/\[\[([a-zA-Z_ \-0-9]*)(:[a-zA-Z_ \-0-9]+)?\]\]$/),
- (state, match, start, end) => {
- const fieldKey = match[1];
- const docid = match[2]?.substring(1);
- if (!fieldKey) {
- if (docid) {
- DocServer.GetRefField(docid).then(docx => {
- const target = ((docx instanceof Doc) && docx) || Docs.Create.FreeformDocument([], { title: docid, _width: 500, _height: 500, _LODdisable: true, }, docid);
- DocUtils.Publish(target, docid, returnFalse, returnFalse);
- DocUtils.MakeLink({ doc: (schema as any).Document }, { doc: target }, "portal link", "");
- });
- const link = state.schema.marks.link.create({ href: Utils.prepend("/doc/" + docid), location: "onRight", title: docid, targetId: docid });
- return state.tr.deleteRange(end - 1, end).deleteRange(start, start + 2).addMark(start, end - 3, link);
- }
- return state.tr;
- }
- const fieldView = state.schema.nodes.dashField.create({ fieldKey, docid });
- return state.tr.deleteRange(start, end).insert(start, fieldView);
- }),
- // create an inline view of a document {{ <layoutKey> : <Doc> }} // {{:Doc}} => show default view of document {{<layout>}} => show layout for this doc {{<layout> : Doc}} => show layout for another doc
- new InputRule(
- new RegExp(/\{\{([a-zA-Z_ \-0-9]*)(:[a-zA-Z_ \-0-9]+)?\}\}$/),
- (state, match, start, end) => {
- const fieldKey = match[1];
- const docid = match[2]?.substring(1);
- if (!fieldKey && !docid) return state.tr;
- docid && DocServer.GetRefField(docid).then(docx => {
- if (!(docx instanceof Doc && docx)) {
- const docx = Docs.Create.FreeformDocument([], { title: docid, _width: 500, _height: 500, _LODdisable: true }, docid);
- DocUtils.Publish(docx, docid, returnFalse, returnFalse);
- }
- });
- const node = (state.doc.resolve(start) as any).nodeAfter;
- const dashDoc = schema.nodes.dashDoc.create({ width: 75, height: 75, title: "dashDoc", docid, fieldKey, float: "right", alias: Utils.GenerateGuid() });
- const sm = state.storedMarks || undefined;
- return node ? state.tr.replaceRangeWith(start, end, dashDoc).setStoredMarks([...node.marks, ...(sm ? sm : [])]) : state.tr;
- }),
- new InputRule(
- new RegExp(/##$/),
- (state, match, start, end) => {
- const schemaDoc = Doc.GetDataDoc((schema as any).Document);
- const textDoc = Doc.GetProto(Cast(schemaDoc[DataSym], Doc, null)!);
- const numInlines = NumCast(textDoc.inlineTextCount);
- textDoc.inlineTextCount = numInlines + 1;
- const inlineFieldKey = "inline" + numInlines; // which field on the text document this annotation will write to
- const inlineLayoutKey = "layout_" + inlineFieldKey; // the field holding the layout string that will render the inline annotation
- const textDocInline = Docs.Create.TextDocument("", { layoutKey: inlineLayoutKey, _width: 75, _height: 35, annotationOn: textDoc, _autoHeight: true, fontSize: 9, title: "inline comment" });
- textDocInline.title = inlineFieldKey; // give the annotation its own title
- textDocInline.customTitle = true; // And make sure that it's 'custom' so that editing text doesn't change the title of the containing doc
- textDocInline.isTemplateForField = inlineFieldKey; // this is needed in case the containing text doc is converted to a template at some point
- textDocInline.proto = textDoc; // make the annotation inherit from the outer text doc so that it can resolve any nested field references, e.g., [[field]]
- textDocInline._textContext = ComputedField.MakeFunction(`copyField(this.${inlineFieldKey})`, { this: Doc.name });
- textDoc[inlineLayoutKey] = FormattedTextBox.LayoutString(inlineFieldKey); // create a layout string for the layout key that will render the annotation text
- textDoc[inlineFieldKey] = ""; // set a default value for the annotation
- const node = (state.doc.resolve(start) as any).nodeAfter;
- const newNode = schema.nodes.dashComment.create({ docid: textDocInline[Id] });
- const dashDoc = schema.nodes.dashDoc.create({ width: 75, height: 35, title: "dashDoc", docid: textDocInline[Id], float: "right" });
- const sm = state.storedMarks || undefined;
- const replaced = node ? state.tr.insert(start, newNode).replaceRangeWith(start + 1, end + 1, dashDoc).insertText(" ", start + 2).setStoredMarks([...node.marks, ...(sm ? sm : [])]) :
- state.tr;
- return replaced;
- }),
- // stop using active style
- new InputRule(
- new RegExp(/%%$/),
- (state, match, start, end) => {
- const tr = state.tr.deleteRange(start, end);
- const marks = state.tr.selection.$anchor.nodeBefore?.marks;
- return marks ? Array.from(marks).filter(m => m !== state.schema.marks.user_mark).reduce((tr, m) => tr.removeStoredMark(m), tr) : tr;
- }),
-
- // set the Todo user-tag on the current selection (assumes % was used to initiate an EnteringStyle mode)
- new InputRule(
- new RegExp(/[ti!x]$/),
- (state, match, start, end) => {
- if (state.selection.to === state.selection.from || !(schema as any).EnteringStyle) return null;
- const tag = match[0] === "t" ? "todo" : match[0] === "i" ? "ignore" : match[0] === "x" ? "disagree" : match[0] === "!" ? "important" : "??";
- const node = (state.doc.resolve(start) as any).nodeAfter;
- if (node?.marks.findIndex((m: any) => m.type === schema.marks.user_tag) !== -1) return state.tr.removeMark(start, end, schema.marks.user_tag);
- return node ? state.tr.addMark(start, end, schema.marks.user_tag.create({ userid: Doc.CurrentUserEmail, tag: tag, modified: Math.round(Date.now() / 1000 / 60) })) : state.tr;
- }),
-
- // set the First-line indent node type for the selection's paragraph (assumes % was used to initiate an EnteringStyle mode)
- new InputRule(
- new RegExp(/(%d|d)$/),
- (state, match, start, end) => {
- if (!match[0].startsWith("%") && !(schema as any).EnteringStyle) return null;
- const pos = (state.doc.resolve(start) as any);
- for (let depth = pos.path.length / 3 - 1; depth >= 0; depth--) {
- const node = pos.node(depth);
- if (node.type === schema.nodes.paragraph) {
- const replaced = state.tr.setNodeMarkup(pos.pos - pos.parentOffset - 1, node.type, { ...node.attrs, indent: node.attrs.indent === 25 ? undefined : 25 });
- const result = replaced.setSelection(new TextSelection(replaced.doc.resolve(start)));
- return match[0].startsWith("%") ? result.deleteRange(start, end) : result;
- }
- }
- return null;
- }),
-
- // set the Hanging indent node type for the current selection's paragraph (assumes % was used to initiate an EnteringStyle mode)
- new InputRule(
- new RegExp(/(%h|h)$/),
- (state, match, start, end) => {
- if (!match[0].startsWith("%") && !(schema as any).EnteringStyle) return null;
- const pos = (state.doc.resolve(start) as any);
- for (let depth = pos.path.length / 3 - 1; depth >= 0; depth--) {
- const node = pos.node(depth);
- if (node.type === schema.nodes.paragraph) {
- const replaced = state.tr.setNodeMarkup(pos.pos - pos.parentOffset - 1, node.type, { ...node.attrs, indent: node.attrs.indent === -25 ? undefined : -25 });
- const result = replaced.setSelection(new TextSelection(replaced.doc.resolve(start)));
- return match[0].startsWith("%") ? result.deleteRange(start, end) : result;
- }
- }
- return null;
- }),
- // set the Quoted indent node type for the current selection's paragraph (assumes % was used to initiate an EnteringStyle mode)
- new InputRule(
- new RegExp(/(%q|q)$/),
- (state, match, start, end) => {
- if (!match[0].startsWith("%") && !(schema as any).EnteringStyle) return null;
- const pos = (state.doc.resolve(start) as any);
- if (state.selection instanceof NodeSelection && state.selection.node.type === schema.nodes.ordered_list) {
- const node = state.selection.node;
- return state.tr.setNodeMarkup(pos.pos, node.type, { ...node.attrs, indent: node.attrs.indent === 30 ? undefined : 30 });
- }
- for (let depth = pos.path.length / 3 - 1; depth >= 0; depth--) {
- const node = pos.node(depth);
- if (node.type === schema.nodes.paragraph) {
- const replaced = state.tr.setNodeMarkup(pos.pos - pos.parentOffset - 1, node.type, { ...node.attrs, inset: node.attrs.inset === 30 ? undefined : 30 });
- const result = replaced.setSelection(new TextSelection(replaced.doc.resolve(start)));
- return match[0].startsWith("%") ? result.deleteRange(start, end) : result;
- }
- }
- return null;
- }),
-
-
- // center justify text
- new InputRule(
- new RegExp(/%\^$/),
- (state, match, start, end) => {
- const node = (state.doc.resolve(start) as any).nodeAfter;
- const sm = state.storedMarks || undefined;
- const replaced = node ? state.tr.replaceRangeWith(start, end, schema.nodes.paragraph.create({ align: "center" })).setStoredMarks([...node.marks, ...(sm ? sm : [])]) :
- state.tr;
- return replaced.setSelection(new TextSelection(replaced.doc.resolve(end - 2)));
- }),
- // left justify text
- new InputRule(
- new RegExp(/%\[$/),
- (state, match, start, end) => {
- const node = (state.doc.resolve(start) as any).nodeAfter;
- const sm = state.storedMarks || undefined;
- const replaced = node ? state.tr.replaceRangeWith(start, end, schema.nodes.paragraph.create({ align: "left" })).setStoredMarks([...node.marks, ...(sm ? sm : [])]) :
- state.tr;
- return replaced.setSelection(new TextSelection(replaced.doc.resolve(end - 2)));
- }),
- // right justify text
- new InputRule(
- new RegExp(/%\]$/),
- (state, match, start, end) => {
- const node = (state.doc.resolve(start) as any).nodeAfter;
- const sm = state.storedMarks || undefined;
- const replaced = node ? state.tr.replaceRangeWith(start, end, schema.nodes.paragraph.create({ align: "right" })).setStoredMarks([...node.marks, ...(sm ? sm : [])]) :
- state.tr;
- return replaced.setSelection(new TextSelection(replaced.doc.resolve(end - 2)));
- }),
- new InputRule(
- new RegExp(/%\(/),
- (state, match, start, end) => {
- const node = (state.doc.resolve(start) as any).nodeAfter;
- 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, end,
- schema.nodes.summary.create({ visibility: true, text: content, textslice: content.toJSON() })) :
- state.tr;
- 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.deleteRange(start, end).removeStoredMark(state.schema.marks.summarizeInclusive.create());
- }),
- new InputRule(
- new RegExp(/%f$/),
- (state, match, start, end) => {
- const newNode = schema.nodes.footnote.create({});
- const tr = state.tr;
- tr.deleteRange(start, end).replaceSelectionWith(newNode); // replace insertion with a footnote.
- return tr.setSelection(new NodeSelection( // select the footnote node to open its display
- tr.doc.resolve( // get the location of the footnote node by subtracting the nodesize of the footnote from the current insertion point anchor (which will be immediately after the footnote node)
- tr.selection.anchor - tr.selection.$anchor.nodeBefore!.nodeSize)));
- }),
-
- // activate a style by name using prefix '%'
- new InputRule(
- new RegExp(/%[a-z]+$/),
- (state, match, start, end) => {
- const color = match[0].substring(1, match[0].length);
- const marks = RichTextMenu.Instance._brushMap.get(color);
- if (marks) {
- const tr = state.tr.deleteRange(start, end);
- return marks ? Array.from(marks).reduce((tr, m) => tr.addStoredMark(m), tr) : tr;
- }
- const isValidColor = (strColor: string) => {
- const s = new Option().style;
- s.color = strColor;
- return s.color === strColor.toLowerCase(); // 'false' if color wasn't assigned
- };
- if (isValidColor(color)) {
- return state.tr.deleteRange(start, end).addStoredMark(schema.marks.pFontColor.create({ color: color }));
- }
- return null;
- }),
- ]
-};
diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx
deleted file mode 100644
index c07ebe2ed..000000000
--- a/src/client/util/RichTextSchema.tsx
+++ /dev/null
@@ -1,1144 +0,0 @@
-import { reaction, IReactionDisposer, observable, runInAction } from "mobx";
-import { baseKeymap, toggleMark } from "prosemirror-commands";
-import { redo, undo } from "prosemirror-history";
-import { keymap } from "prosemirror-keymap";
-import { DOMOutputSpecArray, Fragment, MarkSpec, Node, NodeSpec, Schema, Slice } from "prosemirror-model";
-import { bulletList, listItem, orderedList } from 'prosemirror-schema-list';
-import { EditorState, NodeSelection, TextSelection, Plugin } from "prosemirror-state";
-import { StepMap } from "prosemirror-transform";
-import { EditorView } from "prosemirror-view";
-import * as ReactDOM from 'react-dom';
-import { Doc, WidthSym, HeightSym, DataSym, Field } from "../../new_fields/Doc";
-import { emptyFunction, returnEmptyString, returnFalse, returnOne, Utils } from "../../Utils";
-import { DocServer } from "../DocServer";
-import { DocumentView } from "../views/nodes/DocumentView";
-import { DocumentManager } from "./DocumentManager";
-import ParagraphNodeSpec from "./ParagraphNodeSpec";
-import { Transform } from "./Transform";
-import React = require("react");
-import { BoolCast, NumCast, StrCast } from "../../new_fields/Types";
-import { FormattedTextBox } from "../views/nodes/FormattedTextBox";
-import { ObjectField } from "../../new_fields/ObjectField";
-import { ComputedField } from "../../new_fields/ScriptField";
-import { observer } from "mobx-react";
-import { Id } from "../../new_fields/FieldSymbols";
-import { OnChangeHandler } from "react-color/lib/components/common/ColorWrap";
-
-const blockquoteDOM: DOMOutputSpecArray = ["blockquote", 0], hrDOM: DOMOutputSpecArray = ["hr"],
- preDOM: DOMOutputSpecArray = ["pre", ["code", 0]], brDOM: DOMOutputSpecArray = ["br"], ulDOM: DOMOutputSpecArray = ["ul", 0];
-
-// :: Object
-// [Specs](#model.NodeSpec) for the nodes defined in this schema.
-export const nodes: { [index: string]: NodeSpec } = {
- // :: NodeSpec The top level document node.
- doc: {
- content: "block+"
- },
-
- footnote: {
- group: "inline",
- content: "inline*",
- inline: true,
- attrs: {
- visibility: { default: false }
- },
- // This makes the view treat the node as a leaf, even though it
- // technically has content
- atom: true,
- toDOM: () => ["footnote", 0],
- parseDOM: [{ tag: "footnote" }]
- },
-
- paragraph: ParagraphNodeSpec,
-
- // :: NodeSpec A blockquote (`<blockquote>`) wrapping one or more blocks.
- blockquote: {
- content: "block+",
- group: "block",
- defining: true,
- parseDOM: [{ tag: "blockquote" }],
- toDOM() { return blockquoteDOM; }
- },
-
- // :: NodeSpec A horizontal rule (`<hr>`).
- horizontal_rule: {
- group: "block",
- parseDOM: [{ tag: "hr" }],
- toDOM() { return hrDOM; }
- },
-
- // :: NodeSpec A heading textblock, with a `level` attribute that
- // should hold the number 1 to 6. Parsed and serialized as `<h1>` to
- // `<h6>` elements.
- heading: {
- attrs: { level: { default: 1 } },
- content: "inline*",
- group: "block",
- defining: true,
- parseDOM: [{ tag: "h1", attrs: { level: 1 } },
- { tag: "h2", attrs: { level: 2 } },
- { tag: "h3", attrs: { level: 3 } },
- { tag: "h4", attrs: { level: 4 } },
- { tag: "h5", attrs: { level: 5 } },
- { tag: "h6", attrs: { level: 6 } }],
- toDOM(node: any) { return ["h" + node.attrs.level, 0]; }
- },
-
- // :: NodeSpec A code listing. Disallows marks or non-text inline
- // nodes by default. Represented as a `<pre>` element with a
- // `<code>` element inside of it.
- code_block: {
- content: "text*",
- marks: "",
- group: "block",
- code: true,
- defining: true,
- parseDOM: [{ tag: "pre", preserveWhitespace: "full" }],
- toDOM() { return preDOM; }
- },
-
- // :: NodeSpec The text node.
- text: {
- group: "inline"
- },
-
- dashComment: {
- attrs: {
- docid: { default: "" },
- },
- inline: true,
- group: "inline",
- toDOM(node) {
- const attrs = { style: `width: 40px` };
- return ["span", { ...node.attrs, ...attrs }, "←"];
- },
- },
-
- summary: {
- inline: true,
- attrs: {
- visibility: { default: false },
- text: { default: undefined },
- textslice: { default: undefined },
- },
- group: "inline",
- toDOM(node) {
- const attrs = { style: `width: 40px` };
- return ["span", { ...node.attrs, ...attrs }];
- },
- },
-
- // :: NodeSpec An inline image (`<img>`) node. Supports `src`,
- // `alt`, and `href` attributes. The latter two default to the empty
- // string.
- image: {
- inline: true,
- attrs: {
- src: {},
- width: { default: 100 },
- alt: { default: null },
- title: { default: null },
- float: { default: "left" },
- location: { default: "onRight" },
- docid: { default: "" }
- },
- group: "inline",
- draggable: true,
- parseDOM: [{
- tag: "img[src]", getAttrs(dom: any) {
- return {
- src: dom.getAttribute("src"),
- title: dom.getAttribute("title"),
- alt: dom.getAttribute("alt"),
- width: Math.min(100, Number(dom.getAttribute("width"))),
- };
- }
- }],
- // TODO if we don't define toDom, dragging the image crashes. Why?
- toDOM(node) {
- const attrs = { style: `width: ${node.attrs.width}` };
- return ["img", { ...node.attrs, ...attrs }];
- }
- },
-
- dashDoc: {
- inline: true,
- attrs: {
- width: { default: 200 },
- height: { default: 100 },
- title: { default: null },
- float: { default: "right" },
- location: { default: "onRight" },
- hidden: { default: false },
- fieldKey: { default: "" },
- docid: { default: "" },
- alias: { default: "" }
- },
- group: "inline",
- draggable: false,
- toDOM(node) {
- const attrs = { style: `width: ${node.attrs.width}, height: ${node.attrs.height}` };
- return ["div", { ...node.attrs, ...attrs }];
- }
- },
-
- dashField: {
- inline: true,
- attrs: {
- fieldKey: { default: "" },
- docid: { default: "" }
- },
- group: "inline",
- draggable: false,
- toDOM(node) {
- const attrs = { style: `width: ${node.attrs.width}, height: ${node.attrs.height}` };
- return ["div", { ...node.attrs, ...attrs }];
- }
- },
-
- video: {
- inline: true,
- attrs: {
- src: {},
- width: { default: "100px" },
- alt: { default: null },
- title: { default: null }
- },
- group: "inline",
- draggable: true,
- parseDOM: [{
- tag: "video[src]", getAttrs(dom: any) {
- return {
- src: dom.getAttribute("src"),
- title: dom.getAttribute("title"),
- alt: dom.getAttribute("alt"),
- width: Math.min(100, Number(dom.getAttribute("width"))),
- };
- }
- }],
- toDOM(node) {
- const attrs = { style: `width: ${node.attrs.width}` };
- return ["video", { ...node.attrs, ...attrs }];
- }
- },
-
- // :: NodeSpec A hard line break, represented in the DOM as `<br>`.
- hard_break: {
- inline: true,
- group: "inline",
- selectable: false,
- parseDOM: [{ tag: "br" }],
- toDOM() { return brDOM; }
- },
-
- ordered_list: {
- ...orderedList,
- content: 'list_item+',
- group: 'block',
- attrs: {
- bulletStyle: { default: 0 },
- mapStyle: { default: "decimal" },
- setFontSize: { default: undefined },
- setFontFamily: { default: "inherit" },
- setFontColor: { default: "inherit" },
- inheritedFontSize: { default: undefined },
- visibility: { default: true },
- indent: { default: undefined }
- },
- toDOM(node: Node<any>) {
- if (node.attrs.mapStyle === "bullet") return ['ul', 0];
- const map = node.attrs.bulletStyle ? node.attrs.mapStyle + node.attrs.bulletStyle : "";
- const fsize = node.attrs.setFontSize ? node.attrs.setFontSize : node.attrs.inheritedFontSize;
- const ffam = node.attrs.setFontFamily;
- const color = node.attrs.setFontColor;
- return node.attrs.visibility ?
- ['ol', { class: `${map}-ol`, style: `list-style: none; font-size: ${fsize}; font-family: ${ffam}; color:${color}; margin-left: ${node.attrs.indent}` }, 0] :
- ['ol', { class: `${map}-ol`, style: `list-style: none;` }];
- }
- },
-
- bullet_list: {
- ...bulletList,
- content: 'list_item+',
- group: 'block',
- // parseDOM: [{ tag: "ul" }, { style: 'list-style-type=disc' }],
- toDOM(node: Node<any>) {
- return ['ul', 0];
- }
- },
-
- list_item: {
- attrs: {
- bulletStyle: { default: 0 },
- mapStyle: { default: "decimal" },
- visibility: { default: true }
- },
- ...listItem,
- content: 'paragraph block*',
- toDOM(node: any) {
- const map = node.attrs.bulletStyle ? node.attrs.mapStyle + node.attrs.bulletStyle : "";
- return node.attrs.visibility ? ["li", { class: `${map}` }, 0] : ["li", { class: `${map}` }, "..."];
- //return ["li", { class: `${map}` }, 0];
- }
- },
-};
-
-const emDOM: DOMOutputSpecArray = ["em", 0];
-const strongDOM: DOMOutputSpecArray = ["strong", 0];
-const codeDOM: DOMOutputSpecArray = ["code", 0];
-
-// :: Object [Specs](#model.MarkSpec) for the marks in the schema.
-export const marks: { [index: string]: MarkSpec } = {
- // :: MarkSpec A link. Has `href` and `title` attributes. `title`
- // defaults to the empty string. Rendered and parsed as an `<a>`
- // element.
- link: {
- attrs: {
- href: {},
- targetId: { default: "" },
- showPreview: { default: true },
- location: { default: null },
- title: { default: null },
- docref: { default: false } // flags whether the linked text comes from a document within Dash. If so, an attribution label is appended after the text
- },
- inclusive: false,
- parseDOM: [{
- tag: "a[href]", getAttrs(dom: any) {
- return { href: dom.getAttribute("href"), location: dom.getAttribute("location"), title: dom.getAttribute("title"), targetId: dom.getAttribute("id") };
- }
- }],
- toDOM(node: any) {
- return node.attrs.docref && node.attrs.title ?
- ["div", ["span", `"`], ["span", 0], ["span", `"`], ["br"], ["a", { ...node.attrs, class: "prosemirror-attribution", title: `${node.attrs.title}` }, node.attrs.title], ["br"]] :
- ["a", { ...node.attrs, id: node.attrs.targetId, title: `${node.attrs.title}` }, 0];
- }
- },
-
-
- // :: MarkSpec Coloring on text. Has `color` attribute that defined the color of the marked text.
- pFontColor: {
- attrs: {
- color: { default: "#000" }
- },
- inclusive: true,
- parseDOM: [{
- tag: "span", getAttrs(dom: any) {
- return { color: dom.getAttribute("color") };
- }
- }],
- toDOM(node: any) {
- return node.attrs.color ? ['span', { style: 'color:' + node.attrs.color }] : ['span', 0];
- }
- },
-
- marker: {
- attrs: {
- highlight: { default: "transparent" }
- },
- inclusive: true,
- parseDOM: [{
- tag: "span", getAttrs(dom: any) {
- return { highlight: dom.getAttribute("backgroundColor") };
- }
- }],
- toDOM(node: any) {
- return node.attrs.highlight ? ['span', { style: 'background-color:' + node.attrs.highlight }] : ['span', { style: 'background-color: transparent' }];
- }
- },
-
- // :: MarkSpec An emphasis mark. Rendered as an `<em>` element.
- // Has parse rules that also match `<i>` and `font-style: italic`.
- em: {
- parseDOM: [{ tag: "i" }, { tag: "em" }, { style: "font-style: italic" }],
- toDOM() { return emDOM; }
- },
-
- // :: MarkSpec A strong mark. Rendered as `<strong>`, parse rules
- // also match `<b>` and `font-weight: bold`.
- strong: {
- parseDOM: [{ tag: "strong" },
- { tag: "b" },
- { style: "font-weight" }],
- toDOM() { return strongDOM; }
- },
-
- strikethrough: {
- parseDOM: [
- { tag: 'strike' },
- { style: 'text-decoration=line-through' },
- { style: 'text-decoration-line=line-through' }
- ],
- toDOM: () => ['span', {
- style: 'text-decoration-line:line-through'
- }]
- },
-
- subscript: {
- excludes: 'superscript',
- parseDOM: [
- { tag: 'sub' },
- { style: 'vertical-align=sub' }
- ],
- toDOM: () => ['sub']
- },
-
- superscript: {
- excludes: 'subscript',
- parseDOM: [
- { tag: 'sup' },
- { style: 'vertical-align=super' }
- ],
- toDOM: () => ['sup']
- },
-
- mbulletType: {
- attrs: {
- bulletType: { default: "decimal" }
- },
- toDOM(node: any) {
- return ['span', {
- style: `background: ${node.attrs.bulletType === "decimal" ? "yellow" : node.attrs.bulletType === "upper-alpha" ? "blue" : "green"}`
- }];
- }
- },
-
- metadata: {
- toDOM() {
- return ['span', { style: 'font-size:75%; background:rgba(100, 100, 100, 0.2); ' }];
- }
- },
- metadataKey: {
- toDOM() {
- return ['span', { style: 'font-style:italic; ' }];
- }
- },
- metadataVal: {
- toDOM() {
- return ['span'];
- }
- },
-
- summarizeInclusive: {
- parseDOM: [
- {
- tag: "span",
- getAttrs: (p: any) => {
- if (typeof (p) !== "string") {
- const style = getComputedStyle(p);
- if (style.textDecoration === "underline") return null;
- if (p.parentElement.outerHTML.indexOf("text-decoration: underline") !== -1 &&
- p.parentElement.outerHTML.indexOf("text-decoration-style: solid") !== -1) {
- return null;
- }
- }
- return false;
- }
- },
- ],
- inclusive: true,
- toDOM() {
- return ['span', {
- style: 'text-decoration: underline; text-decoration-style: solid; text-decoration-color: rgba(204, 206, 210, 0.92)'
- }];
- }
- },
-
- summarize: {
- inclusive: false,
- parseDOM: [
- {
- tag: "span",
- getAttrs: (p: any) => {
- if (typeof (p) !== "string") {
- const style = getComputedStyle(p);
- if (style.textDecoration === "underline") return null;
- if (p.parentElement.outerHTML.indexOf("text-decoration: underline") !== -1 &&
- p.parentElement.outerHTML.indexOf("text-decoration-style: dotted") !== -1) {
- return null;
- }
- }
- return false;
- }
- },
- ],
- toDOM() {
- return ['span', {
- style: 'text-decoration: underline; text-decoration-style: dotted; text-decoration-color: rgba(204, 206, 210, 0.92)'
- }];
- }
- },
-
- underline: {
- parseDOM: [
- {
- tag: "span",
- getAttrs: (p: any) => {
- if (typeof (p) !== "string") {
- const style = getComputedStyle(p);
- if (style.textDecoration === "underline" || p.parentElement.outerHTML.indexOf("text-decoration-style:line") !== -1) {
- return null;
- }
- }
- return false;
- }
- }
- // { style: "text-decoration=underline" }
- ],
- toDOM: () => ['span', {
- style: 'text-decoration:underline;text-decoration-style:line'
- }]
- },
-
- search_highlight: {
- attrs: {
- selected: { default: false }
- },
- parseDOM: [{ style: 'background: yellow' }],
- toDOM(node: any) {
- return ['span', {
- style: `background: ${node.attrs.selected ? "orange" : "yellow"}`
- }];
- }
- },
-
- // the id of the user who entered the text
- user_mark: {
- attrs: {
- userid: { default: "" },
- modified: { default: "when?" }, // 5 second intervals since 1970
- },
- group: "inline",
- toDOM(node: any) {
- const uid = node.attrs.userid.replace(".", "").replace("@", "");
- const min = Math.round(node.attrs.modified / 12);
- const hr = Math.round(min / 60);
- const day = Math.round(hr / 60 / 24);
- const remote = node.attrs.userid !== Doc.CurrentUserEmail ? " userMark-remote" : "";
- return ['span', { class: "userMark-" + uid + remote + " userMark-min-" + min + " userMark-hr-" + hr + " userMark-day-" + day }, 0];
- }
- },
- // the id of the user who entered the text
- user_tag: {
- attrs: {
- userid: { default: "" },
- modified: { default: "when?" }, // 5 second intervals since 1970
- tag: { default: "" }
- },
- group: "inline",
- inclusive: false,
- toDOM(node: any) {
- const uid = node.attrs.userid.replace(".", "").replace("@", "");
- return ['span', { class: "userTag-" + uid + " userTag-" + node.attrs.tag }, 0];
- }
- },
-
-
- // :: MarkSpec Code font mark. Represented as a `<code>` element.
- code: {
- parseDOM: [{ tag: "code" }],
- toDOM() { return codeDOM; }
- },
-
- /* FONTS */
- pFontFamily: {
- attrs: {
- family: { default: "Crimson Text" },
- },
- parseDOM: [{
- tag: "span", getAttrs(dom: any) {
- const cstyle = getComputedStyle(dom);
- if (cstyle.font) {
- if (cstyle.font.indexOf("Times New Roman") !== -1) return { family: "Times New Roman" };
- if (cstyle.font.indexOf("Arial") !== -1) return { family: "Arial" };
- if (cstyle.font.indexOf("Georgia") !== -1) return { family: "Georgia" };
- if (cstyle.font.indexOf("Comic Sans") !== -1) return { family: "Comic Sans MS" };
- if (cstyle.font.indexOf("Tahoma") !== -1) return { family: "Tahoma" };
- if (cstyle.font.indexOf("Crimson") !== -1) return { family: "Crimson Text" };
- }
- }
- }],
- toDOM: (node) => ['span', {
- style: `font-family: "${node.attrs.family}";`
- }]
- },
-
- /** FONT SIZES */
- pFontSize: {
- attrs: {
- fontSize: { default: 10 }
- },
- parseDOM: [{ style: 'font-size: 10px;' }],
- toDOM: (node) => ['span', {
- style: `font-size: ${node.attrs.fontSize}px;`
- }]
- },
-};
-
-export class ImageResizeView {
- _handle: HTMLElement;
- _img: HTMLElement;
- _outer: HTMLElement;
- constructor(node: any, view: any, getPos: any, addDocTab: any) {
- this._handle = document.createElement("span");
- this._img = document.createElement("img");
- this._outer = document.createElement("span");
- this._outer.style.position = "relative";
- this._outer.style.width = node.attrs.width;
- this._outer.style.height = node.attrs.height;
- this._outer.style.display = "inline-block";
- this._outer.style.overflow = "hidden";
- (this._outer.style as any).float = node.attrs.float;
-
- this._img.setAttribute("src", node.attrs.src);
- this._img.style.width = "100%";
- this._handle.style.position = "absolute";
- this._handle.style.width = "20px";
- this._handle.style.height = "20px";
- this._handle.style.backgroundColor = "blue";
- this._handle.style.borderRadius = "15px";
- this._handle.style.display = "none";
- this._handle.style.bottom = "-10px";
- this._handle.style.right = "-10px";
- const self = this;
- this._img.onclick = function (e: any) {
- e.stopPropagation();
- e.preventDefault();
- if (view.state.selection.node && view.state.selection.node.type !== view.state.schema.nodes.image) {
- view.dispatch(view.state.tr.setSelection(new NodeSelection(view.state.doc.resolve(view.state.selection.from - 2))));
- }
- };
- this._img.onpointerdown = function (e: any) {
- if (e.ctrlKey) {
- e.preventDefault();
- e.stopPropagation();
- DocServer.GetRefField(node.attrs.docid).then(async linkDoc =>
- (linkDoc instanceof Doc) &&
- DocumentManager.Instance.FollowLink(linkDoc, view.state.schema.Document,
- document => addDocTab(document, undefined, node.attrs.location ? node.attrs.location : "inTab"), false));
- }
- };
- this._handle.onpointerdown = function (e: any) {
- e.preventDefault();
- e.stopPropagation();
- const wid = Number(getComputedStyle(self._img).width.replace(/px/, ""));
- const hgt = Number(getComputedStyle(self._img).height.replace(/px/, ""));
- const startX = e.pageX;
- const startWidth = parseFloat(node.attrs.width);
- const onpointermove = (e: any) => {
- const currentX = e.pageX;
- const diffInPx = currentX - startX;
- self._outer.style.width = `${startWidth + diffInPx}`;
- self._outer.style.height = `${(startWidth + diffInPx) * hgt / wid}`;
- };
-
- const onpointerup = () => {
- document.removeEventListener("pointermove", onpointermove);
- document.removeEventListener("pointerup", onpointerup);
- const pos = view.state.selection.from;
- view.dispatch(view.state.tr.setNodeMarkup(getPos(), null, { ...node.attrs, width: self._outer.style.width, height: self._outer.style.height }));
- view.dispatch(view.state.tr.setSelection(new NodeSelection(view.state.doc.resolve(pos))));
- };
-
- document.addEventListener("pointermove", onpointermove);
- document.addEventListener("pointerup", onpointerup);
- };
-
- this._outer.appendChild(this._img);
- this._outer.appendChild(this._handle);
- (this as any).dom = this._outer;
- }
-
- selectNode() {
- this._img.classList.add("ProseMirror-selectednode");
-
- this._handle.style.display = "";
- }
-
- deselectNode() {
- this._img.classList.remove("ProseMirror-selectednode");
-
- this._handle.style.display = "none";
- }
-}
-
-
-export class DashDocCommentView {
- _collapsed: HTMLElement;
- _view: any;
- constructor(node: any, view: any, getPos: any) {
- this._collapsed = document.createElement("span");
- this._collapsed.className = "formattedTextBox-inlineComment";
- this._collapsed.id = "DashDocCommentView-" + node.attrs.docid;
- this._view = view;
- const targetNode = () => { // search forward in the prosemirror doc for the attached dashDocNode that is the target of the comment anchor
- for (let i = getPos() + 1; i < view.state.doc.content.size; i++) {
- const m = view.state.doc.nodeAt(i);
- if (m && m.type === view.state.schema.nodes.dashDoc && m.attrs.docid === node.attrs.docid) {
- return { node: m, pos: i, hidden: m.attrs.hidden } as { node: any, pos: number, hidden: boolean };
- }
- }
- const dashDoc = view.state.schema.nodes.dashDoc.create({ width: 75, height: 35, title: "dashDoc", docid: node.attrs.docid, float: "right" });
- view.dispatch(view.state.tr.insert(getPos() + 1, dashDoc));
- setTimeout(() => { try { view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.tr.doc, getPos() + 2))); } catch (e) { } }, 0);
- return undefined;
- };
- this._collapsed.onpointerdown = (e: any) => {
- e.stopPropagation();
- };
- this._collapsed.onpointerup = (e: any) => {
- const target = targetNode();
- if (target) {
- const expand = target.hidden;
- const tr = view.state.tr.setNodeMarkup(target.pos, undefined, { ...target.node.attrs, hidden: target.node.attrs.hidden ? false : true });
- view.dispatch(tr.setSelection(TextSelection.create(tr.doc, getPos() + (expand ? 2 : 1)))); // update the attrs
- setTimeout(() => {
- expand && DocServer.GetRefField(node.attrs.docid).then(async dashDoc => dashDoc instanceof Doc && Doc.linkFollowHighlight(dashDoc));
- try { view.dispatch(view.state.tr.setSelection(TextSelection.create(view.state.tr.doc, getPos() + (expand ? 2 : 1)))); } catch (e) { }
- }, 0);
- }
- e.stopPropagation();
- };
- this._collapsed.onpointerenter = (e: any) => {
- DocServer.GetRefField(node.attrs.docid).then(async dashDoc => dashDoc instanceof Doc && Doc.linkFollowHighlight(dashDoc, false));
- e.preventDefault();
- e.stopPropagation();
- };
- this._collapsed.onpointerleave = (e: any) => {
- DocServer.GetRefField(node.attrs.docid).then(async dashDoc => dashDoc instanceof Doc && Doc.linkFollowUnhighlight());
- e.preventDefault();
- e.stopPropagation();
- };
- (this as any).dom = this._collapsed;
- }
- selectNode() { }
-}
-
-export class DashDocView {
- _dashSpan: HTMLDivElement;
- _outer: HTMLElement;
- _dashDoc: Doc | undefined;
- _reactionDisposer: IReactionDisposer | undefined;
- _textBox: FormattedTextBox;
-
- getDocTransform = () => {
- const { scale, translateX, translateY } = Utils.GetScreenTransform(this._outer);
- return new Transform(-translateX, -translateY, 1).scale(1 / this.contentScaling() / scale);
- }
- contentScaling = () => NumCast(this._dashDoc!._nativeWidth) > 0 && !this._dashDoc!.ignoreAspect ? this._dashDoc![WidthSym]() / NumCast(this._dashDoc!._nativeWidth) : 1;
- outerFocus = (target: Doc) => this._textBox.props.focus(this._textBox.props.Document); // ideally, this would scroll to show the focus target
- constructor(node: any, view: any, getPos: any, tbox: FormattedTextBox) {
- this._textBox = tbox;
- this._dashSpan = document.createElement("div");
- this._outer = document.createElement("span");
- this._outer.style.position = "relative";
- this._outer.style.textIndent = "0";
- this._outer.style.width = node.attrs.width;
- this._outer.style.height = node.attrs.height;
- this._outer.style.display = node.attrs.hidden ? "none" : "inline-block";
- // this._outer.style.overflow = "hidden"; // bcz: not sure if this is needed. if it's used, then the doc doesn't highlight when you hover over a docComment
- (this._outer.style as any).float = node.attrs.float;
-
- this._dashSpan.style.width = node.attrs.width;
- this._dashSpan.style.height = node.attrs.height;
- this._dashSpan.style.position = "absolute";
- this._dashSpan.style.display = "inline-block";
- this._dashSpan.onpointerleave = () => {
- const ele = document.getElementById("DashDocCommentView-" + node.attrs.docid);
- if (ele) {
- (ele as HTMLDivElement).style.backgroundColor = "";
- }
- };
- this._dashSpan.onpointerenter = () => {
- const ele = document.getElementById("DashDocCommentView-" + node.attrs.docid);
- if (ele) {
- (ele as HTMLDivElement).style.backgroundColor = "orange";
- }
- };
- const removeDoc = () => {
- const pos = getPos();
- const ns = new NodeSelection(view.state.doc.resolve(pos));
- view.dispatch(view.state.tr.setSelection(ns).deleteSelection());
- return true;
- };
- const alias = node.attrs.alias;
-
- const docid = node.attrs.docid || tbox.props.DataDoc?.[Id] || tbox.dataDoc?.[Id];
- DocServer.GetRefField(docid + alias).then(async dashDoc => {
- if (!(dashDoc instanceof Doc)) {
- alias && DocServer.GetRefField(docid).then(async dashDocBase => {
- if (dashDocBase instanceof Doc) {
- const aliasedDoc = Doc.MakeAlias(dashDocBase, docid + alias);
- aliasedDoc.layoutKey = "layout" + (node.attrs.fieldKey ? "_" + node.attrs.fieldKey : "");
- self.doRender(aliasedDoc, removeDoc, node, view, getPos);
- }
- });
- } else {
- self.doRender(dashDoc, removeDoc, node, view, getPos);
- }
- });
- const self = this;
- this._dashSpan.onkeydown = function (e: any) {
- e.stopPropagation();
- if (e.key === "Tab" || e.key === "Enter") {
- e.preventDefault();
- }
- };
- this._dashSpan.onkeypress = function (e: any) { e.stopPropagation(); };
- this._dashSpan.onwheel = function (e: any) { e.preventDefault(); };
- this._dashSpan.onkeyup = function (e: any) { e.stopPropagation(); };
- this._outer.appendChild(this._dashSpan);
- (this as any).dom = this._outer;
- }
- doRender(dashDoc: Doc, removeDoc: any, node: any, view: any, getPos: any) {
- this._dashDoc = dashDoc;
- if (node.attrs.width !== dashDoc._width + "px" || node.attrs.height !== dashDoc._height + "px") {
- try { // bcz: an exception will be thrown if two aliases are open at the same time when a doc view comment is made
- view.dispatch(view.state.tr.setNodeMarkup(getPos(), null, { ...node.attrs, width: dashDoc._width + "px", height: dashDoc._height + "px" }));
- } catch (e) {
- console.log(e);
- }
- }
- const self = this;
- const finalLayout = Doc.expandTemplateLayout(dashDoc, !Doc.AreProtosEqual(this._textBox.dataDoc, this._textBox.Document) ? this._textBox.dataDoc : undefined);
- if (!finalLayout) setTimeout(() => self.doRender(dashDoc, removeDoc, node, view, getPos), 0);
- else {
- const layoutKey = StrCast(finalLayout.layoutKey);
- const finalKey = layoutKey && StrCast(finalLayout[layoutKey]).split("'")?.[1];
- if (finalLayout !== dashDoc && finalKey) {
- const finalLayoutField = finalLayout[finalKey];
- if (finalLayoutField instanceof ObjectField) {
- finalLayout._textTemplate = ComputedField.MakeFunction(`copyField(this.${finalKey})`, { this: Doc.name });
- }
- }
- this._reactionDisposer?.();
- this._reactionDisposer = reaction(() => [finalLayout[WidthSym](), finalLayout[HeightSym]()], (dim) => {
- this._dashSpan.style.width = this._outer.style.width = Math.max(20, dim[0]) + "px";
- this._dashSpan.style.height = this._outer.style.height = Math.max(20, dim[1]) + "px";
- }, { fireImmediately: true });
- ReactDOM.render(<DocumentView
- Document={finalLayout}
- DataDoc={!node.attrs.docid ? this._textBox.dataDoc : undefined}
- LibraryPath={this._textBox.props.LibraryPath}
- fitToBox={BoolCast(dashDoc._fitToBox)}
- addDocument={returnFalse}
- removeDocument={removeDoc}
- ScreenToLocalTransform={this.getDocTransform}
- addDocTab={this._textBox.props.addDocTab}
- pinToPres={returnFalse}
- renderDepth={1}
- PanelWidth={finalLayout[WidthSym]}
- PanelHeight={finalLayout[HeightSym]}
- focus={this.outerFocus}
- backgroundColor={returnEmptyString}
- parentActive={returnFalse}
- whenActiveChanged={returnFalse}
- bringToFront={emptyFunction}
- zoomToScale={emptyFunction}
- getScale={returnOne}
- dontRegisterView={false}
- ContainingCollectionView={undefined}
- ContainingCollectionDoc={undefined}
- ContentScaling={this.contentScaling}
- />, this._dashSpan);
- }
- }
- destroy() {
- this._reactionDisposer && this._reactionDisposer();
- }
-}
-
-
-export class DashFieldView {
- _fieldWrapper: HTMLDivElement;
- _labelSpan: HTMLSpanElement;
- _fieldSpan: HTMLDivElement;
- _reactionDisposer: IReactionDisposer | undefined;
- _textBoxDoc: Doc;
- @observable _dashDoc: Doc | undefined;
- _fieldKey: string;
-
- constructor(node: any, view: any, getPos: any, tbox: FormattedTextBox) {
- this._fieldKey = node.attrs.fieldKey;
- this._textBoxDoc = tbox.props.Document;
- this._fieldWrapper = document.createElement("div");
- this._fieldWrapper.style.width = node.attrs.width;
- this._fieldWrapper.style.height = node.attrs.height;
- this._fieldWrapper.style.position = "relative";
- this._fieldWrapper.style.display = "inline-block";
-
- this._fieldSpan = document.createElement("div");
- this._fieldSpan.id = Utils.GenerateGuid();
- this._fieldSpan.contentEditable = "true";
- this._fieldSpan.style.position = "relative";
- this._fieldSpan.style.display = "inline-block";
- this._fieldSpan.style.minWidth = "50px";
- this._fieldSpan.style.backgroundColor = "rgba(155, 155, 155, 0.24)";
- this._fieldSpan.addEventListener("input", this.onchanged);
- this._fieldSpan.onkeypress = function (e: any) { e.stopPropagation(); };
- this._fieldSpan.onkeyup = function (e: any) { e.stopPropagation(); };
- this._fieldSpan.onmousedown = function (e: any) {
- console.log(e);
- e.stopPropagation();
- };
- const self = this;
- this._fieldSpan.onkeydown = function (e: any) {
- e.stopPropagation();
- if ((e.key === "a" && e.ctrlKey) || (e.key === "a" && e.metaKey)) {
- if (window.getSelection) {
- var range = document.createRange();
- range.selectNodeContents(self._fieldSpan);
- window.getSelection()!.removeAllRanges();
- window.getSelection()!.addRange(range);
- }
- e.preventDefault();
- }
- };
-
- this._labelSpan = document.createElement("span");
- this._labelSpan.style.position = "relative";
- this._labelSpan.style.display = "inline";
- this._labelSpan.style.fontWeight = "bold";
- this._labelSpan.style.fontSize = "larger";
- this._labelSpan.innerHTML = `${node.attrs.fieldKey}: `;
- if (node.attrs.docid) {
- const self = this;
- DocServer.GetRefField(node.attrs.docid).then(async dashDoc => dashDoc instanceof Doc && runInAction(() => self._dashDoc = dashDoc));
- } else {
- this._dashDoc = tbox.props.DataDoc || tbox.dataDoc;
- }
- this._reactionDisposer?.();
- this._reactionDisposer = reaction(() => this._dashDoc?.[node.attrs.fieldKey], fval => this._fieldSpan.innerHTML = Field.toString(fval as Field) || "(null)", { fireImmediately: true });
-
- this._fieldWrapper.appendChild(this._labelSpan);
- this._fieldWrapper.appendChild(this._fieldSpan);
- (this as any).dom = this._fieldWrapper;
- }
- onchanged = () => {
- this._reactionDisposer?.();
- this._dashDoc![this._fieldKey] = this._fieldSpan.innerText;
- this._reactionDisposer = reaction(() => this._dashDoc?.[this._fieldKey], fval => this._fieldSpan.innerHTML = Field.toString(fval as Field) || "(null)");
-
- }
- destroy() {
- this._reactionDisposer?.();
- }
- selectNode() { }
-}
-
-export class OrderedListView {
- update(node: any) {
- return false; // if attr's of an ordered_list (e.g., bulletStyle) change, return false forces the dom node to be recreated which is necessary for the bullet labels to update
- }
-}
-
-export class FootnoteView {
- innerView: any;
- outerView: any;
- node: any;
- dom: any;
- getPos: any;
-
- constructor(node: any, view: any, getPos: any) {
- // We'll need these later
- this.node = node;
- this.outerView = view;
- this.getPos = getPos;
-
- // The node's representation in the editor (empty, for now)
- this.dom = document.createElement("footnote");
- this.dom.addEventListener("pointerup", this.toggle, true);
- // These are used when the footnote is selected
- this.innerView = null;
- }
- selectNode() {
- const attrs = { ...this.node.attrs };
- attrs.visibility = true;
- this.dom.classList.add("ProseMirror-selectednode");
- if (!this.innerView) this.open();
- }
-
- deselectNode() {
- const attrs = { ...this.node.attrs };
- attrs.visibility = false;
- this.dom.classList.remove("ProseMirror-selectednode");
- if (this.innerView) this.close();
- }
- open() {
- // Append a tooltip to the outer node
- const tooltip = this.dom.appendChild(document.createElement("div"));
- tooltip.className = "footnote-tooltip";
- // And put a sub-ProseMirror into that
- this.innerView = new EditorView(tooltip, {
- // You can use any node as an editor document
- state: EditorState.create({
- doc: this.node,
- plugins: [keymap(baseKeymap),
- keymap({
- "Mod-z": () => undo(this.outerView.state, this.outerView.dispatch),
- "Mod-y": () => redo(this.outerView.state, this.outerView.dispatch),
- "Mod-b": toggleMark(schema.marks.strong)
- }),
- new Plugin({
- view(newView) {
- // TODO -- make this work with RichTextMenu
- // return FormattedTextBox.getToolTip(newView);
- }
- })
- ],
-
- }),
- // This is the magic part
- dispatchTransaction: this.dispatchInner.bind(this),
- handleDOMEvents: {
- pointerdown: ((view: any, e: PointerEvent) => {
- // Kludge to prevent issues due to the fact that the whole
- // footnote is node-selected (and thus DOM-selected) when
- // the parent editor is focused.
- e.stopPropagation();
- document.addEventListener("pointerup", this.ignore, true);
- if (this.outerView.hasFocus()) this.innerView.focus();
- }) as any
- }
-
- });
- setTimeout(() => this.innerView && this.innerView.docView.setSelection(0, 0, this.innerView.root, true), 0);
- }
-
- ignore = (e: PointerEvent) => {
- e.stopPropagation();
- document.removeEventListener("pointerup", this.ignore, true);
- }
-
- toggle = () => {
- if (this.innerView) this.close();
- else {
- this.open();
- }
- }
- close() {
- this.innerView && this.innerView.destroy();
- this.innerView = null;
- this.dom.textContent = "";
- }
- dispatchInner(tr: any) {
- const { state, transactions } = this.innerView.state.applyTransaction(tr);
- this.innerView.updateState(state);
-
- if (!tr.getMeta("fromOutside")) {
- const outerTr = this.outerView.state.tr, offsetMap = StepMap.offset(this.getPos() + 1);
- for (const transaction of transactions) {
- const steps = transaction.steps;
- for (const step of steps) {
- outerTr.step(step.map(offsetMap));
- }
- }
- if (outerTr.docChanged) this.outerView.dispatch(outerTr);
- }
- }
- update(node: any) {
- if (!node.sameMarkup(this.node)) return false;
- this.node = node;
- if (this.innerView) {
- const state = this.innerView.state;
- const start = node.content.findDiffStart(state.doc.content);
- if (start !== null) {
- let { a: endA, b: endB } = node.content.findDiffEnd(state.doc.content);
- const overlap = start - Math.min(endA, endB);
- if (overlap > 0) { endA += overlap; endB += overlap; }
- this.innerView.dispatch(
- state.tr
- .replace(start, endB, node.slice(start, endA))
- .setMeta("fromOutside", true));
- }
- }
- return true;
- }
-
- destroy() {
- if (this.innerView) this.close();
- }
-
- stopEvent(event: any) {
- return this.innerView && this.innerView.dom.contains(event.target);
- }
-
- ignoreMutation() { return true; }
-}
-
-export class SummaryView {
- _collapsed: HTMLElement;
- _view: any;
- constructor(node: any, view: any, getPos: any) {
- this._collapsed = document.createElement("span");
- this._collapsed.className = this.className(node.attrs.visibility);
- this._view = view;
- const js = node.toJSON;
- node.toJSON = function () {
- return js.apply(this, arguments);
- };
-
- this._collapsed.onpointerdown = (e: any) => {
- const visible = !node.attrs.visibility;
- const attrs = { ...node.attrs, visibility: visible };
- let textSelection = TextSelection.create(view.state.doc, getPos() + 1);
- if (!visible) { // update summarized text and save in attrs
- textSelection = this.updateSummarizedText(getPos() + 1);
- attrs.text = textSelection.content();
- attrs.textslice = attrs.text.toJSON();
- }
- view.dispatch(view.state.tr.
- setSelection(textSelection). // select the current summarized text (or where it will be if its collapsed)
- replaceSelection(!visible ? new Slice(Fragment.fromArray([]), 0, 0) : node.attrs.text). // collapse/expand it
- setNodeMarkup(getPos(), undefined, attrs)); // update the attrs
- e.preventDefault();
- e.stopPropagation();
- this._collapsed.className = this.className(visible);
- };
- (this as any).dom = this._collapsed;
- }
- selectNode() { }
-
- deselectNode() { }
-
- className = (visible: boolean) => "formattedTextBox-summarizer" + (visible ? "" : "-collapsed");
-
- updateSummarizedText(start?: any) {
- const mtype = this._view.state.schema.marks.summarize;
- const mtypeInc = this._view.state.schema.marks.summarizeInclusive;
- let endPos = start;
-
- const visited = new Set();
- for (let i: number = start + 1; i < this._view.state.doc.nodeSize - 1; i++) {
- let skip = false;
- this._view.state.doc.nodesBetween(start, i, (node: Node, pos: number, parent: Node, index: number) => {
- if (node.isLeaf && !visited.has(node) && !skip) {
- if (node.marks.find((m: any) => m.type === mtype || m.type === mtypeInc)) {
- visited.add(node);
- endPos = i + node.nodeSize - 1;
- }
- else skip = true;
- }
- });
- }
- return TextSelection.create(this._view.state.doc, start, endPos);
- }
-}
-// :: Schema
-// This schema rougly corresponds to the document schema used by
-// [CommonMark](http://commonmark.org/), minus the list elements,
-// which are defined in the [`prosemirror-schema-list`](#schema-list)
-// module.
-//
-// To reuse elements from this schema, extend or read from its
-// `spec.nodes` and `spec.marks` [properties](#model.Schema.spec).
-export const schema = new Schema({ nodes, marks });
-
-const fromJson = schema.nodeFromJSON;
-
-schema.nodeFromJSON = (json: any) => {
- const node = fromJson(json);
- if (json.type === schema.marks.summarize.name) {
- node.attrs.text = Slice.fromJSON(schema, node.attrs.textslice);
- }
- return node;
-}; \ No newline at end of file
diff --git a/src/client/util/Scripting.ts b/src/client/util/Scripting.ts
index 0fa96963e..12628273b 100644
--- a/src/client/util/Scripting.ts
+++ b/src/client/util/Scripting.ts
@@ -24,6 +24,8 @@ export interface ScriptError {
export type ScriptResult = ScriptSucccess | ScriptError;
+export type ScriptParam = { [name: string]: string };
+
export interface CompiledScript {
readonly compiled: true;
readonly originalScript: string;
@@ -37,6 +39,12 @@ export interface CompileError {
}
export type CompileResult = CompiledScript | CompileError;
+export function isCompileError(toBeDetermined: CompileResult): toBeDetermined is CompileError {
+ if ((toBeDetermined as CompileError).errors) {
+ return true;
+ }
+ return false;
+}
export namespace Scripting {
export function addGlobal(global: { name: string }): void;
@@ -89,9 +97,9 @@ const _scriptingGlobals: { [name: string]: any } = {};
let scriptingGlobals: { [name: string]: any } = _scriptingGlobals;
function Run(script: string | undefined, customParams: string[], diagnostics: any[], originalScript: string, options: ScriptOptions): CompileResult {
- const errors = diagnostics.some(diag => diag.category === ts.DiagnosticCategory.Error);
- if ((options.typecheck !== false && errors) || !script) {
- return { compiled: false, errors: diagnostics };
+ const errors = diagnostics.filter(diag => diag.category === ts.DiagnosticCategory.Error);
+ if ((options.typecheck !== false && errors.length) || !script) {
+ return { compiled: false, errors };
}
const paramNames = Object.keys(scriptingGlobals);
@@ -195,14 +203,14 @@ export type Transformer = {
getVars?: () => { capturedVariables: { [name: string]: Field } }
};
export interface ScriptOptions {
- requiredType?: string;
- addReturn?: boolean;
- params?: { [name: string]: string };
- capturedVariables?: { [name: string]: Field };
- typecheck?: boolean;
- editable?: boolean;
+ requiredType?: string; // does function required a typed return value
+ addReturn?: boolean; // does the compiler automatically add a return statement
+ params?: { [name: string]: string }; // list of function parameters and their types
+ capturedVariables?: { [name: string]: Field }; // list of captured variables
+ typecheck?: boolean; // should the compiler perform typechecking
+ editable?: boolean; // can the script edit Docs
traverser?: TraverserParam;
- transformer?: Transformer;
+ transformer?: Transformer; // does the editor display a text label by each document that can be used as a captured document reference
globals?: { [name: string]: any };
}
@@ -215,6 +223,8 @@ function forEachNode(node: ts.Node, onEnter: Traverser, onExit?: Traverser, inde
export function CompileScript(script: string, options: ScriptOptions = {}): CompileResult {
const { requiredType = "", addReturn = false, params = {}, capturedVariables = {}, typecheck = true } = options;
+ if (options.params && !options.params.this) options.params.this = Doc.name;
+ if (options.params && !options.params.self) options.params.self = Doc.name;
if (options.globals) {
Scripting.setScriptingGlobals(options.globals);
}
diff --git a/src/client/util/SearchUtil.ts b/src/client/util/SearchUtil.ts
index 8ff54d052..6501da34a 100644
--- a/src/client/util/SearchUtil.ts
+++ b/src/client/util/SearchUtil.ts
@@ -34,7 +34,7 @@ export namespace SearchUtil {
export function Search(query: string, returnDocs: false, options?: SearchParams): Promise<IdSearchResult>;
export async function Search(query: string, returnDocs: boolean, options: SearchParams = {}) {
query = query || "*"; //If we just have a filter query, search for * as the query
- const rpquery = Utils.prepend("/search");
+ const rpquery = Utils.prepend("/dashsearch");
const gotten = await rp.get(rpquery, { qs: { ...options, q: query } });
const result: IdSearchResult = gotten.startsWith("<") ? { ids: [], docs: [], numFound: 0, lines: [] } : JSON.parse(gotten);
if (!returnDocs) {
@@ -44,7 +44,7 @@ export namespace SearchUtil {
const { ids, highlighting } = result;
const txtresult = query !== "*" && JSON.parse(await rp.get(Utils.prepend("/textsearch"), {
- qs: { ...options, q: query },
+ qs: { ...options, q: query.replace(/^[ \+\?\*\|]*/, "") }, // a leading '+' leads to a server crash since findInFiles doesn't handle regex failures
}));
const fileids = txtresult ? txtresult.ids : [];
@@ -52,7 +52,7 @@ export namespace SearchUtil {
const newLines: string[][] = [];
await Promise.all(fileids.map(async (tr: string, i: number) => {
const docQuery = "fileUpload_t:" + tr.substr(0, 7); //If we just have a filter query, search for * as the query
- const docResult = JSON.parse(await rp.get(Utils.prepend("/search"), { qs: { ...options, q: docQuery } }));
+ const docResult = JSON.parse(await rp.get(Utils.prepend("/dashsearch"), { qs: { ...options, q: docQuery } }));
newIds.push(...docResult.ids);
newLines.push(...docResult.ids.map((dr: any) => txtresult.lines[i]));
}));
@@ -64,7 +64,7 @@ export namespace SearchUtil {
const textDocs = newIds.map((id: string) => textDocMap[id]).map(doc => doc as Doc);
for (let i = 0; i < textDocs.length; i++) {
const testDoc = textDocs[i];
- if (testDoc instanceof Doc && testDoc.type !== DocumentType.KVP && testDoc.type !== DocumentType.EXTENSION && theDocs.findIndex(d => Doc.AreProtosEqual(d, testDoc)) === -1) {
+ if (testDoc instanceof Doc && testDoc.type !== DocumentType.KVP && theDocs.findIndex(d => Doc.AreProtosEqual(d, testDoc)) === -1) {
theDocs.push(Doc.GetProto(testDoc));
theLines.push(newLines[i].map(line => line.replace(query, query.toUpperCase())));
}
@@ -74,7 +74,7 @@ export namespace SearchUtil {
const docs = ids.map((id: string) => docMap[id]).map(doc => doc as Doc);
for (let i = 0; i < ids.length; i++) {
const testDoc = docs[i];
- if (testDoc instanceof Doc && testDoc.type !== DocumentType.KVP && testDoc.type !== DocumentType.EXTENSION && (options.allowAliases || theDocs.findIndex(d => Doc.AreProtosEqual(d, testDoc)) === -1)) {
+ if (testDoc instanceof Doc && testDoc.type !== DocumentType.KVP && (options.allowAliases || theDocs.findIndex(d => Doc.AreProtosEqual(d, testDoc)) === -1)) {
theDocs.push(testDoc);
theLines.push([]);
}
@@ -118,4 +118,27 @@ export namespace SearchUtil {
aliasContexts.forEach(result => contexts.aliasContexts.push(...result.ids));
return contexts;
}
-} \ No newline at end of file
+
+ export async function GetAllDocs() {
+ const query = "*";
+ const response = await rp.get(Utils.prepend('/dashsearch'), {
+ qs:
+ { start: 0, rows: 10000, q: query },
+
+ });
+ const result: IdSearchResult = JSON.parse(response);
+ const { ids, numFound, highlighting } = result;
+ //console.log(ids.length);
+ const docMap = await DocServer.GetRefFields(ids);
+ const docs: Doc[] = [];
+ for (const id of ids) {
+ const field = docMap[id];
+ if (field instanceof Doc) {
+ docs.push(field);
+ }
+ }
+ return docs;
+ // const docs = ids.map((id: string) => docMap[id]).filter((doc: any) => doc instanceof Doc);
+ // return docs as Doc[];
+ }
+}
diff --git a/src/client/util/SelectionManager.ts b/src/client/util/SelectionManager.ts
index 4612f10f4..a49977c42 100644
--- a/src/client/util/SelectionManager.ts
+++ b/src/client/util/SelectionManager.ts
@@ -28,21 +28,21 @@ export namespace SelectionManager {
manager.SelectedDocuments.clear();
manager.SelectedDocuments.set(docView, true);
}
- Doc.UserDoc().SelectedDocs = new List(SelectionManager.SelectedDocuments().map(dv => dv.props.Document));
+ Doc.UserDoc().activeSelection = new List(SelectionManager.SelectedDocuments().map(dv => dv.props.Document));
}
@action
DeselectDoc(docView: DocumentView): void {
if (manager.SelectedDocuments.get(docView)) {
manager.SelectedDocuments.delete(docView);
docView.props.whenActiveChanged(false);
- Doc.UserDoc().SelectedDocs = new List(SelectionManager.SelectedDocuments().map(dv => dv.props.Document));
+ Doc.UserDoc().activeSelection = new List(SelectionManager.SelectedDocuments().map(dv => dv.props.Document));
}
}
@action
DeselectAll(): void {
Array.from(manager.SelectedDocuments.keys()).map(dv => dv.props.whenActiveChanged(false));
manager.SelectedDocuments.clear();
- Doc.UserDoc().SelectedDocs = new List<Doc>([]);
+ Doc.UserDoc().activeSelection = new List<Doc>([]);
}
}
@@ -55,10 +55,13 @@ export namespace SelectionManager {
manager.SelectDoc(docView, ctrlPressed);
}
+ // computed functions, such as used in IsSelected generate errors if they're called outside of a
+ // reaction context. Specifying the context with 'outsideReaction' allows an efficiency feature
+ // to avoid unnecessary mobx invalidations when running inside a reaction.
export function IsSelected(doc: DocumentView, outsideReaction?: boolean): boolean {
return outsideReaction ?
- manager.SelectedDocuments.get(doc) ? true : false :
- computedFn(function isSelected(doc: DocumentView) {
+ manager.SelectedDocuments.get(doc) ? true : false : // get() accesses a hashtable -- setting anything in the hashtable generates a mobx invalidation for every get()
+ computedFn(function isSelected(doc: DocumentView) { // wraapping get() in a computedFn only generates mobx() invalidations when the return value of the function for the specific get parameters has changed
return manager.SelectedDocuments.get(doc) ? true : false;
})(doc);
}
diff --git a/src/client/util/SettingsManager.scss b/src/client/util/SettingsManager.scss
index 7a0fb0741..6513cb223 100644
--- a/src/client/util/SettingsManager.scss
+++ b/src/client/util/SettingsManager.scss
@@ -1,6 +1,6 @@
@import "../views/globalCssVariables";
-.dialogue-box {
+.settings-interface {
background-color: whitesmoke !important;
color: grey;
width: 450px;
diff --git a/src/client/util/SharingManager.tsx b/src/client/util/SharingManager.tsx
index 7496ac73c..3ce6de80d 100644
--- a/src/client/util/SharingManager.tsx
+++ b/src/client/util/SharingManager.tsx
@@ -109,7 +109,7 @@ export default class SharingManager extends React.Component<{}> {
if (isCandidate) {
const userDocument = await DocServer.GetRefField(user.userDocumentId);
if (userDocument instanceof Doc) {
- const notificationDoc = await Cast(userDocument.optionalRightCollection, Doc);
+ const notificationDoc = await Cast(userDocument.rightSidebarCollection, Doc);
runInAction(() => {
if (notificationDoc instanceof Doc) {
this.users.push({ user, notificationDoc });
diff --git a/src/client/util/prosemirrorPatches.js b/src/client/util/prosemirrorPatches.js
deleted file mode 100644
index 269423482..000000000
--- a/src/client/util/prosemirrorPatches.js
+++ /dev/null
@@ -1,139 +0,0 @@
-'use strict';
-
-Object.defineProperty(exports, '__esModule', { value: true });
-
-var prosemirrorInputRules = require('prosemirror-inputrules');
-var prosemirrorTransform = require('prosemirror-transform');
-var prosemirrorModel = require('prosemirror-model');
-
-exports.liftListItem = liftListItem;
-exports.sinkListItem = sinkListItem;
-exports.wrappingInputRule = wrappingInputRule;
-// :: (NodeType) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool
-// Create a command to lift the list item around the selection up into
-// a wrapping list.
-function liftListItem(itemType) {
- return function (tx, dispatch) {
- var ref = tx.selection;
- var $from = ref.$from;
- var $to = ref.$to;
- var range = $from.blockRange($to, function (node) { return node.childCount && node.firstChild.type == itemType; });
- if (!range) { return false }
- if (!dispatch) { return true }
- if ($from.node(range.depth - 1).type == itemType) // Inside a parent list
- { return liftToOuterList(tx, dispatch, itemType, range) }
- else // Outer list node
- { return liftOutOfList(tx, dispatch, range) }
- }
-}
-
-function liftToOuterList(tr, dispatch, itemType, range) {
- var end = range.end, endOfList = range.$to.end(range.depth);
- if (end < endOfList) {
- // There are siblings after the lifted items, which must become
- // children of the last item
- tr.step(new prosemirrorTransform.ReplaceAroundStep(end - 1, endOfList, end, endOfList,
- new prosemirrorModel.Slice(prosemirrorModel.Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true));
- range = new prosemirrorModel.NodeRange(tr.doc.resolve(range.$from.pos), tr.doc.resolve(endOfList), range.depth);
- }
- dispatch(tr.lift(range, prosemirrorTransform.liftTarget(range)).scrollIntoView());
- return true
-}
-
-function liftOutOfList(tr, dispatch, range) {
- var list = range.parent;
- // Merge the list items into a single big item
- for (var pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) {
- pos -= list.child(i).nodeSize;
- tr.delete(pos - 1, pos + 1);
- }
- var $start = tr.doc.resolve(range.start), item = $start.nodeAfter;
- var atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount;
- var parent = $start.node(-1), indexBefore = $start.index(-1);
- if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1,
- item.content.append(atEnd ? prosemirrorModel.Fragment.empty : prosemirrorModel.Fragment.from(list)))) { return false }
- var start = $start.pos, end = start + item.nodeSize;
- // Strip off the surrounding list. At the sides where we're not at
- // the end of the list, the existing list is closed. At sides where
- // this is the end, it is overwritten to its end.
- tr.step(new prosemirrorTransform.ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1,
- new prosemirrorModel.Slice((atStart ? prosemirrorModel.Fragment.empty : prosemirrorModel.Fragment.from(list.copy(prosemirrorModel.Fragment.empty)))
- .append(atEnd ? prosemirrorModel.Fragment.empty : prosemirrorModel.Fragment.from(list.copy(prosemirrorModel.Fragment.empty))),
- atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1));
- dispatch(tr.scrollIntoView());
- return true
-}
-
-// :: (NodeType) → (state: EditorState, dispatch: ?(tr: Transaction)) → bool
-// Create a command to sink the list item around the selection down
-// into an inner list.
-function sinkListItem(itemType) {
- return function (state, dispatch) {
- var ref = state.selection;
- var $from = ref.$from;
- var $to = ref.$to;
- var range = $from.blockRange($to, function (node) { return node.childCount && node.firstChild.type == itemType; });
- if (!range) { return false }
- var startIndex = range.startIndex;
- if (startIndex == 0) { return false }
- var parent = range.parent, nodeBefore = parent.child(startIndex - 1);
- if (nodeBefore.type != itemType) { return false; }
-
- if (dispatch) {
- var nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type;
- var inner = prosemirrorModel.Fragment.from(nestedBefore ? itemType.create() : null);
- let slice = new prosemirrorModel.Slice(prosemirrorModel.Fragment.from(itemType.create(null, prosemirrorModel.Fragment.from(parent.type.create({ ...parent.attrs, fontSize: parent.attrs.fontSize ? parent.attrs.fontSize - 4 : undefined }, inner)))),
- nestedBefore ? 3 : 1, 0);
- var before = range.start, after = range.end;
- dispatch(state.tr.step(new prosemirrorTransform.ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after,
- before, after, slice, 1, true))
- .scrollIntoView());
- }
- return true
- }
-}
-
-function findWrappingOutside(range, type) {
- var parent = range.parent;
- var startIndex = range.startIndex;
- var endIndex = range.endIndex;
- var around = parent.contentMatchAt(startIndex).findWrapping(type);
- if (!around) { return null }
- var outer = around.length ? around[0] : type;
- return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null
-}
-
-function findWrappingInside(range, type) {
- var parent = range.parent;
- var startIndex = range.startIndex;
- var endIndex = range.endIndex;
- var inner = parent.child(startIndex);
- var inside = type.contentMatch.findWrapping(inner.type);
- if (!inside) { return null }
- var lastType = inside.length ? inside[inside.length - 1] : type;
- var innerMatch = lastType.contentMatch;
- for (var i = startIndex; innerMatch && i < endIndex; i++) { innerMatch = innerMatch.matchType(parent.child(i).type); }
- if (!innerMatch || !innerMatch.validEnd) { return null }
- return inside
-}
-function findWrapping(range, nodeType, attrs, innerRange, customWithAttrs = null) {
- if (innerRange === void 0) innerRange = range;
- let withAttrs = (type) => ({ type: type, attrs: null });
- var around = findWrappingOutside(range, nodeType);
- var inner = around && findWrappingInside(innerRange, nodeType);
- if (!inner) { return null }
- return around.map(withAttrs).concat({ type: nodeType, attrs: attrs }).concat(inner.map(customWithAttrs ? customWithAttrs : withAttrs))
-}
-function wrappingInputRule(regexp, nodeType, getAttrs, joinPredicate, customWithAttrs = null) {
- return new prosemirrorInputRules.InputRule(regexp, function (state, match, start, end) {
- var attrs = getAttrs instanceof Function ? getAttrs(match) : getAttrs;
- var tr = state.tr.delete(start, end);
- var $start = tr.doc.resolve(start), range = $start.blockRange(), wrapping = range && findWrapping(range, nodeType, attrs, undefined, customWithAttrs);
- if (!wrapping) { return null }
- tr.wrap(range, wrapping);
- var before = tr.doc.resolve(start - 1).nodeBefore;
- if (before && before.type == nodeType && prosemirrorTransform.canJoin(tr.doc, start - 1) &&
- (!joinPredicate || joinPredicate(match, before))) { tr.join(start - 1); }
- return tr
- })
-} \ No newline at end of file
diff --git a/src/client/util/type_decls.d b/src/client/util/type_decls.d
index 127f7b798..08aec3724 100644
--- a/src/client/util/type_decls.d
+++ b/src/client/util/type_decls.d
@@ -195,7 +195,6 @@ interface DocumentOptions { }
declare const Docs: {
ImageDocument(url: string, options?: DocumentOptions): Doc;
VideoDocument(url: string, options?: DocumentOptions): Doc;
- // HistogramDocument(url:string, options?:DocumentOptions);
TextDocument(options?: DocumentOptions): Doc;
PdfDocument(url: string, options?: DocumentOptions): Doc;
WebDocument(url: string, options?: DocumentOptions): Doc;
@@ -207,4 +206,5 @@ declare const Docs: {
StackingDocument(documents: Doc[], options?: DocumentOptions): Doc;
};
+declare function assignDoc(doc:Doc, field:any, id:any):string;
declare function d(...args:any[]):any;