fabric 6.4.0 → 6.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/index.js +123 -95
- package/dist/index.js.map +1 -1
- package/dist/index.min.js +1 -1
- package/dist/index.min.js.map +1 -1
- package/dist/index.min.mjs +1 -1
- package/dist/index.min.mjs.map +1 -1
- package/dist/index.mjs +123 -95
- package/dist/index.mjs.map +1 -1
- package/dist/index.node.cjs +123 -95
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.mjs +123 -95
- package/dist/index.node.mjs.map +1 -1
- package/dist/package.json.min.mjs +1 -1
- package/dist/package.json.mjs +1 -1
- package/dist/src/canvas/DOMManagers/CanvasDOMManager.min.mjs +1 -1
- package/dist/src/canvas/DOMManagers/CanvasDOMManager.min.mjs.map +1 -1
- package/dist/src/canvas/DOMManagers/CanvasDOMManager.mjs +0 -1
- package/dist/src/canvas/DOMManagers/CanvasDOMManager.mjs.map +1 -1
- package/dist/src/canvas/SelectableCanvas.min.mjs +1 -1
- package/dist/src/canvas/SelectableCanvas.min.mjs.map +1 -1
- package/dist/src/canvas/SelectableCanvas.mjs +0 -1
- package/dist/src/canvas/SelectableCanvas.mjs.map +1 -1
- package/dist/src/config.d.ts +5 -1
- package/dist/src/config.d.ts.map +1 -1
- package/dist/src/config.min.mjs +1 -1
- package/dist/src/config.min.mjs.map +1 -1
- package/dist/src/config.mjs +6 -2
- package/dist/src/config.mjs.map +1 -1
- package/dist/src/parser/constants.d.ts +0 -1
- package/dist/src/parser/constants.d.ts.map +1 -1
- package/dist/src/parser/constants.min.mjs +1 -1
- package/dist/src/parser/constants.min.mjs.map +1 -1
- package/dist/src/parser/constants.mjs +1 -2
- package/dist/src/parser/constants.mjs.map +1 -1
- package/dist/src/shapes/Line.min.mjs +1 -1
- package/dist/src/shapes/Line.min.mjs.map +1 -1
- package/dist/src/shapes/Line.mjs +0 -1
- package/dist/src/shapes/Line.mjs.map +1 -1
- package/dist/src/shapes/Path.min.mjs +1 -1
- package/dist/src/shapes/Path.min.mjs.map +1 -1
- package/dist/src/shapes/Path.mjs +7 -1
- package/dist/src/shapes/Path.mjs.map +1 -1
- package/dist/src/shapes/Text/StyledText.min.mjs +1 -1
- package/dist/src/shapes/Text/StyledText.min.mjs.map +1 -1
- package/dist/src/shapes/Text/StyledText.mjs +0 -1
- package/dist/src/shapes/Text/StyledText.mjs.map +1 -1
- package/dist/src/util/misc/boundingBoxFromPoints.d.ts.map +1 -1
- package/dist/src/util/misc/boundingBoxFromPoints.min.mjs +1 -1
- package/dist/src/util/misc/boundingBoxFromPoints.min.mjs.map +1 -1
- package/dist/src/util/misc/boundingBoxFromPoints.mjs +17 -30
- package/dist/src/util/misc/boundingBoxFromPoints.mjs.map +1 -1
- package/dist/src/util/path/index.d.ts.map +1 -1
- package/dist/src/util/path/index.min.mjs +1 -1
- package/dist/src/util/path/index.min.mjs.map +1 -1
- package/dist/src/util/path/index.mjs +51 -47
- package/dist/src/util/path/index.mjs.map +1 -1
- package/dist/src/util/path/regex.d.ts +2 -1
- package/dist/src/util/path/regex.d.ts.map +1 -1
- package/dist/src/util/path/regex.min.mjs +1 -1
- package/dist/src/util/path/regex.min.mjs.map +1 -1
- package/dist/src/util/path/regex.mjs +41 -16
- package/dist/src/util/path/regex.mjs.map +1 -1
- package/dist/src/util/path/typedefs.d.ts +1 -0
- package/dist/src/util/path/typedefs.d.ts.map +1 -1
- package/dist-extensions/src/config.d.ts +5 -1
- package/dist-extensions/src/config.d.ts.map +1 -1
- package/dist-extensions/src/parser/constants.d.ts +0 -1
- package/dist-extensions/src/parser/constants.d.ts.map +1 -1
- package/dist-extensions/src/util/misc/boundingBoxFromPoints.d.ts.map +1 -1
- package/dist-extensions/src/util/path/index.d.ts.map +1 -1
- package/dist-extensions/src/util/path/regex.d.ts +2 -1
- package/dist-extensions/src/util/path/regex.d.ts.map +1 -1
- package/dist-extensions/src/util/path/typedefs.d.ts +1 -0
- package/dist-extensions/src/util/path/typedefs.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/config.ts +6 -2
- package/src/parser/constants.ts +0 -2
- package/src/shapes/Path.ts +1 -1
- package/src/util/misc/boundingBoxFromPoints.ts +15 -24
- package/src/util/path/__snapshots__/index.spec.ts.snap +462 -0
- package/src/util/path/index.spec.ts +107 -1
- package/src/util/path/index.ts +56 -51
- package/src/util/path/regex.ts +29 -22
- package/src/util/path/typedefs.ts +22 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.mjs","sources":["../../../src/parser/constants.ts"],"sourcesContent":["import { getSvgRegex } from './getSvgRegex';\nimport { LEFT, TOP } from '../constants';\n\nexport const reNum = String.raw`(?:[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)`;\n\nexport const svgNS = 'http://www.w3.org/2000/svg';\n\nexport const
|
|
1
|
+
{"version":3,"file":"constants.mjs","sources":["../../../src/parser/constants.ts"],"sourcesContent":["import { getSvgRegex } from './getSvgRegex';\nimport { LEFT, TOP } from '../constants';\n\nexport const reNum = String.raw`(?:[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?)`;\n\nexport const svgNS = 'http://www.w3.org/2000/svg';\n\nexport const reFontDeclaration = new RegExp(\n '(normal|italic)?\\\\s*(normal|small-caps)?\\\\s*' +\n '(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\\\s*(' +\n reNum +\n '(?:px|cm|mm|em|pt|pc|in)*)(?:\\\\/(normal|' +\n reNum +\n '))?\\\\s+(.*)',\n);\n\nexport const svgValidTagNames = [\n 'path',\n 'circle',\n 'polygon',\n 'polyline',\n 'ellipse',\n 'rect',\n 'line',\n 'image',\n 'text',\n ],\n svgViewBoxElements = ['symbol', 'image', 'marker', 'pattern', 'view', 'svg'],\n svgInvalidAncestors = [\n 'pattern',\n 'defs',\n 'symbol',\n 'metadata',\n 'clipPath',\n 'mask',\n 'desc',\n ],\n svgValidParents = ['symbol', 'g', 'a', 'svg', 'clipPath', 'defs'],\n attributesMap = {\n cx: LEFT,\n x: LEFT,\n r: 'radius',\n cy: TOP,\n y: TOP,\n display: 'visible',\n visibility: 'visible',\n transform: 'transformMatrix',\n 'fill-opacity': 'fillOpacity',\n 'fill-rule': 'fillRule',\n 'font-family': 'fontFamily',\n 'font-size': 'fontSize',\n 'font-style': 'fontStyle',\n 'font-weight': 'fontWeight',\n 'letter-spacing': 'charSpacing',\n 'paint-order': 'paintFirst',\n 'stroke-dasharray': 'strokeDashArray',\n 'stroke-dashoffset': 'strokeDashOffset',\n 'stroke-linecap': 'strokeLineCap',\n 'stroke-linejoin': 'strokeLineJoin',\n 'stroke-miterlimit': 'strokeMiterLimit',\n 'stroke-opacity': 'strokeOpacity',\n 'stroke-width': 'strokeWidth',\n 'text-decoration': 'textDecoration',\n 'text-anchor': 'textAnchor',\n opacity: 'opacity',\n 'clip-path': 'clipPath',\n 'clip-rule': 'clipRule',\n 'vector-effect': 'strokeUniform',\n 'image-rendering': 'imageSmoothing',\n },\n fSize = 'font-size',\n cPath = 'clip-path';\n\nexport const svgValidTagNamesRegEx = getSvgRegex(svgValidTagNames);\n\nexport const svgViewBoxElementsRegEx = getSvgRegex(svgViewBoxElements);\n\nexport const svgValidParentsRegEx = getSvgRegex(svgValidParents);\n\n// http://www.w3.org/TR/SVG/coords.html#ViewBoxAttribute\n// matches, e.g.: +14.56e-12, etc.\nexport const reViewBoxAttrValue = new RegExp(\n '^' +\n '\\\\s*(' +\n reNum +\n '+)\\\\s*,?' +\n '\\\\s*(' +\n reNum +\n '+)\\\\s*,?' +\n '\\\\s*(' +\n reNum +\n '+)\\\\s*,?' +\n '\\\\s*(' +\n reNum +\n '+)\\\\s*' +\n '$',\n);\n"],"names":["reNum","String","raw","_templateObject","_taggedTemplateLiteral","svgNS","reFontDeclaration","RegExp","svgValidTagNames","svgViewBoxElements","svgInvalidAncestors","svgValidParents","attributesMap","cx","LEFT","x","r","cy","TOP","y","display","visibility","transform","opacity","fSize","cPath","svgValidTagNamesRegEx","getSvgRegex","svgViewBoxElementsRegEx","svgValidParentsRegEx","reViewBoxAttrValue"],"mappings":";;;;;AAGaA,MAAAA,KAAK,GAAGC,MAAM,CAACC,GAAG,CAAAC,eAAA,KAAAA,eAAA,GAAAC,sBAAA,CAA+C,CAAA,yCAAA,CAAA,EAAA,CAAA,qDAAA,CAAA,CAAA,CAAA,EAAA;AAEvE,MAAMC,KAAK,GAAG,6BAA4B;MAEpCC,iBAAiB,GAAG,IAAIC,MAAM,CACzC,8CAA8C,GAC5C,wEAAwE,GACxEP,KAAK,GACL,0CAA0C,GAC1CA,KAAK,GACL,aACJ,EAAC;AAEM,MAAMQ,gBAAgB,GAAG,CAC5B,MAAM,EACN,QAAQ,EACR,SAAS,EACT,UAAU,EACV,SAAS,EACT,MAAM,EACN,MAAM,EACN,OAAO,EACP,MAAM,CACP,CAAA;AACDC,EAAAA,kBAAkB,GAAG,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;AAC5EC,EAAAA,mBAAmB,GAAG,CACpB,SAAS,EACT,MAAM,EACN,QAAQ,EACR,UAAU,EACV,UAAU,EACV,MAAM,EACN,MAAM,CACP,CAAA;AACDC,EAAAA,eAAe,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,CAAC,CAAA;AACjEC,EAAAA,aAAa,GAAG;AACdC,IAAAA,EAAE,EAAEC,IAAI;AACRC,IAAAA,CAAC,EAAED,IAAI;AACPE,IAAAA,CAAC,EAAE,QAAQ;AACXC,IAAAA,EAAE,EAAEC,GAAG;AACPC,IAAAA,CAAC,EAAED,GAAG;AACNE,IAAAA,OAAO,EAAE,SAAS;AAClBC,IAAAA,UAAU,EAAE,SAAS;AACrBC,IAAAA,SAAS,EAAE,iBAAiB;AAC5B,IAAA,cAAc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ual/_rollupPluginBabelHelpers.min.mjs";import{SHARED_ATTRIBUTES as e}from"../parser/attributes.min.mjs";import{parseAttributes as o}from"../parser/parseAttributes.min.mjs";import{classRegistry as r}from"../ClassRegistry.min.mjs";import{FabricObject as n}from"./Object/FabricObject.min.mjs";import{Point as m}from"../Point.min.mjs";import{isFiller as h}from"../util/typeAssertions.min.mjs";import{LEFT as c,TOP as a,CENTER as l}from"../constants.min.mjs";import"../util/misc/vectors.min.mjs";import"../util/misc/projectStroke/StrokeLineJoinProjections.min.mjs";import"../config.min.mjs";import"./Group.min.mjs";import{makeBoundingBoxFromPoints as p}from"../util/misc/boundingBoxFromPoints.min.mjs";import"../cache.min.mjs";import"../
|
|
1
|
+
import{defineProperty as t,objectSpread2 as i,objectWithoutProperties as s}from"../../_virtual/_rollupPluginBabelHelpers.min.mjs";import{SHARED_ATTRIBUTES as e}from"../parser/attributes.min.mjs";import{parseAttributes as o}from"../parser/parseAttributes.min.mjs";import{classRegistry as r}from"../ClassRegistry.min.mjs";import{FabricObject as n}from"./Object/FabricObject.min.mjs";import{Point as m}from"../Point.min.mjs";import{isFiller as h}from"../util/typeAssertions.min.mjs";import{LEFT as c,TOP as a,CENTER as l}from"../constants.min.mjs";import"../util/misc/vectors.min.mjs";import"../util/misc/projectStroke/StrokeLineJoinProjections.min.mjs";import"../config.min.mjs";import"./Group.min.mjs";import{makeBoundingBoxFromPoints as p}from"../util/misc/boundingBoxFromPoints.min.mjs";import"../cache.min.mjs";import"../parser/constants.min.mjs";import"../util/animation/AnimationRegistry.min.mjs";import{cacheProperties as y}from"./Object/defaultValues.min.mjs";const u=["x1","y1","x2","y2"],x=["x1","y1","x2","y2"],j=["x1","x2","y1","y2"];class d extends n{constructor(){let[t,i,s,e]=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0,0,0],o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),Object.assign(this,d.ownDefaults),this.setOptions(o),this.x1=t,this.x2=s,this.y1=i,this.y2=e,this._setWidthHeight();const{left:r,top:n}=o;"number"==typeof r&&this.set(c,r),"number"==typeof n&&this.set(a,n)}_setWidthHeight(){const{x1:t,y1:i,x2:s,y2:e}=this;this.width=Math.abs(s-t),this.height=Math.abs(e-i);const{left:o,top:r,width:n,height:h}=p([{x:t,y:i},{x:s,y:e}]),c=new m(o+n/2,r+h/2);this.setPositionByOrigin(c,l,l)}_set(t,i){return super._set(t,i),j.includes(t)&&this._setWidthHeight(),this}_render(t){t.beginPath();const i=this.calcLinePoints();t.moveTo(i.x1,i.y1),t.lineTo(i.x2,i.y2),t.lineWidth=this.strokeWidth;const s=t.strokeStyle;var e;h(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=null!==(e=this.stroke)&&void 0!==e?e:t.fillStyle;this.stroke&&this._renderStroke(t),t.strokeStyle=s}_findCenterFromElement(){return new m((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return i(i({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:i,y1:s,y2:e,width:o,height:r}=this,n=t<=i?-1:1,m=s<=e?-1:1;return{x1:n*o/2,x2:n*-o/2,y1:m*r/2,y2:m*-r/2}}_toSVG(){const{x1:t,x2:i,y1:s,y2:e}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(i,'" y2="').concat(e,'" />\n')]}static async fromElement(t,i,e){const r=o(t,this.ATTRIBUTE_NAMES,e),{x1:n=0,y1:m=0,x2:h=0,y2:c=0}=r;return new this([n,m,h,c],s(r,u))}static fromObject(t){let{x1:e,y1:o,x2:r,y2:n}=t,m=s(t,x);return this._fromObject(i(i({},m),{},{points:[e,o,r,n]}),{extraParam:"points"})}}t(d,"type","Line"),t(d,"cacheProperties",[...y,...j]),t(d,"ATTRIBUTE_NAMES",e.concat(j)),r.setClass(d),r.setSVGClass(d);export{d as Line};
|
|
2
2
|
//# sourceMappingURL=Line.min.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Line.min.mjs","sources":["../../../src/shapes/Line.ts"],"sourcesContent":["import { SHARED_ATTRIBUTES } from '../parser/attributes';\nimport { parseAttributes } from '../parser/parseAttributes';\nimport type { Abortable, TClassProperties, TOptions } from '../typedefs';\nimport { classRegistry } from '../ClassRegistry';\nimport { FabricObject, cacheProperties } from './Object/FabricObject';\nimport { Point } from '../Point';\nimport { isFiller } from '../util/typeAssertions';\nimport type { FabricObjectProps, SerializedObjectProps } from './Object/types';\nimport type { ObjectEvents } from '../EventTypeDefs';\nimport { makeBoundingBoxFromPoints } from '../util';\nimport { CENTER, LEFT, TOP } from '../constants';\nimport type { CSSRules } from '../parser/typedefs';\n\n// @TODO this code is terrible and Line should be a special case of polyline.\n\nconst coordProps = ['x1', 'x2', 'y1', 'y2'] as const;\n\ninterface UniqueLineProps {\n x1: number;\n x2: number;\n y1: number;\n y2: number;\n}\n\nexport interface SerializedLineProps\n extends SerializedObjectProps,\n UniqueLineProps {}\n\nexport class Line<\n Props extends TOptions<FabricObjectProps> = Partial<FabricObjectProps>,\n SProps extends SerializedLineProps = SerializedLineProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n >\n extends FabricObject<Props, SProps, EventSpec>\n implements UniqueLineProps\n{\n /**\n * x value or first line edge\n * @type number\n * @default\n */\n declare x1: number;\n\n /**\n * y value or first line edge\n * @type number\n * @default\n */\n declare y1: number;\n\n /**\n * x value or second line edge\n * @type number\n * @default\n */\n declare x2: number;\n\n /**\n * y value or second line edge\n * @type number\n * @default\n */\n declare y2: number;\n\n static type = 'Line';\n\n static cacheProperties = [...cacheProperties, ...coordProps];\n /**\n * Constructor\n * @param {Array} [points] Array of points\n * @param {Object} [options] Options object\n * @return {Line} thisArg\n */\n constructor([x1, y1, x2, y2] = [0, 0, 0, 0], options: Partial<Props> = {}) {\n super();\n Object.assign(this, Line.ownDefaults);\n this.setOptions(options);\n this.x1 = x1;\n this.x2 = x2;\n this.y1 = y1;\n this.y2 = y2;\n this._setWidthHeight();\n const { left, top } = options;\n typeof left === 'number' && this.set(LEFT, left);\n typeof top === 'number' && this.set(TOP, top);\n }\n\n /**\n * @private\n * @param {Object} [options] Options\n */\n _setWidthHeight() {\n const { x1, y1, x2, y2 } = this;\n this.width = Math.abs(x2 - x1);\n this.height = Math.abs(y2 - y1);\n const { left, top, width, height } = makeBoundingBoxFromPoints([\n { x: x1, y: y1 },\n { x: x2, y: y2 },\n ]);\n const position = new Point(left + width / 2, top + height / 2);\n this.setPositionByOrigin(position, CENTER, CENTER);\n }\n\n /**\n * @private\n * @param {String} key\n * @param {*} value\n */\n _set(key: string, value: any) {\n super._set(key, value);\n if (coordProps.includes(key as keyof UniqueLineProps)) {\n // this doesn't make sense very much, since setting x1 when top or left\n // are already set, is just going to show a strange result since the\n // line will move way more than the developer expect.\n // in fabric5 it worked only when the line didn't have extra transformations,\n // in fabric6 too. With extra transform they behave bad in different ways.\n // This needs probably a good rework or a tutorial if you have to create a dynamic line\n this._setWidthHeight();\n }\n return this;\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render(ctx: CanvasRenderingContext2D) {\n ctx.beginPath();\n\n const p = this.calcLinePoints();\n ctx.moveTo(p.x1, p.y1);\n ctx.lineTo(p.x2, p.y2);\n\n ctx.lineWidth = this.strokeWidth;\n\n // TODO: test this\n // make sure setting \"fill\" changes color of a line\n // (by copying fillStyle to strokeStyle, since line is stroked, not filled)\n const origStrokeStyle = ctx.strokeStyle;\n if (isFiller(this.stroke)) {\n ctx.strokeStyle = this.stroke.toLive(ctx)!;\n } else {\n ctx.strokeStyle = this.stroke ?? ctx.fillStyle;\n }\n this.stroke && this._renderStroke(ctx);\n ctx.strokeStyle = origStrokeStyle;\n }\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates\n * @private\n * @return {Point} center point from element coordinates\n */\n _findCenterFromElement(): Point {\n return new Point((this.x1 + this.x2) / 2, (this.y1 + this.y2) / 2);\n }\n\n /**\n * Returns object representation of an instance\n * @method toObject\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n return {\n ...super.toObject(propertiesToInclude),\n ...this.calcLinePoints(),\n };\n }\n\n /*\n * Calculate object dimensions from its properties\n * @private\n */\n _getNonTransformedDimensions(): Point {\n const dim = super._getNonTransformedDimensions();\n if (this.strokeLineCap === 'butt') {\n if (this.width === 0) {\n dim.y -= this.strokeWidth;\n }\n if (this.height === 0) {\n dim.x -= this.strokeWidth;\n }\n }\n return dim;\n }\n\n /**\n * Recalculates line points given width and height\n * Those points are simply placed around the center,\n * This is not useful outside internal render functions and svg output\n * Is not meant to be for the developer.\n * @private\n */\n calcLinePoints(): UniqueLineProps {\n const { x1: _x1, x2: _x2, y1: _y1, y2: _y2, width, height } = this;\n const xMult = _x1 <= _x2 ? -1 : 1,\n yMult = _y1 <= _y2 ? -1 : 1,\n x1 = (xMult * width) / 2,\n y1 = (yMult * height) / 2,\n x2 = (xMult * -width) / 2,\n y2 = (yMult * -height) / 2;\n\n return {\n x1,\n x2,\n y1,\n y2,\n };\n }\n\n /* _FROM_SVG_START_ */\n\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG() {\n const { x1, x2, y1, y2 } = this.calcLinePoints();\n return [\n '<line ',\n 'COMMON_PARTS',\n `x1=\"${x1}\" y1=\"${y1}\" x2=\"${x2}\" y2=\"${y2}\" />\\n`,\n ];\n }\n\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link Line.fromElement})\n * @static\n * @memberOf Line\n * @see http://www.w3.org/TR/SVG/shapes.html#LineElement\n */\n static ATTRIBUTE_NAMES = SHARED_ATTRIBUTES.concat(coordProps);\n\n /**\n * Returns Line instance from an SVG element\n * @static\n * @memberOf Line\n * @param {HTMLElement} element Element to parse\n * @param {Object} [options] Options object\n * @param {Function} [callback] callback function invoked after parsing\n */\n static async fromElement(\n element: HTMLElement,\n options: Abortable,\n cssRules?: CSSRules,\n ) {\n const {\n x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0,\n ...parsedAttributes\n } = parseAttributes(element, this.ATTRIBUTE_NAMES, cssRules);\n return new this([x1, y1, x2, y2], parsedAttributes);\n }\n\n /* _FROM_SVG_END_ */\n\n /**\n * Returns Line instance from an object representation\n * @static\n * @memberOf Line\n * @param {Object} object Object to create an instance from\n * @returns {Promise<Line>}\n */\n static fromObject<T extends TOptions<SerializedLineProps>>({\n x1,\n y1,\n x2,\n y2,\n ...object\n }: T) {\n return this._fromObject<Line>(\n {\n ...object,\n points: [x1, y1, x2, y2],\n },\n {\n extraParam: 'points',\n },\n );\n }\n}\n\nclassRegistry.setClass(Line);\nclassRegistry.setSVGClass(Line);\n"],"names":["coordProps","Line","FabricObject","constructor","x1","y1","x2","y2","arguments","length","undefined","options","super","Object","assign","this","ownDefaults","setOptions","_setWidthHeight","left","top","set","LEFT","TOP","width","Math","abs","height","makeBoundingBoxFromPoints","x","y","position","Point","setPositionByOrigin","CENTER","_set","key","value","includes","_render","ctx","beginPath","p","calcLinePoints","moveTo","lineTo","lineWidth","strokeWidth","origStrokeStyle","strokeStyle","_this$stroke","isFiller","stroke","toLive","fillStyle","_renderStroke","_findCenterFromElement","toObject","propertiesToInclude","_objectSpread","_getNonTransformedDimensions","dim","strokeLineCap","_x1","_x2","_y1","_y2","xMult","yMult","_toSVG","concat","fromElement","element","cssRules","_parseAttributes","parseAttributes","ATTRIBUTE_NAMES","_objectWithoutProperties","_excluded","fromObject","_ref","object","_excluded2","_fromObject","points","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ANM6D,GAASzC,EAAU,EAQ7B,CASA0C,MAAAA,GACE,MAAMjE,GAAEA,EAAEE,GAAEA,EAAED,GAAEA,EAAEE,GAAEA,GAAOQ,KAAK4B,iBAChC,MAAO,CACL,SACA,sBAAc2B,OACPlE,EAAEkE,UAAAA,OAASjE,EAAE,UAAAiE,OAAShE,YAAEgE,OAAS/D,EACzC,UACH,CAkBA,wBAAagE,CACXC,EACA7D,EACA8D,GAEA,MAAAC,EAMIC,EAAgBH,EAASzD,KAAK6D,gBAAiBH,IAN7CrE,GACJA,EAAK,EAACC,GACNA,EAAK,EAACC,GACNA,EAAK,EAACC,GACNA,EAAK,GAENmE,EACD,OAAO,IAAI3D,KAAK,CAACX,EAAIC,EAAIC,EAAIC,GAFRsE,EAAAH,EAAAI,GAGvB,CAWA,iBAAOC,CAAUC,GAMX,IANqD5E,GACzDA,EAAEC,GACFA,EAAEC,GACFA,EAAEC,GACFA,GAEEyE,EADCC,EAAMJ,EAAAG,EAAAE,GAET,OAAOnE,KAAKoE,YAAWxB,EAAAA,KAEhBsB,GAAM,GAAA,CACTG,OAAQ,CAAChF,EAAIC,EAAIC,EAAIC,KAEvB,CACE8E,WAAY,UAGlB,EAtOAC,EA7BWrF,EAAI,OAoCD,QAAMqF,EApCTrF,EAsCc,kBAAA,IAAIsF,KAAoBvF,IAAWsF,EAtCjDrF,EAiNcuF,kBAAAA,EAAkBlB,OAAOtE,IAqDpDyF,EAAcC,SAASzF,GACvBwF,EAAcE,YAAY1F"}
|
|
1
|
+
{"version":3,"file":"Line.min.mjs","sources":["../../../src/shapes/Line.ts"],"sourcesContent":["import { SHARED_ATTRIBUTES } from '../parser/attributes';\nimport { parseAttributes } from '../parser/parseAttributes';\nimport type { Abortable, TClassProperties, TOptions } from '../typedefs';\nimport { classRegistry } from '../ClassRegistry';\nimport { FabricObject, cacheProperties } from './Object/FabricObject';\nimport { Point } from '../Point';\nimport { isFiller } from '../util/typeAssertions';\nimport type { FabricObjectProps, SerializedObjectProps } from './Object/types';\nimport type { ObjectEvents } from '../EventTypeDefs';\nimport { makeBoundingBoxFromPoints } from '../util';\nimport { CENTER, LEFT, TOP } from '../constants';\nimport type { CSSRules } from '../parser/typedefs';\n\n// @TODO this code is terrible and Line should be a special case of polyline.\n\nconst coordProps = ['x1', 'x2', 'y1', 'y2'] as const;\n\ninterface UniqueLineProps {\n x1: number;\n x2: number;\n y1: number;\n y2: number;\n}\n\nexport interface SerializedLineProps\n extends SerializedObjectProps,\n UniqueLineProps {}\n\nexport class Line<\n Props extends TOptions<FabricObjectProps> = Partial<FabricObjectProps>,\n SProps extends SerializedLineProps = SerializedLineProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n >\n extends FabricObject<Props, SProps, EventSpec>\n implements UniqueLineProps\n{\n /**\n * x value or first line edge\n * @type number\n * @default\n */\n declare x1: number;\n\n /**\n * y value or first line edge\n * @type number\n * @default\n */\n declare y1: number;\n\n /**\n * x value or second line edge\n * @type number\n * @default\n */\n declare x2: number;\n\n /**\n * y value or second line edge\n * @type number\n * @default\n */\n declare y2: number;\n\n static type = 'Line';\n\n static cacheProperties = [...cacheProperties, ...coordProps];\n /**\n * Constructor\n * @param {Array} [points] Array of points\n * @param {Object} [options] Options object\n * @return {Line} thisArg\n */\n constructor([x1, y1, x2, y2] = [0, 0, 0, 0], options: Partial<Props> = {}) {\n super();\n Object.assign(this, Line.ownDefaults);\n this.setOptions(options);\n this.x1 = x1;\n this.x2 = x2;\n this.y1 = y1;\n this.y2 = y2;\n this._setWidthHeight();\n const { left, top } = options;\n typeof left === 'number' && this.set(LEFT, left);\n typeof top === 'number' && this.set(TOP, top);\n }\n\n /**\n * @private\n * @param {Object} [options] Options\n */\n _setWidthHeight() {\n const { x1, y1, x2, y2 } = this;\n this.width = Math.abs(x2 - x1);\n this.height = Math.abs(y2 - y1);\n const { left, top, width, height } = makeBoundingBoxFromPoints([\n { x: x1, y: y1 },\n { x: x2, y: y2 },\n ]);\n const position = new Point(left + width / 2, top + height / 2);\n this.setPositionByOrigin(position, CENTER, CENTER);\n }\n\n /**\n * @private\n * @param {String} key\n * @param {*} value\n */\n _set(key: string, value: any) {\n super._set(key, value);\n if (coordProps.includes(key as keyof UniqueLineProps)) {\n // this doesn't make sense very much, since setting x1 when top or left\n // are already set, is just going to show a strange result since the\n // line will move way more than the developer expect.\n // in fabric5 it worked only when the line didn't have extra transformations,\n // in fabric6 too. With extra transform they behave bad in different ways.\n // This needs probably a good rework or a tutorial if you have to create a dynamic line\n this._setWidthHeight();\n }\n return this;\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render(ctx: CanvasRenderingContext2D) {\n ctx.beginPath();\n\n const p = this.calcLinePoints();\n ctx.moveTo(p.x1, p.y1);\n ctx.lineTo(p.x2, p.y2);\n\n ctx.lineWidth = this.strokeWidth;\n\n // TODO: test this\n // make sure setting \"fill\" changes color of a line\n // (by copying fillStyle to strokeStyle, since line is stroked, not filled)\n const origStrokeStyle = ctx.strokeStyle;\n if (isFiller(this.stroke)) {\n ctx.strokeStyle = this.stroke.toLive(ctx)!;\n } else {\n ctx.strokeStyle = this.stroke ?? ctx.fillStyle;\n }\n this.stroke && this._renderStroke(ctx);\n ctx.strokeStyle = origStrokeStyle;\n }\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates\n * @private\n * @return {Point} center point from element coordinates\n */\n _findCenterFromElement(): Point {\n return new Point((this.x1 + this.x2) / 2, (this.y1 + this.y2) / 2);\n }\n\n /**\n * Returns object representation of an instance\n * @method toObject\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n return {\n ...super.toObject(propertiesToInclude),\n ...this.calcLinePoints(),\n };\n }\n\n /*\n * Calculate object dimensions from its properties\n * @private\n */\n _getNonTransformedDimensions(): Point {\n const dim = super._getNonTransformedDimensions();\n if (this.strokeLineCap === 'butt') {\n if (this.width === 0) {\n dim.y -= this.strokeWidth;\n }\n if (this.height === 0) {\n dim.x -= this.strokeWidth;\n }\n }\n return dim;\n }\n\n /**\n * Recalculates line points given width and height\n * Those points are simply placed around the center,\n * This is not useful outside internal render functions and svg output\n * Is not meant to be for the developer.\n * @private\n */\n calcLinePoints(): UniqueLineProps {\n const { x1: _x1, x2: _x2, y1: _y1, y2: _y2, width, height } = this;\n const xMult = _x1 <= _x2 ? -1 : 1,\n yMult = _y1 <= _y2 ? -1 : 1,\n x1 = (xMult * width) / 2,\n y1 = (yMult * height) / 2,\n x2 = (xMult * -width) / 2,\n y2 = (yMult * -height) / 2;\n\n return {\n x1,\n x2,\n y1,\n y2,\n };\n }\n\n /* _FROM_SVG_START_ */\n\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG() {\n const { x1, x2, y1, y2 } = this.calcLinePoints();\n return [\n '<line ',\n 'COMMON_PARTS',\n `x1=\"${x1}\" y1=\"${y1}\" x2=\"${x2}\" y2=\"${y2}\" />\\n`,\n ];\n }\n\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link Line.fromElement})\n * @static\n * @memberOf Line\n * @see http://www.w3.org/TR/SVG/shapes.html#LineElement\n */\n static ATTRIBUTE_NAMES = SHARED_ATTRIBUTES.concat(coordProps);\n\n /**\n * Returns Line instance from an SVG element\n * @static\n * @memberOf Line\n * @param {HTMLElement} element Element to parse\n * @param {Object} [options] Options object\n * @param {Function} [callback] callback function invoked after parsing\n */\n static async fromElement(\n element: HTMLElement,\n options: Abortable,\n cssRules?: CSSRules,\n ) {\n const {\n x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0,\n ...parsedAttributes\n } = parseAttributes(element, this.ATTRIBUTE_NAMES, cssRules);\n return new this([x1, y1, x2, y2], parsedAttributes);\n }\n\n /* _FROM_SVG_END_ */\n\n /**\n * Returns Line instance from an object representation\n * @static\n * @memberOf Line\n * @param {Object} object Object to create an instance from\n * @returns {Promise<Line>}\n */\n static fromObject<T extends TOptions<SerializedLineProps>>({\n x1,\n y1,\n x2,\n y2,\n ...object\n }: T) {\n return this._fromObject<Line>(\n {\n ...object,\n points: [x1, y1, x2, y2],\n },\n {\n extraParam: 'points',\n },\n );\n }\n}\n\nclassRegistry.setClass(Line);\nclassRegistry.setSVGClass(Line);\n"],"names":["coordProps","Line","FabricObject","constructor","x1","y1","x2","y2","arguments","length","undefined","options","super","Object","assign","this","ownDefaults","setOptions","_setWidthHeight","left","top","set","LEFT","TOP","width","Math","abs","height","makeBoundingBoxFromPoints","x","y","position","Point","setPositionByOrigin","CENTER","_set","key","value","includes","_render","ctx","beginPath","p","calcLinePoints","moveTo","lineTo","lineWidth","strokeWidth","origStrokeStyle","strokeStyle","_this$stroke","isFiller","stroke","toLive","fillStyle","_renderStroke","_findCenterFromElement","toObject","propertiesToInclude","_objectSpread","_getNonTransformedDimensions","dim","strokeLineCap","_x1","_x2","_y1","_y2","xMult","yMult","_toSVG","concat","fromElement","element","cssRules","_parseAttributes","parseAttributes","ATTRIBUTE_NAMES","_objectWithoutProperties","_excluded","fromObject","_ref","object","_excluded2","_fromObject","points","extraParam","_defineProperty","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":"4/BAeMA,EAAa,CAAC,KAAM,KAAM,KAAM,MAa/B,MAAMC,UAKHC,EAwCRC,WAAAA,GAA2E,IAA9DC,EAAIC,EAAIC,EAAIC,GAAGC,UAAAC,OAAA,QAAAC,IAAAF,UAAA,GAAAA,UAAA,GAAG,CAAC,EAAG,EAAG,EAAG,GAAIG,EAAuBH,UAAAC,OAAA,QAAAC,IAAAF,UAAA,GAAAA,UAAA,GAAG,CAAA,EACrEI,QACAC,OAAOC,OAAOC,KAAMd,EAAKe,aACzBD,KAAKE,WAAWN,GAChBI,KAAKX,GAAKA,EACVW,KAAKT,GAAKA,EACVS,KAAKV,GA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sE,EAAAH,EAAAI,GAGvB,CAWA,iBAAOC,CAAUC,GAMX,IANqD5E,GACzDA,EAAEC,GACFA,EAAEC,GACFA,EAAEC,GACFA,GAEEyE,EADCC,EAAMJ,EAAAG,EAAAE,GAET,OAAOnE,KAAKoE,YAAWxB,EAAAA,KAEhBsB,GAAM,GAAA,CACTG,OAAQ,CAAChF,EAAIC,EAAIC,EAAIC,KAEvB,CACE8E,WAAY,UAGlB,EAtOAC,EA7BWrF,EAAI,OAoCD,QAAMqF,EApCTrF,EAsCc,kBAAA,IAAIsF,KAAoBvF,IAAWsF,EAtCjDrF,EAiNcuF,kBAAAA,EAAkBlB,OAAOtE,IAqDpDyF,EAAcC,SAASzF,GACvBwF,EAAcE,YAAY1F"}
|
package/dist/src/shapes/Line.mjs
CHANGED
|
@@ -12,7 +12,6 @@ import '../config.mjs';
|
|
|
12
12
|
import './Group.mjs';
|
|
13
13
|
import { makeBoundingBoxFromPoints } from '../util/misc/boundingBoxFromPoints.mjs';
|
|
14
14
|
import '../cache.mjs';
|
|
15
|
-
import '../util/path/regex.mjs';
|
|
16
15
|
import '../parser/constants.mjs';
|
|
17
16
|
import '../util/animation/AnimationRegistry.mjs';
|
|
18
17
|
import { cacheProperties } from './Object/defaultValues.mjs';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Line.mjs","sources":["../../../src/shapes/Line.ts"],"sourcesContent":["import { SHARED_ATTRIBUTES } from '../parser/attributes';\nimport { parseAttributes } from '../parser/parseAttributes';\nimport type { Abortable, TClassProperties, TOptions } from '../typedefs';\nimport { classRegistry } from '../ClassRegistry';\nimport { FabricObject, cacheProperties } from './Object/FabricObject';\nimport { Point } from '../Point';\nimport { isFiller } from '../util/typeAssertions';\nimport type { FabricObjectProps, SerializedObjectProps } from './Object/types';\nimport type { ObjectEvents } from '../EventTypeDefs';\nimport { makeBoundingBoxFromPoints } from '../util';\nimport { CENTER, LEFT, TOP } from '../constants';\nimport type { CSSRules } from '../parser/typedefs';\n\n// @TODO this code is terrible and Line should be a special case of polyline.\n\nconst coordProps = ['x1', 'x2', 'y1', 'y2'] as const;\n\ninterface UniqueLineProps {\n x1: number;\n x2: number;\n y1: number;\n y2: number;\n}\n\nexport interface SerializedLineProps\n extends SerializedObjectProps,\n UniqueLineProps {}\n\nexport class Line<\n Props extends TOptions<FabricObjectProps> = Partial<FabricObjectProps>,\n SProps extends SerializedLineProps = SerializedLineProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n >\n extends FabricObject<Props, SProps, EventSpec>\n implements UniqueLineProps\n{\n /**\n * x value or first line edge\n * @type number\n * @default\n */\n declare x1: number;\n\n /**\n * y value or first line edge\n * @type number\n * @default\n */\n declare y1: number;\n\n /**\n * x value or second line edge\n * @type number\n * @default\n */\n declare x2: number;\n\n /**\n * y value or second line edge\n * @type number\n * @default\n */\n declare y2: number;\n\n static type = 'Line';\n\n static cacheProperties = [...cacheProperties, ...coordProps];\n /**\n * Constructor\n * @param {Array} [points] Array of points\n * @param {Object} [options] Options object\n * @return {Line} thisArg\n */\n constructor([x1, y1, x2, y2] = [0, 0, 0, 0], options: Partial<Props> = {}) {\n super();\n Object.assign(this, Line.ownDefaults);\n this.setOptions(options);\n this.x1 = x1;\n this.x2 = x2;\n this.y1 = y1;\n this.y2 = y2;\n this._setWidthHeight();\n const { left, top } = options;\n typeof left === 'number' && this.set(LEFT, left);\n typeof top === 'number' && this.set(TOP, top);\n }\n\n /**\n * @private\n * @param {Object} [options] Options\n */\n _setWidthHeight() {\n const { x1, y1, x2, y2 } = this;\n this.width = Math.abs(x2 - x1);\n this.height = Math.abs(y2 - y1);\n const { left, top, width, height } = makeBoundingBoxFromPoints([\n { x: x1, y: y1 },\n { x: x2, y: y2 },\n ]);\n const position = new Point(left + width / 2, top + height / 2);\n this.setPositionByOrigin(position, CENTER, CENTER);\n }\n\n /**\n * @private\n * @param {String} key\n * @param {*} value\n */\n _set(key: string, value: any) {\n super._set(key, value);\n if (coordProps.includes(key as keyof UniqueLineProps)) {\n // this doesn't make sense very much, since setting x1 when top or left\n // are already set, is just going to show a strange result since the\n // line will move way more than the developer expect.\n // in fabric5 it worked only when the line didn't have extra transformations,\n // in fabric6 too. With extra transform they behave bad in different ways.\n // This needs probably a good rework or a tutorial if you have to create a dynamic line\n this._setWidthHeight();\n }\n return this;\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render(ctx: CanvasRenderingContext2D) {\n ctx.beginPath();\n\n const p = this.calcLinePoints();\n ctx.moveTo(p.x1, p.y1);\n ctx.lineTo(p.x2, p.y2);\n\n ctx.lineWidth = this.strokeWidth;\n\n // TODO: test this\n // make sure setting \"fill\" changes color of a line\n // (by copying fillStyle to strokeStyle, since line is stroked, not filled)\n const origStrokeStyle = ctx.strokeStyle;\n if (isFiller(this.stroke)) {\n ctx.strokeStyle = this.stroke.toLive(ctx)!;\n } else {\n ctx.strokeStyle = this.stroke ?? ctx.fillStyle;\n }\n this.stroke && this._renderStroke(ctx);\n ctx.strokeStyle = origStrokeStyle;\n }\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates\n * @private\n * @return {Point} center point from element coordinates\n */\n _findCenterFromElement(): Point {\n return new Point((this.x1 + this.x2) / 2, (this.y1 + this.y2) / 2);\n }\n\n /**\n * Returns object representation of an instance\n * @method toObject\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n return {\n ...super.toObject(propertiesToInclude),\n ...this.calcLinePoints(),\n };\n }\n\n /*\n * Calculate object dimensions from its properties\n * @private\n */\n _getNonTransformedDimensions(): Point {\n const dim = super._getNonTransformedDimensions();\n if (this.strokeLineCap === 'butt') {\n if (this.width === 0) {\n dim.y -= this.strokeWidth;\n }\n if (this.height === 0) {\n dim.x -= this.strokeWidth;\n }\n }\n return dim;\n }\n\n /**\n * Recalculates line points given width and height\n * Those points are simply placed around the center,\n * This is not useful outside internal render functions and svg output\n * Is not meant to be for the developer.\n * @private\n */\n calcLinePoints(): UniqueLineProps {\n const { x1: _x1, x2: _x2, y1: _y1, y2: _y2, width, height } = this;\n const xMult = _x1 <= _x2 ? -1 : 1,\n yMult = _y1 <= _y2 ? -1 : 1,\n x1 = (xMult * width) / 2,\n y1 = (yMult * height) / 2,\n x2 = (xMult * -width) / 2,\n y2 = (yMult * -height) / 2;\n\n return {\n x1,\n x2,\n y1,\n y2,\n };\n }\n\n /* _FROM_SVG_START_ */\n\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG() {\n const { x1, x2, y1, y2 } = this.calcLinePoints();\n return [\n '<line ',\n 'COMMON_PARTS',\n `x1=\"${x1}\" y1=\"${y1}\" x2=\"${x2}\" y2=\"${y2}\" />\\n`,\n ];\n }\n\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link Line.fromElement})\n * @static\n * @memberOf Line\n * @see http://www.w3.org/TR/SVG/shapes.html#LineElement\n */\n static ATTRIBUTE_NAMES = SHARED_ATTRIBUTES.concat(coordProps);\n\n /**\n * Returns Line instance from an SVG element\n * @static\n * @memberOf Line\n * @param {HTMLElement} element Element to parse\n * @param {Object} [options] Options object\n * @param {Function} [callback] callback function invoked after parsing\n */\n static async fromElement(\n element: HTMLElement,\n options: Abortable,\n cssRules?: CSSRules,\n ) {\n const {\n x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0,\n ...parsedAttributes\n } = parseAttributes(element, this.ATTRIBUTE_NAMES, cssRules);\n return new this([x1, y1, x2, y2], parsedAttributes);\n }\n\n /* _FROM_SVG_END_ */\n\n /**\n * Returns Line instance from an object representation\n * @static\n * @memberOf Line\n * @param {Object} object Object to create an instance from\n * @returns {Promise<Line>}\n */\n static fromObject<T extends TOptions<SerializedLineProps>>({\n x1,\n y1,\n x2,\n y2,\n ...object\n }: T) {\n return this._fromObject<Line>(\n {\n ...object,\n points: [x1, y1, x2, y2],\n },\n {\n extraParam: 'points',\n },\n );\n }\n}\n\nclassRegistry.setClass(Line);\nclassRegistry.setSVGClass(Line);\n"],"names":["coordProps","Line","FabricObject","constructor","x1","y1","x2","y2","arguments","length","undefined","options","Object","assign","ownDefaults","setOptions","_setWidthHeight","left","top","set","LEFT","TOP","width","Math","abs","height","makeBoundingBoxFromPoints","x","y","position","Point","setPositionByOrigin","CENTER","_set","key","value","includes","_render","ctx","beginPath","p","calcLinePoints","moveTo","lineTo","lineWidth","strokeWidth","origStrokeStyle","strokeStyle","isFiller","stroke","toLive","_this$stroke","fillStyle","_renderStroke","_findCenterFromElement","toObject","propertiesToInclude","_objectSpread","_getNonTransformedDimensions","dim","strokeLineCap","_x1","_x2","_y1","_y2","xMult","yMult","_toSVG","concat","fromElement","element","cssRules","_parseAttributes","parseAttributes","ATTRIBUTE_NAMES","parsedAttributes","_objectWithoutProperties","_excluded","fromObject","_ref","object","_excluded2","_fromObject","points","extraParam","_defineProperty","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAaA;;AAEA,MAAMA,UAAU,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAU,CAAA;AAa7C,MAAMC,IAAI,SAKPC,YAAY,CAEtB;AAgCE;AACF;AACA;AACA;AACA;AACA;AACEC,EAAAA,WAAWA,GAAgE;AAAA,IAAA,IAA/D,CAACC,EAAE,EAAEC,EAAE,EAAEC,EAAE,EAAEC,EAAE,CAAC,GAAAC,SAAA,CAAAC,MAAA,GAAA,CAAA,IAAAD,SAAA,CAAA,CAAA,CAAA,KAAAE,SAAA,GAAAF,SAAA,CAAA,CAAA,CAAA,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;AAAA,IAAA,IAAEG,OAAuB,GAAAH,SAAA,CA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AAW,CAAAzB,cAAA,CAAAA,cAAA,KAEhBuB,MAAM,CAAA,EAAA,EAAA,EAAA;MACTG,MAAM,EAAE,CAAC/E,EAAE,EAAEC,EAAE,EAAEC,EAAE,EAAEC,EAAE,CAAA;KAEzB,CAAA,EAAA;AACE6E,MAAAA,UAAU,EAAE,QAAA;AACd,KACF,CAAC,CAAA;AACH,GAAA;AACF,CAAA;AA5PE;AACF;AACA;AACA;AACA;AAGE;AACF;AACA;AACA;AACA;AAGE;AACF;AACA;AACA;AACA;AAGE;AACF;AACA;AACA;AACA;AAJEC,eAAA,CA7BWpF,IAAI,EAAA,MAAA,EAoCD,MAAM,CAAA,CAAA;AAAAoF,eAAA,CApCTpF,IAAI,EAsCU,iBAAA,EAAA,CAAC,GAAGqF,eAAe,EAAE,GAAGtF,UAAU,CAAC,CAAA,CAAA;AAAAqF,eAAA,CAtCjDpF,IAAI,EAiNUsF,iBAAAA,EAAAA,iBAAiB,CAACnB,MAAM,CAACpE,UAAU,CAAC,CAAA,CAAA;AAqD/DwF,aAAa,CAACC,QAAQ,CAACxF,IAAI,CAAC,CAAA;AAC5BuF,aAAa,CAACE,WAAW,CAACzF,IAAI,CAAC;;;;"}
|
|
1
|
+
{"version":3,"file":"Line.mjs","sources":["../../../src/shapes/Line.ts"],"sourcesContent":["import { SHARED_ATTRIBUTES } from '../parser/attributes';\nimport { parseAttributes } from '../parser/parseAttributes';\nimport type { Abortable, TClassProperties, TOptions } from '../typedefs';\nimport { classRegistry } from '../ClassRegistry';\nimport { FabricObject, cacheProperties } from './Object/FabricObject';\nimport { Point } from '../Point';\nimport { isFiller } from '../util/typeAssertions';\nimport type { FabricObjectProps, SerializedObjectProps } from './Object/types';\nimport type { ObjectEvents } from '../EventTypeDefs';\nimport { makeBoundingBoxFromPoints } from '../util';\nimport { CENTER, LEFT, TOP } from '../constants';\nimport type { CSSRules } from '../parser/typedefs';\n\n// @TODO this code is terrible and Line should be a special case of polyline.\n\nconst coordProps = ['x1', 'x2', 'y1', 'y2'] as const;\n\ninterface UniqueLineProps {\n x1: number;\n x2: number;\n y1: number;\n y2: number;\n}\n\nexport interface SerializedLineProps\n extends SerializedObjectProps,\n UniqueLineProps {}\n\nexport class Line<\n Props extends TOptions<FabricObjectProps> = Partial<FabricObjectProps>,\n SProps extends SerializedLineProps = SerializedLineProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n >\n extends FabricObject<Props, SProps, EventSpec>\n implements UniqueLineProps\n{\n /**\n * x value or first line edge\n * @type number\n * @default\n */\n declare x1: number;\n\n /**\n * y value or first line edge\n * @type number\n * @default\n */\n declare y1: number;\n\n /**\n * x value or second line edge\n * @type number\n * @default\n */\n declare x2: number;\n\n /**\n * y value or second line edge\n * @type number\n * @default\n */\n declare y2: number;\n\n static type = 'Line';\n\n static cacheProperties = [...cacheProperties, ...coordProps];\n /**\n * Constructor\n * @param {Array} [points] Array of points\n * @param {Object} [options] Options object\n * @return {Line} thisArg\n */\n constructor([x1, y1, x2, y2] = [0, 0, 0, 0], options: Partial<Props> = {}) {\n super();\n Object.assign(this, Line.ownDefaults);\n this.setOptions(options);\n this.x1 = x1;\n this.x2 = x2;\n this.y1 = y1;\n this.y2 = y2;\n this._setWidthHeight();\n const { left, top } = options;\n typeof left === 'number' && this.set(LEFT, left);\n typeof top === 'number' && this.set(TOP, top);\n }\n\n /**\n * @private\n * @param {Object} [options] Options\n */\n _setWidthHeight() {\n const { x1, y1, x2, y2 } = this;\n this.width = Math.abs(x2 - x1);\n this.height = Math.abs(y2 - y1);\n const { left, top, width, height } = makeBoundingBoxFromPoints([\n { x: x1, y: y1 },\n { x: x2, y: y2 },\n ]);\n const position = new Point(left + width / 2, top + height / 2);\n this.setPositionByOrigin(position, CENTER, CENTER);\n }\n\n /**\n * @private\n * @param {String} key\n * @param {*} value\n */\n _set(key: string, value: any) {\n super._set(key, value);\n if (coordProps.includes(key as keyof UniqueLineProps)) {\n // this doesn't make sense very much, since setting x1 when top or left\n // are already set, is just going to show a strange result since the\n // line will move way more than the developer expect.\n // in fabric5 it worked only when the line didn't have extra transformations,\n // in fabric6 too. With extra transform they behave bad in different ways.\n // This needs probably a good rework or a tutorial if you have to create a dynamic line\n this._setWidthHeight();\n }\n return this;\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx Context to render on\n */\n _render(ctx: CanvasRenderingContext2D) {\n ctx.beginPath();\n\n const p = this.calcLinePoints();\n ctx.moveTo(p.x1, p.y1);\n ctx.lineTo(p.x2, p.y2);\n\n ctx.lineWidth = this.strokeWidth;\n\n // TODO: test this\n // make sure setting \"fill\" changes color of a line\n // (by copying fillStyle to strokeStyle, since line is stroked, not filled)\n const origStrokeStyle = ctx.strokeStyle;\n if (isFiller(this.stroke)) {\n ctx.strokeStyle = this.stroke.toLive(ctx)!;\n } else {\n ctx.strokeStyle = this.stroke ?? ctx.fillStyle;\n }\n this.stroke && this._renderStroke(ctx);\n ctx.strokeStyle = origStrokeStyle;\n }\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates\n * @private\n * @return {Point} center point from element coordinates\n */\n _findCenterFromElement(): Point {\n return new Point((this.x1 + this.x2) / 2, (this.y1 + this.y2) / 2);\n }\n\n /**\n * Returns object representation of an instance\n * @method toObject\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n return {\n ...super.toObject(propertiesToInclude),\n ...this.calcLinePoints(),\n };\n }\n\n /*\n * Calculate object dimensions from its properties\n * @private\n */\n _getNonTransformedDimensions(): Point {\n const dim = super._getNonTransformedDimensions();\n if (this.strokeLineCap === 'butt') {\n if (this.width === 0) {\n dim.y -= this.strokeWidth;\n }\n if (this.height === 0) {\n dim.x -= this.strokeWidth;\n }\n }\n return dim;\n }\n\n /**\n * Recalculates line points given width and height\n * Those points are simply placed around the center,\n * This is not useful outside internal render functions and svg output\n * Is not meant to be for the developer.\n * @private\n */\n calcLinePoints(): UniqueLineProps {\n const { x1: _x1, x2: _x2, y1: _y1, y2: _y2, width, height } = this;\n const xMult = _x1 <= _x2 ? -1 : 1,\n yMult = _y1 <= _y2 ? -1 : 1,\n x1 = (xMult * width) / 2,\n y1 = (yMult * height) / 2,\n x2 = (xMult * -width) / 2,\n y2 = (yMult * -height) / 2;\n\n return {\n x1,\n x2,\n y1,\n y2,\n };\n }\n\n /* _FROM_SVG_START_ */\n\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG() {\n const { x1, x2, y1, y2 } = this.calcLinePoints();\n return [\n '<line ',\n 'COMMON_PARTS',\n `x1=\"${x1}\" y1=\"${y1}\" x2=\"${x2}\" y2=\"${y2}\" />\\n`,\n ];\n }\n\n /**\n * List of attribute names to account for when parsing SVG element (used by {@link Line.fromElement})\n * @static\n * @memberOf Line\n * @see http://www.w3.org/TR/SVG/shapes.html#LineElement\n */\n static ATTRIBUTE_NAMES = SHARED_ATTRIBUTES.concat(coordProps);\n\n /**\n * Returns Line instance from an SVG element\n * @static\n * @memberOf Line\n * @param {HTMLElement} element Element to parse\n * @param {Object} [options] Options object\n * @param {Function} [callback] callback function invoked after parsing\n */\n static async fromElement(\n element: HTMLElement,\n options: Abortable,\n cssRules?: CSSRules,\n ) {\n const {\n x1 = 0,\n y1 = 0,\n x2 = 0,\n y2 = 0,\n ...parsedAttributes\n } = parseAttributes(element, this.ATTRIBUTE_NAMES, cssRules);\n return new this([x1, y1, x2, y2], parsedAttributes);\n }\n\n /* _FROM_SVG_END_ */\n\n /**\n * Returns Line instance from an object representation\n * @static\n * @memberOf Line\n * @param {Object} object Object to create an instance from\n * @returns {Promise<Line>}\n */\n static fromObject<T extends TOptions<SerializedLineProps>>({\n x1,\n y1,\n x2,\n y2,\n ...object\n }: T) {\n return this._fromObject<Line>(\n {\n ...object,\n points: [x1, y1, x2, y2],\n },\n {\n extraParam: 'points',\n },\n );\n }\n}\n\nclassRegistry.setClass(Line);\nclassRegistry.setSVGClass(Line);\n"],"names":["coordProps","Line","FabricObject","constructor","x1","y1","x2","y2","arguments","length","undefined","options","Object","assign","ownDefaults","setOptions","_setWidthHeight","left","top","set","LEFT","TOP","width","Math","abs","height","makeBoundingBoxFromPoints","x","y","position","Point","setPositionByOrigin","CENTER","_set","key","value","includes","_render","ctx","beginPath","p","calcLinePoints","moveTo","lineTo","lineWidth","strokeWidth","origStrokeStyle","strokeStyle","isFiller","stroke","toLive","_this$stroke","fillStyle","_renderStroke","_findCenterFromElement","toObject","propertiesToInclude","_objectSpread","_getNonTransformedDimensions","dim","strokeLineCap","_x1","_x2","_y1","_y2","xMult","yMult","_toSVG","concat","fromElement","element","cssRules","_parseAttributes","parseAttributes","ATTRIBUTE_NAMES","parsedAttributes","_objectWithoutProperties","_excluded","fromObject","_ref","object","_excluded2","_fromObject","points","extraParam","_defineProperty","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":";;;;;;;;;;;;;;;;;;;;AAaA;;AAEA,MAAMA,UAAU,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAU,CAAA;AAa7C,MAAMC,IAAI,SAKPC,YAAY,CAEtB;AAgCE;AACF;AACA;AACA;AACA;AACA;AACEC,EAAAA,WAAWA,GAAgE;AAAA,IAAA,IAA/D,CAACC,EAAE,EAAEC,EAAE,EAAEC,EAAE,EAAEC,EAAE,CAAC,GAAAC,SAAA,CAAAC,MAAA,GAAA,CAAA,IAAAD,SAAA,CAAA,CAAA,CAAA,KAAAE,SAAA,GAAAF,SAAA,CAAA,CAAA,CAAA,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAA;AAAA,IAAA,IAAEG,OAAuB,GAAAH,SAAA,CAAAC,MAAA,GAAA,CAAA,IAAAD,SAAA,CAAA,CAAA,CAAA,KAAAE,S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AA,EAAA;MACTG,MAAM,EAAE,CAAC/E,EAAE,EAAEC,EAAE,EAAEC,EAAE,EAAEC,EAAE,CAAA;KAEzB,CAAA,EAAA;AACE6E,MAAAA,UAAU,EAAE,QAAA;AACd,KACF,CAAC,CAAA;AACH,GAAA;AACF,CAAA;AA5PE;AACF;AACA;AACA;AACA;AAGE;AACF;AACA;AACA;AACA;AAGE;AACF;AACA;AACA;AACA;AAGE;AACF;AACA;AACA;AACA;AAJEC,eAAA,CA7BWpF,IAAI,EAAA,MAAA,EAoCD,MAAM,CAAA,CAAA;AAAAoF,eAAA,CApCTpF,IAAI,EAsCU,iBAAA,EAAA,CAAC,GAAGqF,eAAe,EAAE,GAAGtF,UAAU,CAAC,CAAA,CAAA;AAAAqF,eAAA,CAtCjDpF,IAAI,EAiNUsF,iBAAAA,EAAAA,iBAAiB,CAACnB,MAAM,CAACpE,UAAU,CAAC,CAAA,CAAA;AAqD/DwF,aAAa,CAACC,QAAQ,CAACxF,IAAI,CAAC,CAAA;AAC5BuF,aAAa,CAACE,WAAW,CAACzF,IAAI,CAAC;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{defineProperty as t,objectWithoutProperties as e,objectSpread2 as s}from"../../_virtual/_rollupPluginBabelHelpers.min.mjs";import{config as r}from"../config.min.mjs";import{SHARED_ATTRIBUTES as i}from"../parser/attributes.min.mjs";import{parseAttributes as o}from"../parser/parseAttributes.min.mjs";import{Point as a}from"../Point.min.mjs";import{makeBoundingBoxFromPoints as n}from"../util/misc/boundingBoxFromPoints.min.mjs";import{toFixed as h}from"../util/misc/toFixed.min.mjs";import{makePathSimpler as c,parsePath as m,joinPath as p,getBoundsOfCurve as f}from"../util/path/index.min.mjs";import{classRegistry as l}from"../ClassRegistry.min.mjs";import{FabricObject as u}from"./Object/FabricObject.min.mjs";import{LEFT as d,TOP as _,CENTER as b}from"../constants.min.mjs";import{cacheProperties as O}from"./Object/defaultValues.min.mjs";const P=["path","left","top"],j=["d"];class g extends u{constructor(t){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{path:r,left:i,top:o}=s,a=e(s,P);super(),Object.assign(this,g.ownDefaults),this.setOptions(a),this._setPath(t||[],!0),"number"==typeof i&&this.set(d,i),"number"==typeof o&&this.set(_,o)}_setPath(t,e){this.path=c(Array.isArray(t)?t:m(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new a(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const r of this.path)switch(r[0]){case"L":t.lineTo(r[1]+e,r[2]+s);break;case"M":t.moveTo(r[1]+e,r[2]+s);break;case"C":t.bezierCurveTo(r[1]+e,r[2]+s,r[3]+e,r[4]+s,r[5]+e,r[6]+s);break;case"Q":t.quadraticCurveTo(r[1]+e,r[2]+s,r[3]+e,r[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return s(s({},super.toObject(t)),{},{path:this.path.map((t=>t.slice()))})}toDatalessObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=p(this.path,r.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,'" stroke-linecap="round" />\n')]}_getOffsetTransform(){const t=r.NUM_FRACTION_DIGITS;return" translate(".concat(h(-this.pathOffset.x,t),", ").concat(h(-this.pathOffset.y,t),")")}toClipPathSVG(t){const e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){const e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{width:e,height:s,pathOffset:r}=this._calcDimensions();this.set({width:e,height:s,pathOffset:r}),t&&this.setPositionByOrigin(r,b,b)}_calcBoundsFromPath(){const t=[];let e=0,s=0,r=0,i=0;for(const o of this.path)switch(o[0]){case"L":r=o[1],i=o[2],t.push(
|
|
1
|
+
import{defineProperty as t,objectWithoutProperties as e,objectSpread2 as s}from"../../_virtual/_rollupPluginBabelHelpers.min.mjs";import{config as r}from"../config.min.mjs";import{SHARED_ATTRIBUTES as i}from"../parser/attributes.min.mjs";import{parseAttributes as o}from"../parser/parseAttributes.min.mjs";import{Point as a}from"../Point.min.mjs";import{makeBoundingBoxFromPoints as n}from"../util/misc/boundingBoxFromPoints.min.mjs";import{toFixed as h}from"../util/misc/toFixed.min.mjs";import{makePathSimpler as c,parsePath as m,joinPath as p,getBoundsOfCurve as f}from"../util/path/index.min.mjs";import{classRegistry as l}from"../ClassRegistry.min.mjs";import{FabricObject as u}from"./Object/FabricObject.min.mjs";import{LEFT as d,TOP as _,CENTER as b}from"../constants.min.mjs";import{cacheProperties as O}from"./Object/defaultValues.min.mjs";const P=["path","left","top"],j=["d"];class g extends u{constructor(t){let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},{path:r,left:i,top:o}=s,a=e(s,P);super(),Object.assign(this,g.ownDefaults),this.setOptions(a),this._setPath(t||[],!0),"number"==typeof i&&this.set(d,i),"number"==typeof o&&this.set(_,o)}_setPath(t,e){this.path=c(Array.isArray(t)?t:m(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new a(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const r of this.path)switch(r[0]){case"L":t.lineTo(r[1]+e,r[2]+s);break;case"M":t.moveTo(r[1]+e,r[2]+s);break;case"C":t.bezierCurveTo(r[1]+e,r[2]+s,r[3]+e,r[4]+s,r[5]+e,r[6]+s);break;case"Q":t.quadraticCurveTo(r[1]+e,r[2]+s,r[3]+e,r[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return s(s({},super.toObject(t)),{},{path:this.path.map((t=>t.slice()))})}toDatalessObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=p(this.path,r.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,'" stroke-linecap="round" />\n')]}_getOffsetTransform(){const t=r.NUM_FRACTION_DIGITS;return" translate(".concat(h(-this.pathOffset.x,t),", ").concat(h(-this.pathOffset.y,t),")")}toClipPathSVG(t){const e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){const e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{width:e,height:s,pathOffset:r}=this._calcDimensions();this.set({width:e,height:s,pathOffset:r}),t&&this.setPositionByOrigin(r,b,b)}_calcBoundsFromPath(){const t=[];let e=0,s=0,r=0,i=0;for(const o of this.path)switch(o[0]){case"L":r=o[1],i=o[2],t.push({x:e,y:s},{x:r,y:i});break;case"M":r=o[1],i=o[2],e=r,s=i;break;case"C":t.push(...f(r,i,o[1],o[2],o[3],o[4],o[5],o[6])),r=o[5],i=o[6];break;case"Q":t.push(...f(r,i,o[1],o[2],o[1],o[2],o[3],o[4])),r=o[3],i=o[4];break;case"Z":r=e,i=s}return n(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return s(s({},t),{},{pathOffset:new a(t.left+t.width/2,t.top+t.height/2)})}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,r,i){const a=o(t,this.ATTRIBUTE_NAMES,i),{d:n}=a,h=e(a,j);return new this(n,s(s(s({},h),r),{},{left:void 0,top:void 0}))}}t(g,"type","Path"),t(g,"cacheProperties",[...O,"path","fillRule"]),t(g,"ATTRIBUTE_NAMES",[...i,"d"]),l.setClass(g),l.setSVGClass(g);export{g as Path};
|
|
2
2
|
//# sourceMappingURL=Path.min.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Path.min.mjs","sources":["../../../src/shapes/Path.ts"],"sourcesContent":["import { config } from '../config';\nimport { SHARED_ATTRIBUTES } from '../parser/attributes';\nimport { parseAttributes } from '../parser/parseAttributes';\nimport type { XY } from '../Point';\nimport { Point } from '../Point';\nimport { makeBoundingBoxFromPoints } from '../util/misc/boundingBoxFromPoints';\nimport { toFixed } from '../util/misc/toFixed';\nimport {\n getBoundsOfCurve,\n joinPath,\n makePathSimpler,\n parsePath,\n} from '../util/path';\nimport { classRegistry } from '../ClassRegistry';\nimport { FabricObject, cacheProperties } from './Object/FabricObject';\nimport type {\n TComplexPathData,\n TPathSegmentInfo,\n TSimplePathData,\n} from '../util/path/typedefs';\nimport type { FabricObjectProps, SerializedObjectProps } from './Object/types';\nimport type { ObjectEvents } from '../EventTypeDefs';\nimport type {\n TBBox,\n TClassProperties,\n TSVGReviver,\n TOptions,\n} from '../typedefs';\nimport { CENTER, LEFT, TOP } from '../constants';\nimport type { CSSRules } from '../parser/typedefs';\n\ninterface UniquePathProps {\n sourcePath?: string;\n path?: TSimplePathData;\n}\n\nexport interface SerializedPathProps\n extends SerializedObjectProps,\n UniquePathProps {}\n\nexport interface PathProps extends FabricObjectProps, UniquePathProps {}\n\nexport interface IPathBBox extends TBBox {\n left: number;\n top: number;\n pathOffset: Point;\n}\n\nexport class Path<\n Props extends TOptions<PathProps> = Partial<PathProps>,\n SProps extends SerializedPathProps = SerializedPathProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n> extends FabricObject<Props, SProps, EventSpec> {\n /**\n * Array of path points\n * @type Array\n * @default\n */\n declare path: TSimplePathData;\n\n declare pathOffset: Point;\n\n declare sourcePath?: string;\n\n declare segmentsInfo?: TPathSegmentInfo[];\n\n static type = 'Path';\n\n static cacheProperties = [...cacheProperties, 'path', 'fillRule'];\n\n /**\n * Constructor\n * @param {TComplexPathData} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {Partial<PathProps>} [options] Options object\n * @return {Path} thisArg\n */\n constructor(\n path: TComplexPathData | string,\n // todo: evaluate this spread here\n { path: _, left, top, ...options }: Partial<Props> = {},\n ) {\n super();\n Object.assign(this, Path.ownDefaults);\n this.setOptions(options);\n this._setPath(path || [], true);\n typeof left === 'number' && this.set(LEFT, left);\n typeof top === 'number' && this.set(TOP, top);\n }\n\n /**\n * @private\n * @param {TComplexPathData | string} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {boolean} [adjustPosition] pass true to reposition the object according to the bounding box\n * @returns {Point} top left position of the bounding box, useful for complementary positioning\n */\n _setPath(path: TComplexPathData | string, adjustPosition?: boolean) {\n this.path = makePathSimpler(Array.isArray(path) ? path : parsePath(path));\n this.setBoundingBox(adjustPosition);\n }\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates, by look at the polyline/polygon points.\n * @private\n * @return {Point} center point from element coordinates\n */\n _findCenterFromElement(): Point {\n const bbox = this._calcBoundsFromPath();\n return new Point(bbox.left + bbox.width / 2, bbox.top + bbox.height / 2);\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _renderPathCommands(ctx: CanvasRenderingContext2D) {\n const l = -this.pathOffset.x,\n t = -this.pathOffset.y;\n\n ctx.beginPath();\n\n for (const command of this.path) {\n switch (\n command[0] // first letter\n ) {\n case 'L': // lineto, absolute\n ctx.lineTo(command[1] + l, command[2] + t);\n break;\n\n case 'M': // moveTo, absolute\n ctx.moveTo(command[1] + l, command[2] + t);\n break;\n\n case 'C': // bezierCurveTo, absolute\n ctx.bezierCurveTo(\n command[1] + l,\n command[2] + t,\n command[3] + l,\n command[4] + t,\n command[5] + l,\n command[6] + t,\n );\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n ctx.quadraticCurveTo(\n command[1] + l,\n command[2] + t,\n command[3] + l,\n command[4] + t,\n );\n break;\n\n case 'Z':\n ctx.closePath();\n break;\n }\n }\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _render(ctx: CanvasRenderingContext2D) {\n this._renderPathCommands(ctx);\n this._renderPaintInOrder(ctx);\n }\n\n /**\n * Returns string representation of an instance\n * @return {string} string representation of an instance\n */\n toString() {\n return `#<Path (${this.complexity()}): { \"top\": ${this.top}, \"left\": ${\n this.left\n } }>`;\n }\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n return {\n ...super.toObject(propertiesToInclude),\n path: this.path.map((pathCmd) => pathCmd.slice()),\n };\n }\n\n /**\n * Returns dataless object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toDatalessObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n const o = this.toObject<T, K>(propertiesToInclude);\n if (this.sourcePath) {\n delete o.path;\n o.sourcePath = this.sourcePath;\n }\n return o;\n }\n\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG() {\n const path = joinPath(this.path, config.NUM_FRACTION_DIGITS);\n return [\n '<path ',\n 'COMMON_PARTS',\n `d=\"${path}\" stroke-linecap=\"round\" />\\n`,\n ];\n }\n\n /**\n * @private\n * @return the path command's translate transform attribute\n */\n _getOffsetTransform() {\n const digits = config.NUM_FRACTION_DIGITS;\n return ` translate(${toFixed(-this.pathOffset.x, digits)}, ${toFixed(\n -this.pathOffset.y,\n digits,\n )})`;\n }\n\n /**\n * Returns svg clipPath representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {string} svg representation of an instance\n */\n toClipPathSVG(reviver?: TSVGReviver): string {\n const additionalTransform = this._getOffsetTransform();\n return (\n '\\t' +\n this._createBaseClipPathSVGMarkup(this._toSVG(), {\n reviver,\n additionalTransform: additionalTransform,\n })\n );\n }\n\n /**\n * Returns svg representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {string} svg representation of an instance\n */\n toSVG(reviver?: TSVGReviver): string {\n const additionalTransform = this._getOffsetTransform();\n return this._createBaseSVGMarkup(this._toSVG(), {\n reviver,\n additionalTransform: additionalTransform,\n });\n }\n\n /**\n * Returns number representation of an instance complexity\n * @return {number} complexity of this instance\n */\n complexity() {\n return this.path.length;\n }\n\n setDimensions() {\n this.setBoundingBox();\n }\n\n setBoundingBox(adjustPosition?: boolean) {\n const { width, height, pathOffset } = this._calcDimensions();\n this.set({ width, height, pathOffset });\n // using pathOffset because it match the use case.\n // if pathOffset change here we need to use left + width/2 , top + height/2\n adjustPosition && this.setPositionByOrigin(pathOffset, CENTER, CENTER);\n }\n\n _calcBoundsFromPath(): TBBox {\n const bounds: XY[] = [];\n let subpathStartX = 0,\n subpathStartY = 0,\n x = 0, // current x\n y = 0; // current y\n\n for (const command of this.path) {\n // current instruction\n switch (\n command[0] // first letter\n ) {\n case 'L': // lineto, absolute\n x = command[1];\n y = command[2];\n bounds.push(new Point(subpathStartX, subpathStartY), new Point(x, y));\n break;\n\n case 'M': // moveTo, absolute\n x = command[1];\n y = command[2];\n subpathStartX = x;\n subpathStartY = y;\n break;\n\n case 'C': // bezierCurveTo, absolute\n bounds.push(\n ...getBoundsOfCurve(\n x,\n y,\n command[1],\n command[2],\n command[3],\n command[4],\n command[5],\n command[6],\n ),\n );\n x = command[5];\n y = command[6];\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n bounds.push(\n ...getBoundsOfCurve(\n x,\n y,\n command[1],\n command[2],\n command[1],\n command[2],\n command[3],\n command[4],\n ),\n );\n x = command[3];\n y = command[4];\n break;\n\n case 'Z':\n x = subpathStartX;\n y = subpathStartY;\n break;\n }\n }\n return makeBoundingBoxFromPoints(bounds);\n }\n\n /**\n * @private\n */\n _calcDimensions(): IPathBBox {\n const bbox = this._calcBoundsFromPath();\n\n return {\n ...bbox,\n pathOffset: new Point(\n bbox.left + bbox.width / 2,\n bbox.top + bbox.height / 2,\n ),\n };\n }\n\n /**\n * List of attribute names to account for when parsing SVG element (used by `Path.fromElement`)\n * @static\n * @memberOf Path\n * @see http://www.w3.org/TR/SVG/paths.html#PathElement\n */\n static ATTRIBUTE_NAMES = [...SHARED_ATTRIBUTES, 'd'];\n\n /**\n * Creates an instance of Path from an object\n * @static\n * @memberOf Path\n * @param {Object} object\n * @returns {Promise<Path>}\n */\n static fromObject<T extends TOptions<SerializedPathProps>>(object: T) {\n return this._fromObject<Path>(object, {\n extraParam: 'path',\n });\n }\n\n /**\n * Creates an instance of Path from an SVG <path> element\n * @static\n * @memberOf Path\n * @param {HTMLElement} element to parse\n * @param {Partial<PathProps>} [options] Options object\n */\n static async fromElement(\n element: HTMLElement,\n options: Partial<PathProps>,\n cssRules?: CSSRules,\n ) {\n const { d, ...parsedAttributes } = parseAttributes(\n element,\n this.ATTRIBUTE_NAMES,\n cssRules,\n );\n return new this(d, {\n ...parsedAttributes,\n ...options,\n // we pass undefined to instruct the constructor to position the object using the bbox\n left: undefined,\n top: undefined,\n });\n }\n}\n\nclassRegistry.setClass(Path);\nclassRegistry.setSVGClass(Path);\n\n/* _FROM_SVG_START_ */\n"],"names":["Path","FabricObject","constructor","path","_ref","arguments","length","undefined","_","left","top","options","_objectWithoutProperties","_excluded","super","Object","assign","this","ownDefaults","setOptions","_setPath","set","LEFT","TOP","adjustPosition","makePathSimpler","Array","isArray","parsePath","setBoundingBox","_findCenterFromElement","bbox","_calcBoundsFromPath","Point","width","height","_renderPathCommands","ctx","l","pathOffset","x","t","y","beginPath","command","lineTo","moveTo","bezierCurveTo","quadraticCurveTo","closePath","_render","_renderPaintInOrder","toString","concat","complexity","toObject","propertiesToInclude","_objectSpread","map","pathCmd","slice","toDatalessObject","o","sourcePath","_toSVG","joinPath","config","NUM_FRACTION_DIGITS","_getOffsetTransform","digits","toFixed","toClipPathSVG","reviver","additionalTransform","_createBaseClipPathSVGMarkup","toSVG","_createBaseSVGMarkup","setDimensions","_calcDimensions","setPositionByOrigin","CENTER","bounds","subpathStartX","subpathStartY","push","getBoundsOfCurve","makeBoundingBoxFromPoints","fromObject","object","_fromObject","extraParam","fromElement","element","cssRules","_parseAttributes","parseAttributes","ATTRIBUTE_NAMES","d","parsedAttributes","_excluded2","_defineProperty","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":"u3BAgDO,MAAMA,UAIHC,EAwBRC,WAAAA,CACEC,GAGA,IAAAC,EAAAC,UAAAC,OAAA,QAAAC,IAAAF,UAAA,GAAAA,UAAA,GADqD,CAAE,GAArDF,KAAMK,EAACC,KAAEA,EAAIC,IAAEA,GAAiCN,EAAzBO,EAAOC,EAAAR,EAAAS,GAEhCC,QACAC,OAAOC,OAAOC,KAAMjB,EAAKkB,aACzBD,KAAKE,WAAWR,GAChBM,KAAKG,SAASjB,GAAQ,IAAI,GACV,iBAATM,GAAqBQ,KAAKI,IAAIC,EAAMb,GAC5B,iBAARC,GAAoBO,KAAKI,IAAIE,EAAKb,EAC3C,CAQAU,QAAAA,CAASjB,EAAiCqB,GACxCP,KAAKd,KAAOsB,EAAgBC,MAAMC,QAAQxB,GAAQA,EAAOyB,EAAUzB,IACnEc,KAAKY,eAAeL,EACtB,CAQAM,sBAAAA,GACE,MAAMC,EAAO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AcC,SAASxG,GACvBuG,EAAcE,YAAYzG"}
|
|
1
|
+
{"version":3,"file":"Path.min.mjs","sources":["../../../src/shapes/Path.ts"],"sourcesContent":["import { config } from '../config';\nimport { SHARED_ATTRIBUTES } from '../parser/attributes';\nimport { parseAttributes } from '../parser/parseAttributes';\nimport type { XY } from '../Point';\nimport { Point } from '../Point';\nimport { makeBoundingBoxFromPoints } from '../util/misc/boundingBoxFromPoints';\nimport { toFixed } from '../util/misc/toFixed';\nimport {\n getBoundsOfCurve,\n joinPath,\n makePathSimpler,\n parsePath,\n} from '../util/path';\nimport { classRegistry } from '../ClassRegistry';\nimport { FabricObject, cacheProperties } from './Object/FabricObject';\nimport type {\n TComplexPathData,\n TPathSegmentInfo,\n TSimplePathData,\n} from '../util/path/typedefs';\nimport type { FabricObjectProps, SerializedObjectProps } from './Object/types';\nimport type { ObjectEvents } from '../EventTypeDefs';\nimport type {\n TBBox,\n TClassProperties,\n TSVGReviver,\n TOptions,\n} from '../typedefs';\nimport { CENTER, LEFT, TOP } from '../constants';\nimport type { CSSRules } from '../parser/typedefs';\n\ninterface UniquePathProps {\n sourcePath?: string;\n path?: TSimplePathData;\n}\n\nexport interface SerializedPathProps\n extends SerializedObjectProps,\n UniquePathProps {}\n\nexport interface PathProps extends FabricObjectProps, UniquePathProps {}\n\nexport interface IPathBBox extends TBBox {\n left: number;\n top: number;\n pathOffset: Point;\n}\n\nexport class Path<\n Props extends TOptions<PathProps> = Partial<PathProps>,\n SProps extends SerializedPathProps = SerializedPathProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n> extends FabricObject<Props, SProps, EventSpec> {\n /**\n * Array of path points\n * @type Array\n * @default\n */\n declare path: TSimplePathData;\n\n declare pathOffset: Point;\n\n declare sourcePath?: string;\n\n declare segmentsInfo?: TPathSegmentInfo[];\n\n static type = 'Path';\n\n static cacheProperties = [...cacheProperties, 'path', 'fillRule'];\n\n /**\n * Constructor\n * @param {TComplexPathData} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {Partial<PathProps>} [options] Options object\n * @return {Path} thisArg\n */\n constructor(\n path: TComplexPathData | string,\n // todo: evaluate this spread here\n { path: _, left, top, ...options }: Partial<Props> = {},\n ) {\n super();\n Object.assign(this, Path.ownDefaults);\n this.setOptions(options);\n this._setPath(path || [], true);\n typeof left === 'number' && this.set(LEFT, left);\n typeof top === 'number' && this.set(TOP, top);\n }\n\n /**\n * @private\n * @param {TComplexPathData | string} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {boolean} [adjustPosition] pass true to reposition the object according to the bounding box\n * @returns {Point} top left position of the bounding box, useful for complementary positioning\n */\n _setPath(path: TComplexPathData | string, adjustPosition?: boolean) {\n this.path = makePathSimpler(Array.isArray(path) ? path : parsePath(path));\n this.setBoundingBox(adjustPosition);\n }\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates, by look at the polyline/polygon points.\n * @private\n * @return {Point} center point from element coordinates\n */\n _findCenterFromElement(): Point {\n const bbox = this._calcBoundsFromPath();\n return new Point(bbox.left + bbox.width / 2, bbox.top + bbox.height / 2);\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _renderPathCommands(ctx: CanvasRenderingContext2D) {\n const l = -this.pathOffset.x,\n t = -this.pathOffset.y;\n\n ctx.beginPath();\n\n for (const command of this.path) {\n switch (\n command[0] // first letter\n ) {\n case 'L': // lineto, absolute\n ctx.lineTo(command[1] + l, command[2] + t);\n break;\n\n case 'M': // moveTo, absolute\n ctx.moveTo(command[1] + l, command[2] + t);\n break;\n\n case 'C': // bezierCurveTo, absolute\n ctx.bezierCurveTo(\n command[1] + l,\n command[2] + t,\n command[3] + l,\n command[4] + t,\n command[5] + l,\n command[6] + t,\n );\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n ctx.quadraticCurveTo(\n command[1] + l,\n command[2] + t,\n command[3] + l,\n command[4] + t,\n );\n break;\n\n case 'Z':\n ctx.closePath();\n break;\n }\n }\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _render(ctx: CanvasRenderingContext2D) {\n this._renderPathCommands(ctx);\n this._renderPaintInOrder(ctx);\n }\n\n /**\n * Returns string representation of an instance\n * @return {string} string representation of an instance\n */\n toString() {\n return `#<Path (${this.complexity()}): { \"top\": ${this.top}, \"left\": ${\n this.left\n } }>`;\n }\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n return {\n ...super.toObject(propertiesToInclude),\n path: this.path.map((pathCmd) => pathCmd.slice()),\n };\n }\n\n /**\n * Returns dataless object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toDatalessObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n const o = this.toObject<T, K>(propertiesToInclude);\n if (this.sourcePath) {\n delete o.path;\n o.sourcePath = this.sourcePath;\n }\n return o;\n }\n\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG() {\n const path = joinPath(this.path, config.NUM_FRACTION_DIGITS);\n return [\n '<path ',\n 'COMMON_PARTS',\n `d=\"${path}\" stroke-linecap=\"round\" />\\n`,\n ];\n }\n\n /**\n * @private\n * @return the path command's translate transform attribute\n */\n _getOffsetTransform() {\n const digits = config.NUM_FRACTION_DIGITS;\n return ` translate(${toFixed(-this.pathOffset.x, digits)}, ${toFixed(\n -this.pathOffset.y,\n digits,\n )})`;\n }\n\n /**\n * Returns svg clipPath representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {string} svg representation of an instance\n */\n toClipPathSVG(reviver?: TSVGReviver): string {\n const additionalTransform = this._getOffsetTransform();\n return (\n '\\t' +\n this._createBaseClipPathSVGMarkup(this._toSVG(), {\n reviver,\n additionalTransform: additionalTransform,\n })\n );\n }\n\n /**\n * Returns svg representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {string} svg representation of an instance\n */\n toSVG(reviver?: TSVGReviver): string {\n const additionalTransform = this._getOffsetTransform();\n return this._createBaseSVGMarkup(this._toSVG(), {\n reviver,\n additionalTransform: additionalTransform,\n });\n }\n\n /**\n * Returns number representation of an instance complexity\n * @return {number} complexity of this instance\n */\n complexity() {\n return this.path.length;\n }\n\n setDimensions() {\n this.setBoundingBox();\n }\n\n setBoundingBox(adjustPosition?: boolean) {\n const { width, height, pathOffset } = this._calcDimensions();\n this.set({ width, height, pathOffset });\n // using pathOffset because it match the use case.\n // if pathOffset change here we need to use left + width/2 , top + height/2\n adjustPosition && this.setPositionByOrigin(pathOffset, CENTER, CENTER);\n }\n\n _calcBoundsFromPath(): TBBox {\n const bounds: XY[] = [];\n let subpathStartX = 0,\n subpathStartY = 0,\n x = 0, // current x\n y = 0; // current y\n\n for (const command of this.path) {\n // current instruction\n switch (\n command[0] // first letter\n ) {\n case 'L': // lineto, absolute\n x = command[1];\n y = command[2];\n bounds.push({ x: subpathStartX, y: subpathStartY }, { x, y });\n break;\n\n case 'M': // moveTo, absolute\n x = command[1];\n y = command[2];\n subpathStartX = x;\n subpathStartY = y;\n break;\n\n case 'C': // bezierCurveTo, absolute\n bounds.push(\n ...getBoundsOfCurve(\n x,\n y,\n command[1],\n command[2],\n command[3],\n command[4],\n command[5],\n command[6],\n ),\n );\n x = command[5];\n y = command[6];\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n bounds.push(\n ...getBoundsOfCurve(\n x,\n y,\n command[1],\n command[2],\n command[1],\n command[2],\n command[3],\n command[4],\n ),\n );\n x = command[3];\n y = command[4];\n break;\n\n case 'Z':\n x = subpathStartX;\n y = subpathStartY;\n break;\n }\n }\n return makeBoundingBoxFromPoints(bounds);\n }\n\n /**\n * @private\n */\n _calcDimensions(): IPathBBox {\n const bbox = this._calcBoundsFromPath();\n\n return {\n ...bbox,\n pathOffset: new Point(\n bbox.left + bbox.width / 2,\n bbox.top + bbox.height / 2,\n ),\n };\n }\n\n /**\n * List of attribute names to account for when parsing SVG element (used by `Path.fromElement`)\n * @static\n * @memberOf Path\n * @see http://www.w3.org/TR/SVG/paths.html#PathElement\n */\n static ATTRIBUTE_NAMES = [...SHARED_ATTRIBUTES, 'd'];\n\n /**\n * Creates an instance of Path from an object\n * @static\n * @memberOf Path\n * @param {Object} object\n * @returns {Promise<Path>}\n */\n static fromObject<T extends TOptions<SerializedPathProps>>(object: T) {\n return this._fromObject<Path>(object, {\n extraParam: 'path',\n });\n }\n\n /**\n * Creates an instance of Path from an SVG <path> element\n * @static\n * @memberOf Path\n * @param {HTMLElement} element to parse\n * @param {Partial<PathProps>} [options] Options object\n */\n static async fromElement(\n element: HTMLElement,\n options: Partial<PathProps>,\n cssRules?: CSSRules,\n ) {\n const { d, ...parsedAttributes } = parseAttributes(\n element,\n this.ATTRIBUTE_NAMES,\n cssRules,\n );\n return new this(d, {\n ...parsedAttributes,\n ...options,\n // we pass undefined to instruct the constructor to position the object using the bbox\n left: undefined,\n top: undefined,\n });\n }\n}\n\nclassRegistry.setClass(Path);\nclassRegistry.setSVGClass(Path);\n\n/* _FROM_SVG_START_ */\n"],"names":["Path","FabricObject","constructor","path","_ref","arguments","length","undefined","_","left","top","options","_objectWithoutProperties","_excluded","super","Object","assign","this","ownDefaults","setOptions","_setPath","set","LEFT","TOP","adjustPosition","makePathSimpler","Array","isArray","parsePath","setBoundingBox","_findCenterFromElement","bbox","_calcBoundsFromPath","Point","width","height","_renderPathCommands","ctx","l","pathOffset","x","t","y","beginPath","command","lineTo","moveTo","bezierCurveTo","quadraticCurveTo","closePath","_render","_renderPaintInOrder","toString","concat","complexity","toObject","propertiesToInclude","_objectSpread","map","pathCmd","slice","toDatalessObject","o","sourcePath","_toSVG","joinPath","config","NUM_FRACTION_DIGITS","_getOffsetTransform","digits","toFixed","toClipPathSVG","reviver","additionalTransform","_createBaseClipPathSVGMarkup","toSVG","_createBaseSVGMarkup","setDimensions","_calcDimensions","setPositionByOrigin","CENTER","bounds","subpathStartX","subpathStartY","push","getBoundsOfCurve","makeBoundingBoxFromPoints","fromObject","object","_fromObject","extraParam","fromElement","element","cssRules","_parseAttributes","parseAttributes","ATTRIBUTE_NAMES","d","parsedAttributes","_excluded2","_defineProperty","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":"u3BAgDO,MAAMA,UAIHC,EAwBRC,WAAAA,CACEC,GAGA,IAAAC,EAAAC,UAAAC,OAAA,QAAAC,IAAAF,UAAA,GAAAA,UAAA,GADqD,CAAE,GAArDF,KAAMK,EAACC,KAAEA,EAAIC,IAAEA,GAAiCN,EAAzBO,EAAOC,EAAAR,EAAAS,GAEhCC,QACAC,OAAOC,OAAOC,KAAMjB,EAAKkB,aACzBD,KAAKE,WAAWR,GAChBM,KAAKG,SAASjB,GAAQ,IAAI,GACV,iBAATM,GAAqBQ,KAAKI,IAAIC,EAAMb,GAC5B,iBAARC,GAAoBO,KAAKI,IAAIE,EAAKb,EAC3C,CAQAU,QAAAA,CAASjB,EAAiCqB,GACxCP,KAAKd,KAAOsB,EAAgBC,MAAMC,QAAQxB,GAAQA,EAAOyB,EAAUzB,IACnEc,KAAKY,eAAeL,EACtB,CAQAM,sBAAAA,GACE,MAAMC,EAAOd,KAAKe,sBAClB,OAAO,IAAIC,EAAMF,EAAKtB,KAAOsB,EAAKG,MAAQ,EAAGH,EAAKrB,IAAMqB,EAAKI,OAAS,EACxE,CAMAC,mBAAAA,CAAoBC,GAClB,MAAMC,GAAKrB,KAAKsB,WAAWC,EACzBC,GAAKxB,KAAKsB,WAAWG,EAEvBL,EAAIM,YAEJ,IAAK,MAAMC,KAAW3B,KAAKd,KACzB,OACEyC,EAAQ,IAER,IAAK,IACH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IAAK,IACHqC,EAAOG,QACFC,EACD7C,EACAE,EACAE,EAAQ,GACRA,EAAQ,GACRA,EAAQ,GACRA,EAAQ,GACRA,EAAQ,GACRA,EAAQ,KAGZJ,EAAII,EAAQ,GACZF,EAAIE,EAAQ,GACZ,MAEF,IAAK,IACHJ,EAAI0C,EACJxC,EAAIyC,EAIV,OAAOG,EAA0BL,EACnC,CAKAH,eAAAA,GACE,MAAM/C,EAAOd,KAAKe,sBAElB,OAAAyB,EAAAA,EAAA,CAAA,EACK1B,GAAI,CAAA,EAAA,CACPQ,WAAY,IAAIN,EACdF,EAAKtB,KAAOsB,EAAKG,MAAQ,EACzBH,EAAKrB,IAAMqB,EAAKI,OAAS,IAG/B,CAiBA,iBAAOoD,CAAoDC,GACzD,OAAOvE,KAAKwE,YAAkBD,EAAQ,CACpCE,WAAY,QAEhB,CASA,wBAAaC,CACXC,EACAjF,EACAkF,GAEA,MAAAC,EAAmCC,EACjCH,EACA3E,KAAK+E,gBACLH,IAHII,EAAEA,GAAwBH,EAAlBI,EAAgBtF,EAAAkF,EAAAK,GAK9B,OAAO,IAAIlF,KAAKgF,EAACxC,EAAAA,EAAAA,EACZyC,CAAAA,EAAAA,GACAvF,GAAO,CAAA,EAAA,CAEVF,UAAMF,EACNG,SAAKH,IAET,EAzWA6F,EALWpG,EAAI,OAkBD,QAAMoG,EAlBTpG,EAAI,kBAoBU,IAAIqG,EAAiB,OAAQ,aAAWD,EApBtDpG,EAuUc,kBAAA,IAAIsG,EAAmB,MA0ClDC,EAAcC,SAASxG,GACvBuG,EAAcE,YAAYzG"}
|
package/dist/src/shapes/Path.mjs
CHANGED
|
@@ -222,7 +222,13 @@ class Path extends FabricObject {
|
|
|
222
222
|
// lineto, absolute
|
|
223
223
|
x = command[1];
|
|
224
224
|
y = command[2];
|
|
225
|
-
bounds.push(
|
|
225
|
+
bounds.push({
|
|
226
|
+
x: subpathStartX,
|
|
227
|
+
y: subpathStartY
|
|
228
|
+
}, {
|
|
229
|
+
x,
|
|
230
|
+
y
|
|
231
|
+
});
|
|
226
232
|
break;
|
|
227
233
|
case 'M':
|
|
228
234
|
// moveTo, absolute
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Path.mjs","sources":["../../../src/shapes/Path.ts"],"sourcesContent":["import { config } from '../config';\nimport { SHARED_ATTRIBUTES } from '../parser/attributes';\nimport { parseAttributes } from '../parser/parseAttributes';\nimport type { XY } from '../Point';\nimport { Point } from '../Point';\nimport { makeBoundingBoxFromPoints } from '../util/misc/boundingBoxFromPoints';\nimport { toFixed } from '../util/misc/toFixed';\nimport {\n getBoundsOfCurve,\n joinPath,\n makePathSimpler,\n parsePath,\n} from '../util/path';\nimport { classRegistry } from '../ClassRegistry';\nimport { FabricObject, cacheProperties } from './Object/FabricObject';\nimport type {\n TComplexPathData,\n TPathSegmentInfo,\n TSimplePathData,\n} from '../util/path/typedefs';\nimport type { FabricObjectProps, SerializedObjectProps } from './Object/types';\nimport type { ObjectEvents } from '../EventTypeDefs';\nimport type {\n TBBox,\n TClassProperties,\n TSVGReviver,\n TOptions,\n} from '../typedefs';\nimport { CENTER, LEFT, TOP } from '../constants';\nimport type { CSSRules } from '../parser/typedefs';\n\ninterface UniquePathProps {\n sourcePath?: string;\n path?: TSimplePathData;\n}\n\nexport interface SerializedPathProps\n extends SerializedObjectProps,\n UniquePathProps {}\n\nexport interface PathProps extends FabricObjectProps, UniquePathProps {}\n\nexport interface IPathBBox extends TBBox {\n left: number;\n top: number;\n pathOffset: Point;\n}\n\nexport class Path<\n Props extends TOptions<PathProps> = Partial<PathProps>,\n SProps extends SerializedPathProps = SerializedPathProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n> extends FabricObject<Props, SProps, EventSpec> {\n /**\n * Array of path points\n * @type Array\n * @default\n */\n declare path: TSimplePathData;\n\n declare pathOffset: Point;\n\n declare sourcePath?: string;\n\n declare segmentsInfo?: TPathSegmentInfo[];\n\n static type = 'Path';\n\n static cacheProperties = [...cacheProperties, 'path', 'fillRule'];\n\n /**\n * Constructor\n * @param {TComplexPathData} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {Partial<PathProps>} [options] Options object\n * @return {Path} thisArg\n */\n constructor(\n path: TComplexPathData | string,\n // todo: evaluate this spread here\n { path: _, left, top, ...options }: Partial<Props> = {},\n ) {\n super();\n Object.assign(this, Path.ownDefaults);\n this.setOptions(options);\n this._setPath(path || [], true);\n typeof left === 'number' && this.set(LEFT, left);\n typeof top === 'number' && this.set(TOP, top);\n }\n\n /**\n * @private\n * @param {TComplexPathData | string} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {boolean} [adjustPosition] pass true to reposition the object according to the bounding box\n * @returns {Point} top left position of the bounding box, useful for complementary positioning\n */\n _setPath(path: TComplexPathData | string, adjustPosition?: boolean) {\n this.path = makePathSimpler(Array.isArray(path) ? path : parsePath(path));\n this.setBoundingBox(adjustPosition);\n }\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates, by look at the polyline/polygon points.\n * @private\n * @return {Point} center point from element coordinates\n */\n _findCenterFromElement(): Point {\n const bbox = this._calcBoundsFromPath();\n return new Point(bbox.left + bbox.width / 2, bbox.top + bbox.height / 2);\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _renderPathCommands(ctx: CanvasRenderingContext2D) {\n const l = -this.pathOffset.x,\n t = -this.pathOffset.y;\n\n ctx.beginPath();\n\n for (const command of this.path) {\n switch (\n command[0] // first letter\n ) {\n case 'L': // lineto, absolute\n ctx.lineTo(command[1] + l, command[2] + t);\n break;\n\n case 'M': // moveTo, absolute\n ctx.moveTo(command[1] + l, command[2] + t);\n break;\n\n case 'C': // bezierCurveTo, absolute\n ctx.bezierCurveTo(\n command[1] + l,\n command[2] + t,\n command[3] + l,\n command[4] + t,\n command[5] + l,\n command[6] + t,\n );\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n ctx.quadraticCurveTo(\n command[1] + l,\n command[2] + t,\n command[3] + l,\n command[4] + t,\n );\n break;\n\n case 'Z':\n ctx.closePath();\n break;\n }\n }\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _render(ctx: CanvasRenderingContext2D) {\n this._renderPathCommands(ctx);\n this._renderPaintInOrder(ctx);\n }\n\n /**\n * Returns string representation of an instance\n * @return {string} string representation of an instance\n */\n toString() {\n return `#<Path (${this.complexity()}): { \"top\": ${this.top}, \"left\": ${\n this.left\n } }>`;\n }\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n return {\n ...super.toObject(propertiesToInclude),\n path: this.path.map((pathCmd) => pathCmd.slice()),\n };\n }\n\n /**\n * Returns dataless object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toDatalessObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n const o = this.toObject<T, K>(propertiesToInclude);\n if (this.sourcePath) {\n delete o.path;\n o.sourcePath = this.sourcePath;\n }\n return o;\n }\n\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG() {\n const path = joinPath(this.path, config.NUM_FRACTION_DIGITS);\n return [\n '<path ',\n 'COMMON_PARTS',\n `d=\"${path}\" stroke-linecap=\"round\" />\\n`,\n ];\n }\n\n /**\n * @private\n * @return the path command's translate transform attribute\n */\n _getOffsetTransform() {\n const digits = config.NUM_FRACTION_DIGITS;\n return ` translate(${toFixed(-this.pathOffset.x, digits)}, ${toFixed(\n -this.pathOffset.y,\n digits,\n )})`;\n }\n\n /**\n * Returns svg clipPath representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {string} svg representation of an instance\n */\n toClipPathSVG(reviver?: TSVGReviver): string {\n const additionalTransform = this._getOffsetTransform();\n return (\n '\\t' +\n this._createBaseClipPathSVGMarkup(this._toSVG(), {\n reviver,\n additionalTransform: additionalTransform,\n })\n );\n }\n\n /**\n * Returns svg representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {string} svg representation of an instance\n */\n toSVG(reviver?: TSVGReviver): string {\n const additionalTransform = this._getOffsetTransform();\n return this._createBaseSVGMarkup(this._toSVG(), {\n reviver,\n additionalTransform: additionalTransform,\n });\n }\n\n /**\n * Returns number representation of an instance complexity\n * @return {number} complexity of this instance\n */\n complexity() {\n return this.path.length;\n }\n\n setDimensions() {\n this.setBoundingBox();\n }\n\n setBoundingBox(adjustPosition?: boolean) {\n const { width, height, pathOffset } = this._calcDimensions();\n this.set({ width, height, pathOffset });\n // using pathOffset because it match the use case.\n // if pathOffset change here we need to use left + width/2 , top + height/2\n adjustPosition && this.setPositionByOrigin(pathOffset, CENTER, CENTER);\n }\n\n _calcBoundsFromPath(): TBBox {\n const bounds: XY[] = [];\n let subpathStartX = 0,\n subpathStartY = 0,\n x = 0, // current x\n y = 0; // current y\n\n for (const command of this.path) {\n // current instruction\n switch (\n command[0] // first letter\n ) {\n case 'L': // lineto, absolute\n x = command[1];\n y = command[2];\n bounds.push(new Point(subpathStartX, subpathStartY), new Point(x, y));\n break;\n\n case 'M': // moveTo, absolute\n x = command[1];\n y = command[2];\n subpathStartX = x;\n subpathStartY = y;\n break;\n\n case 'C': // bezierCurveTo, absolute\n bounds.push(\n ...getBoundsOfCurve(\n x,\n y,\n command[1],\n command[2],\n command[3],\n command[4],\n command[5],\n command[6],\n ),\n );\n x = command[5];\n y = command[6];\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n bounds.push(\n ...getBoundsOfCurve(\n x,\n y,\n command[1],\n command[2],\n command[1],\n command[2],\n command[3],\n command[4],\n ),\n );\n x = command[3];\n y = command[4];\n break;\n\n case 'Z':\n x = subpathStartX;\n y = subpathStartY;\n break;\n }\n }\n return makeBoundingBoxFromPoints(bounds);\n }\n\n /**\n * @private\n */\n _calcDimensions(): IPathBBox {\n const bbox = this._calcBoundsFromPath();\n\n return {\n ...bbox,\n pathOffset: new Point(\n bbox.left + bbox.width / 2,\n bbox.top + bbox.height / 2,\n ),\n };\n }\n\n /**\n * List of attribute names to account for when parsing SVG element (used by `Path.fromElement`)\n * @static\n * @memberOf Path\n * @see http://www.w3.org/TR/SVG/paths.html#PathElement\n */\n static ATTRIBUTE_NAMES = [...SHARED_ATTRIBUTES, 'd'];\n\n /**\n * Creates an instance of Path from an object\n * @static\n * @memberOf Path\n * @param {Object} object\n * @returns {Promise<Path>}\n */\n static fromObject<T extends TOptions<SerializedPathProps>>(object: T) {\n return this._fromObject<Path>(object, {\n extraParam: 'path',\n });\n }\n\n /**\n * Creates an instance of Path from an SVG <path> element\n * @static\n * @memberOf Path\n * @param {HTMLElement} element to parse\n * @param {Partial<PathProps>} [options] Options object\n */\n static async fromElement(\n element: HTMLElement,\n options: Partial<PathProps>,\n cssRules?: CSSRules,\n ) {\n const { d, ...parsedAttributes } = parseAttributes(\n element,\n this.ATTRIBUTE_NAMES,\n cssRules,\n );\n return new this(d, {\n ...parsedAttributes,\n ...options,\n // we pass undefined to instruct the constructor to position the object using the bbox\n left: undefined,\n top: undefined,\n });\n }\n}\n\nclassRegistry.setClass(Path);\nclassRegistry.setSVGClass(Path);\n\n/* _FROM_SVG_START_ */\n"],"names":["Path","FabricObject","constructor","path","_ref","arguments","length","undefined","_","left","top","options","_objectWithoutProperties","_excluded","Object","assign","ownDefaults","setOptions","_setPath","set","LEFT","TOP","adjustPosition","makePathSimpler","Array","isArray","parsePath","setBoundingBox","_findCenterFromElement","bbox","_calcBoundsFromPath","Point","width","height","_renderPathCommands","ctx","l","pathOffset","x","t","y","beginPath","command","lineTo","moveTo","bezierCurveTo","quadraticCurveTo","closePath","_render","_renderPaintInOrder","toString","concat","complexity","toObject","propertiesToInclude","_objectSpread","map","pathCmd","slice","toDatalessObject","o","sourcePath","_toSVG","joinPath","config","NUM_FRACTION_DIGITS","_getOffsetTransform","digits","toFixed","toClipPathSVG","reviver","additionalTransform","_createBaseClipPathSVGMarkup","toSVG","_createBaseSVGMarkup","setDimensions","_calcDimensions","setPositionByOrigin","CENTER","bounds","subpathStartX","subpathStartY","push","getBoundsOfCurve","makeBoundingBoxFromPoints","fromObject","object","_fromObject","extraParam","fromElement","element","cssRules","_parseAttributes","parseAttributes","ATTRIBUTE_NAMES","d","parsedAttributes","_excluded2","_defineProperty","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":";;;;;;;;;;;;;;;AAgDO,MAAMA,IAAI,SAIPC,YAAY,CAA2B;AAkB/C;AACF;AACA;AACA;AACA;AACA;EACEC,WAAWA,CACTC,IAA+B,EAG/B;AAAA,IAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,GAAA,CAAA,IAAAD,SAAA,CAAA,CAAA,CAAA,KAAAE,SAAA,GAAAF,SAAA,CAAA,CAAA,CAAA,GADqD,EAAE;AAAvD,MAAA;AAAEF,QAAAA,IAAI,EAAEK,CAAC;QAAEC,IAAI;AAAEC,QAAAA,GAAAA;AAAgC,OAAC,GAAAN,IAAA;AAAzBO,MAAAA,OAAO,GAAAC,wBAAA,CAAAR,IAAA,EAAAS,SAAA,CAAA,CAAA;AAEhC,IAAA,KAAK,EAAE,CAAA;IACPC,MAAM,CAACC,MAAM,CAAC,IAAI,EAAEf,IAAI,CAACgB,WAAW,CAAC,CAAA;AACrC,IAAA,IAAI,CAACC,UAAU,CAACN,OAAO,CAAC,CAAA;IACxB,IAAI,CAACO,QAAQ,CAACf,IAAI,IAAI,EAAE,EAAE,IAAI,CAAC,CAAA;IAC/B,OAAOM,IAAI,KAAK,QAAQ,IAAI,IAAI,CAACU,GAAG,CAACC,IAAI,EAAEX,IAAI,CAAC,CAAA;I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AA,CAlBTlG,IAAI,EAAA,iBAAA,EAoBU,CAAC,GAAGmG,eAAe,EAAE,MAAM,EAAE,UAAU,CAAC,CAAA,CAAA;AAAAD,eAAA,CApBtDlG,IAAI,EAuUU,iBAAA,EAAA,CAAC,GAAGoG,iBAAiB,EAAE,GAAG,CAAC,CAAA,CAAA;AA0CtDC,aAAa,CAACC,QAAQ,CAACtG,IAAI,CAAC,CAAA;AAC5BqG,aAAa,CAACE,WAAW,CAACvG,IAAI,CAAC,CAAA;;AAE/B;;;;"}
|
|
1
|
+
{"version":3,"file":"Path.mjs","sources":["../../../src/shapes/Path.ts"],"sourcesContent":["import { config } from '../config';\nimport { SHARED_ATTRIBUTES } from '../parser/attributes';\nimport { parseAttributes } from '../parser/parseAttributes';\nimport type { XY } from '../Point';\nimport { Point } from '../Point';\nimport { makeBoundingBoxFromPoints } from '../util/misc/boundingBoxFromPoints';\nimport { toFixed } from '../util/misc/toFixed';\nimport {\n getBoundsOfCurve,\n joinPath,\n makePathSimpler,\n parsePath,\n} from '../util/path';\nimport { classRegistry } from '../ClassRegistry';\nimport { FabricObject, cacheProperties } from './Object/FabricObject';\nimport type {\n TComplexPathData,\n TPathSegmentInfo,\n TSimplePathData,\n} from '../util/path/typedefs';\nimport type { FabricObjectProps, SerializedObjectProps } from './Object/types';\nimport type { ObjectEvents } from '../EventTypeDefs';\nimport type {\n TBBox,\n TClassProperties,\n TSVGReviver,\n TOptions,\n} from '../typedefs';\nimport { CENTER, LEFT, TOP } from '../constants';\nimport type { CSSRules } from '../parser/typedefs';\n\ninterface UniquePathProps {\n sourcePath?: string;\n path?: TSimplePathData;\n}\n\nexport interface SerializedPathProps\n extends SerializedObjectProps,\n UniquePathProps {}\n\nexport interface PathProps extends FabricObjectProps, UniquePathProps {}\n\nexport interface IPathBBox extends TBBox {\n left: number;\n top: number;\n pathOffset: Point;\n}\n\nexport class Path<\n Props extends TOptions<PathProps> = Partial<PathProps>,\n SProps extends SerializedPathProps = SerializedPathProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n> extends FabricObject<Props, SProps, EventSpec> {\n /**\n * Array of path points\n * @type Array\n * @default\n */\n declare path: TSimplePathData;\n\n declare pathOffset: Point;\n\n declare sourcePath?: string;\n\n declare segmentsInfo?: TPathSegmentInfo[];\n\n static type = 'Path';\n\n static cacheProperties = [...cacheProperties, 'path', 'fillRule'];\n\n /**\n * Constructor\n * @param {TComplexPathData} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {Partial<PathProps>} [options] Options object\n * @return {Path} thisArg\n */\n constructor(\n path: TComplexPathData | string,\n // todo: evaluate this spread here\n { path: _, left, top, ...options }: Partial<Props> = {},\n ) {\n super();\n Object.assign(this, Path.ownDefaults);\n this.setOptions(options);\n this._setPath(path || [], true);\n typeof left === 'number' && this.set(LEFT, left);\n typeof top === 'number' && this.set(TOP, top);\n }\n\n /**\n * @private\n * @param {TComplexPathData | string} path Path data (sequence of coordinates and corresponding \"command\" tokens)\n * @param {boolean} [adjustPosition] pass true to reposition the object according to the bounding box\n * @returns {Point} top left position of the bounding box, useful for complementary positioning\n */\n _setPath(path: TComplexPathData | string, adjustPosition?: boolean) {\n this.path = makePathSimpler(Array.isArray(path) ? path : parsePath(path));\n this.setBoundingBox(adjustPosition);\n }\n\n /**\n * This function is an helper for svg import. it returns the center of the object in the svg\n * untransformed coordinates, by look at the polyline/polygon points.\n * @private\n * @return {Point} center point from element coordinates\n */\n _findCenterFromElement(): Point {\n const bbox = this._calcBoundsFromPath();\n return new Point(bbox.left + bbox.width / 2, bbox.top + bbox.height / 2);\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _renderPathCommands(ctx: CanvasRenderingContext2D) {\n const l = -this.pathOffset.x,\n t = -this.pathOffset.y;\n\n ctx.beginPath();\n\n for (const command of this.path) {\n switch (\n command[0] // first letter\n ) {\n case 'L': // lineto, absolute\n ctx.lineTo(command[1] + l, command[2] + t);\n break;\n\n case 'M': // moveTo, absolute\n ctx.moveTo(command[1] + l, command[2] + t);\n break;\n\n case 'C': // bezierCurveTo, absolute\n ctx.bezierCurveTo(\n command[1] + l,\n command[2] + t,\n command[3] + l,\n command[4] + t,\n command[5] + l,\n command[6] + t,\n );\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n ctx.quadraticCurveTo(\n command[1] + l,\n command[2] + t,\n command[3] + l,\n command[4] + t,\n );\n break;\n\n case 'Z':\n ctx.closePath();\n break;\n }\n }\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} ctx context to render path on\n */\n _render(ctx: CanvasRenderingContext2D) {\n this._renderPathCommands(ctx);\n this._renderPaintInOrder(ctx);\n }\n\n /**\n * Returns string representation of an instance\n * @return {string} string representation of an instance\n */\n toString() {\n return `#<Path (${this.complexity()}): { \"top\": ${this.top}, \"left\": ${\n this.left\n } }>`;\n }\n\n /**\n * Returns object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n return {\n ...super.toObject(propertiesToInclude),\n path: this.path.map((pathCmd) => pathCmd.slice()),\n };\n }\n\n /**\n * Returns dataless object representation of an instance\n * @param {Array} [propertiesToInclude] Any properties that you might want to additionally include in the output\n * @return {Object} object representation of an instance\n */\n toDatalessObject<\n T extends Omit<Props & TClassProperties<this>, keyof SProps>,\n K extends keyof T = never,\n >(propertiesToInclude: K[] = []): Pick<T, K> & SProps {\n const o = this.toObject<T, K>(propertiesToInclude);\n if (this.sourcePath) {\n delete o.path;\n o.sourcePath = this.sourcePath;\n }\n return o;\n }\n\n /**\n * Returns svg representation of an instance\n * @return {Array} an array of strings with the specific svg representation\n * of the instance\n */\n _toSVG() {\n const path = joinPath(this.path, config.NUM_FRACTION_DIGITS);\n return [\n '<path ',\n 'COMMON_PARTS',\n `d=\"${path}\" stroke-linecap=\"round\" />\\n`,\n ];\n }\n\n /**\n * @private\n * @return the path command's translate transform attribute\n */\n _getOffsetTransform() {\n const digits = config.NUM_FRACTION_DIGITS;\n return ` translate(${toFixed(-this.pathOffset.x, digits)}, ${toFixed(\n -this.pathOffset.y,\n digits,\n )})`;\n }\n\n /**\n * Returns svg clipPath representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {string} svg representation of an instance\n */\n toClipPathSVG(reviver?: TSVGReviver): string {\n const additionalTransform = this._getOffsetTransform();\n return (\n '\\t' +\n this._createBaseClipPathSVGMarkup(this._toSVG(), {\n reviver,\n additionalTransform: additionalTransform,\n })\n );\n }\n\n /**\n * Returns svg representation of an instance\n * @param {Function} [reviver] Method for further parsing of svg representation.\n * @return {string} svg representation of an instance\n */\n toSVG(reviver?: TSVGReviver): string {\n const additionalTransform = this._getOffsetTransform();\n return this._createBaseSVGMarkup(this._toSVG(), {\n reviver,\n additionalTransform: additionalTransform,\n });\n }\n\n /**\n * Returns number representation of an instance complexity\n * @return {number} complexity of this instance\n */\n complexity() {\n return this.path.length;\n }\n\n setDimensions() {\n this.setBoundingBox();\n }\n\n setBoundingBox(adjustPosition?: boolean) {\n const { width, height, pathOffset } = this._calcDimensions();\n this.set({ width, height, pathOffset });\n // using pathOffset because it match the use case.\n // if pathOffset change here we need to use left + width/2 , top + height/2\n adjustPosition && this.setPositionByOrigin(pathOffset, CENTER, CENTER);\n }\n\n _calcBoundsFromPath(): TBBox {\n const bounds: XY[] = [];\n let subpathStartX = 0,\n subpathStartY = 0,\n x = 0, // current x\n y = 0; // current y\n\n for (const command of this.path) {\n // current instruction\n switch (\n command[0] // first letter\n ) {\n case 'L': // lineto, absolute\n x = command[1];\n y = command[2];\n bounds.push({ x: subpathStartX, y: subpathStartY }, { x, y });\n break;\n\n case 'M': // moveTo, absolute\n x = command[1];\n y = command[2];\n subpathStartX = x;\n subpathStartY = y;\n break;\n\n case 'C': // bezierCurveTo, absolute\n bounds.push(\n ...getBoundsOfCurve(\n x,\n y,\n command[1],\n command[2],\n command[3],\n command[4],\n command[5],\n command[6],\n ),\n );\n x = command[5];\n y = command[6];\n break;\n\n case 'Q': // quadraticCurveTo, absolute\n bounds.push(\n ...getBoundsOfCurve(\n x,\n y,\n command[1],\n command[2],\n command[1],\n command[2],\n command[3],\n command[4],\n ),\n );\n x = command[3];\n y = command[4];\n break;\n\n case 'Z':\n x = subpathStartX;\n y = subpathStartY;\n break;\n }\n }\n return makeBoundingBoxFromPoints(bounds);\n }\n\n /**\n * @private\n */\n _calcDimensions(): IPathBBox {\n const bbox = this._calcBoundsFromPath();\n\n return {\n ...bbox,\n pathOffset: new Point(\n bbox.left + bbox.width / 2,\n bbox.top + bbox.height / 2,\n ),\n };\n }\n\n /**\n * List of attribute names to account for when parsing SVG element (used by `Path.fromElement`)\n * @static\n * @memberOf Path\n * @see http://www.w3.org/TR/SVG/paths.html#PathElement\n */\n static ATTRIBUTE_NAMES = [...SHARED_ATTRIBUTES, 'd'];\n\n /**\n * Creates an instance of Path from an object\n * @static\n * @memberOf Path\n * @param {Object} object\n * @returns {Promise<Path>}\n */\n static fromObject<T extends TOptions<SerializedPathProps>>(object: T) {\n return this._fromObject<Path>(object, {\n extraParam: 'path',\n });\n }\n\n /**\n * Creates an instance of Path from an SVG <path> element\n * @static\n * @memberOf Path\n * @param {HTMLElement} element to parse\n * @param {Partial<PathProps>} [options] Options object\n */\n static async fromElement(\n element: HTMLElement,\n options: Partial<PathProps>,\n cssRules?: CSSRules,\n ) {\n const { d, ...parsedAttributes } = parseAttributes(\n element,\n this.ATTRIBUTE_NAMES,\n cssRules,\n );\n return new this(d, {\n ...parsedAttributes,\n ...options,\n // we pass undefined to instruct the constructor to position the object using the bbox\n left: undefined,\n top: undefined,\n });\n }\n}\n\nclassRegistry.setClass(Path);\nclassRegistry.setSVGClass(Path);\n\n/* _FROM_SVG_START_ */\n"],"names":["Path","FabricObject","constructor","path","_ref","arguments","length","undefined","_","left","top","options","_objectWithoutProperties","_excluded","Object","assign","ownDefaults","setOptions","_setPath","set","LEFT","TOP","adjustPosition","makePathSimpler","Array","isArray","parsePath","setBoundingBox","_findCenterFromElement","bbox","_calcBoundsFromPath","Point","width","height","_renderPathCommands","ctx","l","pathOffset","x","t","y","beginPath","command","lineTo","moveTo","bezierCurveTo","quadraticCurveTo","closePath","_render","_renderPaintInOrder","toString","concat","complexity","toObject","propertiesToInclude","_objectSpread","map","pathCmd","slice","toDatalessObject","o","sourcePath","_toSVG","joinPath","config","NUM_FRACTION_DIGITS","_getOffsetTransform","digits","toFixed","toClipPathSVG","reviver","additionalTransform","_createBaseClipPathSVGMarkup","toSVG","_createBaseSVGMarkup","setDimensions","_calcDimensions","setPositionByOrigin","CENTER","bounds","subpathStartX","subpathStartY","push","getBoundsOfCurve","makeBoundingBoxFromPoints","fromObject","object","_fromObject","extraParam","fromElement","element","cssRules","_parseAttributes","parseAttributes","ATTRIBUTE_NAMES","d","parsedAttributes","_excluded2","_defineProperty","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":";;;;;;;;;;;;;;;AAgDO,MAAMA,IAAI,SAIPC,YAAY,CAA2B;AAkB/C;AACF;AACA;AACA;AACA;AACA;EACEC,WAAWA,CACTC,IAA+B,EAG/B;AAAA,IAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,GAAA,CAAA,IAAAD,SAAA,CAAA,CAAA,CAAA,KAAAE,SAAA,GAAAF,SAAA,CAAA,CAAA,CAAA,GADqD,EAAE;AAAvD,MAAA;AAAEF,QAAAA,IAAI,EAAEK,CAAC;QAAEC,IAAI;AAAEC,QAAAA,GAAAA;AAAgC,OAAC,GAAAN,IAAA;AAAzBO,MAAAA,OAAO,GAAAC,wBAAA,CAAAR,IAAA,EAAAS,SAAA,CAAA,CAAA;AAEhC,IAAA,KAAK,EAAE,CAAA;IACPC,MAAM,CAACC,MAAM,CAAC,IAAI,EAAEf,IAAI,CAACgB,WAAW,CAAC,CAAA;AACrC,IAAA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AAA,EAAA,EAAA,EAAA;AACV;AACAF,MAAAA,IAAI,EAAEF,SAAS;AACfG,MAAAA,GAAG,EAAEH,SAAAA;AAAS,KAAA,CACf,CAAC,CAAA;AACJ,GAAA;AACF,CAAA;AA1WE;AACF;AACA;AACA;AACA;AAJE2F,eAAA,CALWlG,IAAI,EAAA,MAAA,EAkBD,MAAM,CAAA,CAAA;AAAAkG,eAAA,CAlBTlG,IAAI,EAAA,iBAAA,EAoBU,CAAC,GAAGmG,eAAe,EAAE,MAAM,EAAE,UAAU,CAAC,CAAA,CAAA;AAAAD,eAAA,CApBtDlG,IAAI,EAuUU,iBAAA,EAAA,CAAC,GAAGoG,iBAAiB,EAAE,GAAG,CAAC,CAAA,CAAA;AA0CtDC,aAAa,CAACC,QAAQ,CAACtG,IAAI,CAAC,CAAA;AAC5BqG,aAAa,CAACE,WAAW,CAACvG,IAAI,CAAC,CAAA;;AAE/B;;;;"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{defineProperty as t,objectSpread2 as e}from"../../../_virtual/_rollupPluginBabelHelpers.min.mjs";import{FabricObject as s}from"../Object/FabricObject.min.mjs";import{styleProperties as i}from"./constants.min.mjs";import"../../util/misc/vectors.min.mjs";import"../../Point.min.mjs";import"../../util/misc/projectStroke/StrokeLineJoinProjections.min.mjs";import"../../config.min.mjs";import"../Group.min.mjs";import{pickBy as n,pick as
|
|
1
|
+
import{defineProperty as t,objectSpread2 as e}from"../../../_virtual/_rollupPluginBabelHelpers.min.mjs";import{FabricObject as s}from"../Object/FabricObject.min.mjs";import{styleProperties as i}from"./constants.min.mjs";import"../../util/misc/vectors.min.mjs";import"../../Point.min.mjs";import"../../util/misc/projectStroke/StrokeLineJoinProjections.min.mjs";import"../../config.min.mjs";import"../Group.min.mjs";import{pickBy as n,pick as o}from"../../util/misc/pick.min.mjs";import"../../cache.min.mjs";import"../../parser/constants.min.mjs";import"../../util/animation/AnimationRegistry.min.mjs";class r extends s{isEmptyStyles(t){if(!this.styles)return!0;if(void 0!==t&&!this.styles[t])return!0;const e=void 0===t?this.styles:{line:this.styles[t]};for(const t in e)for(const s in e[t])for(const i in e[t][s])return!1;return!0}styleHas(t,e){if(!this.styles)return!1;if(void 0!==e&&!this.styles[e])return!1;const s=void 0===e?this.styles:{0:this.styles[e]};for(const e in s)for(const i in s[e])if(void 0!==s[e][i][t])return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,i,n=0,o=!0,r=0;for(const r in e){s=0;for(const l in e[r]){const c=e[r][l]||{};n++,void 0!==c[t]?(i?c[t]!==i&&(o=!1):i=c[t],c[t]===this[t]&&delete c[t]):o=!1,0!==Object.keys(c).length?s++:delete e[r][l]}0===s&&delete e[r]}for(let t=0;t<this._textLines.length;t++)r+=this._textLines[t].length;o&&n===r&&(this[t]=i,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,i,n;for(i in e){for(n in s=e[i],s)delete s[n][t],0===Object.keys(s[n]).length&&delete s[n];0===Object.keys(s).length&&delete e[i]}}_extendStyles(t,s){const{lineIndex:i,charIndex:o}=this.get2DCursorLocation(t);this._getLineStyle(i)||this._setLineStyle(i);const r=n(e(e({},this._getStyleDeclaration(i,o)),s),(t=>void 0!==t));this._setStyleDeclaration(i,o,r)}getSelectionStyles(t,e,s){const i=[];for(let n=t;n<(e||t);n++)i.push(this.getStyleAtPosition(n,s));return i}getStyleAtPosition(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(s,i):this._getStyleDeclaration(s,i)}setSelectionStyles(t,e,s){for(let i=e;i<(s||e);i++)this._extendStyles(i,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var s;const i=this.styles&&this.styles[t];return i&&null!==(s=i[e])&&void 0!==s?s:{}}getCompleteStyleDeclaration(t,s){return e(e({},o(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,s))}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}t(r,"_styleProperties",i);export{r as StyledText};
|
|
2
2
|
//# sourceMappingURL=StyledText.min.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StyledText.min.mjs","sources":["../../../../src/shapes/Text/StyledText.ts"],"sourcesContent":["import type { ObjectEvents } from '../../EventTypeDefs';\nimport type { FabricObjectProps, SerializedObjectProps } from '../Object/types';\nimport type { TOptions } from '../../typedefs';\nimport { FabricObject } from '../Object/FabricObject';\nimport { styleProperties } from './constants';\nimport type { StylePropertiesType } from './constants';\nimport type { FabricText } from './Text';\nimport { pick } from '../../util';\nimport { pickBy } from '../../util/misc/pick';\n\nexport type CompleteTextStyleDeclaration = Pick<\n FabricText,\n StylePropertiesType\n>;\n\nexport type TextStyleDeclaration = Partial<CompleteTextStyleDeclaration>;\n\nexport type TextStyle = {\n [line: number | string]: { [char: number | string]: TextStyleDeclaration };\n};\n\nexport abstract class StyledText<\n Props extends TOptions<FabricObjectProps> = Partial<FabricObjectProps>,\n SProps extends SerializedObjectProps = SerializedObjectProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n> extends FabricObject<Props, SProps, EventSpec> {\n declare abstract styles: TextStyle;\n protected declare abstract _textLines: string[][];\n protected declare _forceClearCache: boolean;\n static _styleProperties: Readonly<StylePropertiesType[]> = styleProperties;\n abstract get2DCursorLocation(\n selectionStart: number,\n skipWrapping?: boolean,\n ): { charIndex: number; lineIndex: number };\n\n /**\n * Returns true if object has no styling or no styling in a line\n * @param {Number} lineIndex , lineIndex is on wrapped lines.\n * @return {Boolean}\n */\n isEmptyStyles(lineIndex?: number): boolean {\n if (!this.styles) {\n return true;\n }\n if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {\n return true;\n }\n const obj =\n typeof lineIndex === 'undefined'\n ? this.styles\n : { line: this.styles[lineIndex] };\n for (const p1 in obj) {\n for (const p2 in obj[p1]) {\n // eslint-disable-next-line no-unused-vars\n for (const p3 in obj[p1][p2]) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Returns true if object has a style property or has it ina specified line\n * This function is used to detect if a text will use a particular property or not.\n * @param {String} property to check for\n * @param {Number} lineIndex to check the style on\n * @return {Boolean}\n */\n styleHas(property: keyof TextStyleDeclaration, lineIndex?: number): boolean {\n if (!this.styles) {\n return false;\n }\n if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {\n return false;\n }\n const obj =\n typeof lineIndex === 'undefined'\n ? this.styles\n : { 0: this.styles[lineIndex] };\n // eslint-disable-next-line\n for (const p1 in obj) {\n // eslint-disable-next-line\n for (const p2 in obj[p1]) {\n if (typeof obj[p1][p2][property] !== 'undefined') {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Check if characters in a text have a value for a property\n * whose value matches the textbox's value for that property. If so,\n * the character-level property is deleted. If the character\n * has no other properties, then it is also deleted. Finally,\n * if the line containing that character has no other characters\n * then it also is deleted.\n *\n * @param {string} property The property to compare between characters and text.\n */\n cleanStyle(property: keyof TextStyleDeclaration) {\n if (!this.styles) {\n return false;\n }\n const obj = this.styles;\n let stylesCount = 0,\n letterCount,\n stylePropertyValue,\n allStyleObjectPropertiesMatch = true,\n graphemeCount = 0;\n for (const p1 in obj) {\n letterCount = 0;\n for (const p2 in obj[p1]) {\n const styleObject = obj[p1][p2] || {},\n stylePropertyHasBeenSet = styleObject[property] !== undefined;\n\n stylesCount++;\n\n if (stylePropertyHasBeenSet) {\n if (!stylePropertyValue) {\n stylePropertyValue = styleObject[property];\n } else if (styleObject[property] !== stylePropertyValue) {\n allStyleObjectPropertiesMatch = false;\n }\n\n if (styleObject[property] === this[property as keyof this]) {\n delete styleObject[property];\n }\n } else {\n allStyleObjectPropertiesMatch = false;\n }\n\n if (Object.keys(styleObject).length !== 0) {\n letterCount++;\n } else {\n delete obj[p1][p2];\n }\n }\n\n if (letterCount === 0) {\n delete obj[p1];\n }\n }\n // if every grapheme has the same style set then\n // delete those styles and set it on the parent\n for (let i = 0; i < this._textLines.length; i++) {\n graphemeCount += this._textLines[i].length;\n }\n if (allStyleObjectPropertiesMatch && stylesCount === graphemeCount) {\n // @ts-expect-error conspiracy theory of TS\n this[property as keyof this] = stylePropertyValue;\n this.removeStyle(property);\n }\n }\n\n /**\n * Remove a style property or properties from all individual character styles\n * in a text object. Deletes the character style object if it contains no other style\n * props. Deletes a line style object if it contains no other character styles.\n *\n * @param {String} props The property to remove from character styles.\n */\n removeStyle(property: keyof TextStyleDeclaration) {\n if (!this.styles) {\n return;\n }\n const obj = this.styles;\n let line, lineNum, charNum;\n for (lineNum in obj) {\n line = obj[lineNum];\n for (charNum in line) {\n delete line[charNum][property];\n if (Object.keys(line[charNum]).length === 0) {\n delete line[charNum];\n }\n }\n if (Object.keys(line).length === 0) {\n delete obj[lineNum];\n }\n }\n }\n\n private _extendStyles(index: number, style: TextStyleDeclaration): void {\n const { lineIndex, charIndex } = this.get2DCursorLocation(index);\n\n if (!this._getLineStyle(lineIndex)) {\n this._setLineStyle(lineIndex);\n }\n\n const newStyle = pickBy(\n {\n // first create a new object that is a merge of existing and new\n ...this._getStyleDeclaration(lineIndex, charIndex),\n ...style,\n // use the predicate to discard undefined values\n },\n (value) => value !== undefined,\n );\n\n // finally assign to the old position the new style\n this._setStyleDeclaration(lineIndex, charIndex, newStyle);\n }\n\n /**\n * Gets style of a current selection/cursor (at the start position)\n * @param {Number} startIndex Start index to get styles at\n * @param {Number} endIndex End index to get styles at, if not specified startIndex + 1\n * @param {Boolean} [complete] get full style or not\n * @return {Array} styles an array with one, zero or more Style objects\n */\n getSelectionStyles(\n startIndex: number,\n endIndex?: number,\n complete?: boolean,\n ): TextStyleDeclaration[] {\n const styles: TextStyleDeclaration[] = [];\n for (let i = startIndex; i < (endIndex || startIndex); i++) {\n styles.push(this.getStyleAtPosition(i, complete));\n }\n return styles;\n }\n\n /**\n * Gets style of a current selection/cursor position\n * @param {Number} position to get styles at\n * @param {Boolean} [complete] full style if true\n * @return {Object} style Style object at a specified index\n * @private\n */\n getStyleAtPosition(position: number, complete?: boolean) {\n const { lineIndex, charIndex } = this.get2DCursorLocation(position);\n return complete\n ? this.getCompleteStyleDeclaration(lineIndex, charIndex)\n : this._getStyleDeclaration(lineIndex, charIndex);\n }\n\n /**\n * Sets style of a current selection, if no selection exist, do not set anything.\n * @param {Object} styles Styles object\n * @param {Number} startIndex Start index to get styles at\n * @param {Number} [endIndex] End index to get styles at, if not specified startIndex + 1\n */\n setSelectionStyles(styles: object, startIndex: number, endIndex?: number) {\n for (let i = startIndex; i < (endIndex || startIndex); i++) {\n this._extendStyles(i, styles);\n }\n /* not included in _extendStyles to avoid clearing cache more than once */\n this._forceClearCache = true;\n }\n\n /**\n * Get a reference, not a clone, to the style object for a given character,\n * if no style is set for a line or char, return a new empty object.\n * This is tricky and confusing because when you get an empty object you can't\n * determine if it is a reference or a new one.\n * @TODO this should always return a reference or always a clone or undefined when necessary.\n * @protected\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @return {TextStyleDeclaration} a style object reference to the existing one or a new empty object when undefined\n */\n _getStyleDeclaration(\n lineIndex: number,\n charIndex: number,\n ): TextStyleDeclaration {\n const lineStyle = this.styles && this.styles[lineIndex];\n return lineStyle ? lineStyle[charIndex] ?? {} : {};\n }\n\n /**\n * return a new object that contains all the style property for a character\n * the object returned is newly created\n * @param {Number} lineIndex of the line where the character is\n * @param {Number} charIndex position of the character on the line\n * @return {Object} style object\n */\n getCompleteStyleDeclaration(\n lineIndex: number,\n charIndex: number,\n ): CompleteTextStyleDeclaration {\n return {\n // @ts-expect-error readonly\n ...pick(this, (this.constructor as typeof StyledText)._styleProperties),\n ...this._getStyleDeclaration(lineIndex, charIndex),\n } as CompleteTextStyleDeclaration;\n }\n\n /**\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @param {Object} style\n * @private\n */\n protected _setStyleDeclaration(\n lineIndex: number,\n charIndex: number,\n style: object,\n ) {\n this.styles[lineIndex][charIndex] = style;\n }\n\n /**\n *\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @private\n */\n protected _deleteStyleDeclaration(lineIndex: number, charIndex: number) {\n delete this.styles[lineIndex][charIndex];\n }\n\n /**\n * @param {Number} lineIndex\n * @return {Boolean} if the line exists or not\n * @private\n */\n protected _getLineStyle(lineIndex: number): boolean {\n return !!this.styles[lineIndex];\n }\n\n /**\n * Set the line style to an empty object so that is initialized\n * @param {Number} lineIndex\n * @private\n */\n protected _setLineStyle(lineIndex: number) {\n this.styles[lineIndex] = {};\n }\n\n protected _deleteLineStyle(lineIndex: number) {\n delete this.styles[lineIndex];\n }\n}\n"],"names":["StyledText","FabricObject","isEmptyStyles","lineIndex","this","styles","obj","line","p1","p2","p3","styleHas","property","cleanStyle","letterCount","stylePropertyValue","stylesCount","allStyleObjectPropertiesMatch","graphemeCount","styleObject","undefined","Object","keys","length","i","_textLines","removeStyle","lineNum","charNum","_extendStyles","index","style","charIndex","get2DCursorLocation","_getLineStyle","_setLineStyle","newStyle","pickBy","_objectSpread","_getStyleDeclaration","value","_setStyleDeclaration","getSelectionStyles","startIndex","endIndex","complete","push","getStyleAtPosition","position","getCompleteStyleDeclaration","setSelectionStyles","_forceClearCache","_lineStyle$charIndex","lineStyle","pick","constructor","_styleProperties","_deleteStyleDeclaration","_deleteLineStyle","_defineProperty","styleProperties"],"mappings":"8nBAqBO,MAAeA,UAIZC,EAeRC,aAAAA,CAAcC,GACZ,IAAKC,KAAKC,OACR,OAAO,EAET,QAAyB,IAAdF,IAA8BC,KAAKC,OAAOF,GACnD,OAAO,EAET,MAAMG,OACiB,IAAdH,EACHC,KAAKC,OACL,CAAEE,KAAMH,KAAKC,OAAOF,IAC1B,IAAK,MAAMK,KAAMF,EACf,IAAK,MAAMG,KAAMH,EAAIE,GAEnB,IAAK,MAAME,KAAMJ,EAAIE,GAAIC,GACvB,OAAO,EAIb,OAAO,CACT,CASAE,QAAAA,CA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,KAAKmD,YAAkCC,mBACnDpD,KAAKmC,qBAAqBpC,EAAW6B,GAE5C,CAQUS,oBAAAA,CACRtC,EACA6B,EACAD,GAEA3B,KAAKC,OAAOF,GAAW6B,GAAaD,CACtC,CAQU0B,uBAAAA,CAAwBtD,EAAmB6B,UAC5C5B,KAAKC,OAAOF,GAAW6B,EAChC,CAOUE,aAAAA,CAAc/B,GACtB,QAASC,KAAKC,OAAOF,EACvB,CAOUgC,aAAAA,CAAchC,GACtBC,KAAKC,OAAOF,GAAa,EAC3B,CAEUuD,gBAAAA,CAAiBvD,UAClBC,KAAKC,OAAOF,EACrB,EACDwD,EAzTqB3D,EAAU,mBAQ6B4D"}
|
|
1
|
+
{"version":3,"file":"StyledText.min.mjs","sources":["../../../../src/shapes/Text/StyledText.ts"],"sourcesContent":["import type { ObjectEvents } from '../../EventTypeDefs';\nimport type { FabricObjectProps, SerializedObjectProps } from '../Object/types';\nimport type { TOptions } from '../../typedefs';\nimport { FabricObject } from '../Object/FabricObject';\nimport { styleProperties } from './constants';\nimport type { StylePropertiesType } from './constants';\nimport type { FabricText } from './Text';\nimport { pick } from '../../util';\nimport { pickBy } from '../../util/misc/pick';\n\nexport type CompleteTextStyleDeclaration = Pick<\n FabricText,\n StylePropertiesType\n>;\n\nexport type TextStyleDeclaration = Partial<CompleteTextStyleDeclaration>;\n\nexport type TextStyle = {\n [line: number | string]: { [char: number | string]: TextStyleDeclaration };\n};\n\nexport abstract class StyledText<\n Props extends TOptions<FabricObjectProps> = Partial<FabricObjectProps>,\n SProps extends SerializedObjectProps = SerializedObjectProps,\n EventSpec extends ObjectEvents = ObjectEvents,\n> extends FabricObject<Props, SProps, EventSpec> {\n declare abstract styles: TextStyle;\n protected declare abstract _textLines: string[][];\n protected declare _forceClearCache: boolean;\n static _styleProperties: Readonly<StylePropertiesType[]> = styleProperties;\n abstract get2DCursorLocation(\n selectionStart: number,\n skipWrapping?: boolean,\n ): { charIndex: number; lineIndex: number };\n\n /**\n * Returns true if object has no styling or no styling in a line\n * @param {Number} lineIndex , lineIndex is on wrapped lines.\n * @return {Boolean}\n */\n isEmptyStyles(lineIndex?: number): boolean {\n if (!this.styles) {\n return true;\n }\n if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {\n return true;\n }\n const obj =\n typeof lineIndex === 'undefined'\n ? this.styles\n : { line: this.styles[lineIndex] };\n for (const p1 in obj) {\n for (const p2 in obj[p1]) {\n // eslint-disable-next-line no-unused-vars\n for (const p3 in obj[p1][p2]) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * Returns true if object has a style property or has it ina specified line\n * This function is used to detect if a text will use a particular property or not.\n * @param {String} property to check for\n * @param {Number} lineIndex to check the style on\n * @return {Boolean}\n */\n styleHas(property: keyof TextStyleDeclaration, lineIndex?: number): boolean {\n if (!this.styles) {\n return false;\n }\n if (typeof lineIndex !== 'undefined' && !this.styles[lineIndex]) {\n return false;\n }\n const obj =\n typeof lineIndex === 'undefined'\n ? this.styles\n : { 0: this.styles[lineIndex] };\n // eslint-disable-next-line\n for (const p1 in obj) {\n // eslint-disable-next-line\n for (const p2 in obj[p1]) {\n if (typeof obj[p1][p2][property] !== 'undefined') {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * Check if characters in a text have a value for a property\n * whose value matches the textbox's value for that property. If so,\n * the character-level property is deleted. If the character\n * has no other properties, then it is also deleted. Finally,\n * if the line containing that character has no other characters\n * then it also is deleted.\n *\n * @param {string} property The property to compare between characters and text.\n */\n cleanStyle(property: keyof TextStyleDeclaration) {\n if (!this.styles) {\n return false;\n }\n const obj = this.styles;\n let stylesCount = 0,\n letterCount,\n stylePropertyValue,\n allStyleObjectPropertiesMatch = true,\n graphemeCount = 0;\n for (const p1 in obj) {\n letterCount = 0;\n for (const p2 in obj[p1]) {\n const styleObject = obj[p1][p2] || {},\n stylePropertyHasBeenSet = styleObject[property] !== undefined;\n\n stylesCount++;\n\n if (stylePropertyHasBeenSet) {\n if (!stylePropertyValue) {\n stylePropertyValue = styleObject[property];\n } else if (styleObject[property] !== stylePropertyValue) {\n allStyleObjectPropertiesMatch = false;\n }\n\n if (styleObject[property] === this[property as keyof this]) {\n delete styleObject[property];\n }\n } else {\n allStyleObjectPropertiesMatch = false;\n }\n\n if (Object.keys(styleObject).length !== 0) {\n letterCount++;\n } else {\n delete obj[p1][p2];\n }\n }\n\n if (letterCount === 0) {\n delete obj[p1];\n }\n }\n // if every grapheme has the same style set then\n // delete those styles and set it on the parent\n for (let i = 0; i < this._textLines.length; i++) {\n graphemeCount += this._textLines[i].length;\n }\n if (allStyleObjectPropertiesMatch && stylesCount === graphemeCount) {\n // @ts-expect-error conspiracy theory of TS\n this[property as keyof this] = stylePropertyValue;\n this.removeStyle(property);\n }\n }\n\n /**\n * Remove a style property or properties from all individual character styles\n * in a text object. Deletes the character style object if it contains no other style\n * props. Deletes a line style object if it contains no other character styles.\n *\n * @param {String} props The property to remove from character styles.\n */\n removeStyle(property: keyof TextStyleDeclaration) {\n if (!this.styles) {\n return;\n }\n const obj = this.styles;\n let line, lineNum, charNum;\n for (lineNum in obj) {\n line = obj[lineNum];\n for (charNum in line) {\n delete line[charNum][property];\n if (Object.keys(line[charNum]).length === 0) {\n delete line[charNum];\n }\n }\n if (Object.keys(line).length === 0) {\n delete obj[lineNum];\n }\n }\n }\n\n private _extendStyles(index: number, style: TextStyleDeclaration): void {\n const { lineIndex, charIndex } = this.get2DCursorLocation(index);\n\n if (!this._getLineStyle(lineIndex)) {\n this._setLineStyle(lineIndex);\n }\n\n const newStyle = pickBy(\n {\n // first create a new object that is a merge of existing and new\n ...this._getStyleDeclaration(lineIndex, charIndex),\n ...style,\n // use the predicate to discard undefined values\n },\n (value) => value !== undefined,\n );\n\n // finally assign to the old position the new style\n this._setStyleDeclaration(lineIndex, charIndex, newStyle);\n }\n\n /**\n * Gets style of a current selection/cursor (at the start position)\n * @param {Number} startIndex Start index to get styles at\n * @param {Number} endIndex End index to get styles at, if not specified startIndex + 1\n * @param {Boolean} [complete] get full style or not\n * @return {Array} styles an array with one, zero or more Style objects\n */\n getSelectionStyles(\n startIndex: number,\n endIndex?: number,\n complete?: boolean,\n ): TextStyleDeclaration[] {\n const styles: TextStyleDeclaration[] = [];\n for (let i = startIndex; i < (endIndex || startIndex); i++) {\n styles.push(this.getStyleAtPosition(i, complete));\n }\n return styles;\n }\n\n /**\n * Gets style of a current selection/cursor position\n * @param {Number} position to get styles at\n * @param {Boolean} [complete] full style if true\n * @return {Object} style Style object at a specified index\n * @private\n */\n getStyleAtPosition(position: number, complete?: boolean) {\n const { lineIndex, charIndex } = this.get2DCursorLocation(position);\n return complete\n ? this.getCompleteStyleDeclaration(lineIndex, charIndex)\n : this._getStyleDeclaration(lineIndex, charIndex);\n }\n\n /**\n * Sets style of a current selection, if no selection exist, do not set anything.\n * @param {Object} styles Styles object\n * @param {Number} startIndex Start index to get styles at\n * @param {Number} [endIndex] End index to get styles at, if not specified startIndex + 1\n */\n setSelectionStyles(styles: object, startIndex: number, endIndex?: number) {\n for (let i = startIndex; i < (endIndex || startIndex); i++) {\n this._extendStyles(i, styles);\n }\n /* not included in _extendStyles to avoid clearing cache more than once */\n this._forceClearCache = true;\n }\n\n /**\n * Get a reference, not a clone, to the style object for a given character,\n * if no style is set for a line or char, return a new empty object.\n * This is tricky and confusing because when you get an empty object you can't\n * determine if it is a reference or a new one.\n * @TODO this should always return a reference or always a clone or undefined when necessary.\n * @protected\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @return {TextStyleDeclaration} a style object reference to the existing one or a new empty object when undefined\n */\n _getStyleDeclaration(\n lineIndex: number,\n charIndex: number,\n ): TextStyleDeclaration {\n const lineStyle = this.styles && this.styles[lineIndex];\n return lineStyle ? lineStyle[charIndex] ?? {} : {};\n }\n\n /**\n * return a new object that contains all the style property for a character\n * the object returned is newly created\n * @param {Number} lineIndex of the line where the character is\n * @param {Number} charIndex position of the character on the line\n * @return {Object} style object\n */\n getCompleteStyleDeclaration(\n lineIndex: number,\n charIndex: number,\n ): CompleteTextStyleDeclaration {\n return {\n // @ts-expect-error readonly\n ...pick(this, (this.constructor as typeof StyledText)._styleProperties),\n ...this._getStyleDeclaration(lineIndex, charIndex),\n } as CompleteTextStyleDeclaration;\n }\n\n /**\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @param {Object} style\n * @private\n */\n protected _setStyleDeclaration(\n lineIndex: number,\n charIndex: number,\n style: object,\n ) {\n this.styles[lineIndex][charIndex] = style;\n }\n\n /**\n *\n * @param {Number} lineIndex\n * @param {Number} charIndex\n * @private\n */\n protected _deleteStyleDeclaration(lineIndex: number, charIndex: number) {\n delete this.styles[lineIndex][charIndex];\n }\n\n /**\n * @param {Number} lineIndex\n * @return {Boolean} if the line exists or not\n * @private\n */\n protected _getLineStyle(lineIndex: number): boolean {\n return !!this.styles[lineIndex];\n }\n\n /**\n * Set the line style to an empty object so that is initialized\n * @param {Number} lineIndex\n * @private\n */\n protected _setLineStyle(lineIndex: number) {\n this.styles[lineIndex] = {};\n }\n\n protected _deleteLineStyle(lineIndex: number) {\n delete this.styles[lineIndex];\n }\n}\n"],"names":["StyledText","FabricObject","isEmptyStyles","lineIndex","this","styles","obj","line","p1","p2","p3","styleHas","property","cleanStyle","letterCount","stylePropertyValue","stylesCount","allStyleObjectPropertiesMatch","graphemeCount","styleObject","undefined","Object","keys","length","i","_textLines","removeStyle","lineNum","charNum","_extendStyles","index","style","charIndex","get2DCursorLocation","_getLineStyle","_setLineStyle","newStyle","pickBy","_objectSpread","_getStyleDeclaration","value","_setStyleDeclaration","getSelectionStyles","startIndex","endIndex","complete","push","getStyleAtPosition","position","getCompleteStyleDeclaration","setSelectionStyles","_forceClearCache","_lineStyle$charIndex","lineStyle","pick","constructor","_styleProperties","_deleteStyleDeclaration","_deleteLineStyle","_defineProperty","styleProperties"],"mappings":"wlBAqBO,MAAeA,UAIZC,EAeRC,aAAAA,CAAcC,GACZ,IAAKC,KAAKC,OACR,OAAO,EAET,QAAyB,IAAdF,IAA8BC,KAAKC,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EACA6B,GACsB,IAAAoB,EACtB,MAAMC,EAAYjD,KAAKC,QAAUD,KAAKC,OAAOF,GAC7C,OAAOkD,GAAgCD,QAAvBA,EAAGC,EAAUrB,cAAUoB,EAAAA,EAAS,CAAA,CAClD,CASAH,2BAAAA,CACE9C,EACA6B,GAEA,OAAAM,EAAAA,EAAA,CAAA,EAEKgB,EAAKlD,KAAOA,KAAKmD,YAAkCC,mBACnDpD,KAAKmC,qBAAqBpC,EAAW6B,GAE5C,CAQUS,oBAAAA,CACRtC,EACA6B,EACAD,GAEA3B,KAAKC,OAAOF,GAAW6B,GAAaD,CACtC,CAQU0B,uBAAAA,CAAwBtD,EAAmB6B,UAC5C5B,KAAKC,OAAOF,GAAW6B,EAChC,CAOUE,aAAAA,CAAc/B,GACtB,QAASC,KAAKC,OAAOF,EACvB,CAOUgC,aAAAA,CAAchC,GACtBC,KAAKC,OAAOF,GAAa,EAC3B,CAEUuD,gBAAAA,CAAiBvD,UAClBC,KAAKC,OAAOF,EACrB,EACDwD,EAzTqB3D,EAAU,mBAQ6B4D"}
|
|
@@ -8,7 +8,6 @@ import '../../config.mjs';
|
|
|
8
8
|
import '../Group.mjs';
|
|
9
9
|
import { pickBy, pick } from '../../util/misc/pick.mjs';
|
|
10
10
|
import '../../cache.mjs';
|
|
11
|
-
import '../../util/path/regex.mjs';
|
|
12
11
|
import '../../parser/constants.mjs';
|
|
13
12
|
import '../../util/animation/AnimationRegistry.mjs';
|
|
14
13
|
|