From e4a3b962f8de00f5bc0463bed886d9f8f526ff89 Mon Sep 17 00:00:00 2001 From: bobzel Date: Mon, 20 Nov 2023 09:09:50 -0500 Subject: fixes for selecting/moving docs that are rotated. --- src/client/util/DragManager.ts | 16 ++- src/client/views/DocumentDecorations.tsx | 23 ++++- .../collectionFreeForm/CollectionFreeFormView.tsx | 26 ++--- .../views/nodes/CollectionFreeFormDocumentView.tsx | 3 +- src/client/views/nodes/WebBoxRenderer.js | 113 +++++++++++---------- 5 files changed, 104 insertions(+), 77 deletions(-) (limited to 'src') diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index f928a1bf9..6e4de252d 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -8,6 +8,7 @@ import { ScriptCast, StrCast } from '../../fields/Types'; import { emptyFunction, Utils } from '../../Utils'; import { Docs, DocUtils } from '../documents/Documents'; import * as globalCssVariables from '../views/global/globalCssVariables.scss'; +import { CollectionFreeFormDocumentView } from '../views/nodes/CollectionFreeFormDocumentView'; import { DocumentView } from '../views/nodes/DocumentView'; import { ScriptingGlobals } from './ScriptingGlobals'; import { SelectionManager } from './SelectionManager'; @@ -360,11 +361,18 @@ export namespace DragManager { const docsToDrag = dragData instanceof DocumentDragData ? dragData.draggedDocuments : dragData instanceof AnchorAnnoDragData ? [dragData.dragDocument] : []; const dragElements = eles.map(ele => { // bcz: very hacky -- if dragged element is a freeForm view with a rotation, then extract the rotation in order to apply it to the dragged element - let useDim = false; // if doc is rotated by freeformview, then the dragged elements width and height won't reflect the unrotated dimensions, so we need to rely on the element knowing its own width/height. \ + // bcz: used to be false, but that made dragging collection w/ native dim's not work... + let useDim = true; // if doc is rotated by freeformview, then the dragged elements width and height won't reflect the unrotated dimensions, so we need to rely on the element knowing its own width/height. \ // if the parent isn't a freeform view, then the element's width and height are presumed to match the acutal doc's dimensions (eg, dragging from import sidebar menu) - if (ele?.parentElement?.parentElement?.parentElement?.className === 'collectionFreeFormDocumentView-container') { - ele = ele.parentElement.parentElement.parentElement; - rot.push(Number(ele.style.transform.replace(/.*rotate\(([-0-9.e]*)deg\).*/, '$1') || 0)); + let rotation: number | undefined; + for (let parEle: HTMLElement | null | undefined = ele.parentElement; parEle; parEle = parEle?.parentElement) { + if (parEle.className === CollectionFreeFormDocumentView.CollectionFreeFormDocViewClassName) { + rotation = (rotation ?? 0) + Number(parEle.style.transform.replace(/.*rotate\(([-0-9.e]*)deg\).*/, '$1') || 0); + } + parEle = parEle.parentElement; + } + if (rotation !== undefined) { + rot.push(rotation); } else { useDim = true; rot.push(0); diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 77554bd51..6663c5ee8 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 '@material-ui/core'; import { IconButton } from 'browndash-components'; -import { action, computed, observable, reaction, runInAction } from 'mobx'; +import { action, computed, observable, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import { FaUndo } from 'react-icons/fa'; import { DateField } from '../../fields/DateField'; @@ -65,7 +65,17 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P super(props); DocumentDecorations.Instance = this; document.addEventListener('pointermove', // show decorations whenever pointer moves outside of selection bounds. - action(e => (this._showNothing = !(this.Bounds.x !== Number.MAX_VALUE && (this.Bounds.x > e.clientX + this._resizeBorderWidth / 2 || this.Bounds.r < e.clientX - this._resizeBorderWidth / 2 || this.Bounds.y > e.clientY + this._resizeBorderWidth / 2 || this.Bounds.b < e.clientY - this._resizeBorderWidth / 2))))); // prettier-ignore + action(e => { + const center = {x: (this.Bounds.x+this.Bounds.r)/2, y: (this.Bounds.y+this.Bounds.b)/2}; + const {x,y} = Utils.rotPt(e.clientX - center.x, + e.clientY - center.y, + -NumCast(SelectionManager.Docs().lastElement()?.rotation)/180*Math.PI); + (this._showNothing = !(this.Bounds.x !== Number.MAX_VALUE && // + (this.Bounds.x > center.x+x + this._resizeBorderWidth / 2 || + this.Bounds.r < center.x+x - this._resizeBorderWidth / 2 || + this.Bounds.y > center.y+y + this._resizeBorderWidth / 2 || + this.Bounds.b < center.y+y - this._resizeBorderWidth / 2))); + })); // prettier-ignore } @computed get ClippedBounds() { @@ -524,7 +534,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P (doc.layout_reflowVertical && (opts.dragHdl === 'bottom' || opts.dragHdl === 'top' || opts.ctrlKey)); // eg rtf, web, pdf if (nwidth && nheight && !modifyNativeDim) { // eg., dragging right resizer on PDF -- enforce native dimensions because not expliclty overridden with ctrl or bottom resize drag - scale.x === 1 ? (scale.x = scale.y) : (scale.x = scale.x); + scale.x === 1 ? (scale.x = scale.y) : (scale.y = scale.x); } if (['right', 'left'].includes(opts.dragHdl) && modifyNativeDim && Doc.NativeWidth(doc)) { @@ -688,7 +698,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P const bounds = this.ClippedBounds; const useLock = bounds.r - bounds.x > 135 && seldocview.CollectionFreeFormDocumentView; const useRotation = !hideResizers && seldocview.rootDoc.type !== DocumentType.EQUATION && seldocview.CollectionFreeFormDocumentView; // when do we want an object to not rotate? - const rotation = SelectionManager.Views().length == 1 ? NumCast(seldocview.rootDoc._rotation) : 0; + const rotation = SelectionManager.Views().length == 1 ? seldocview.docViewPath.reduce((rot, view) => rot + NumCast(view.rootDoc._rotation), 0) : 0; // Radius constants const useRounding = seldocview.ComponentView instanceof ImageBox || seldocview.ComponentView instanceof FormattedTextBox || seldocview.ComponentView instanceof CollectionFreeFormView; @@ -748,6 +758,8 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P )} ); + const centery = hideTitle ? 0 : this._titleHeight; + const transformOrigin = `${50}% calc(50% + ${centery / 2}px)`; const freeformDoc = SelectionManager.Views().some(v => v.CollectionFreeFormDocumentView); return (
@@ -758,9 +770,11 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P height: bounds.b - bounds.y + this._resizeBorderWidth + 'px', left: bounds.x - this._resizeBorderWidth / 2, top: bounds.y - this._resizeBorderWidth / 2, + transformOrigin, background: SnappingManager.GetShiftKey() ? undefined : 'yellow', pointerEvents: SnappingManager.GetShiftKey() || DocumentView.Interacting ? 'none' : 'all', display: SelectionManager.Views().length <= 1 || hideDecorations ? 'none' : undefined, + transform: `rotate(${rotation}deg)`, }} onPointerDown={this.onBackgroundDown} /> @@ -770,6 +784,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P className={`documentDecorations-container ${this._showNothing ? 'showNothing' : ''}`} style={{ transform: `translate(${bounds.x - this._resizeBorderWidth / 2}px, ${bounds.y - this._resizeBorderWidth / 2 - this._titleHeight}px) rotate(${rotation}deg)`, + transformOrigin, width: bounds.r - bounds.x + this._resizeBorderWidth + 'px', height: bounds.b - bounds.y + this._resizeBorderWidth + (this._showNothing ? 0 : this._titleHeight) + 'px', }}> diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 45af1064a..75e27aa43 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -341,16 +341,17 @@ export class CollectionFreeFormView extends CollectionSubView= panX + panelWidMax / 2) panX = ranges.xrange.max + (this.props.originTopLeft ? 0 : panelWidMax / 2); else if (ranges.xrange.max <= panX - panelWidMin / 2) panX = ranges.xrange.min - (this.props.originTopLeft ? panelWidMax / 2 : panelWidMin / 2); if (ranges.yrange.min >= panY + panelHgtMax / 2) panY = ranges.yrange.max + (this.props.originTopLeft ? 0 : panelHgtMax / 2); @@ -1537,8 +1539,8 @@ export class CollectionFreeFormView extends CollectionSubView { this.dataDoc.icon = new ImageField(iconFile); - this.dataDoc['icon_nativeWidth'] = nativeWidth; - this.dataDoc['icon_nativeHeight'] = nativeHeight; + this.dataDoc.icon_nativeWidth = nativeWidth; + this.dataDoc.icon_nativeHeight = nativeHeight; } ); diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index 582a5518a..5fbe5d0e3 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -239,12 +239,13 @@ export class CollectionFreeFormDocumentView extends DocComponent key.startsWith('w_'))).omit; // prettier-ignore return (
{ const reader = new FileReader(); reader.readAsDataURL(binStr); reader.onloadend = function () { @@ -31,17 +31,17 @@ var ForeignHtmlRenderer = function (styleSheets) { * @returns {Promise} */ const getResourceAsBase64 = function (webUrl, inurl) { - return new Promise(function (resolve, reject) { + return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); - //const url = inurl.startsWith("/") && !inurl.startsWith("//") ? webUrl + inurl : inurl; - //const url = CorsProxy(inurl.startsWith("/") && !inurl.startsWith("//") ? webUrl + inurl : inurl);// inurl.startsWith("http") ? CorsProxy(inurl) : inurl; - var url = inurl; + // const url = inurl.startsWith("/") && !inurl.startsWith("//") ? webUrl + inurl : inurl; + // const url = CorsProxy(inurl.startsWith("/") && !inurl.startsWith("//") ? webUrl + inurl : inurl);// inurl.startsWith("http") ? CorsProxy(inurl) : inurl; + let url = inurl; if (inurl.startsWith('/static')) { url = new URL(webUrl).origin + inurl; } else if (inurl.startsWith('/') && !inurl.startsWith('//')) { url = CorsProxy(new URL(webUrl).origin + inurl); } else if (!inurl.startsWith('http') && !inurl.startsWith('//')) { - url = CorsProxy(webUrl + '/' + inurl); + url = CorsProxy(`${webUrl}/${inurl}`); } else if (inurl.startsWith('https') && !inurl.startsWith(window.location.origin)) { url = CorsProxy(inurl); } @@ -57,7 +57,7 @@ var ForeignHtmlRenderer = function (styleSheets) { resourceBase64: resBase64, }); } else if (xhr.readyState === XMLHttpRequest.DONE) { - console.log("COULDN'T FIND: " + (inurl.startsWith('/') ? webUrl + inurl : inurl)); + console.log(`COULDN'T FIND: ${inurl.startsWith('/') ? webUrl + inurl : inurl}`); resolve({ resourceUrl: '', resourceBase64: inurl, @@ -76,7 +76,7 @@ var ForeignHtmlRenderer = function (styleSheets) { */ const getMultipleResourcesAsBase64 = function (webUrl, urls) { const promises = []; - for (let i = 0; i < urls.length; i++) { + for (let i = 0; i < urls.length; i += 1) { promises.push(getResourceAsBase64(webUrl, urls[i])); } return Promise.all(promises); @@ -98,7 +98,7 @@ var ForeignHtmlRenderer = function (styleSheets) { } let val = ''; - for (let i = idx + prefixToken.length; i < str.length; i++) { + for (let i = idx + prefixToken.length; i < str.length; i += 1) { if (suffixTokens.indexOf(str[i]) !== -1) { break; } @@ -112,6 +112,15 @@ var ForeignHtmlRenderer = function (styleSheets) { }; }; + /** + * + * @param {String} str + * @returns {String} + */ + const removeQuotes = function (str) { + return str.replace(/["']/g, ''); + }; + /** * * @param {String} cssRuleStr @@ -127,13 +136,12 @@ var ForeignHtmlRenderer = function (styleSheets) { break; } searchStartIndex = url.foundAtIndex + url.value.length + 1; - if (mustEndWithQuote && url.value[url.value.length - 1] !== '"') continue; - const unquoted = removeQuotes(url.value); - if (!unquoted /* || (!unquoted.startsWith('http')&& !unquoted.startsWith("/") )*/ || unquoted === 'http://' || unquoted === 'https://') { - continue; + if (!mustEndWithQuote || url.value[url.value.length - 1] === '"') { + const unquoted = removeQuotes(url.value); + if (unquoted /* || (!unquoted.startsWith('http')&& !unquoted.startsWith("/") ) */ && unquoted !== 'http://' && unquoted !== 'https://') { + if (unquoted) urlsFound.push(unquoted); + } } - - unquoted && urlsFound.push(unquoted); } return urlsFound; @@ -151,15 +159,6 @@ var ForeignHtmlRenderer = function (styleSheets) { return getUrlsFromCssString(html, 'source=', [' ', '>', '\t'], true); }; - /** - * - * @param {String} str - * @returns {String} - */ - const removeQuotes = function (str) { - return str.replace(/["']/g, ''); - }; - const escapeRegExp = function (string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }; @@ -172,8 +171,8 @@ var ForeignHtmlRenderer = function (styleSheets) { * * @returns {Promise} */ - const buildSvgDataUri = async function (webUrl, contentHtml, width, height, scroll, xoff) { - return new Promise(async function (resolve, reject) { + const buildSvgDataUri = async function (webUrl, inputContentHtml, width, height, scroll, xoff) { + return new Promise(async (resolve, reject) => { /* !! The problems !! * 1. CORS (not really an issue, expect perhaps for images, as this is a general security consideration to begin with) * 2. Platform won't wait for external assets to load (fonts, images, etc.) @@ -181,17 +180,19 @@ var ForeignHtmlRenderer = function (styleSheets) { // copy styles let cssStyles = ''; - let urlsFoundInCss = []; + const urlsFoundInCss = []; - for (let i = 0; i < styleSheets.length; i++) { + for (let i = 0; i < styleSheets.length; i += 1) { try { const rules = styleSheets[i].cssRules; - for (let j = 0; j < rules.length; j++) { + for (let j = 0; j < rules.length; j += 1) { const cssRuleStr = rules[j].cssText; urlsFoundInCss.push(...getUrlsFromCssString(cssRuleStr)); cssStyles += cssRuleStr; } - } catch (e) {} + } catch (e) { + /* empty */ + } } // const fetchedResourcesFromStylesheets = await getMultipleResourcesAsBase64(webUrl, urlsFoundInCss); @@ -202,15 +203,15 @@ var ForeignHtmlRenderer = function (styleSheets) { // } // } - contentHtml = contentHtml + let contentHtml = inputContentHtml .replace(/]*>/g, '') // tags have a which has a srcset field of image refs. instead of converting each, just use the default of the picture .replace(/noscript/g, 'div') .replace(/
<\/div>/g, '') // when scripting isn't available (ie, rendering web pages here),