{"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, 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   */\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    return [\n      '<path ',\n      'COMMON_PARTS',\n      `d=\"${joinPath(this.path, config.NUM_FRACTION_DIGITS)}\" 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   * @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   * @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   * @param {HTMLElement} element to parse\n   * @param {Partial<PathProps>} [options] Options object\n   */\n  static async fromElement(\n    element: HTMLElement | SVGElement,\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","_","left","top","options","arguments","length","undefined","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","complexity","toObject","propertiesToInclude","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","d","parsedAttributes","parseAttributes","ATTRIBUTE_NAMES","_defineProperty","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":"iyBA+CO,MAAMA,UAIHC,EAuBRC,WAAAA,CACEC,GAGA,IADEA,KAAMC,EAACC,KAAEA,EAAIC,IAAEA,KAAQC,GAAyBC,UAAAC,OAAA,QAAAC,IAAAF,UAAA,GAAAA,UAAA,GAAG,CAAA,EAErDG,QACAC,OAAOC,OAAOC,KAAMd,EAAKe,aACzBD,KAAKE,WAAWT,GAChBO,KAAKG,SAASd,GAAQ,IAAI,GACV,iBAATE,GAAqBS,KAAKI,IAAIC,EAAMd,GAC5B,iBAARC,GAAoBQ,KAAKI,IAAIE,EAAKd,EAC3C,CAQAW,QAAAA,CAASd,EAAiCkB,GACxCP,KAAKX,KAAOmB,EAAgBC,MAAMC,QAAQrB,GAAQA,EAAOsB,EAAUtB,IACnEW,KAAKY,eAAeL,EACtB,CAQAM,sBAAAA,GACE,MAAMC,EAAOd,KAAKe,sBAClB,OAAO,IAAIC,EAAMF,EAAKvB,KAAOuB,EAAKG,MAAQ,EAAGH,EAAKtB,IAAMsB,EAA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