From ba3b3f6f261074bd3f35012bde8730f5d4a36905 Mon Sep 17 00:00:00 2001 From: bobzel Date: Wed, 29 Nov 2023 10:02:34 -0500 Subject: numerous changes to fix bugs and to fix/remove old or hacky code. fixed doc dec resizing. moving this.rootDoc => this.Document . fixing template artifacts. --- src/client/views/nodes/FunctionPlotBox.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/client/views/nodes/FunctionPlotBox.tsx') diff --git a/src/client/views/nodes/FunctionPlotBox.tsx b/src/client/views/nodes/FunctionPlotBox.tsx index 40f48dafe..daf6cd9a6 100644 --- a/src/client/views/nodes/FunctionPlotBox.tsx +++ b/src/client/views/nodes/FunctionPlotBox.tsx @@ -38,7 +38,7 @@ export class FunctionPlotBox extends ViewBoxAnnotatableComponent componentDidMount() { this.props.setContentView?.(this); reaction( - () => [DocListCast(this.dataDoc[this.fieldKey]).map(doc => doc?.text), this.layoutDoc.width, this.layoutDoc.height, this.rootDoc.xRange, this.rootDoc.yRange], + () => [DocListCast(this.dataDoc[this.fieldKey]).map(doc => doc?.text), this.layoutDoc.width, this.layoutDoc.height, this.layoutDoc.xRange, this.layoutDoc.yRange], () => this.createGraph() ); } @@ -64,8 +64,8 @@ export class FunctionPlotBox extends ViewBoxAnnotatableComponent target: '#' + this._plotEle.id, width, height, - xAxis: { domain: Cast(this.rootDoc.xRange, listSpec('number'), [-10, 10]) }, - yAxis: { domain: Cast(this.rootDoc.yRange, listSpec('number'), [-1, 9]) }, + xAxis: { domain: Cast(this.layoutDoc.xRange, listSpec('number'), [-10, 10]) }, + yAxis: { domain: Cast(this.layoutDoc.yRange, listSpec('number'), [-1, 9]) }, grid: true, data: fns.map(fn => ({ fn, -- cgit v1.2.3-70-g09d2 From c94bbf5b9f1a37630208d4ba64a93c5399044042 Mon Sep 17 00:00:00 2001 From: bobzel Date: Thu, 30 Nov 2023 20:47:28 -0500 Subject: completed transition from rootDoc => Document, dataDoc, layoutDoc --- src/client/views/DocComponent.tsx | 4 - src/client/views/SidebarAnnos.tsx | 22 ++-- src/client/views/collections/CollectionView.tsx | 32 ++--- src/client/views/nodes/AudioBox.tsx | 18 +-- .../views/nodes/CollectionFreeFormDocumentView.tsx | 4 +- src/client/views/nodes/ComparisonBox.tsx | 10 +- src/client/views/nodes/DataVizBox/DataVizBox.tsx | 12 +- .../nodes/DataVizBox/components/LineChart.tsx | 8 +- src/client/views/nodes/FunctionPlotBox.tsx | 7 +- src/client/views/nodes/ImageBox.tsx | 52 ++++---- src/client/views/nodes/LoadingBox.tsx | 16 +-- src/client/views/nodes/MapBox/MapBox.tsx | 44 +++---- src/client/views/nodes/MapBox/MapBox2.tsx | 6 +- src/client/views/nodes/PDFBox.tsx | 34 +++--- src/client/views/nodes/ScreenshotBox.tsx | 24 ++-- src/client/views/nodes/ScriptingBox.tsx | 58 +++++---- src/client/views/nodes/VideoBox.tsx | 36 +++--- src/client/views/nodes/WebBox.tsx | 10 +- .../views/nodes/formattedText/FormattedTextBox.tsx | 131 +++++++++------------ .../formattedText/FormattedTextBoxComment.tsx | 2 +- 20 files changed, 252 insertions(+), 278 deletions(-) (limited to 'src/client/views/nodes/FunctionPlotBox.tsx') diff --git a/src/client/views/DocComponent.tsx b/src/client/views/DocComponent.tsx index c04359d80..04956d974 100644 --- a/src/client/views/DocComponent.tsx +++ b/src/client/views/DocComponent.tsx @@ -96,10 +96,6 @@ export function ViewBoxAnnotatableComponent

() @computed get Document() { return this.props.Document; } - // This is the "The Document" -- it encapsulates, data, layout, and any templates - @computed get rootDoc() { - return Cast(this.props.Document.rootDocument, Doc, null) || this.props.Document; - } // This is the rendering data of a document -- it may be "The Document", or it may be some template document that holds the rendering info @computed get layoutDoc() { return Doc.Layout(this.props.Document); diff --git a/src/client/views/SidebarAnnos.tsx b/src/client/views/SidebarAnnos.tsx index 1e1b8e0e6..9377aabe9 100644 --- a/src/client/views/SidebarAnnos.tsx +++ b/src/client/views/SidebarAnnos.tsx @@ -20,8 +20,8 @@ import React = require('react'); interface ExtraProps { fieldKey: string; + Document: Doc; layoutDoc: Doc; - rootDoc: Doc; dataDoc: Doc; // usePanelWidth: boolean; showSidebar: boolean; @@ -42,7 +42,7 @@ export class SidebarAnnos extends React.Component { _stackRef = React.createRef(); @computed get allMetadata() { const keys = new Map>(); - DocListCast(this.props.rootDoc[this.sidebarKey]).forEach(doc => + DocListCast(this.props.Document[this.sidebarKey]).forEach(doc => SearchUtil.documentKeys(doc) .filter(key => key[0] && key[0] !== '_' && key[0] === key[0].toUpperCase()) .map(key => keys.set(key, doc[key])) @@ -51,7 +51,7 @@ export class SidebarAnnos extends React.Component { } @computed get allHashtags() { const keys = new Set(); - DocListCast(this.props.rootDoc[this.sidebarKey]).forEach(doc => StrListCast(doc.tags).forEach(tag => keys.add(tag))); + DocListCast(this.props.Document[this.sidebarKey]).forEach(doc => StrListCast(doc.tags).forEach(tag => keys.add(tag))); return Array.from(keys.keys()) .filter(key => key[0]) .filter(key => !key.startsWith('_') && (key[0] === '#' || key[0] === key[0].toUpperCase())) @@ -59,7 +59,7 @@ export class SidebarAnnos extends React.Component { } @computed get allUsers() { const keys = new Set(); - DocListCast(this.props.rootDoc[this.sidebarKey]).forEach(doc => keys.add(StrCast(doc.author))); + DocListCast(this.props.Document[this.sidebarKey]).forEach(doc => keys.add(StrCast(doc.author))); return Array.from(keys.keys()).sort(); } @@ -69,7 +69,7 @@ export class SidebarAnnos extends React.Component { .join(' '); const target = Docs.Create.TextDocument(startup, { title: '-note-', - annotationOn: this.props.rootDoc, + annotationOn: this.props.Document, _width: 200, _height: 50, _layout_fitWidth: true, @@ -147,7 +147,7 @@ export class SidebarAnnos extends React.Component { return target; }; makeDocUnfiltered = (doc: Doc) => { - if (DocListCast(this.props.rootDoc[this.sidebarKey]).find(anno => Doc.AreProtosEqual(doc.layout_unrendered ? DocCast(doc.annotationOn) : doc, anno))) { + if (DocListCast(this.props.Document[this.sidebarKey]).find(anno => Doc.AreProtosEqual(doc.layout_unrendered ? DocCast(doc.annotationOn) : doc, anno))) { if (this.childFilters()) { // if any child filters exist, get rid of them this.props.layoutDoc._childFilters = new List(); @@ -188,7 +188,7 @@ export class SidebarAnnos extends React.Component { const renderTag = (tag: string) => { const active = this.childFilters().includes(`tags${Doc.FilterSep}${tag}${Doc.FilterSep}check`); return ( -

