{"version":3,"file":"elements_parser.min.mjs","sources":["../../../src/parser/elements_parser.ts"],"sourcesContent":["import { Gradient } from '../gradient/Gradient';\nimport { Pattern } from '../Pattern/Pattern';\nimport { Group } from '../shapes/Group';\nimport { FabricImage } from '../shapes/Image';\nimport { classRegistry } from '../ClassRegistry';\nimport {\n  invertTransform,\n  multiplyTransformMatrices,\n  qrDecompose,\n} from '../util/misc/matrix';\nimport { removeTransformMatrixForSvgParsing } from '../util/transform_matrix_removal';\nimport type { FabricObject } from '../shapes/Object/FabricObject';\nimport { Point } from '../Point';\nimport { CENTER, FILL, STROKE } from '../constants';\nimport { getGradientDefs } from './getGradientDefs';\nimport { getCSSRules } from './getCSSRules';\nimport type { LoadImageOptions } from '../util';\nimport type { CSSRules, TSvgReviverCallback } from './typedefs';\nimport type { ParsedViewboxTransform } from './applyViewboxTransform';\nimport type { SVGOptions } from '../gradient';\nimport { getTagName } from './getTagName';\nimport { parseTransformAttribute } from './parseTransformAttribute';\nimport { getPatternDefs } from './getPatternDefs';\nimport { PatternOptions, SerializedPatternOptions } from '../Pattern';\n\nconst findTag = (el: Element) => {\n  let tagName = getTagName(el).toLowerCase();\n  if (tagName === 'text') tagName = 'textbox';\n\n  return classRegistry.getSVGClass(tagName);\n};\n\ntype StorageType = {\n  fill: SVGGradientElement | PatternOptions;\n  stroke: SVGGradientElement;\n  clipPath: Element[];\n};\n\ntype NotParsedFabricObject = FabricObject & {\n  fill: string;\n  stroke: string;\n  clipPath?: string;\n  clipRule?: CanvasFillRule;\n};\n\nexport class ElementsParser {\n  declare elements: Element[];\n  declare options: LoadImageOptions & ParsedViewboxTransform;\n  declare reviver?: TSvgReviverCallback;\n  declare regexUrl: RegExp;\n  declare doc: Document;\n  declare clipPaths: Record<string, Element[]>;\n  declare gradientDefs: Record<string, SVGGradientElement>;\n  declare patternDefs: Record<string, PatternOptions>;\n  declare cssRules: CSSRules;\n\n  constructor(\n    elements: Element[],\n    options: LoadImageOptions & ParsedViewboxTransform,\n    reviver: TSvgReviverCallback | undefined,\n    doc: Document,\n    clipPaths: Record<string, Element[]>,\n  ) {\n    this.elements = elements;\n    this.options = options;\n    this.reviver = reviver;\n    this.regexUrl = /^url\\(['\"]?#([^'\"]+)['\"]?\\)/g;\n    this.doc = doc;\n    this.clipPaths = clipPaths;\n    this.gradientDefs = getGradientDefs(doc);\n    this.patternDefs = getPatternDefs(doc);\n    this.cssRules = getCSSRules(doc);\n  }\n\n  parse(): Promise<Array<FabricObject | null>> {\n    return Promise.all(\n      this.elements.map((element) => this.createObject(element)),\n    );\n  }\n\n  async createObject(el: Element): Promise<FabricObject | null> {\n    const klass = findTag(el);\n    if (klass) {\n      const obj: NotParsedFabricObject = await klass.fromElement(\n        el,\n        this.options,\n        this.cssRules,\n      );\n      this.resolveGradient(obj, el, FILL);\n      // James modified\n      this.resolvePattern(obj, el, FILL);\n      this.resolveGradient(obj, el, STROKE);\n      if (obj instanceof FabricImage && obj._originalElement) {\n        removeTransformMatrixForSvgParsing(\n          obj,\n          obj.parsePreserveAspectRatioAttribute(),\n        );\n      } else {\n        removeTransformMatrixForSvgParsing(obj);\n      }\n      await this.resolveClipPath(obj, el);\n      this.reviver && this.reviver(el, obj);\n      return obj;\n    }\n    return null;\n  }\n\n  extractPropertyDefinition(\n    obj: NotParsedFabricObject,\n    property: 'fill' | 'stroke' | 'clipPath',\n    storage: Record<string, StorageType[typeof property]>,\n  ): StorageType[typeof property] | undefined {\n    const value = obj[property]!,\n      regex = this.regexUrl;\n    if (!regex.test(value)) {\n      return undefined;\n    }\n    // verify: can we remove the 'g' flag? and remove lastIndex changes?\n    regex.lastIndex = 0;\n    // we passed the regex test, so we know is not null;\n    const id = regex.exec(value)![1];\n    regex.lastIndex = 0;\n    // @todo fix this\n    return storage[id];\n  }\n\n  resolveGradient(\n    obj: NotParsedFabricObject,\n    el: Element,\n    property: 'fill' | 'stroke',\n  ) {\n    const gradientDef = this.extractPropertyDefinition(\n      obj,\n      property,\n      this.gradientDefs,\n    ) as SVGGradientElement;\n    if (gradientDef) {\n      const opacityAttr = el.getAttribute(property + '-opacity');\n      const gradient = Gradient.fromElement(gradientDef, obj, {\n        ...this.options,\n        opacity: opacityAttr,\n      } as SVGOptions);\n      obj.set(property, gradient);\n    }\n  }\n\n  /**\n   * James modified\n   * @param {*} obj\n   * @param {*} el\n   * @param {*} property\n   */\n  resolvePattern(obj: NotParsedFabricObject, el: Element, property: 'fill') {\n    var patternDef = this.extractPropertyDefinition(\n      obj,\n      property,\n      this.patternDefs,\n    ) as PatternOptions;\n    if (patternDef) {\n      var pattern = new Pattern(patternDef);\n      obj.set(property, pattern);\n    }\n  }\n\n  // TODO: resolveClipPath could be run once per clippath with minor work per object.\n  // is a refactor that i m not sure is worth on this code\n  async resolveClipPath(\n    obj: NotParsedFabricObject,\n    usingElement: Element,\n    exactOwner?: Element,\n  ) {\n    const clipPathElements = this.extractPropertyDefinition(\n      obj,\n      'clipPath',\n      this.clipPaths,\n    ) as Element[];\n    if (clipPathElements) {\n      const objTransformInv = invertTransform(obj.calcTransformMatrix());\n      const clipPathTag = clipPathElements[0].parentElement!;\n      let clipPathOwner = usingElement;\n      while (\n        !exactOwner &&\n        clipPathOwner.parentElement &&\n        clipPathOwner.getAttribute('clip-path') !== obj.clipPath\n      ) {\n        clipPathOwner = clipPathOwner.parentElement;\n      }\n\n      // James modified\n      // 把 ClipPath 节点移出clipPathOwner, 避免重复解析clipPath 并造成 Maximum call stack size\n      // 但是这个操作导致了 clipPath的父节点的矩阵在调用fabric.parseAttributes没有乘到clipPath上\n      // 通常矩阵是 svg > g > clipPath > path, 这样的话变成了 svg > clipPath > path\n      // 因此把 下面的移出操作放到创建path(klass.fromElement)之后\n      // clipPathOwner.parentNode.appendChild(clipPathTag);\n\n      // 暂时通过修改 clipPath的transform处理\n      if (clipPathOwner.hasAttribute('transform'))\n        clipPathTag.setAttribute(\n          'transform',\n          clipPathOwner.getAttribute('transform')!,\n        );\n      // move the clipPath tag as sibling to the real element that is using it\n      clipPathOwner.parentElement!.appendChild(clipPathTag!);\n\n      // this multiplication order could be opposite.\n      // but i don't have an svg to test it\n      // at the first SVG that has a transform on both places and is misplaced\n      // try to invert this multiplication order\n      const finalTransform = parseTransformAttribute(\n        `${clipPathOwner.getAttribute('transform') || ''} ${\n          clipPathTag.getAttribute('originalTransform') || ''\n        }`,\n      );\n\n      clipPathTag.setAttribute(\n        'transform',\n        `matrix(${finalTransform.join(',')})`,\n      );\n\n      const container = await Promise.all(\n        clipPathElements.map((clipPathElement) => {\n          return findTag(clipPathElement)\n            .fromElement(clipPathElement, this.options, this.cssRules)\n            .then((enlivedClippath: NotParsedFabricObject) => {\n              removeTransformMatrixForSvgParsing(enlivedClippath);\n              enlivedClippath.fillRule = enlivedClippath.clipRule!;\n              delete enlivedClippath.clipRule;\n              return enlivedClippath;\n            });\n        }),\n      );\n      const clipPath =\n        container.length === 1 ? container[0] : new Group(container);\n      const gTransform = multiplyTransformMatrices(\n        objTransformInv,\n        clipPath.calcTransformMatrix(),\n      );\n      if (clipPath.clipPath) {\n        await this.resolveClipPath(\n          clipPath,\n          clipPathOwner,\n          // this is tricky.\n          // it tries to differentiate from when clipPaths are inherited by outside groups\n          // or when are really clipPaths referencing other clipPaths\n          clipPathTag.getAttribute('clip-path') ? clipPathOwner : undefined,\n        );\n      }\n      const { scaleX, scaleY, angle, skewX, translateX, translateY } =\n        qrDecompose(gTransform);\n      clipPath.set({\n        flipX: false,\n        flipY: false,\n      });\n      clipPath.set({\n        scaleX,\n        scaleY,\n        angle,\n        skewX,\n        skewY: 0,\n      });\n      clipPath.setPositionByOrigin(\n        new Point(translateX, translateY),\n        CENTER,\n        CENTER,\n      );\n      obj.clipPath = clipPath;\n    } else {\n      // if clip-path does not resolve to any element, delete the property.\n      delete obj.clipPath;\n      return;\n    }\n  }\n}\n"],"names":["findTag","el","tagName","getTagName","toLowerCase","classRegistry","getSVGClass","ElementsParser","constructor","elements","options","reviver","doc","clipPaths","this","regexUrl","gradientDefs","getGradientDefs","patternDefs","getPatternDefs","cssRules","getCSSRules","parse","Promise","all","map","element","createObject","klass","obj","fromElement","resolveGradient","FILL","resolvePattern","STROKE","FabricImage","_originalElement","removeTransformMatrixForSvgParsing","parsePreserveAspectRatioAttribute","resolveClipPath","extractPropertyDefinition","property","storage","value","regex","test","lastIndex","id","exec","gradientDef","opacityAttr","getAttribute","gradient","Gradient","opacity","set","patternDef","pattern","Pattern","usingElement","exactOwner","clipPathElements","objTransformInv","invertTransform","calcTransformMatrix","clipPathTag","parentElement","clipPathOwner","clipPath","hasAttribute","setAttribute","appendChild","finalTransform","parseTransformAttribute","join","container","clipPathElement","then","enlivedClippath","fillRule","clipRule","length","Group","gTransform","multiplyTransformMatrices","undefined","scaleX","scaleY","angle","skewX","translateX","translateY","qrDecompose","flipX","flipY","skewY","setPositionByOrigin","Point","CENTER"],"mappings":"62BAyBA,MAAMA,EAAWC,IACf,IAAIC,EAAUC,EAAWF,GAAIG,cAG7B,MAFgB,SAAZF,IAAoBA,EAAU,WAE3BG,EAAcC,YAAYJ,EAAQ,EAgBpC,MAAMK,EAWXC,WAAAA,CACEC,EACAC,EACAC,EACAC,EACAC,GAEAC,KAAKL,SAAWA,EAChBK,KAAKJ,QAAUA,EACfI,KAAKH,QAAUA,EACfG,KAAKC,SAAW,+BAChBD,KAAKF,IAAMA,EACXE,KAAKD,UAAYA,EACjBC,KAAKE,aAAeC,EAAgBL,GACpCE,KAAKI,YAAcC,EAAeP,GAClCE,KAAKM,SAAWC,EAAYT,EAC9B,CAEAU,KAAAA,GACE,OAAOC,QAAQC,IACbV,KAAKL,SAASgB,KAAKC,GAAYZ,KAAKa,aAAaD,KAErD,CAEA,kBAAMC,CAAa1B,GACjB,MAAM2B,EAAQ5B,EAAQC,GACtB,GAAI2B,EAAO,CACT,MAAMC,QAAmCD,EAAME,YAC7C7B,EACAa,KAAKJ,QACLI,KAAKM,UAgBP,OAdAN,KAAKiB,gBAAgBF,EAAK5B,EAAI+B,GAE9BlB,KAAKmB,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