diff options
author | geireann <geireann.lindfield@gmail.com> | 2024-07-24 17:13:46 -0400 |
---|---|---|
committer | geireann <geireann.lindfield@gmail.com> | 2024-07-24 17:13:46 -0400 |
commit | 9c91debc77000470642d5ddd28b24f3b02d35eb6 (patch) | |
tree | efb5da1388a5e85abe78f4d2e9f58392beed670c /src | |
parent | 740d588a4cd5df9877664877149120bf4cacacaa (diff) |
switched to using textfit for label fitting text.
Diffstat (limited to 'src')
-rw-r--r-- | src/client/views/nodes/LabelBigText.js | 270 | ||||
-rw-r--r-- | src/client/views/nodes/LabelBox.tsx | 215 |
2 files changed, 89 insertions, 396 deletions
diff --git a/src/client/views/nodes/LabelBigText.js b/src/client/views/nodes/LabelBigText.js deleted file mode 100644 index 290152cd0..000000000 --- a/src/client/views/nodes/LabelBigText.js +++ /dev/null @@ -1,270 +0,0 @@ -/* -Brorlandi/big-text.js v1.0.0, 2017 -Adapted from DanielHoffmann/jquery-bigtext, v1.3.0, May 2014 -And from Jetroid/bigtext.js v1.0.0, September 2016 - -Usage: -BigText("#myElement",{ - rotateText: {Number}, (null) - fontSizeFactor: {Number}, (0.8) - maximumFontSize: {Number}, (null) - limitingDimension: {String}, ("both") - horizontalAlign: {String}, ("center") - verticalAlign: {String}, ("center") - textAlign: {String}, ("center") - whiteSpace: {String}, ("nowrap") -}); - - -Original Projects: -https://github.com/DanielHoffmann/jquery-bigtext -https://github.com/Jetroid/bigtext.js - -Options: - -rotateText: Rotates the text inside the element by X degrees. - -fontSizeFactor: This option is used to give some vertical spacing for letters that overflow the line-height (like 'g', 'Á' and most other accentuated uppercase letters). This does not affect the font-size if the limiting factor is the width of the parent div. The default is 0.8 - -maximumFontSize: maximum font size to use. - -minimumFontSize: minimum font size to use. if font is calculated smaller than this, text will be rendered at this size and wrapped - -limitingDimension: In which dimension the font size should be limited. Possible values: "width", "height" or "both". Defaults to both. Using this option with values different than "both" overwrites the element parent width or height. - -horizontalAlign: Where to align the text horizontally. Possible values: "left", "center", "right". Defaults to "center". - -verticalAlign: Where to align the text vertically. Possible values: "top", "center", "bottom". Defaults to "center". - -textAlign: Sets the text align of the element. Possible values: "left", "center", "right". Defaults to "center". This option is only useful if there are linebreaks (<br> tags) inside the text. - -whiteSpace: Sets whitespace handling. Possible values: "nowrap", "pre". Defaults to "nowrap". (Can also be set to enable wrapping but this doesn't work well.) - -Bruno Orlandi - 2017 - -Copyright (C) 2013 Daniel Hoffmann Bernardes, Ícaro Technologies -Copyright (C) 2016 Jet Holt - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -function _calculateInnerDimensions(computedStyle) { - //Calculate the inner width and height - var innerWidth; - var innerHeight; - - var width = parseInt(computedStyle.getPropertyValue("width")); - var height = parseInt(computedStyle.getPropertyValue("height")); - var paddingLeft = parseInt(computedStyle.getPropertyValue("padding-left")); - var paddingRight = parseInt(computedStyle.getPropertyValue("padding-right")); - var paddingTop = parseInt(computedStyle.getPropertyValue("padding-top")); - var paddingBottom = parseInt(computedStyle.getPropertyValue("padding-bottom")); - var borderLeft = parseInt(computedStyle.getPropertyValue("border-left-width")); - var borderRight = parseInt(computedStyle.getPropertyValue("border-right-width")); - var borderTop = parseInt(computedStyle.getPropertyValue("border-top-width")); - var borderBottom = parseInt(computedStyle.getPropertyValue("border-bottom-width")); - - //If box-sizing is border-box, we need to subtract padding and border. - var parentBoxSizing = computedStyle.getPropertyValue("box-sizing"); - if (parentBoxSizing == "border-box") { - innerWidth = width - (paddingLeft + paddingRight + borderLeft + borderRight); - innerHeight = height - (paddingTop + paddingBottom + borderTop + borderBottom); - } else { - innerWidth = width; - innerHeight = height; - } - var obj = {}; - obj["width"] = innerWidth; - obj["height"] = innerHeight; - return obj; -} - -export default function BigText(element, options) { - - if (typeof element === 'string') { - element = document.querySelector(element); - } else if (element.length) { - // Support for array based queries (such as jQuery) - element = element[0]; - } - - var defaultOptions = { - rotateText: null, - fontSizeFactor: 0.8, - maximumFontSize: null, - limitingDimension: "both", - horizontalAlign: "center", - verticalAlign: "center", - textAlign: "center", - whiteSpace: "nowrap", - singleLine: true - }; - - //Merge provided options and default options - options = options || {}; - for (var opt in defaultOptions) - if (defaultOptions.hasOwnProperty(opt) && !options.hasOwnProperty(opt)) - options[opt] = defaultOptions[opt]; - - //Get variables which we will reference frequently - var style = element.style; - var parent = element.parentNode; - var parentStyle = parent.style; - var parentComputedStyle = document.defaultView.getComputedStyle(parent); - - //hides the element to prevent "flashing" - style.visibility = "hidden"; - //Set some properties - style.display = "inline-block"; - style.clear = "both"; - style.float = "left"; - var fontSize = options.maximumFontSize; - if (options.singleLine) { - style.fontSize = (fontSize * options.fontSizeFactor) + "px"; - style.lineHeight = fontSize + "px"; - } else { - for (; fontSize > options.minimumFontSize; fontSize = fontSize - Math.min(fontSize / 2, Math.max(0, fontSize - 48) + 2)) { - style.fontSize = (fontSize * options.fontSizeFactor) + "px"; - style.lineHeight = "1"; - if (element.offsetHeight <= +parentComputedStyle.height.replace("px", "")) { - break; - } - } - } - style.whiteSpace = options.whiteSpace; - style.textAlign = options.textAlign; - style.position = "relative"; - style.padding = 0; - style.margin = 0; - style.left = "50%"; - style.top = "50%"; - var computedStyle = document.defaultView.getComputedStyle(element); - - //Get properties of parent to allow easier referencing later. - var parentPadding = { - top: parseInt(parentComputedStyle.getPropertyValue("padding-top")), - right: parseInt(parentComputedStyle.getPropertyValue("padding-right")), - bottom: parseInt(parentComputedStyle.getPropertyValue("padding-bottom")), - left: parseInt(parentComputedStyle.getPropertyValue("padding-left")), - }; - var parentBorder = { - top: parseInt(parentComputedStyle.getPropertyValue("border-top")), - right: parseInt(parentComputedStyle.getPropertyValue("border-right")), - bottom: parseInt(parentComputedStyle.getPropertyValue("border-bottom")), - left: parseInt(parentComputedStyle.getPropertyValue("border-left")), - }; - - //Calculate the parent inner width and height - var parentInnerDimensions = _calculateInnerDimensions(parentComputedStyle); - var parentInnerWidth = parentInnerDimensions["width"]; - var parentInnerHeight = parentInnerDimensions["height"]; - - var box = { - width: element.offsetWidth, //Note: This is slightly larger than the jQuery version - height: element.offsetHeight, - }; - if (!box.width || !box.height) return element; - - - if (options.rotateText !== null) { - if (typeof options.rotateText !== "number") - throw "bigText error: rotateText value must be a number"; - var rotate = "rotate(" + options.rotateText + "deg)"; - style.webkitTransform = rotate; - style.msTransform = rotate; - style.MozTransform = rotate; - style.OTransform = rotate; - style.transform = rotate; - //calculating bounding box of the rotated element - var sine = Math.abs(Math.sin(options.rotateText * Math.PI / 180)); - var cosine = Math.abs(Math.cos(options.rotateText * Math.PI / 180)); - box.width = element.offsetWidth * cosine + element.offsetHeight * sine; - box.height = element.offsetWidth * sine + element.offsetHeight * cosine; - } - - var parentWidth = (parentInnerWidth - parentPadding.left - parentPadding.right); - var parentHeight = (parentInnerHeight - parentPadding.top - parentPadding.bottom); - var widthFactor = parentWidth / box.width; - var heightFactor = parentHeight / box.height; - var lineHeight; - - if (options.limitingDimension.toLowerCase() === "width") { - lineHeight = Math.floor(widthFactor * fontSize); - } else if (options.limitingDimension.toLowerCase() === "height") { - lineHeight = Math.floor(heightFactor * fontSize); - } else if (widthFactor < heightFactor) - lineHeight = Math.floor(widthFactor * fontSize); - else if (widthFactor >= heightFactor) - lineHeight = Math.floor(heightFactor * fontSize); - - var fontSize = lineHeight * options.fontSizeFactor; - if (fontSize < options.minimumFontSize) { - parentStyle.display = "flex"; - parentStyle.alignItems = "center"; - style.textAlign = "center"; - style.visibility = ""; - style.fontSize = options.minimumFontSize + "px"; - style.lineHeight = ""; - style.overflow = "hidden"; - style.textOverflow = "ellipsis"; - style.top = ""; - style.left = ""; - style.margin = ""; - return element; - } - if (options.maximumFontSize && fontSize > options.maximumFontSize) { - fontSize = options.maximumFontSize; - lineHeight = fontSize / options.fontSizeFactor; - } - - style.fontSize = Math.floor(fontSize) + "px"; - style.lineHeight = Math.ceil(lineHeight) + "px"; - style.marginBottom = "0px"; - style.marginRight = "0px"; - - // if (options.limitingDimension.toLowerCase() === "height") { - // //this option needs the font-size to be set already so computedStyle.getPropertyValue("width") returns the right size - // //this +4 is to compensate the rounding erros that can occur due to the calls to Math.floor in the centering code - // parentStyle.width = (parseInt(computedStyle.getPropertyValue("width")) + 4) + "px"; - // } - - //Calculate the inner width and height - var innerDimensions = _calculateInnerDimensions(computedStyle); - var innerWidth = innerDimensions["width"]; - var innerHeight = innerDimensions["height"]; - - switch (options.verticalAlign.toLowerCase()) { - case "top": - style.top = "0%"; - break; - case "bottom": - style.top = "100%"; - style.marginTop = Math.floor(-innerHeight) + "px"; - break; - default: - style.marginTop = Math.ceil((-innerHeight / 2)) + "px"; - break; - } - - switch (options.horizontalAlign.toLowerCase()) { - case "left": - style.left = "0%"; - break; - case "right": - style.left = "100%"; - style.marginLeft = Math.floor(-innerWidth) + "px"; - break; - default: - style.marginLeft = Math.ceil((-innerWidth / 2)) + "px"; - break; - } - - //shows the element after the work is done - style.visibility = "visible"; - - return element; -} diff --git a/src/client/views/nodes/LabelBox.tsx b/src/client/views/nodes/LabelBox.tsx index f80ff5f94..088cd15be 100644 --- a/src/client/views/nodes/LabelBox.tsx +++ b/src/client/views/nodes/LabelBox.tsx @@ -1,21 +1,17 @@ -import { action, computed, makeObservable, observable } from 'mobx'; +import { Property } from 'csstype'; +import { action, computed, makeObservable, trace } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; -import { Doc, DocListCast, Field, FieldType } from '../../../fields/Doc'; -import { List } from '../../../fields/List'; -import { listSpec } from '../../../fields/Schema'; -import { BoolCast, Cast, NumCast, StrCast } from '../../../fields/Types'; +import * as textfit from 'textfit'; +import { Field, FieldType } from '../../../fields/Doc'; +import { BoolCast, NumCast, StrCast } from '../../../fields/Types'; import { DocumentType } from '../../documents/DocumentTypes'; import { Docs } from '../../documents/Documents'; import { DragManager } from '../../util/DragManager'; -import { undoBatch } from '../../util/UndoManager'; -import { ContextMenu } from '../ContextMenu'; -import { ContextMenuProps } from '../ContextMenuItem'; import { ViewBoxBaseComponent } from '../DocComponent'; import { PinDocView, PinProps } from '../PinFuncs'; import { StyleProp } from '../StyleProp'; import { FieldView, FieldViewProps } from './FieldView'; -import BigText from './LabelBigText'; import './LabelBox.scss'; @observer @@ -27,24 +23,14 @@ export class LabelBox extends ViewBoxBaseComponent<FieldViewProps>() { return !label ? LabelBox.LayoutString(fieldStr) : `<LabelBox fieldKey={'${fieldStr}'} label={'${label}'} {...props} />`; // e.g., "<ImageBox {...props} fieldKey={"data} />" } private dropDisposer?: DragManager.DragDropDisposer; - private _timeout: any; + private _timeout: NodeJS.Timeout | undefined; + _divRef: HTMLDivElement|null = null; constructor(props: FieldViewProps) { super(props); makeObservable(this); } - componentDidMount() { - this._props.setContentViewBox?.(this); - } - componentWillUnMount() { - this._timeout && clearTimeout(this._timeout); - } - - @computed get Title() { - return Field.toString(this.dataDoc[this.fieldKey] as FieldType) || StrCast(this.Document.title); - } - protected createDropTarget = (ele: HTMLDivElement) => { this.dropDisposer?.(); if (ele) { @@ -52,44 +38,28 @@ export class LabelBox extends ViewBoxBaseComponent<FieldViewProps>() { } }; - get paramsDoc() { - return Doc.AreProtosEqual(this.layoutDoc, this.dataDoc) ? this.dataDoc : this.layoutDoc; + @computed get Title() { + return Field.toString(this.dataDoc[this.fieldKey] as FieldType) || StrCast(this.Document.title); + } + + @computed get backgroundColor() { + return this._props.styleProvider?.(this.Document, this._props, StyleProp.BackgroundColor) as string; + } + + componentDidMount() { + this._props.setContentViewBox?.(this); + } + componentWillUnMount() { + this._timeout && clearTimeout(this._timeout); } - specificContextMenu = (): void => { - const funcs: ContextMenuProps[] = []; - !Doc.noviceMode && - funcs.push({ - description: 'Clear Script Params', - event: () => { - const params = Cast(this.paramsDoc['onClick-paramFieldKeys'], listSpec('string'), []); - params?.forEach(p => { - this.paramsDoc[p] = undefined; - }); - }, - icon: 'trash', - }); - funcs.length && ContextMenu.Instance.addItem({ description: 'OnClick...', noexpand: true, subitems: funcs, icon: 'mouse-pointer' }); + specificContextMenu = (): void => { }; - @undoBatch - drop = (e: Event, de: DragManager.DropEvent) => { - const { docDragData } = de.complete; - const params = Cast(this.paramsDoc['onClick-paramFieldKeys'], listSpec('string'), []); - const missingParams = params?.filter(p => !this.paramsDoc[p]); - if (docDragData && missingParams?.includes((e.target as any).textContent)) { - this.paramsDoc[(e.target as any).textContent] = new List<Doc>(docDragData.droppedDocuments.map((d, i) => (d.onDragStart ? docDragData.draggedDocuments[i] : d))); - e.stopPropagation(); - return true; - } + drop = (/* e: Event, de: DragManager.DropEvent */) => { return false; }; - @observable _mouseOver = false; - @computed get hoverColor() { - return this._mouseOver ? StrCast(this.layoutDoc._hoverBackgroundColor) : this._props.styleProvider?.(this.Document, this._props, StyleProp.BackgroundColor); - } - getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps) => { if (!pinProps) return this.Document; const anchor = Docs.Create.ConfigDocument({ title: StrCast(this.Document.title), annotationOn: this.Document }); @@ -103,102 +73,95 @@ export class LabelBox extends ViewBoxBaseComponent<FieldViewProps>() { return anchor; }; - fitTextToBox = ( - r: any - ): - | NodeJS.Timeout - | { - rotateText: null; - fontSizeFactor: number; - minimumFontSize: number; - maximumFontSize: number; - limitingDimension: string; - horizontalAlign: string; - verticalAlign: string; - textAlign: string; - singleLine: boolean; - whiteSpace: string; - } => { - const singleLine = BoolCast(this.layoutDoc._singleLine, true); - const params = { - rotateText: null, - fontSizeFactor: 1, - minimumFontSize: NumCast(this.layoutDoc._label_minFontSize, 8), - maximumFontSize: NumCast(this.layoutDoc._label_maxFontSize, 1000), - limitingDimension: 'both', - horizontalAlign: 'center', - verticalAlign: 'center', - textAlign: 'center', - singleLine, - whiteSpace: singleLine ? 'nowrap' : 'pre-wrap', + fitTextToBox = (r: HTMLElement | null | undefined): { + minFontSize: number, + maxFontSize: number, + multiLine: boolean, + alignHoriz: boolean, + alignVert: boolean, + detectMultiLine: boolean, + } => + { + this._timeout && clearTimeout(this._timeout); + const textfitParams = { + minFontSize: NumCast(this.layoutDoc._label_minFontSize, 1), + maxFontSize: NumCast(this.layoutDoc._label_maxFontSize, 100), + multiLine: BoolCast(this.layoutDoc._singleLine, true) ? false : true, + alignHoriz: true, + alignVert: true, + detectMultiLine: true, }; - this._timeout = undefined; - if (!r) return params; - if (!r.offsetHeight || !r.offsetWidth) { - this._timeout = setTimeout(() => this.fitTextToBox(r)); - return this._timeout; + if (r) { + if (!r.offsetHeight || !r.offsetWidth) { + console.log("CAN'T FIT TO EMPTY BOX"); + this._timeout && clearTimeout(this._timeout); + this._timeout = setTimeout(() => this.fitTextToBox(r)); + return textfitParams; + } + textfit(r, textfitParams); } - const parent = r.parentNode; - const parentStyle = parent.style; - parentStyle.display = ''; - parentStyle.alignItems = ''; - r.setAttribute('style', ''); - r.style.width = singleLine ? '' : '100%'; - - r.style.textOverflow = 'ellipsis'; - r.style.overflow = 'hidden'; - BigText(r, params); - return params; + return textfitParams; }; - // (!missingParams || !missingParams.length ? "" : "(" + missingParams.map(m => m + ":").join(" ") + ")") render() { - const boxParams = this.fitTextToBox(null); // this causes mobx to trigger re-render when data changes - const params = Cast(this.paramsDoc['onClick-paramFieldKeys'], listSpec('string'), []); - const missingParams = params?.filter(p => !this.paramsDoc[p]); - params?.map(p => DocListCast(this.paramsDoc[p])); // bcz: really hacky form of prefetching ... - const label = this.Title; + trace(); + const boxParams = this.fitTextToBox(undefined); // this causes mobx to trigger re-render when data changes + const label = this.Title.startsWith("#") ? null : this.Title; return ( <div + key={label?.length} className="labelBox-outerDiv" - onMouseLeave={action(() => { - this._mouseOver = false; - })} - // eslint-disable-next-line jsx-a11y/mouse-events-have-key-events - onMouseOver={action(() => { - this._mouseOver = true; - })} ref={this.createDropTarget} onContextMenu={this.specificContextMenu} - style={{ boxShadow: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BoxShadow) }}> + style={{ boxShadow: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BoxShadow) as string }}> <div className="labelBox-mainButton" style={{ - backgroundColor: this.hoverColor, - fontSize: StrCast(this.layoutDoc._text_fontSize), + backgroundColor: this.backgroundColor, + // fontSize: StrCast(this.layoutDoc._text_fontSize), color: StrCast(this.layoutDoc._color), fontFamily: StrCast(this.layoutDoc._text_fontFamily) || 'inherit', letterSpacing: StrCast(this.layoutDoc.letterSpacing), - textTransform: StrCast(this.layoutDoc.textTransform) as any, + textTransform: StrCast(this.layoutDoc.textTransform) as Property.TextTransform, paddingLeft: NumCast(this.layoutDoc._xPadding), paddingRight: NumCast(this.layoutDoc._xPadding), paddingTop: NumCast(this.layoutDoc._yPadding), paddingBottom: NumCast(this.layoutDoc._yPadding), width: this._props.PanelWidth(), height: this._props.PanelHeight(), - whiteSpace: 'singleLine' in boxParams && boxParams.singleLine ? 'pre' : 'pre-wrap', + whiteSpace: 'multiLine' in boxParams && boxParams.multiLine ? 'pre-wrap' : 'pre', }}> - <span style={{ width: 'singleLine' in boxParams ? '' : '100%' }} ref={action((r: any) => this.fitTextToBox(r))}> - {label.startsWith('#') ? null : label.replace(/([^a-zA-Z])/g, '$1\u200b')} - </span> - </div> - <div className="labelBox-fieldKeyParams"> - {!missingParams?.length - ? null - : missingParams.map(m => ( - <div key={m} className="labelBox-missingParam"> - {m} - </div> - ))} + <div style={{ + width: this._props.PanelWidth()- 2*NumCast(this.layoutDoc._xPadding), + height: this._props.PanelHeight()-2*NumCast(this.layoutDoc._yPadding), + outline: 'unset !important' + }} + onKeyDown={action(e => { + e.stopPropagation(); + })} + onKeyUp={action(e => { + e.stopPropagation(); + if (e.key === 'Enter') { + this.dataDoc[this.fieldKey] = this._divRef?.innerText ?? ""; + setTimeout(() => this._props.select(false)); + } + })} + onBlur={() => { + this.dataDoc[this.fieldKey] = this._divRef?.innerText ?? ""; + }} + contentEditable={this._props.onClickScript?.() ? false: true} + ref={r => {this._divRef = r; + this.fitTextToBox(r); + if (this._props.isSelected() && this._divRef) { + const range = document.createRange(); + range.setStart(this._divRef, this._divRef.childNodes.length); + range.setEnd(this._divRef, this._divRef.childNodes.length) + const sel = window.getSelection(); + sel?.removeAllRanges(); + sel?.addRange(range); + } + }}> + {label} + </div> </div> </div> ); |