Doc.setDocFilter(this.props.rootDoc, 'tags', tag, 'check', true, undefined, e.shiftKey)}> +
Doc.setDocFilter(this.props.Document, 'tags', tag, 'check', true, undefined, e.shiftKey)}> {tag}
); @@ -196,7 +196,7 @@ export class SidebarAnnos extends React.Component { const renderMeta = (tag: string, dflt: FieldResult) => { const active = this.childFilters().includes(`${tag}${Doc.FilterSep}${Doc.FilterAny}${Doc.FilterSep}exists`); return ( -
Doc.setDocFilter(this.props.rootDoc, tag, Doc.FilterAny, 'exists', true, undefined, e.shiftKey)}> +
Doc.setDocFilter(this.props.Document, tag, Doc.FilterAny, 'exists', true, undefined, e.shiftKey)}> {tag}
); @@ -204,7 +204,7 @@ export class SidebarAnnos extends React.Component { const renderUsers = (user: string) => { const active = this.childFilters().includes(`author:${user}:check`); return ( -
Doc.setDocFilter(this.props.rootDoc, 'author', user, 'check', true, undefined, e.shiftKey)}> +
Doc.setDocFilter(this.props.Document, 'author', user, 'check', true, undefined, e.shiftKey)}> {user}
); @@ -215,9 +215,9 @@ export class SidebarAnnos extends React.Component { style={{ position: 'absolute', pointerEvents: this.props.isContentActive() ? 'all' : undefined, - top: this.props.rootDoc.type !== DocumentType.RTF && StrCast(this.props.rootDoc._layout_showTitle) === 'title' ? 15 : 0, + top: this.props.Document.type !== DocumentType.RTF && StrCast(this.props.Document._layout_showTitle) === 'title' ? 15 : 0, right: 0, - background: this.props.styleProvider?.(this.props.rootDoc, this.props, StyleProp.WidgetColor), + background: this.props.styleProvider?.(this.props.Document, this.props, StyleProp.WidgetColor), width: `100%`, height: '100%', }}> diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 389a9a534..dc2ee63f5 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -141,7 +141,7 @@ export class CollectionView extends ViewBoxAnnotatableComponent Doc) { - if (!Doc.IsSystem(this.rootDoc) && this.rootDoc._type_collection !== CollectionViewType.Docking && !this.rootDoc.isGroup && !this.rootDoc.annotationOn) { + if (!Doc.IsSystem(this.Document) && this.Document._type_collection !== CollectionViewType.Docking && !this.dataDoc.isGroup && !this.Document.annotationOn) { // prettier-ignore const subItems: ContextMenuProps[] = [ { description: 'Freeform', event: () => func(CollectionViewType.Freeform), icon: 'signature' }, @@ -172,7 +172,7 @@ export class CollectionView extends ViewBoxAnnotatableComponent { - const newRendition = Doc.MakeEmbedding(this.rootDoc); + const newRendition = Doc.MakeEmbedding(this.Document); newRendition._type_collection = vtype; this.props.addDocTab(newRendition, OpenWhere.addRight); return newRendition; @@ -180,18 +180,18 @@ export class CollectionView extends ViewBoxAnnotatableComponent (this.rootDoc.forceActive = !this.rootDoc.forceActive), icon: 'project-diagram' }) : null; - if (this.rootDoc.childLayout instanceof Doc) { - optionItems.push({ description: 'View Child Layout', event: () => this.props.addDocTab(this.rootDoc.childLayout as Doc, OpenWhere.addRight), icon: 'project-diagram' }); + !Doc.noviceMode ? optionItems.splice(0, 0, { description: `${this.Document.forceActive ? 'Select' : 'Force'} Contents Active`, event: () => (this.Document.forceActive = !this.Document.forceActive), icon: 'project-diagram' }) : null; + if (this.Document.childLayout instanceof Doc) { + optionItems.push({ description: 'View Child Layout', event: () => this.props.addDocTab(this.Document.childLayout as Doc, OpenWhere.addRight), icon: 'project-diagram' }); } - if (this.rootDoc.childClickedOpenTemplateView instanceof Doc) { - optionItems.push({ description: 'View Child Detailed Layout', event: () => this.props.addDocTab(this.rootDoc.childClickedOpenTemplateView as Doc, OpenWhere.addRight), icon: 'project-diagram' }); + if (this.Document.childClickedOpenTemplateView instanceof Doc) { + optionItems.push({ description: 'View Child Detailed Layout', event: () => this.props.addDocTab(this.Document.childClickedOpenTemplateView as Doc, OpenWhere.addRight), icon: 'project-diagram' }); } - !Doc.noviceMode && optionItems.push({ description: `${this.rootDoc._isLightbox ? 'Unset' : 'Set'} is Lightbox`, event: () => (this.rootDoc._isLightbox = !this.rootDoc._isLightbox), icon: 'project-diagram' }); + !Doc.noviceMode && optionItems.push({ description: `${this.layoutDoc._isLightbox ? 'Unset' : 'Set'} is Lightbox`, event: () => (this.layoutDoc._isLightbox = !this.layoutDoc._isLightbox), icon: 'project-diagram' }); !options && cm.addItem({ description: 'Options...', subitems: optionItems, icon: 'hand-point-right' }); - if (!Doc.noviceMode && !this.rootDoc.annotationOn) { + if (!Doc.noviceMode && !this.Document.annotationOn) { const existingOnClick = cm.findByDescription('OnClick...'); const onClicks = existingOnClick && 'subitems' in existingOnClick ? existingOnClick.subitems : []; const funcs = [ @@ -203,7 +203,7 @@ export class CollectionView extends ViewBoxAnnotatableComponent { - const embedding = Doc.MakeEmbedding(this.rootDoc); + const embedding = Doc.MakeEmbedding(this.Document); DocUtils.makeCustomViewClicked(embedding, undefined, func.key); this.props.addDocTab(embedding, OpenWhere.addRight); }, @@ -213,16 +213,16 @@ export class CollectionView extends ViewBoxAnnotatableComponent (Doc.GetProto(this.rootDoc)[StrCast(childClick.targetScriptKey)] = ObjectField.MakeCopy(ScriptCast(childClick.data))), + event: () => (this.dataDoc[StrCast(childClick.targetScriptKey)] = ObjectField.MakeCopy(ScriptCast(childClick.data))), }) ); - !Doc.IsSystem(this.rootDoc) && !existingOnClick && cm.addItem({ description: 'OnClick...', noexpand: true, subitems: onClicks, icon: 'mouse-pointer' }); + !Doc.IsSystem(this.Document) && !existingOnClick && cm.addItem({ description: 'OnClick...', noexpand: true, subitems: onClicks, icon: 'mouse-pointer' }); } if (!Doc.noviceMode) { const more = cm.findByDescription('More...'); const moreItems = more && 'subitems' in more ? more.subitems : []; - moreItems.push({ description: 'Export Image Hierarchy', icon: 'columns', event: () => ImageUtils.ExportHierarchyToFileSystem(this.rootDoc) }); + moreItems.push({ description: 'Export Image Hierarchy', icon: 'columns', event: () => ImageUtils.ExportHierarchyToFileSystem(this.Document) }); !more && cm.addItem({ description: 'More...', subitems: moreItems, icon: 'hand-point-right' }); } } @@ -232,7 +232,7 @@ export class CollectionView extends ViewBoxAnnotatableComponent this.props.childHideResizeHandles?.() ?? BoolCast(this.Document.childHideResizeHandles); childHideDecorationTitle = () => this.props.childHideDecorationTitle?.() ?? BoolCast(this.Document.childHideDecorationTitle); - childLayoutTemplate = () => this.props.childLayoutTemplate?.() || Cast(this.rootDoc.childLayoutTemplate, Doc, null); + childLayoutTemplate = () => this.props.childLayoutTemplate?.() || Cast(this.Document.childLayoutTemplate, Doc, null); isContentActive = (outsideReaction?: boolean) => this._isContentActive; render() { @@ -249,7 +249,7 @@ export class CollectionView extends ViewBoxAnnotatableComponent + style={{ pointerEvents: this.props.DocumentView?.()?.props.docViewPath().lastElement()?.rootDoc?._type_collection === CollectionViewType.Freeform && this.layoutDoc._lockedPosition ? 'none' : undefined }}> {this.renderSubView(this.collectionViewType, props)}
); diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index 807a77233..dacdbe986 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -139,17 +139,17 @@ export class AudioBox extends ViewBoxAnnotatableComponent { - const newDoc = DocUtils.GetNewTextDoc('', NumCast(this.rootDoc.x), NumCast(this.rootDoc.y) + NumCast(this.layoutDoc._height) + 10, NumCast(this.layoutDoc._width), 2 * NumCast(this.layoutDoc._height)); + const newDoc = DocUtils.GetNewTextDoc('', NumCast(this.Document.x), NumCast(this.Document.y) + NumCast(this.layoutDoc._height) + 10, NumCast(this.layoutDoc._width), 2 * NumCast(this.layoutDoc._height)); const textField = Doc.LayoutFieldKey(newDoc); Doc.GetProto(newDoc)[`${textField}_recordingSource`] = this.dataDoc; Doc.GetProto(newDoc)[`${textField}_recordingStart`] = ComputedField.MakeFunction(`this.${textField}_recordingSource.${this.fieldKey}_recordingStart`); Doc.GetProto(newDoc).mediaState = ComputedField.MakeFunction(`this.${textField}_recordingSource.mediaState`); - if (Doc.IsInMyOverlay(this.rootDoc)) { - newDoc.overlayX = this.rootDoc.x; - newDoc.overlayY = NumCast(this.rootDoc.y) + NumCast(this.rootDoc._height); + if (Doc.IsInMyOverlay(this.Document)) { + newDoc.overlayX = this.Document.x; + newDoc.overlayY = NumCast(this.Document.y) + NumCast(this.layoutDoc._height); Doc.AddToMyOverlay(newDoc); } else { this.props.addDocument?.(newDoc); @@ -424,7 +424,7 @@ export class AudioBox extends ViewBoxAnnotatableComponent { - if (link.annotationOn === this.rootDoc) { + if (link.annotationOn === this.Document) { if (!this.layoutDoc.dontAutoPlayFollowedLinks) { this.playFrom(this.timeline?.anchorStart(link) || 0, this.timeline?.anchorEnd(link)); } else { diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index 2c53a1d5b..b7cd306ae 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -72,7 +72,7 @@ export class CollectionFreeFormDocumentViewWrapper extends DocComponent this.Highlight; // prettier-ignore w_Width = () => this.Width; // prettier-ignore w_Height = () => this.Height; // prettier-ignore - w_AutoDim = () => this.AutoDim; + w_AutoDim = () => this.AutoDim; w_Transition = () => this.Transition; // prettier-ignore w_DataTransition = () => this.DataTransition; // prettier-ignore @@ -254,7 +254,7 @@ export class CollectionFreeFormDocumentView extends DocComponent { if (this.CollectionFreeFormView.isAnyChildContentActive()) return undefined; - const isGroup = this.Document.isGroup && (!this.layoutDoc.backgroundColor || this.layoutDoc.backgroundColor === 'transparent'); + const isGroup = this.dataDoc.isGroup && (!this.layoutDoc.backgroundColor || this.layoutDoc.backgroundColor === 'transparent'); return isGroup ? (this.props.isDocumentActive?.() ? 'group' : this.props.isGroupActive?.() ? 'child' : 'inactive') : this.props.isGroupActive?.() ? 'child' : undefined; }; public static CollectionFreeFormDocViewClassName = 'collectionFreeFormDocumentView-container'; diff --git a/src/client/views/nodes/ComparisonBox.tsx b/src/client/views/nodes/ComparisonBox.tsx index ff394e5f5..b050e3252 100644 --- a/src/client/views/nodes/ComparisonBox.tsx +++ b/src/client/views/nodes/ComparisonBox.tsx @@ -44,7 +44,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent { if (dropEvent.complete.docDragData) { const droppedDocs = dropEvent.complete.docDragData?.droppedDocuments; - const added = dropEvent.complete.docDragData.moveDocument?.(droppedDocs, this.rootDoc, (doc: Doc | Doc[]) => this.addDoc(doc instanceof Doc ? doc : doc.lastElement(), fieldKey)); + const added = dropEvent.complete.docDragData.moveDocument?.(droppedDocs, this.Document, (doc: Doc | Doc[]) => this.addDoc(doc instanceof Doc ? doc : doc.lastElement(), fieldKey)); Doc.SetContainer(droppedDocs.lastElement(), this.dataDoc); !added && e.preventDefault(); e.stopPropagation(); // prevent parent Doc from registering new position so that it snaps back into place @@ -93,18 +93,18 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent { const anchor = Docs.Create.ConfigDocument({ - title: 'CompareAnchor:' + this.rootDoc.title, + title: 'CompareAnchor:' + this.Document.title, // set presentation timing properties for restoring view presentation_transition: 1000, - annotationOn: this.rootDoc, + annotationOn: this.Document, }); if (anchor) { if (!addAsAnnotation) anchor.backgroundColor = 'transparent'; /* addAsAnnotation &&*/ this.addDocument(anchor); - PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ?? {}), clippable: true } }, this.rootDoc); + PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ?? {}), clippable: true } }, this.Document); return anchor; } - return this.rootDoc; + return this.Document; }; @undoBatch diff --git a/src/client/views/nodes/DataVizBox/DataVizBox.tsx b/src/client/views/nodes/DataVizBox/DataVizBox.tsx index 1cb0a50f3..cc2c44435 100644 --- a/src/client/views/nodes/DataVizBox/DataVizBox.tsx +++ b/src/client/views/nodes/DataVizBox/DataVizBox.tsx @@ -35,7 +35,7 @@ export class DataVizBox extends ViewBoxAnnotatableComponent() { // all CSV records in the dataset (that aren't an empty row) @computed.struct get records() { - var records = DataVizBox.dataset.get(CsvCast(this.rootDoc[this.fieldKey]).url.href); + var records = DataVizBox.dataset.get(CsvCast(this.dataDoc[this.fieldKey]).url.href); return records?.filter(record => Object.keys(record).some(key => record[key])) ?? []; } @@ -75,7 +75,7 @@ export class DataVizBox extends ViewBoxAnnotatableComponent() { }; getAnchor = (addAsAnnotation?: boolean, pinProps?: PinProps) => { const anchor = !pinProps - ? this.rootDoc + ? this.Document : this._vizRenderer?.getAnchor(pinProps) ?? Docs.Create.ConfigDocument({ // when we clear selection -> we should have it so chartBox getAnchor returns undefined @@ -99,20 +99,20 @@ export class DataVizBox extends ViewBoxAnnotatableComponent() { componentDidMount() { this.props.setContentView?.(this); - if (!DataVizBox.dataset.has(CsvCast(this.rootDoc[this.fieldKey]).url.href)) this.fetchData(); + if (!DataVizBox.dataset.has(CsvCast(this.dataDoc[this.fieldKey]).url.href)) this.fetchData(); } fetchData = () => { - DataVizBox.dataset.set(CsvCast(this.rootDoc[this.fieldKey]).url.href, []); // assign temporary dataset as a lock to prevent duplicate server requests + DataVizBox.dataset.set(CsvCast(this.dataDoc[this.fieldKey]).url.href, []); // assign temporary dataset as a lock to prevent duplicate server requests fetch('/csvData?uri=' + this.dataUrl?.url.href) // - .then(res => res.json().then(action(res => !res.errno && DataVizBox.dataset.set(CsvCast(this.rootDoc[this.fieldKey]).url.href, res)))); + .then(res => res.json().then(action(res => !res.errno && DataVizBox.dataset.set(CsvCast(this.dataDoc[this.fieldKey]).url.href, res)))); }; // toggles for user to decide which chart type to view the data in @computed get renderVizView() { const scale = this.props.NativeDimScaling?.() || 1; const sharedProps = { - rootDoc: this.rootDoc, + rootDoc: this.Document, layoutDoc: this.layoutDoc, records: this.records, axes: this.axes, diff --git a/src/client/views/nodes/DataVizBox/components/LineChart.tsx b/src/client/views/nodes/DataVizBox/components/LineChart.tsx index 3de7a0c4a..ad34a0c99 100644 --- a/src/client/views/nodes/DataVizBox/components/LineChart.tsx +++ b/src/client/views/nodes/DataVizBox/components/LineChart.tsx @@ -23,7 +23,7 @@ export interface SelectedDataPoint extends DataPoint { elem?: d3.Selection; } export interface LineChartProps { - rootDoc: Doc; + Document: Doc; layoutDoc: Doc; axes: string[]; records: { [key: string]: any }[]; @@ -63,7 +63,7 @@ export class LineChart extends React.Component { return this.props.axes[1] + ' vs. ' + this.props.axes[0] + ' Line Chart'; } @computed get parentViz() { - return DocCast(this.props.rootDoc.dataViz_parentViz); + return DocCast(this.props.Document.dataViz_parentViz); // return LinkManager.Instance.getAllRelatedLinks(this.props.rootDoc) // out of all links // .filter(link => { // return link.link_anchor_1 == this.props.rootDoc.dataViz_parentViz; @@ -74,7 +74,7 @@ export class LineChart extends React.Component { // return selected x and y axes // otherwise, use the selection of whatever is linked to us const incomingVizBox = DocumentManager.Instance.getFirstDocumentView(this.parentViz)?.ComponentView as DataVizBox; - const highlitedRowIds = NumListCast(incomingVizBox?.rootDoc?.dataViz_highlitedRows); + const highlitedRowIds = NumListCast(incomingVizBox?.layoutDoc?.dataViz_highlitedRows); return this._tableData.filter((record, i) => highlitedRowIds.includes(this._tableDataIds[i])); // get all the datapoints they have selected field set by incoming anchor } @computed get rangeVals(): { xMin?: number; xMax?: number; yMin?: number; yMax?: number } { @@ -170,7 +170,7 @@ export class LineChart extends React.Component { // title: 'line doc selection' + this._currSelected?.x, }); - PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: pinProps?.pinData }, this.props.rootDoc); + PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: pinProps?.pinData }, this.props.Document); anchor.config_dataVizSelection = this._currSelected ? new List([this._currSelected.x, this._currSelected.y]) : undefined; return anchor; }; diff --git a/src/client/views/nodes/FunctionPlotBox.tsx b/src/client/views/nodes/FunctionPlotBox.tsx index daf6cd9a6..5ed5fa8fd 100644 --- a/src/client/views/nodes/FunctionPlotBox.tsx +++ b/src/client/views/nodes/FunctionPlotBox.tsx @@ -43,11 +43,8 @@ export class FunctionPlotBox extends ViewBoxAnnotatableComponent ); } getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps) => { - const anchor = Docs.Create.ConfigDocument({ - // - annotationOn: this.rootDoc, - }); - PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ?? {}), datarange: true } }, this.rootDoc); + const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document }); + PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ?? {}), datarange: true } }, this.Document); anchor.config_xRange = new List(Array.from(this._plot.options.xAxis.domain)); anchor.config_yRange = new List(Array.from(this._plot.options.yAxis.domain)); if (addAsAnnotation) this.addDocument(anchor); diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 19e393968..7e85c33b8 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -89,26 +89,26 @@ export class ImageBox extends ViewBoxAnnotatableComponent ({ forceFull: this.props.renderDepth < 1 || this.layoutDoc._showFullRes, - scrSize: (this.props.ScreenToLocalTransform().inverse().transformDirection(this.nativeSize.nativeWidth, this.nativeSize.nativeHeight)[0] / this.nativeSize.nativeWidth) * NumCast(this.rootDoc._freeform_scale, 1), + scrSize: (this.props.ScreenToLocalTransform().inverse().transformDirection(this.nativeSize.nativeWidth, this.nativeSize.nativeHeight)[0] / this.nativeSize.nativeWidth) * NumCast(this.layoutDoc._freeform_scale, 1), selected: this.props.isSelected(), }), ({ forceFull, scrSize, selected }) => (this._curSuffix = selected ? '_o' : this.fieldKey === 'icon' ? '_m' : forceFull ? '_o' : scrSize < 0.25 ? '_s' : scrSize < 0.5 ? '_m' : scrSize < 0.8 ? '_l' : '_o'), @@ -152,7 +152,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent { - this.rootDoc[this.fieldKey + '_usePath'] = 'alternate:hover'; + this.layoutDoc[this.fieldKey + '_usePath'] = 'alternate:hover'; return last && Doc.AddDocToList(this.dataDoc, this.fieldKey + '-alternates', drop); }, true); } else if (de.altKey || !this.dataDoc[this.fieldKey]) { @@ -177,13 +177,13 @@ export class ImageBox extends ViewBoxAnnotatableComponent { - const scaling = (this.props.DocumentView?.().props.ScreenToLocalTransform().Scale || 1) / NumCast(this.rootDoc._freeform_scale, 1); + const scaling = (this.props.DocumentView?.().props.ScreenToLocalTransform().Scale || 1) / NumCast(this.layoutDoc._freeform_scale, 1); const nscale = NumCast(this.props.PanelWidth()) / scaling; const nw = nscale / NumCast(this.dataDoc[this.fieldKey + '_nativeWidth']); this.dataDoc[this.fieldKey + '_nativeHeight'] = NumCast(this.dataDoc[this.fieldKey + '_nativeHeight']) * nw; this.dataDoc[this.fieldKey + '_nativeWidth'] = NumCast(this.dataDoc[this.fieldKey + '_nativeWidth']) * nw; - this.rootDoc._freeform_panX = nw * NumCast(this.rootDoc._freeform_panX); - this.rootDoc._freeform_panY = nw * NumCast(this.rootDoc._freeform_panY); + this.layoutDoc._freeform_panX = nw * NumCast(this.layoutDoc._freeform_panX); + this.layoutDoc._freeform_panY = nw * NumCast(this.layoutDoc._freeform_panY); this.dataDoc._freeform_panXMax = this.dataDoc._freeform_panXMax ? nw * NumCast(this.dataDoc._freeform_panXMax) : undefined; this.dataDoc._freeform_panXMin = this.dataDoc._freeform_panXMin ? nw * NumCast(this.dataDoc._freeform_panXMin) : undefined; this.dataDoc._freeform_panYMax = this.dataDoc._freeform_panYMax ? nw * NumCast(this.dataDoc._freeform_panYMax) : undefined; @@ -206,17 +206,17 @@ export class ImageBox extends ViewBoxAnnotatableComponent setTimeout(() => (dv.ComponentView as ImageBox).setNativeSize(), 200)); @@ -263,7 +263,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent; }; - getScrollHeight = () => (this.props.layout_fitWidth?.(this.rootDoc) !== false && NumCast(this.rootDoc._freeform_scale, 1) === NumCast(this.rootDoc._freeform_scaleMin, 1) ? this.nativeSize.nativeHeight : undefined); + getScrollHeight = () => (this.props.layout_fitWidth?.(this.Document) !== false && NumCast(this.layoutDoc._freeform_scale, 1) === NumCast(this.dataDoc._freeform_scaleMin, 1) ? this.nativeSize.nativeHeight : undefined); @computed private get considerDownloadIcon() { @@ -384,7 +384,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent setupMoveUpEvents(e.target, e, returnFalse, emptyFunction, e => (this.rootDoc[`_${this.fieldKey}_usePath`] = usePath === undefined ? 'alternate' : usePath === 'alternate' ? 'alternate:hover' : undefined))} + onPointerDown={e => setupMoveUpEvents(e.target, e, returnFalse, emptyFunction, e => (this.layoutDoc[`_${this.fieldKey}_usePath`] = usePath === undefined ? 'alternate' : usePath === 'alternate' ? 'alternate:hover' : undefined))} style={{ display: (this.props.isContentActive() !== false && DragManager.DocDragData?.canEmbed) || DocListCast(this.dataDoc[this.fieldKey + '-alternates']).length ? 'block' : 'none', width: 'min(10%, 25px)', @@ -434,7 +434,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent (this._isHovering = true))} onPointerLeave={action(() => (this._isHovering = false))} key={this.layoutDoc[Id]} ref={this.createDropTarget} onPointerDown={this.marqueeDown}> @@ -481,7 +481,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent this.props.ScreenToLocalTransform().translate(0, NumCast(this.layoutDoc._layout_scrollTop) * this.props.ScreenToLocalTransform().Scale); marqueeDown = (e: React.PointerEvent) => { - if (!e.altKey && e.button === 0 && NumCast(this.rootDoc._freeform_scale, 1) <= NumCast(this.rootDoc.freeform_scaleMin, 1) && this.props.isContentActive(true) && ![InkTool.Highlighter, InkTool.Pen, InkTool.Write].includes(Doc.ActiveTool)) { + if (!e.altKey && e.button === 0 && NumCast(this.layoutDoc._freeform_scale, 1) <= NumCast(this.dataDoc.freeform_scaleMin, 1) && this.props.isContentActive(true) && ![InkTool.Highlighter, InkTool.Pen, InkTool.Write].includes(Doc.ActiveTool)) { setupMoveUpEvents( this, e, @@ -529,7 +529,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent () { _timer: any; @observable progress = ''; componentDidMount() { - if (!LoadingBox.CurrentlyLoading?.includes(this.rootDoc)) { - this.rootDoc.loadingError = 'Upload interrupted, please try again'; + if (!LoadingBox.CurrentlyLoading?.includes(this.Document)) { + this.Document.loadingError = 'Upload interrupted, please try again'; } else { const updateFunc = async () => { - const result = await Networking.QueryYoutubeProgress(StrCast(this.rootDoc[Id])); // We use the guid of the overwriteDoc to track file uploads. + const result = await Networking.QueryYoutubeProgress(StrCast(this.Document[Id])); // We use the guid of the overwriteDoc to track file uploads. runInAction(() => (this.progress = result.progress)); - !this.rootDoc.loadingError && (this._timer = setTimeout(updateFunc, 1000)); + !this.Document.loadingError && (this._timer = setTimeout(updateFunc, 1000)); }; this._timer = setTimeout(updateFunc, 1000); } @@ -74,11 +74,11 @@ export class LoadingBox extends ViewBoxAnnotatableComponent() { render() { return ( -
+
- {StrCast(this.rootDoc.title)} -

{StrCast(this.rootDoc.loadingError, 'Loading ' + (this.progress.replace('[download]', '') || '(can take several minutes)'))}

- {this.rootDoc.loadingError ? null : ( + {StrCast(this.Document.title)} +

{StrCast(this.Document.loadingError, 'Loading ' + (this.progress.replace('[download]', '') || '(can take several minutes)'))}

+ {this.rootDDocumentoc.loadingError ? null : (
diff --git a/src/client/views/nodes/MapBox/MapBox.tsx b/src/client/views/nodes/MapBox/MapBox.tsx index 9b75ca7e3..8d3cd1d96 100644 --- a/src/client/views/nodes/MapBox/MapBox.tsx +++ b/src/client/views/nodes/MapBox/MapBox.tsx @@ -195,7 +195,7 @@ export class MapBox extends ViewBoxAnnotatableComponent @@ -227,7 +227,7 @@ export class MapBox extends ViewBoxAnnotatableComponent { - const target = DocUtils.GetNewTextDoc('Note linked to ' + this.rootDoc.title, 0, 0, 100, 100, undefined, annotationOn, undefined, 'yellow'); + const target = DocUtils.GetNewTextDoc('Note linked to ' + this.Document.title, 0, 0, 100, 100, undefined, annotationOn, undefined, 'yellow'); FormattedTextBox.SelectOnLoad = target[Id]; return target; }; @@ -321,7 +321,7 @@ export class MapBox extends ViewBoxAnnotatableComponent { if (this.selectedPin) { // Removes filter - Doc.setDocFilter(this.rootDoc, 'latitude', this.selectedPin.latitude, 'remove'); - Doc.setDocFilter(this.rootDoc, 'longitude', this.selectedPin.longitude, 'remove'); - Doc.setDocFilter(this.rootDoc, LinkedTo, `mapPin=${Field.toScriptString(DocCast(this.selectedPin))}`, 'remove'); + Doc.setDocFilter(this.layoutDoc, 'latitude', this.selectedPin.latitude, 'remove'); + Doc.setDocFilter(this.layoutDoc, 'longitude', this.selectedPin.longitude, 'remove'); + Doc.setDocFilter(this.layoutDoc, LinkedTo, `mapPin=${Field.toScriptString(DocCast(this.selectedPin))}`, 'remove'); const temp = this.selectedPin; if (!this._unmounting) { @@ -369,7 +369,7 @@ export class MapBox extends ViewBoxAnnotatableComponent { /// this should use SELECTED pushpin for lat/long if there is a selection, otherwise CENTER const anchor = Docs.Create.ConfigDocument({ - title: 'MapAnchor:' + this.rootDoc.title, - text: StrCast(this.selectedPin?.map) || StrCast(this.rootDoc.map) || 'map location', + title: 'MapAnchor:' + this.Document.title, + text: StrCast(this.selectedPin?.map) || StrCast(this.dataDoc.map) || 'map location', config_latitude: NumCast((existingPin ?? this.selectedPin)?.latitude ?? this.dataDoc.latitude), config_longitude: NumCast((existingPin ?? this.selectedPin)?.longitude ?? this.dataDoc.longitude), config_map_zoom: NumCast(this.dataDoc.map_zoom), @@ -466,15 +466,15 @@ export class MapBox extends ViewBoxAnnotatableComponent(); @@ -521,9 +521,9 @@ export class MapBox extends ViewBoxAnnotatableComponent { if (this.selectedPin) { // Removes filter - Doc.setDocFilter(this.rootDoc, 'latitude', this.selectedPin.latitude, 'remove'); - Doc.setDocFilter(this.rootDoc, 'longitude', this.selectedPin.longitude, 'remove'); - Doc.setDocFilter(this.rootDoc, LinkedTo, `mapPin=${Field.toScriptString(DocCast(this.selectedPin))}`, 'remove'); + Doc.setDocFilter(this.layoutDoc, 'latitude', this.selectedPin.latitude, 'remove'); + Doc.setDocFilter(this.layoutDoc, 'longitude', this.selectedPin.longitude, 'remove'); + Doc.setDocFilter(this.layoutDoc, LinkedTo, `mapPin=${Field.toScriptString(DocCast(this.selectedPin))}`, 'remove'); this.removePushpin(this.selectedPin); } @@ -611,7 +611,7 @@ export class MapBox extends ViewBoxAnnotatableComponent this.rootDoc.map, + () => this.dataDoc.map, mapLoc => (this.bingSearchBarContents = mapLoc), { fireImmediately: true } ); @@ -636,7 +636,7 @@ export class MapBox extends ViewBoxAnnotatableComponent ({ lat: this.rootDoc.latitude, lng: this.rootDoc.longitude, zoom: this.rootDoc.map_zoom, mapType: this.rootDoc.map_type }), + () => ({ lat: this.dataDoc.latitude, lng: this.dataDoc.longitude, zoom: this.dataDoc.map_zoom, mapType: this.dataDoc.map_type }), locationObject => { // if (this._bingMap.current) try { @@ -687,7 +687,7 @@ export class MapBox extends ViewBoxAnnotatableComponent { - const createPin = () => this.createPushpin(this.rootDoc.latitude, this.rootDoc.longitude, this.rootDoc.map); + const createPin = () => this.createPushpin(this.dataDoc.latitude, this.dataDoc.longitude, this.dataDoc.map); if (this.bingSearchBarContents) { this.bingSearch().then(createPin); } else createPin(); @@ -703,7 +703,7 @@ export class MapBox extends ViewBoxAnnotatableComponent @@ -495,7 +495,7 @@ export class MapBox2 extends ViewBoxAnnotatableComponent AnchorMenu.Instance?.GetAnchor(this._savedAnnotations, addAsAnnotation) ?? this.rootDoc; + getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps) => AnchorMenu.Instance?.GetAnchor(this._savedAnnotations, addAsAnnotation) ?? this.Document; /** * render contents in allMapMarkers (e.g. images with exifData) into google maps as map marker @@ -577,7 +577,7 @@ export class MapBox2 extends ViewBoxAnnotatableComponent { @@ -173,7 +173,7 @@ export class PDFBox extends ViewBoxAnnotatableComponent { @@ -200,13 +200,13 @@ export class PDFBox extends ViewBoxAnnotatableComponent this.rootDoc.layout_scrollTop, + () => this.layoutDoc.layout_scrollTop, () => { if (!(ComputedField.WithoutComputed(() => FieldValue(this.props.Document[this.SidebarKey + '_panY'])) instanceof ComputedField)) { this.props.Document[this.SidebarKey + '_panY'] = ComputedField.MakeFunction('this.layout_scrollTop'); } - this.props.Document[this.SidebarKey + '_freeform_scale'] = 1; - this.props.Document[this.SidebarKey + '_freeform_panX'] = 0; + this.layoutDoc[this.SidebarKey + '_freeform_scale'] = 1; + this.layoutDoc[this.SidebarKey + '_freeform_panX'] = 0; } ); } @@ -236,12 +236,12 @@ export class PDFBox extends ViewBoxAnnotatableComponent Docs.Create.ConfigDocument({ - title: StrCast(this.rootDoc.title + '@' + NumCast(this.layoutDoc._layout_scrollTop)?.toFixed(0)), - annotationOn: this.rootDoc, + title: StrCast(this.Document.title + '@' + NumCast(this.layoutDoc._layout_scrollTop)?.toFixed(0)), + annotationOn: this.Document, }); const visibleAnchor = this._pdfViewer?._getAnchor?.(this._pdfViewer.savedAnnotations(), true); const anchor = visibleAnchor ?? docAnchor(); - PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ?? {}), scrollable: true, pannable: true } }, this.rootDoc); + PresBox.pinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ?? {}), scrollable: true, pannable: true } }, this.Document); anchor.text = ele?.textContent ?? ''; anchor.text_html = ele?.innerHTML; addAsAnnotation && this.addDocument(anchor); @@ -434,7 +434,7 @@ export class PDFBox extends ViewBoxAnnotatableComponent (this.rootDoc[this.SidebarKey + '_type_collection'] = this.rootDoc[this.SidebarKey + '_type_collection'] === CollectionViewType.Freeform ? CollectionViewType.Stacking : CollectionViewType.Freeform); + toggleSidebarType = () => (this.dataDoc[this.SidebarKey + '_type_collection'] = this.dataDoc[this.SidebarKey + '_type_collection'] === CollectionViewType.Freeform ? CollectionViewType.Stacking : CollectionViewType.Freeform); specificContextMenu = (e: React.MouseEvent): void => { const cm = ContextMenu.Instance; const options = cm.findByDescription('Options...'); @@ -473,7 +473,7 @@ export class PDFBox extends ViewBoxAnnotatableComponent this.sidebarBtnDown(e, true)}> @@ -509,7 +509,7 @@ export class PDFBox extends ViewBoxAnnotatableComponent { const startTime = Cast(this.layoutDoc._layout_currentTimecode, 'number', null) || (this._videoRec ? (Date.now() - (this.recordingStart || 0)) / 1000 : undefined); - return CollectionStackedTimeline.createAnchor(this.rootDoc, this.dataDoc, this.annotationKey, startTime, startTime === undefined ? undefined : startTime + 3, undefined, addAsAnnotation) || this.rootDoc; + return CollectionStackedTimeline.createAnchor(this.Document, this.dataDoc, this.annotationKey, startTime, startTime === undefined ? undefined : startTime + 3, undefined, addAsAnnotation) || this.Document; }; videoLoad = () => { @@ -151,7 +151,7 @@ export class ScreenshotBox extends ViewBoxAnnotatableComponent ({ width: this.props.PanelWidth(), height: this.props.PanelHeight() }), + // this.layoutDoc.videoWall && reaction(() => ({ width: this.props.PanelWidth(), height: this.props.PanelHeight() }), // ({ width, height }) => { // if (this._camera) { // const angle = -Math.abs(1 - width / height); @@ -173,7 +173,7 @@ export class ScreenshotBox extends ViewBoxAnnotatableComponent { this._videoRef = r; setTimeout(() => { - if (this.rootDoc.mediaState === media_state.PendingRecording && this._videoRef) { + if (this.layoutDoc.mediaState === media_state.PendingRecording && this._videoRef) { this.toggleRecording(); } }, 100); @@ -202,12 +202,12 @@ export class ScreenshotBox extends ViewBoxAnnotatableComponent this._raised = r; @computed get threed() { - // if (this.rootDoc.videoWall) { + // if (this.layoutDoc.videoWall) { // const screens: any[] = []; // const colors = ["yellow", "red", "orange", "brown", "maroon", "gray"]; // let count = 0; // numberRange(this._numScreens).forEach(x => numberRange(this._numScreens).forEach(y => screens.push( - // ))); + // ))); // return { // this._camera = props.camera; // props.camera.position.set(this._numScreens / 2, this._numScreens / 2, this._numScreens - 2); @@ -250,7 +250,7 @@ export class ScreenshotBox extends ViewBoxAnnotatableComponent { if (this.dataDoc[this.fieldKey + '_dictation']) return; - const dictationText = DocUtils.GetNewTextDoc('dictation', NumCast(this.rootDoc.x), NumCast(this.rootDoc.y) + NumCast(this.layoutDoc._height) + 10, NumCast(this.layoutDoc._width), 2 * NumCast(this.layoutDoc._height)); + const dictationText = DocUtils.GetNewTextDoc('dictation', NumCast(this.Document.x), NumCast(this.Document.y) + NumCast(this.layoutDoc._height) + 10, NumCast(this.layoutDoc._width), 2 * NumCast(this.layoutDoc._height)); const textField = Doc.LayoutFieldKey(dictationText); dictationText._layout_autoHeight = false; const dictationTextProto = Doc.GetProto(dictationText); diff --git a/src/client/views/nodes/ScriptingBox.tsx b/src/client/views/nodes/ScriptingBox.tsx index a51a83b26..127edaed7 100644 --- a/src/client/views/nodes/ScriptingBox.tsx +++ b/src/client/views/nodes/ScriptingBox.tsx @@ -61,7 +61,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent !p.startsWith('_')) @@ -78,30 +78,30 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent p.split(':')[1].trim()); } @computed({ keepAlive: true }) get rawScript() { - return ScriptCast(this.rootDoc[this.fieldKey])?.script.originalScript ?? ''; + return ScriptCast(this.dataDoc[this.fieldKey])?.script.originalScript ?? ''; } @computed({ keepAlive: true }) get functionName() { - return StrCast(this.rootDoc[this.props.fieldKey + '-functionName'], ''); + return StrCast(this.dataDoc[this.fieldKey + '-functionName'], ''); } @computed({ keepAlive: true }) get functionDescription() { - return StrCast(this.rootDoc[this.props.fieldKey + '-functionDescription'], ''); + return StrCast(this.dataDoc[this.fieldKey + '-functionDescription'], ''); } @computed({ keepAlive: true }) get compileParams() { - return Cast(this.rootDoc[this.props.fieldKey + '-params'], listSpec('string'), []); + return Cast(this.dataDoc[this.fieldKey + '-params'], listSpec('string'), []); } set rawScript(value) { - Doc.SetInPlace(this.rootDoc, this.props.fieldKey, new ScriptField(undefined, undefined, value), true); + this.dataDoc[this.fieldKey] = new ScriptField(undefined, undefined, value); } set functionName(value) { - Doc.SetInPlace(this.rootDoc, this.props.fieldKey + '-functionName', value, true); + this.dataDoc[this.fieldKey + '-functionName'] = value; } set functionDescription(value) { - Doc.SetInPlace(this.rootDoc, this.props.fieldKey + '-functionDescription', value, true); + this.dataDoc[this.fieldKey + '-functionDescription'] = value; } set compileParams(value) { - Doc.SetInPlace(this.rootDoc, this.props.fieldKey + '-params', new List(value), true); + this.dataDoc[this.fieldKey + '-params'] = new List(value); } getValue(result: any, descrip: boolean) { @@ -165,9 +165,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent { - this.rootDoc.layout_fieldKey = 'layout'; - }; + onFinish = () => (this.layoutDoc.layout_fieldKey = 'layout'); // displays error message @action @@ -189,7 +187,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent { if (this.onCompile()) { const bindings: { [name: string]: any } = {}; - this.paramsNames.forEach(key => (bindings[key] = this.rootDoc[key])); + this.paramsNames.forEach(key => (bindings[key] = this.dataDoc[key])); // binds vars so user doesnt have to refer to everything as this. - ScriptCast(this.rootDoc[this.fieldKey], null)?.script.run({ ...bindings, self: this.rootDoc, this: this.layoutDoc }, this.onError); + ScriptCast(this.dataDoc[this.fieldKey], null)?.script.run({ ...bindings, this: this.Document }, this.onError); } }; @@ -270,7 +268,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent { if (de.complete.docDragData) { - de.complete.docDragData.droppedDocuments.forEach(doc => Doc.SetInPlace(this.rootDoc, fieldKey, doc, true)); + de.complete.docDragData.droppedDocuments.forEach(doc => (this.dataDoc[fieldKey] = doc)); e.stopPropagation(); return true; } @@ -280,7 +278,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent { - Doc.SetInPlace(this.rootDoc, this.paramsNames[num], undefined, true); + this.dataDoc[this.paramsNames[num]] = undefined; this.compileParams.splice(num, 1); return true; }; @@ -290,13 +288,13 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent { //@ts-ignore const val = e.target.selectedOptions[0].value; - Doc.SetInPlace(this.rootDoc, name, val[0] === 'S' ? val.substring(1) : val[0] === 'N' ? parseInt(val.substring(1)) : val.substring(1) === 'true', true); + this.dataDoc[name] = val[0] === 'S' ? val.substring(1) : val[0] === 'N' ? parseInt(val.substring(1)) : val.substring(1) === 'true'; }; // creates a copy of the script document onCopy = () => { - const copy = Doc.MakeCopy(this.rootDoc, true); - copy.x = NumCast(this.dataDoc.x) + NumCast(this.dataDoc._width); + const copy = Doc.MakeCopy(this.Document, true); + copy.x = NumCast(this.Document.x) + NumCast(this.dataDoc._width); this.props.addDocument?.(copy); }; @@ -346,8 +344,8 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent StrCast(DocCast(this.rootDoc[parameter])?.title, 'undefined')} + contents={StrCast(DocCast(this.dataDoc[parameter])?.title, 'undefined')} + GetValue={() => StrCast(DocCast(this.dataDoc[parameter])?.title, 'undefined')} SetValue={action((value: string) => { const script = CompileScript(value, { addReturn: true, @@ -357,7 +355,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent e.stopPropagation()} onChange={e => this.viewChanged(e, parameter)} - value={typeof this.rootDoc[parameter] === 'string' ? 'S' + StrCast(this.rootDoc[parameter]) : typeof this.rootDoc[parameter] === 'number' ? 'N' + NumCast(this.rootDoc[parameter]) : 'B' + BoolCast(this.rootDoc[parameter])}> + value={typeof this.dataDoc[parameter] === 'string' ? 'S' + StrCast(this.dataDoc[parameter]) : typeof this.dataDoc[parameter] === 'number' ? 'N' + NumCast(this.dataDoc[parameter]) : 'B' + BoolCast(this.dataDoc[parameter])}> {types.map((type, i) => (
); diff --git a/src/client/util/SettingsManager.tsx b/src/client/util/SettingsManager.tsx index 39c471970..ccf6fb820 100644 --- a/src/client/util/SettingsManager.tsx +++ b/src/client/util/SettingsManager.tsx @@ -1,6 +1,6 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Button, ColorPicker, Dropdown, DropdownType, EditableText, Group, NumberDropdown, Size, Toggle, ToggleType, Type } from 'browndash-components'; -import { action, computed, observable, runInAction } from 'mobx'; +import { action, computed, makeObservable, observable, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; import { BsGoogle } from 'react-icons/bs'; @@ -45,11 +45,12 @@ export class SettingsManager extends React.Component<{}> { @observable private new_confirm = ''; @observable activeTab = 'Accounts'; - @observable public static propertiesWidth: number = 0; - @observable public static headerBarHeight: number = 0; + @observable public propertiesWidth: number = 0; + @observable public headerBarHeight: number = 0; constructor(props: {}) { super(props); + makeObservable(this); SettingsManager.Instance = this; this.matchSystem(); window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => { @@ -116,7 +117,6 @@ export class SettingsManager extends React.Component<{}> { }); @undoBatch - @action changeColorScheme = action((scheme: string) => { Doc.UserDoc().userTheme = scheme; switch (scheme) { diff --git a/src/client/util/SharingManager.tsx b/src/client/util/SharingManager.tsx index 403f4e090..a46c6363e 100644 --- a/src/client/util/SharingManager.tsx +++ b/src/client/util/SharingManager.tsx @@ -67,8 +67,8 @@ export class SharingManager extends React.Component<{}> { public static Instance: SharingManager; @observable private isOpen = false; // whether the SharingManager modal is open or not @observable public users: ValidatedUser[] = []; // the list of users with sharing docs - @observable private targetDoc: Doc | undefined; // the document being shared - @observable private targetDocView: DocumentView | undefined; // the DocumentView of the document being shared + @observable private targetDoc: Doc | undefined = undefined; // the document being shared + @observable private targetDocView: DocumentView | undefined = undefined; // the DocumentView of the document being shared // @observable private copied = false; @observable private dialogueBoxOpacity = 1; // for the modal @observable private overlayOpacity = 0.4; // for the modal diff --git a/src/client/util/SnappingManager.ts b/src/client/util/SnappingManager.ts index fce43eef6..715eb021f 100644 --- a/src/client/util/SnappingManager.ts +++ b/src/client/util/SnappingManager.ts @@ -6,7 +6,7 @@ export namespace SnappingManager { @observable ShiftKey = false; @observable CtrlKey = false; @observable IsDragging: boolean = false; - @observable IsResizing: Doc | undefined; + @observable IsResizing: Doc | undefined = undefined; @observable CanEmbed: boolean = false; @observable public horizSnapLines: number[] = []; @observable public vertSnapLines: number[] = []; diff --git a/src/client/views/AntimodeMenu.tsx b/src/client/views/AntimodeMenu.tsx index 412b8ba6e..f89624941 100644 --- a/src/client/views/AntimodeMenu.tsx +++ b/src/client/views/AntimodeMenu.tsx @@ -1,9 +1,8 @@ +import { action, makeObservable, observable, runInAction } from 'mobx'; import * as React from 'react'; -import { observable, action, runInAction } from 'mobx'; -import './AntimodeMenu.scss'; -import { StrCast } from '../../fields/Types'; -import { Doc } from '../../fields/Doc'; import { SettingsManager } from '../util/SettingsManager'; +import { copyProps } from '../../Utils'; +import './AntimodeMenu.scss'; export interface AntimodeMenuProps {} /** @@ -16,6 +15,18 @@ export abstract class AntimodeMenu extends React.Co protected _mainCont: React.RefObject = React.createRef(); protected _dragging: boolean = false; + _prevProps: React.PropsWithChildren; + @observable _props: React.PropsWithChildren; + constructor(props: React.PropsWithChildren) { + super(props); + this._props = this._prevProps = props; + makeObservable(this); + } + + componentDidUpdate() { + copyProps(this); + } + @observable protected _top: number = -300; @observable protected _left: number = -300; @observable protected _opacity: number = 0; diff --git a/src/client/views/AudioWaveform.scss b/src/client/views/AudioWaveform.scss deleted file mode 100644 index 6cbd1759a..000000000 --- a/src/client/views/AudioWaveform.scss +++ /dev/null @@ -1,17 +0,0 @@ -.audioWaveform { - position: relative; - width: 100%; - height: 200%; - overflow: hidden; - z-index: -1000; - bottom: 0; - pointer-events: none; - div { - height: 100% !important; - width: 100% !important; - } - canvas { - height: 100% !important; - width: 100% !important; - } -} diff --git a/src/client/views/AudioWaveform.tsx b/src/client/views/AudioWaveform.tsx deleted file mode 100644 index 1fd2fedc3..000000000 --- a/src/client/views/AudioWaveform.tsx +++ /dev/null @@ -1,117 +0,0 @@ -import * as React from 'react'; -import axios from 'axios'; -import { action, computed, IReactionDisposer, reaction } from 'mobx'; -import { observer } from 'mobx-react'; -import Waveform from 'react-audio-waveform'; -import { Doc, NumListCast } from '../../fields/Doc'; -import { List } from '../../fields/List'; -import { listSpec } from '../../fields/Schema'; -import { Cast } from '../../fields/Types'; -import { numberRange } from '../../Utils'; -import './AudioWaveform.scss'; -import { Colors } from './global/globalEnums'; - -/** - * AudioWaveform - * - * Used in CollectionStackedTimeline to render a canvas with a visual of an audio waveform for AudioBox and VideoBox documents. - * Uses react-audio-waveform package. - * Bins the audio data into audioBuckets which are passed to package to render the lines. - * Calculates new buckets each time a new zoom factor or new set of trim bounds is created and stores it in a field on the layout doc with a title indicating the bounds and zoom for that list (see audioBucketField) - */ - -export interface AudioWaveformProps { - duration: number; // length of media clip - rawDuration: number; // length of underlying media data - mediaPath: string; - layoutDoc: Doc; - clipStart: number; - clipEnd: number; - zoomFactor: number; - PanelHeight: number; - PanelWidth: number; - fieldKey: string; -} - -@observer -export class AudioWaveform extends React.Component { - public static NUMBER_OF_BUCKETS = 100; // number of buckets data is divided into to draw waveform lines - - _disposer: IReactionDisposer | undefined; - - @computed get waveHeight() { - return Math.max(50, this.props.PanelHeight); - } - - @computed get clipStart() { - return this.props.clipStart; - } - @computed get clipEnd() { - return this.props.clipEnd; - } - @computed get zoomFactor() { - return this.props.zoomFactor; - } - - @computed get audioBuckets() { - return NumListCast(this.props.layoutDoc[this.audioBucketField(this.clipStart, this.clipEnd, this.zoomFactor)]); - } - audioBucketField = (start: number, end: number, zoomFactor: number) => this.props.fieldKey + '_audioBuckets/' + '/' + start.toFixed(2).replace('.', '_') + '/' + end.toFixed(2).replace('.', '_') + '/' + zoomFactor * 10; - - componentWillUnmount() { - this._disposer?.(); - } - - componentDidMount() { - this._disposer = reaction( - () => ({ clipStart: this.clipStart, clipEnd: this.clipEnd, fieldKey: this.audioBucketField(this.clipStart, this.clipEnd, this.zoomFactor), zoomFactor: this.props.zoomFactor }), - ({ clipStart, clipEnd, fieldKey, zoomFactor }) => { - if (!this.props.layoutDoc[fieldKey]) { - // setting these values here serves as a "lock" to prevent multiple attempts to create the waveform at nerly the same time. - const waveform = Cast(this.props.layoutDoc[this.audioBucketField(0, this.props.rawDuration, 1)], listSpec('number')); - this.props.layoutDoc[fieldKey] = waveform && new List(waveform.slice((clipStart / this.props.rawDuration) * waveform.length, (clipEnd / this.props.rawDuration) * waveform.length)); - setTimeout(() => this.createWaveformBuckets(fieldKey, clipStart, clipEnd, zoomFactor)); - } - }, - { fireImmediately: true } - ); - } - - // decodes the audio file into peaks for generating the waveform - createWaveformBuckets = async (fieldKey: string, clipStart: number, clipEnd: number, zoomFactor: number) => { - axios({ url: this.props.mediaPath, responseType: 'arraybuffer' }).then(response => { - const context = new window.AudioContext(); - context.decodeAudioData( - response.data, - action(buffer => { - const rawDecodedAudioData = buffer.getChannelData(0); - const startInd = clipStart / this.props.rawDuration; - const endInd = clipEnd / this.props.rawDuration; - const decodedAudioData = rawDecodedAudioData.slice(Math.floor(startInd * rawDecodedAudioData.length), Math.floor(endInd * rawDecodedAudioData.length)); - const numBuckets = Math.floor(AudioWaveform.NUMBER_OF_BUCKETS * zoomFactor); - - const bucketDataSize = Math.floor(decodedAudioData.length / numBuckets); - const brange = Array.from(Array(bucketDataSize)); - const bucketList = numberRange(numBuckets).map((i: number) => brange.reduce((p, x, j) => Math.abs(Math.max(p, decodedAudioData[i * bucketDataSize + j])), 0) / 2); - this.props.layoutDoc[fieldKey] = new List(bucketList); - }) - ); - }); - }; - - render() { - return ( -
- -
- ); - } -} diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index 57bc11385..249e2c3a3 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -1,40 +1,42 @@ -import * as React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { action, computed, IReactionDisposer, observable } from 'mobx'; +import { action, computed, IReactionDisposer, makeObservable, observable, reaction } from 'mobx'; import { observer } from 'mobx-react'; -import './ContextMenu.scss'; -import { ContextMenuItem, ContextMenuProps, OriginalMenuProps } from './ContextMenuItem'; -import { Utils } from '../../Utils'; +import * as React from 'react'; import { StrCast } from '../../fields/Types'; -import { Doc } from '../../fields/Doc'; import { SettingsManager } from '../util/SettingsManager'; +import './ContextMenu.scss'; +import { ContextMenuItem, ContextMenuProps, OriginalMenuProps } from './ContextMenuItem'; @observer export class ContextMenu extends React.Component { static Instance: ContextMenu; - @observable private _items: Array = []; - @observable private _pageX: number = 0; - @observable private _pageY: number = 0; - @observable private _display: boolean = false; - @observable private _searchString: string = ''; - @observable private _showSearch: boolean = false; + private _ignoreUp = false; + private _reactionDisposer?: IReactionDisposer; + private _defaultPrefix: string = ''; + private _defaultItem: ((name: string) => void) | undefined; + private _onDisplay?: () => void = undefined; + + @observable _items: ContextMenuProps[] = observable([]); + @observable _pageX: number = 0; + @observable _pageY: number = 0; + @observable _display: boolean = false; + @observable _searchString: string = ''; + @observable _showSearch: boolean = false; // afaik displaymenu can be called before all the items are added to the menu, so can't determine in displayMenu what the height of the menu will be - @observable private _yRelativeToTop: boolean = true; - @observable selectedIndex = -1; + @observable _yRelativeToTop: boolean = true; + @observable _selectedIndex = -1; - @observable private _width: number = 0; - @observable private _height: number = 0; + @observable _width: number = 0; + @observable _height: number = 0; - @observable private _mouseX: number = -1; - @observable private _mouseY: number = -1; - @observable private _shouldDisplay: boolean = false; - private _ignoreUp = false; - private _reactionDisposer?: IReactionDisposer; + @observable _mouseX: number = -1; + @observable _mouseY: number = -1; + @observable _shouldDisplay: boolean = false; - constructor(props: Readonly<{}>) { + constructor(props: any) { super(props); - + makeObservable(this); ContextMenu.Instance = this; } @@ -74,36 +76,27 @@ export class ContextMenu extends React.Component { this._reactionDisposer?.(); } - @action - componentDidMount = () => { + componentDidMount() { document.addEventListener('pointerdown', this.onPointerDown, true); document.addEventListener('pointerup', this.onPointerUp); - }; + } @action clearItems() { - this._items = []; + this._items.length = 0; this._defaultPrefix = ''; this._defaultItem = undefined; } - _defaultPrefix: string = ''; - _defaultItem: ((name: string) => void) | undefined; - - findByDescription = (target: string, toLowerCase = false) => { - return this._items.find(menuItem => { - let reference = menuItem.description; - toLowerCase && (reference = reference.toLowerCase()); - return reference === target; - }); - }; + findByDescription = (target: string, toLowerCase = false) => + this._items.find(menuItem => + (toLowerCase ? menuItem.description.toLowerCase() : menuItem.description) === target); // prettier-ignore @action addItem(item: ContextMenuProps) { - if (this._items.indexOf(item) === -1) { - this._items.push(item); - } + !this._items.includes(item) && this._items.push(item); } + @action moveAfter(item: ContextMenuProps, after?: ContextMenuProps) { const curInd = this._items.findIndex(i => i.description === item.description); @@ -111,6 +104,7 @@ export class ContextMenu extends React.Component { const afterInd = after && this.findByDescription(after.description) ? this._items.findIndex(i => i.description === after.description) : this._items.length; this._items.splice(afterInd, 0, item); } + @action setDefaultItem(prefix: string, item: (name: string) => void) { this._defaultPrefix = prefix; @@ -126,7 +120,6 @@ export class ContextMenu extends React.Component { return this._pageY + this._height > window.innerHeight - ContextMenu.buffer ? window.innerHeight - ContextMenu.buffer - this._height : Math.max(0, this._pageY); } - _onDisplay?: () => void = undefined; @action displayMenu = (x: number, y: number, initSearch = '', showSearch = false, onDisplay?: () => void) => { //maxX and maxY will change if the UI/font size changes, but will work for any amount @@ -201,7 +194,7 @@ export class ContextMenu extends React.Component {
{value.join(' -> ')}
) : ( - + ) ); } @@ -211,7 +204,8 @@ export class ContextMenu extends React.Component { } render() { - return !this._display ? null : ( + console.log('DISPLAY = ' + this._display); + return (
{ @@ -221,6 +215,7 @@ export class ContextMenu extends React.Component { } })} style={{ + display: this._display ? '' : 'none', left: this.pageX, ...(this._yRelativeToTop ? { top: this.pageY } : { bottom: this.pageY }), background: SettingsManager.userBackgroundColor, @@ -242,17 +237,17 @@ export class ContextMenu extends React.Component { @action onKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'ArrowDown') { - if (this.selectedIndex < this.flatItems.length - 1) { - this.selectedIndex++; + if (this._selectedIndex < this.flatItems.length - 1) { + this._selectedIndex++; } e.preventDefault(); } else if (e.key === 'ArrowUp') { - if (this.selectedIndex > 0) { - this.selectedIndex--; + if (this._selectedIndex > 0) { + this._selectedIndex--; } e.preventDefault(); } else if (e.key === 'Enter' || e.key === 'Tab') { - const item = this.flatItems[this.selectedIndex]; + const item = this.flatItems[this._selectedIndex]; if (item) { item.event({ x: this.pageX, y: this.pageY }); } else if (this._searchString.startsWith(this._defaultPrefix)) { @@ -268,12 +263,12 @@ export class ContextMenu extends React.Component { onChange = (e: React.ChangeEvent) => { this._searchString = e.target.value; if (!this._searchString) { - this.selectedIndex = -1; + this._selectedIndex = -1; } else { - if (this.selectedIndex === -1) { - this.selectedIndex = 0; + if (this._selectedIndex === -1) { + this._selectedIndex = 0; } else { - this.selectedIndex = Math.min(this.flatItems.length - 1, this.selectedIndex); + this._selectedIndex = Math.min(this.flatItems.length - 1, this._selectedIndex); } } }; diff --git a/src/client/views/ContextMenuItem.tsx b/src/client/views/ContextMenuItem.tsx index 6d97d965e..59b223c14 100644 --- a/src/client/views/ContextMenuItem.tsx +++ b/src/client/views/ContextMenuItem.tsx @@ -1,12 +1,11 @@ import * as React from 'react'; -import { observable, action, runInAction } from 'mobx'; +import { observable, action, runInAction, makeObservable } from 'mobx'; import { observer } from 'mobx-react'; import { IconProp } from '@fortawesome/fontawesome-svg-core'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { UndoManager } from '../util/UndoManager'; -import { Doc } from '../../fields/Doc'; -import { StrCast } from '../../fields/Types'; import { SettingsManager } from '../util/SettingsManager'; +import { copyProps } from '../../Utils'; export interface OriginalMenuProps { description: string; @@ -32,9 +31,20 @@ export class ContextMenuItem extends React.Component = []; @observable private overItem = false; - @action + _prevProps: ContextMenuProps & { selected?: boolean }; + @observable _props: ContextMenuProps & { selected?: boolean }; + constructor(props: ContextMenuProps & { selected?: boolean }) { + super(props); + this._props = this._prevProps = props; + makeObservable(this); + } + + componentDidUpdate() { + copyProps(this); + } + componentDidMount() { - this._items.length = 0; + runInAction(() => this._items.length = 0); if ((this.props as SubmenuProps)?.subitems) { (this.props as SubmenuProps).subitems?.forEach(i => runInAction(() => this._items.push(i))); } diff --git a/src/client/views/DocComponent.tsx b/src/client/views/DocComponent.tsx index d104eb90c..2ce0c085a 100644 --- a/src/client/views/DocComponent.tsx +++ b/src/client/views/DocComponent.tsx @@ -1,4 +1,4 @@ -import { action, computed, observable } from 'mobx'; +import { action, computed, makeObservable, observable, runInAction, untracked } from 'mobx'; import { DateField } from '../../fields/DateField'; import { Doc, DocListCast, Opt } from '../../fields/Doc'; import { AclAdmin, AclAugment, AclEdit, AclPrivate, AclReadonly, DocData } from '../../fields/DocSymbols'; @@ -21,17 +21,26 @@ export interface DocComponentProps { } export function DocComponent

() { class Component extends React.Component> { + @observable _props!: React.PropsWithChildren

; + constructor(props: React.PropsWithChildren

) { + super(props); + this._props = props; + makeObservable(this); + } + componentDidUpdate() { + // untracked(() => (this._props = this.props)); + } //TODO This might be pretty inefficient if doc isn't observed, because computed doesn't cache then @computed get Document() { - return this.props.Document; + return this._props.Document; } // This is the rendering data of a document -- it may be "The Document", or it may be some template document that holds the rendering info @computed get layoutDoc() { - return this.props.LayoutTemplateString ? this.props.Document : Doc.Layout(this.props.Document, this.props.LayoutTemplate?.()); + return this._props.LayoutTemplateString ? this.Document : Doc.Layout(this.Document, this._props.LayoutTemplate?.()); } // This is the data part of a document -- ie, the data that is constant across all views of the document @computed get dataDoc() { - return this.props.Document[DocData] as Doc; + return this._props.Document[DocData] as Doc; } } return Component; @@ -49,22 +58,28 @@ interface ViewBoxBaseProps { } export function ViewBoxBaseComponent

() { class Component extends React.Component> { + @observable _props: React.PropsWithChildren

; + constructor(props: React.PropsWithChildren

) { + super(props); + this._props = props; + makeObservable(this); + } //TODO This might be pretty inefficient if doc isn't observed, because computed doesn't cache then //@computed get Document(): T { return schemaCtor(this.props.Document); } - @computed get Document() { - return this.props.Document; + get Document() { + return this._props.Document; } // This is the rendering data of a document -- it may be "The Document", or it may be some template document that holds the rendering info - @computed get layoutDoc() { - return Doc.Layout(this.props.Document); + get layoutDoc() { + return Doc.Layout(this.Document); } // This is the data part of a document -- ie, the data that is constant across all views of the document - @computed get dataDoc() { - return this.props.Document.isTemplateForField || this.props.Document.isTemplateDoc ? this.props.TemplateDataDocument ?? this.props.Document[DocData] : this.props.Document[DocData]; + get dataDoc() { + return this.Document.isTemplateForField || this.Document.isTemplateDoc ? this._props.TemplateDataDocument ?? this.Document[DocData] : this.Document[DocData]; } // key where data is stored - @computed get fieldKey() { - return this.props.fieldKey; + get fieldKey() { + return this._props.fieldKey; } } return Component; @@ -85,24 +100,30 @@ export interface ViewBoxAnnotatableProps { } export function ViewBoxAnnotatableComponent

() { class Component extends React.Component> { + @observable _props: React.PropsWithChildren

; + constructor(props: React.PropsWithChildren

) { + super(props); + this._props = props; + makeObservable(this); + } @observable _annotationKeySuffix = () => 'annotations'; @observable _isAnyChildContentActive = false; //TODO This might be pretty inefficient if doc isn't observed, because computed doesn't cache then @computed get Document() { - return this.props.Document; + return this._props.Document; } // This is the rendering data of a document -- it may be "The Document", or it may be some template document that holds the rendering info @computed get layoutDoc() { - return Doc.Layout(this.props.Document); + return Doc.Layout(this.Document); } // This is the data part of a document -- ie, the data that is constant across all views of the document @computed get dataDoc() { - return this.props.Document.isTemplateForField || this.props.Document.isTemplateDoc ? this.props.TemplateDataDocument ?? this.props.Document[DocData] : this.props.Document[DocData]; + return this.Document.isTemplateForField || this.Document.isTemplateDoc ? this._props.TemplateDataDocument ?? this.Document[DocData] : this.Document[DocData]; } // key where data is stored @computed get fieldKey() { - return this.props.fieldKey; + return this._props.fieldKey; } isAnyChildContentActive = () => this._isAnyChildContentActive; @@ -136,7 +157,7 @@ export function ViewBoxAnnotatableComponent

() if (targetDataDoc.isGroup && DocListCast(targetDataDoc[annotationKey ?? this.annotationKey]).length < 2) { (DocumentManager.Instance.getFirstDocumentView(targetDataDoc)?.ComponentView as CollectionFreeFormView)?.promoteCollection(); } else { - this.isAnyChildContentActive() && this.props.select(false); + this.isAnyChildContentActive() && this._props.select(false); } return true; } @@ -149,7 +170,7 @@ export function ViewBoxAnnotatableComponent

() // moving it into the target. @action.bound moveDocument = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[], annotationKey?: string) => boolean, annotationKey?: string): boolean => { - if (Doc.AreProtosEqual(this.props.Document, targetCollection)) { + if (Doc.AreProtosEqual(this._props.Document, targetCollection)) { return true; } const first = doc instanceof Doc ? doc : doc[0]; @@ -161,7 +182,7 @@ export function ViewBoxAnnotatableComponent

() @action.bound addDocument = (doc: Doc | Doc[], annotationKey?: string): boolean => { const docs = doc instanceof Doc ? [doc] : doc; - if (this.props.filterAddDocument?.(docs) === false || docs.find(doc => Doc.AreProtosEqual(doc, this.props.Document) && Doc.LayoutField(doc) === Doc.LayoutField(this.props.Document))) { + if (this._props.filterAddDocument?.(docs) === false || docs.find(doc => Doc.AreProtosEqual(doc, this.Document) && Doc.LayoutField(doc) === Doc.LayoutField(this.Document))) { return false; } const targetDataDoc = this.dataDoc; @@ -190,7 +211,7 @@ export function ViewBoxAnnotatableComponent

() return true; }; - whenChildContentsActiveChanged = action((isActive: boolean) => this.props.whenChildContentsActiveChanged((this._isAnyChildContentActive = isActive))); + whenChildContentsActiveChanged = action((isActive: boolean) => this._props.whenChildContentsActiveChanged((this._isAnyChildContentActive = isActive))); } return Component; } diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index a64722a0b..47ec0f1b4 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -1,7 +1,7 @@ import { IconProp } from '@fortawesome/fontawesome-svg-core'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Tooltip } from '@mui/material'; -import { action, computed, observable, runInAction } from 'mobx'; +import { action, computed, makeObservable, observable, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import { Doc } from '../../fields/Doc'; import { RichTextField } from '../../fields/RichTextField'; @@ -60,8 +60,11 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV public static hasPushedHack = false; public static hasPulledHack = false; + @observable _props: { views: () => (DocumentView | undefined)[] }; constructor(props: { views: () => (DocumentView | undefined)[] }) { super(props); + this._props = props; + makeObservable(this); runInAction(() => (DocumentButtonBar.Instance = this)); } @@ -111,12 +114,12 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV }); get view0() { - return this.props.views()?.[0]; + return this._props.views()?.[0]; } @computed get considerGoogleDocsPush() { - const targetDoc = this.view0?.props.Document; + const targetDoc = this.view0?.Document; const published = targetDoc && Doc.GetProto(targetDoc)[GoogleRef] !== undefined; const animation = this.isAnimatingPulse ? 'shadow-pulse 1s linear infinite' : 'none'; return !targetDoc ? null : ( @@ -143,7 +146,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV @computed get considerGoogleDocsPull() { - const targetDoc = this.view0?.props.Document; + const targetDoc = this.view0?.Document; const dataDoc = targetDoc && Doc.GetProto(targetDoc); const animation = this.isAnimatingFetch ? 'spin 0.5s linear infinite' : 'none'; @@ -214,7 +217,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV @observable subFollow = ''; @computed get followLinkButton() { - const targetDoc = this.view0?.props.Document; + const targetDoc = this.view0?.Document; const followBtn = (allDocs: boolean, click: (doc: Doc) => void, isSet: (doc?: Doc) => boolean, icon: IconProp) => { const tooltip = `Follow ${this.subPin}documents`; return !tooltip ? null : ( @@ -229,7 +232,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV onPointerEnter={action(e => (this.subPin = allDocs ? 'All ' : ''))} onPointerLeave={action(e => (this.subPin = ''))} onClick={e => { - this.props.views().forEach(dv => click(dv!.Document)); + this._props.views().forEach(dv => click(dv!.Document)); e.stopPropagation(); }} /> @@ -243,7 +246,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV

this.props.views().map(view => view?.docView?.toggleFollowLink(undefined, false)))}> + onClick={undoBatch(e => this._props.views().map(view => view?.docView?.toggleFollowLink(undefined, false)))}>
{followBtn( true, @@ -260,7 +263,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV @observable subLink = ''; @computed get linkButton() { - const targetDoc = this.view0?.props.Document; + const targetDoc = this.view0?.Document; return !targetDoc || !this.view0 ? null : (
@@ -304,7 +307,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV onPointerLeave={action(e => (this.subEndLink = ''))} onClick={e => { this.view0 && - DocumentLinksButton.finishLinkClick(e.clientX, e.clientY, DocumentLinksButton.StartLink, this.view0.props.Document, true, this.view0, { + DocumentLinksButton.finishLinkClick(e.clientX, e.clientY, DocumentLinksButton.StartLink, this.view0.Document, true, this.view0, { pinDocLayout: pinLayout, pinData: !pinContent ? {} : { poslayoutview: true, dataannos: true, dataview: pinContent }, } as PinProps); @@ -331,7 +334,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV @observable subPin = ''; @computed get pinButton() { - const targetDoc = this.view0?.props.Document; + const targetDoc = this.view0?.Document; const pinBtn = (pinLayoutView: boolean, pinContentView: boolean, icon: IconProp) => { const tooltip = `Pin Document and Save ${this.subPin} to trail`; return !tooltip ? null : ( @@ -353,7 +356,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV )} onPointerLeave={action(e => (this.subPin = ''))} onClick={e => { - const docs = this.props + const docs = this._props .views() .filter(v => v) .map(dv => dv!.Document); @@ -376,7 +379,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV
{ - const docs = this.props + const docs = this._props .views() .filter(v => v) .map(dv => dv!.Document); @@ -396,7 +399,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV @computed get shareButton() { - const targetDoc = this.view0?.props.Document; + const targetDoc = this.view0?.Document; return !targetDoc ? null : ( {'Open Sharing Manager'}
}>
SharingManager.Instance.open(this.view0, targetDoc)}> @@ -408,10 +411,10 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV @computed get menuButton() { - const targetDoc = this.view0?.props.Document; + const targetDoc = this.view0?.Document; return !targetDoc ? null : ( {`Open Context Menu`}
}> -
+
setupMoveUpEvents(this, e, returnFalse, emptyFunction, e => this.openContextMenu(e))}>
@@ -427,10 +430,10 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV anchorPoint={anchorPoints.LEFT_TOP} content={ dv) - .map(dv => dv!.props.Document)} + .map(dv => dv!.Document)} suggestWithFunction /> // tfs: @bcz This might need to be the data document? }> @@ -447,7 +450,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV _stopFunc: () => void = emptyFunction; @computed get recordButton() { - const targetDoc = this.view0?.props.Document; + const targetDoc = this.view0?.Document; return !targetDoc ? null : ( Press to record audio annotation
}>
(DocumentV style={{ backgroundColor: this._isRecording ? Colors.ERROR_RED : Colors.DARK_GRAY, color: Colors.WHITE }} onPointerDown={action((e: React.PointerEvent) => { this._isRecording = true; - this.props.views().map(view => view && DocumentViewInternal.recordAudioAnnotation(view.dataDoc, view.LayoutFieldKey, stopFunc => (this._stopFunc = stopFunc), emptyFunction)); + this._props.views().map(view => view && DocumentViewInternal.recordAudioAnnotation(view.dataDoc, view.LayoutFieldKey, stopFunc => (this._stopFunc = stopFunc), emptyFunction)); const b = UndoManager.StartBatch('Recording'); setupMoveUpEvents( this, @@ -482,8 +485,8 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV onEmbedButtonMoved = () => { if (this._dragRef.current) { const dragDocView = this.view0!; - const dragData = new DragManager.DocumentDragData([dragDocView.props.Document]); - const [left, top] = dragDocView.props.ScreenToLocalTransform().inverse().transformPoint(0, 0); + const dragData = new DragManager.DocumentDragData([dragDocView.Document]); + const [left, top] = dragDocView._props.ScreenToLocalTransform().inverse().transformPoint(0, 0); dragData.defaultDropAction = 'embed'; dragData.canEmbed = true; DragManager.StartDocumentDrag([dragDocView.ContentDiv!], dragData, left, top, { hideSource: false }); @@ -497,7 +500,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV @computed get templateButton() { const view0 = this.view0; - const views = this.props.views(); + const views = this._props.views(); return !view0 ? null : ( Tap to Customize Layout. Drag an embedding
} open={this._tooltipOpen} onClose={action(() => (this._tooltipOpen = false))} placement="bottom">
!this._ref.current?.getBoundingClientRect().width && (this._tooltipOpen = true))}> @@ -522,7 +525,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV ); } - openContextMenu = (e: React.MouseEvent) => { + openContextMenu = (e: PointerEvent) => { let child = SelectionManager.Views()[0].ContentDiv!.children[0]; while (child.children.length) { const next = Array.from(child.children).find(c => c.className?.toString().includes('SVGAnimatedString') || typeof c.className === 'string'); @@ -559,7 +562,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV @action toggleTrail = (e: React.PointerEvent) => { - const rootView = this.props.views()[0]; + const rootView = this._props.views()[0]; const doc = rootView?.Document; if (doc) { const anchor = rootView.ComponentView?.getAnchor?.(true) ?? doc; @@ -569,12 +572,12 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV anchor.presentationTrail = trail; } Doc.ActivePresentation = trail; - this.props.views().lastElement()?.props.addDocTab(trail, OpenWhere.replaceRight); + this._props.views().lastElement()?._props.addDocTab(trail, OpenWhere.replaceRight); } e.stopPropagation(); }; render() { - const doc = this.view0?.props.Document; + const doc = this.view0?.Document; if (!doc || !this.view0) return null; const isText = () => doc[this.view0!.LayoutFieldKey] instanceof RichTextField; @@ -589,9 +592,9 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV
(link.link_displayLine = !IsFollowLinkScript(this.props.views().lastElement()?.Document.onClick))} - linkCreateAnchor={() => this.props.views().lastElement()?.ComponentView?.getAnchor?.(true)} - linkFrom={() => this.props.views().lastElement()?.Document} + linkCreated={link => (link.link_displayLine = !IsFollowLinkScript(this._props.views().lastElement()?.Document.onClick))} + linkCreateAnchor={() => this._props.views().lastElement()?.ComponentView?.getAnchor?.(true)} + linkFrom={() => this._props.views().lastElement()?.Document} />
) : ( diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index b4c19df2d..6ef3fcc66 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,7 +1,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Tooltip } from '@mui/material'; import { IconButton } from 'browndash-components'; -import { action, computed, observable, runInAction } from 'mobx'; +import { action, computed, makeObservable, observable, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import { FaUndo } from 'react-icons/fa'; import { DateField } from '../../fields/DateField'; @@ -34,10 +34,15 @@ import { DocumentView, OpenWhereMod } from './nodes/DocumentView'; import { FormattedTextBox } from './nodes/formattedText/FormattedTextBox'; import { ImageBox } from './nodes/ImageBox'; import * as React from 'react'; -import * as _ from 'lodash'; +interface DocumentDecorationsProps { + PanelWidth: number; + PanelHeight: number; + boundsLeft: number; + boundsTop: number; +} @observer -export class DocumentDecorations extends React.Component<{ PanelWidth: number; PanelHeight: number; boundsLeft: number; boundsTop: number }, { value: string }> { +export class DocumentDecorations extends React.Component { static Instance: DocumentDecorations; private _resizeHdlId = ''; private _keyinput = React.createRef(); @@ -61,8 +66,11 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P @observable private _showRotCenter = false; // whether to show a draggable green dot that represents the center of rotation @observable private _rotCenter = [0, 0]; // the center of rotation in object coordinates (0,0) = object center (not top left!) - constructor(props: any) { + @observable _props: React.PropsWithChildren; + constructor(props: React.PropsWithChildren) { super(props); + this._props = props; + makeObservable(this); DocumentDecorations.Instance = this; document.addEventListener('pointermove', // show decorations whenever pointer moves outside of selection bounds. action(e => { @@ -78,8 +86,8 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P @computed get ClippedBounds() { const bounds = this.Bounds; - const leftBounds = this.props.boundsLeft; - const topBounds = LightboxView.LightboxDoc ? 0 : this.props.boundsTop; + const leftBounds = this._props.boundsLeft; + const topBounds = LightboxView.LightboxDoc ? 0 : this._props.boundsTop; bounds.x = Math.max(leftBounds, bounds.x - this._resizeBorderWidth / 2) + this._resizeBorderWidth / 2; bounds.y = Math.max(topBounds, bounds.y - this._resizeBorderWidth / 2 - this._titleHeight) + this._resizeBorderWidth / 2 + this._titleHeight; const borderRadiusDraggerWidth = 15; @@ -92,7 +100,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P return (LinkFollower.IsFollowing || DocumentView.ExploreMode) ? { x: 0, y: 0, r: 0, b: 0 } : SelectionManager.Views() - .filter(dv => dv.props.renderDepth > 0) + .filter(dv => dv._props.renderDepth > 0) .map(dv => dv.getBounds()) .reduce((bounds, rect) => !rect ? bounds : { x: Math.min(rect.left, bounds.x), @@ -198,12 +206,12 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P if (containers.size > 1) return false; const { left, top } = dragDocView.getBounds() || { left: 0, top: 0 }; const dragData = new DragManager.DocumentDragData( - SelectionManager.Views().map(dv => dv.props.Document), - dragDocView.props.dropAction + SelectionManager.Views().map(dv => dv.Document), + dragDocView._props.dropAction ); - dragData.offset = dragDocView.props.ScreenToLocalTransform().transformDirection(e.x - left, e.y - top); - dragData.moveDocument = dragDocView.props.moveDocument; - dragData.removeDocument = dragDocView.props.removeDocument; + dragData.offset = dragDocView._props.ScreenToLocalTransform().transformDirection(e.x - left, e.y - top); + dragData.moveDocument = dragDocView._props.moveDocument; + dragData.removeDocument = dragDocView._props.removeDocument; dragData.isDocDecorationMove = true; dragData.canEmbed = dragTitle; this._hidden = true; @@ -223,7 +231,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P _deleteAfterIconify = false; _iconifyBatch: UndoManager.Batch | undefined; onCloseClick = (forceDeleteOrIconify: boolean | undefined) => { - const views = SelectionManager.Views().filter(v => v && v.props.renderDepth > 0); + const views = SelectionManager.Views().filter(v => v && v._props.renderDepth > 0); if (forceDeleteOrIconify === false && this._iconifyBatch) return; this._deleteAfterIconify = forceDeleteOrIconify || this._iconifyBatch ? true : false; var iconifyingCount = views.length; @@ -231,11 +239,11 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P if ((force || --iconifyingCount === 0) && this._iconifyBatch) { if (this._deleteAfterIconify) { views.forEach(iconView => { - Doc.setNativeView(iconView.props.Document); - if (iconView.props.Document.activeFrame) { - iconView.props.Document.opacity = 0; // bcz: hacky ... allows inkMasks and other documents to be "turned off" without removing them from the animated collection which allows them to function properly in a presenation. + Doc.setNativeView(iconView.Document); + if (iconView.Document.activeFrame) { + iconView.Document.opacity = 0; // bcz: hacky ... allows inkMasks and other documents to be "turned off" without removing them from the animated collection which allows them to function properly in a presenation. } else { - iconView.props.removeDocument?.(iconView.props.Document); + iconView._props.removeDocument?.(iconView.Document); } }); views.forEach(SelectionManager.DeselectView); @@ -296,7 +304,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P SelectionManager.DeselectAll(); }; - onSelectContainerDocClick = () => SelectionManager.Views()?.[0]?.props.docViewPath?.().lastElement()?.select(false); + onSelectContainerDocClick = () => SelectionManager.Views()?.[0]?._props.docViewPath?.().lastElement()?.select(false); /** * sets up events when user clicks on the border radius editor */ @@ -344,7 +352,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P }; setRotateCenter = (seldocview: DocumentView, rotCenter: number[]) => { - const newloccentern = seldocview.props.ScreenToLocalTransform().transformPoint(rotCenter[0], rotCenter[1]); + const newloccentern = seldocview._props.ScreenToLocalTransform().transformPoint(rotCenter[0], rotCenter[1]); const newlocenter = [newloccentern[0] - NumCast(seldocview.layoutDoc._width) / 2, newloccentern[1] - NumCast(seldocview.layoutDoc._height) / 2]; const final = Utils.rotPt(newlocenter[0], newlocenter[1], -(NumCast(seldocview.Document._rotation) / 180) * Math.PI); seldocview.Document.rotation_centerX = final.x / NumCast(seldocview.layoutDoc._width); @@ -376,7 +384,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P const seldocview = SelectionManager.Views()[0]; SelectionManager.Views().forEach(dv => { const accumRot = (NumCast(dv.Document._rotation) / 180) * Math.PI; - const localRotCtr = dv.props.ScreenToLocalTransform().transformPoint(rcScreen.X, rcScreen.Y); + const localRotCtr = dv._props.ScreenToLocalTransform().transformPoint(rcScreen.X, rcScreen.Y); const localRotCtrOffset = [localRotCtr[0] - NumCast(dv.Document.width) / 2, localRotCtr[1] - NumCast(dv.Document.height) / 2]; const startRotCtr = Utils.rotPt(localRotCtrOffset[0], localRotCtrOffset[1], -accumRot); const unrotatedDocPos = { x: NumCast(dv.Document.x) + localRotCtrOffset[0] - startRotCtr.x, y: NumCast(dv.Document.y) + localRotCtrOffset[1] - startRotCtr.y }; @@ -454,7 +462,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P dot = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]); return [a[0] + atob[0] * t, a[1] + atob[1] * t]; }; - const tl = docView.props.ScreenToLocalTransform().inverse().transformPoint(0, 0); + const tl = docView._props.ScreenToLocalTransform().inverse().transformPoint(0, 0); return project([e.clientX + this._offset.x, e.clientY + this._offset.y], tl, [tl[0] + fixedAspect, tl[1] + 1]); }; onPointerMove = (e: PointerEvent, down: number[], move: number[]): boolean => { @@ -475,7 +483,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P !this._interactionLock && runInAction(async () => { // resize selected docs if we're not in the middle of a resize (ie, throttle input events to frame rate) this._interactionLock = true; this._snapPt = thisPt; - e.ctrlKey && (SelectionManager.Views().forEach(docView => !Doc.NativeHeight(docView.props.Document) && docView.toggleNativeDimensions())); + e.ctrlKey && (SelectionManager.Views().forEach(docView => !Doc.NativeHeight(docView.Document) && docView.toggleNativeDimensions())); const fixedAspect = SelectionManager.Docs().some(this.hasFixedAspect); const scaleAspect = {x:scale.x === 1 && fixedAspect ? scale.y : scale.x, y: scale.x !== 1 && fixedAspect ? scale.x : scale.y}; SelectionManager.Views().forEach(docView => @@ -522,7 +530,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P doc.xPadding = NumCast(doc.xPadding) * scale.x; doc.yPadding = NumCast(doc.yPadding) * scale.y; } else { - const refCent = docView.props.ScreenToLocalTransform().transformPoint(refPt[0], refPt[1]); // fixed reference point for resize (ie, a point that doesn't move) + const refCent = docView._props.ScreenToLocalTransform().transformPoint(refPt[0], refPt[1]); // fixed reference point for resize (ie, a point that doesn't move) const [nwidth, nheight] = [docView.nativeWidth, docView.nativeHeight]; const [initWidth, initHeight] = [NumCast(doc._width, 1), NumCast(doc._height)]; @@ -615,7 +623,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P return ScriptField.MakeFunction(this._titleControlString.substring(1), { doc: Doc.name })!.script.run({ self: selected.Document, this: selected.layoutDoc }, console.log).result?.toString() || ''; } if (this._titleControlString.startsWith('#')) { - return Field.toString(selected.props.Document[this._titleControlString.substring(1)] as Field) || '-unset-'; + return Field.toString(selected.Document[this._titleControlString.substring(1)] as Field) || '-unset-'; } return this._accumulatedTitle; } @@ -625,7 +633,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P @computed get rotCenter() { const lastView = SelectionManager.Views().lastElement(); if (lastView) { - const invXf = lastView.props.ScreenToLocalTransform().inverse(); + const invXf = lastView._props.ScreenToLocalTransform().inverse(); const seldoc = lastView.layoutDoc; const loccenter = Utils.rotPt(NumCast(seldoc.rotation_centerX) * NumCast(seldoc._width), NumCast(seldoc.rotation_centerY) * NumCast(seldoc._height), invXf.Rotate); return invXf.transformPoint(loccenter.x + NumCast(seldoc._width) / 2, loccenter.y + NumCast(seldoc._height) / 2); @@ -648,16 +656,16 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P var shareSymbolIcon = ReverseHierarchyMap.get(shareMode)?.image; // hide the decorations if the parent chooses to hide it or if the document itself hides it - const hideDecorations = SnappingManager.GetIsResizing() || seldocview.props.hideDecorations || seldocview.Document.layout_hideDecorations; + const hideDecorations = SnappingManager.GetIsResizing() || seldocview._props.hideDecorations || seldocview.Document.layout_hideDecorations; const hideResizers = - ![AclAdmin, AclEdit, AclAugment].includes(GetEffectiveAcl(seldocview.Document)) || hideDecorations || seldocview.props.hideResizeHandles || seldocview.Document.layout_hideResizeHandles || this._isRounding || this._isRotating; - const hideTitle = this._showNothing || hideDecorations || seldocview.props.hideDecorationTitle || seldocview.Document.layout_hideDecorationTitle || this._isRounding || this._isRotating; - const hideDocumentButtonBar = hideDecorations || seldocview.props.hideDocumentButtonBar || seldocview.Document.layout_hideDocumentButtonBar || this._isRounding || this._isRotating; + ![AclAdmin, AclEdit, AclAugment].includes(GetEffectiveAcl(seldocview.Document)) || hideDecorations || seldocview._props.hideResizeHandles || seldocview.Document.layout_hideResizeHandles || this._isRounding || this._isRotating; + const hideTitle = this._showNothing || hideDecorations || seldocview._props.hideDecorationTitle || seldocview.Document.layout_hideDecorationTitle || this._isRounding || this._isRotating; + const hideDocumentButtonBar = hideDecorations || seldocview._props.hideDocumentButtonBar || seldocview.Document.layout_hideDocumentButtonBar || this._isRounding || this._isRotating; // if multiple documents have been opened at the same time, then don't show open button const hideOpenButton = this._showNothing || hideDecorations || - seldocview.props.hideOpenButton || + seldocview._props.hideOpenButton || seldocview.Document.layout_hideOpenButton || SelectionManager.Views().some(docView => docView.Document._dragOnlyWithinContainer || docView.Document.isGroup || docView.Document.layout_hideOpenButton) || this._isRounding || @@ -667,10 +675,10 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P hideDecorations || this._isRounding || this._isRotating || - seldocview.props.hideDeleteButton || + seldocview._props.hideDeleteButton || seldocview.Document.hideDeleteButton || SelectionManager.Views().some(docView => { - const collectionAcl = docView.props.docViewPath()?.lastElement() ? GetEffectiveAcl(docView.props.docViewPath().lastElement().dataDoc) : AclEdit; + const collectionAcl = docView._props.docViewPath()?.lastElement() ? GetEffectiveAcl(docView._props.docViewPath().lastElement().dataDoc) : AclEdit; return collectionAcl !== AclAdmin && collectionAcl !== AclEdit && GetEffectiveAcl(docView.Document) !== AclAdmin; }); const topBtn = (key: string, icon: string, pointerDown: undefined | ((e: React.PointerEvent) => void), click: undefined | ((e: any) => void), title: string) => ( @@ -798,7 +806,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P
)} - {seldocview.props.renderDepth <= 1 || !seldocview.props.docViewPath().lastElement() ? null : topBtn('selector', 'arrow-alt-circle-up', undefined, this.onSelectContainerDocClick, 'tap to select containing document')} + {seldocview._props.renderDepth <= 1 || !seldocview._props.docViewPath().lastElement() ? null : topBtn('selector', 'arrow-alt-circle-up', undefined, this.onSelectContainerDocClick, 'tap to select containing document')} {useRounding && (
{ _editingDisposer?: IReactionDisposer; @observable _editing: boolean = false; + _prevProps: EditableProps; + @observable _props: EditableProps; constructor(props: EditableProps) { super(props); - this._editing = this.props.editing ? true : false; + this._props = this._prevProps = props; + makeObservable(this); + this._editing = this._props.editing ? true : false; } componentDidMount(): void { @@ -89,12 +96,12 @@ export class EditableView extends React.Component { ); } - @action componentDidUpdate() { - if (this._editing && this.props.editing === false) { + copyProps(this); + if (this._editing && this._props.editing === false) { this._inputref?.value && this.finalizeEdit(this._inputref.value, false, true, false); - } else if (this.props.editing !== undefined) { - this._editing = this.props.editing; + } else if (this._props.editing !== undefined) { + this._editing = this._props.editing; } } @@ -120,28 +127,28 @@ export class EditableView extends React.Component { case 'Tab': e.stopPropagation(); this.finalizeEdit(e.currentTarget.value, e.shiftKey, false, false); - this.props.OnTab?.(e.shiftKey); + this._props.OnTab?.(e.shiftKey); break; case 'Backspace': e.stopPropagation(); - if (!e.currentTarget.value) this.props.OnEmpty?.(); + if (!e.currentTarget.value) this._props.OnEmpty?.(); break; case 'Enter': - if (this.props.allowCRs !== true) { + if (this._props.allowCRs !== true) { e.stopPropagation(); if (!e.ctrlKey) { this.finalizeEdit(e.currentTarget.value, e.shiftKey, false, true); - } else if (this.props.OnFillDown) { - this.props.OnFillDown(e.currentTarget.value); + } else if (this._props.OnFillDown) { + this._props.OnFillDown(e.currentTarget.value); this._editing = false; - this.props.isEditingCallback?.(false); + this._props.isEditingCallback?.(false); } } break; case 'Escape': e.stopPropagation(); this._editing = false; - this.props.isEditingCallback?.(false); + this._props.isEditingCallback?.(false); break; case 'ArrowUp': case 'ArrowDown': @@ -155,30 +162,30 @@ export class EditableView extends React.Component { case 'Control': break; case ':': - if (this.props.menuCallback) { + if (this._props.menuCallback) { e.stopPropagation(); - this.props.menuCallback(e.currentTarget.getBoundingClientRect().x, e.currentTarget.getBoundingClientRect().y); + this._props.menuCallback(e.currentTarget.getBoundingClientRect().x, e.currentTarget.getBoundingClientRect().y); break; } default: - if (this.props.textCallback?.(e.key)) { + if (this._props.textCallback?.(e.key)) { e.stopPropagation(); this._editing = false; - this.props.isEditingCallback?.(false); + this._props.isEditingCallback?.(false); } } }; @action onClick = (e: React.MouseEvent) => { - if (this.props.editing !== false) { + if (this._props.editing !== false) { e.nativeEvent.stopPropagation(); - if (this._ref.current && this.props.showMenuOnLoad) { - this.props.menuCallback?.(this._ref.current.getBoundingClientRect().x, this._ref.current.getBoundingClientRect().y); + if (this._ref.current && this._props.showMenuOnLoad) { + this._props.menuCallback?.(this._ref.current.getBoundingClientRect().x, this._ref.current.getBoundingClientRect().y); } else { this._editing = true; - this.props.isEditingCallback?.(true); + this._props.isEditingCallback?.(true); } // e.stopPropagation(); } @@ -186,17 +193,17 @@ export class EditableView extends React.Component { @action finalizeEdit(value: string, shiftDown: boolean, lostFocus: boolean, enterKey: boolean) { - if (this.props.SetValue(value, shiftDown, enterKey)) { + if (this._props.SetValue(value, shiftDown, enterKey)) { this._editing = false; - this.props.isEditingCallback?.(false); + this._props.isEditingCallback?.(false); } else { this._editing = false; - this.props.isEditingCallback?.(false); + this._props.isEditingCallback?.(false); !lostFocus && setTimeout( action(() => { this._editing = true; - this.props.isEditingCallback?.(true); + this._props.isEditingCallback?.(true); }), 0 ); @@ -215,9 +222,9 @@ export class EditableView extends React.Component { }; renderEditor() { - return this.props.autosuggestProps ? ( + return this._props.autosuggestProps ? ( { onClick: this.stopPropagation, onPointerUp: this.stopPropagation, onKeyPress: this.stopPropagation, - value: this.props.autosuggestProps.value, + value: this._props.autosuggestProps.value, // @ts-ignore - onChange: this.props.autosuggestProps.onChange, + onChange: this._props.autosuggestProps.onChange, }} /> - ) : this.props.oneLine !== false && this.props.GetValue()?.toString().indexOf('\n') === -1 ? ( + ) : this._props.oneLine !== false && this._props.GetValue()?.toString().indexOf('\n') === -1 ? ( (this._inputref = r)} - style={{ display: this.props.display, overflow: 'auto', fontSize: this.props.fontSize, minWidth: 20, background: this.props.background }} - placeholder={this.props.placeholder} + style={{ display: this._props.display, overflow: 'auto', fontSize: this._props.fontSize, minWidth: 20, background: this._props.background }} + placeholder={this._props.placeholder} onBlur={e => this.finalizeEdit(e.currentTarget.value, false, true, false)} - defaultValue={this.props.GetValue()} + defaultValue={this._props.GetValue()} autoFocus={true} onChange={this.onChange} onKeyDown={this.onKeyDown} @@ -253,10 +260,10 @@ export class EditableView extends React.Component {