{"version":3,"file":"XPath.min.mjs","sources":["../../../../src/shapes/canvasx/XPath.ts"],"sourcesContent":["import { config } from '../../config';\nimport { SHARED_ATTRIBUTES } from '../../parser/attributes';\nimport { Point, XY } 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 {\n  TComplexPathData,\n  TPathSegmentInfo,\n  TSimplePathData,\n} from '../../util/path/typedefs';\nimport type { FabricObjectProps, SerializedObjectProps } from '../Object/types';\nimport type { TOptions } from '../../typedefs';\nimport type { ObjectEvents } from '../../EventTypeDefs';\nimport { TBBox, TClassProperties, TSVGReviver } from '../../typedefs';\nimport { cloneDeep } from '../../util/internals/cloneDeep';\nimport { createPathDefaultControls } from '../../controls/commonControls';\nimport { WidgetPathInterface, EntityKeys } from './type/widget.entity.path';\nimport { WidgetType } from './type/widget.type';\n\ninterface UniquePathProps {\n  sourcePath?: string;\n  path?: TSimplePathData;\n  objType: 'XPath';\n}\n\nexport interface SerializedPathProps\n  extends SerializedObjectProps,\n  UniquePathProps { }\n\nexport interface PathProps extends FabricObjectProps {\n  objType: 'XPath';\n}\n\nexport interface IPathBBox extends TBBox {\n  left: number;\n  top: number;\n  pathOffset: Point;\n}\n\nexport class XPath<\n  Props extends TOptions<PathProps> = Partial<PathProps>,\n  SProps extends SerializedPathProps = SerializedPathProps,\n  EventSpec extends ObjectEvents = ObjectEvents\n> extends FabricObject<Props, SProps, EventSpec> implements WidgetPathInterface {\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 cacheProperties = [...cacheProperties, 'path', 'fillRule'];\n\n  declare locked: boolean;\n\n  declare boardId: string;\n\n  declare userId: string;\n\n  declare timestamp: Date;\n\n  declare zIndex: number;\n\n  declare lines: object[];\n\n  declare relationship: object[];\n\n  declare id: string;\n\n  declare userNo: string;\n\n  declare version: string;\n\n  declare lineWidth: any;\n\n  declare radius: any;\n\n  static objType: WidgetType = 'XPath';\n  static type: WidgetType = 'XPath';\n\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    { path: _, left, top, ...options }: Partial<any> = {}\n  ) {\n\n    //fixed default value\n    options.perPixelTargetFind = true;\n\n    super(options as Props);\n    this._setPath(path || [], true);\n    typeof left === 'number' && this.set('left', left);\n    typeof top === 'number' && this.set('top', top);\n\n\n    Object.assign(this, options);\n    this.objType = 'XPath';\n  }\n  updatedBy: string;\n  updatedByName: string;\n\n  createdByName: string;\n  objType: WidgetType;\n  updatedAt: number;\n\n  createdAt: number;\n  createdBy: string;\n\n  static getDefaults() {\n    return {\n      ...super.getDefaults(),\n      controls: createPathDefaultControls(),\n    };\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    let subpathStartX = 0,\n      subpathStartY = 0,\n      x = 0, // current x\n      y = 0, // current y\n      controlX = 0, // current control point x\n      controlY = 0; // current control point y\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          x = command[1];\n          y = command[2];\n          ctx.lineTo(x + l, y + t);\n          break;\n\n        case 'M': // moveTo, absolute\n          x = command[1];\n          y = command[2];\n          subpathStartX = x;\n          subpathStartY = y;\n          ctx.moveTo(x + l, y + t);\n          break;\n\n        case 'C': // bezierCurveTo, absolute\n          x = command[5];\n          y = command[6];\n          controlX = command[3];\n          controlY = command[4];\n          ctx.bezierCurveTo(\n            command[1] + l,\n            command[2] + t,\n            controlX + l,\n            controlY + t,\n            x + l,\n            y + 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          x = command[3];\n          y = command[4];\n          controlX = command[1];\n          controlY = command[2];\n          break;\n\n        case 'Z':\n          x = subpathStartX;\n          y = subpathStartY;\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\": ${this.left\n      } }>`;\n  }\n\n\n  getObject() {\n    const entityKeys: string[] = EntityKeys;\n    const result: Record<string, any> = {};\n\n    entityKeys.forEach((key) => {\n      if (key in this) {\n        result[key] = (this as any)[key];\n      }\n    });\n\n    return result;\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: cloneDeep(this.path),\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): any {\n    const additionalTransform = this._getOffsetTransform();\n    return (\n      '\\t' +\n      this._createBaseClipPathSVGMarkup(this._toSVG(), {\n        reviver: 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): any {\n    const additionalTransform = this._getOffsetTransform();\n    return this._createBaseSVGMarkup(this._toSVG(), {\n      reviver: 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<XPath>(object, {\n      extraParam: 'path',\n    });\n  }\n}\n\nclassRegistry.setClass(XPath);\nclassRegistry.setSVGClass(XPath);\n\n/* _FROM_SVG_START_ */\n"],"names":["XPath","FabricObject","constructor","path","_ref","arguments","length","undefined","_","left","top","options","_objectWithoutProperties","_excluded","perPixelTargetFind","super","_defineProperty","this","_setPath","set","Object","assign","objType","getDefaults","_objectSpread","controls","createPathDefaultControls","adjustPosition","makePathSimpler","Array","isArray","parsePath","setBoundingBox","_findCenterFromElement","bbox","_calcBoundsFromPath","Point","width","height","_renderPathCommands","ctx","subpathStartX","subpathStartY","x","y","controlX","controlY","l","pathOffset","t","beginPath","command","lineTo","moveTo","bezierCurveTo","quadraticCurveTo","closePath","_render","_renderPaintInOrder","toString","concat","complexity","getObject","result","EntityKeys","forEach","key","toObject","propertiesToInclude","cloneDeep","toDatalessObject","o","sourcePath","_toSVG","joinPath","config","NUM_FRACTION_DIGITS","_getOffsetTransform","digits","toFixed","toClipPathSVG","reviver","additionalTransform","_createBaseClipPathSVGMarkup","toSVG","_createBaseSVGMarkup","setDimensions","_calcDimensions","setPositionByOrigin","bounds","push","getBoundsOfCurve","makeBoundingBoxFromPoints","fromObject","object","_fromObject","extraParam","cacheProperties","SHARED_ATTRIBUTES","classRegistry","setClass","setSVGClass"],"mappings":"w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