import { readFileSync } from 'fs' ; import { parse , RootNode , ElementNode } from 'svg-parser' ; function deepSearch ( object , key , predicate ) { if ( object . hasOwnProperty ( key ) && predicate ( key , object [ key ] ) === true ) return object ; for ( let i = 0 ; i < Object . keys ( object ) . length ; i ++ ) { if ( typeof object [ Object . keys ( object ) [ i ] ] === "object" ) { let o = deepSearch ( object [ Object . keys ( object ) [ i ] ] , key , predicate ) ; if ( o !== null ) return o ; } } return null ; } export default class ImportPathFromSVGAction { private svgRootNode : RootNode | undefined ; constructor ( fileName ) { this . svgRootNode = this . parseSVGFileAsHAST ( fileName ) ; } public parseSVGFileAsHAST ( fileName ) { const fileData = readFileSync ( fileName ) ; if ( fileData ) { const svgString = fileData . toString ( ) ; if ( svgString ) { const svgJSON = parse ( svgString ) ; return svgJSON ; } } } /**
     * Find and return all <polygon> elements inside the given RootNode.
     */ public getPolygonsFromSVG ( ) { const node = < ElementNode | null > deepSearch ( this . svgRootNode , 'tagName' , ( k , v ) => v === 'polygon' ) ; console . log ( node ) ; return node ; } param points private convertPointsToPolygon ( points ) { const polygon = [ ] ; const pointsArray = points . split ( ' ' ) ; for ( let i = 0 ; i < pointsArray . length ; i += 2 ) { polygon . push ( [ parseFloat ( pointsArray [ i ] ) , parseFloat ( pointsArray [ i + 1 ] ) ] ) ; } return polygon ; } param points public convertSVGPolygonToJSCADString ( polygonNode ) { if ( ! polygonNode . properties || typeof polygonNode . properties . points !== 'string' ) { throw new Error ( 'convertSVGPolygonToJSCADString expects ElementNode with "points" property as argument' ) ; } const polygons = this . convertPointsToPolygon ( polygonNode . properties . points ) ; if ( ! polygons || polygons . length === 0 || polygons . length % 2 !== 0 ) { throw new Error ( 'convertSVGPolygonToJSCADString encountered invalid "points" property on <polygon>' ) ; } const jscadPoints = [ ] ; polygons . forEach ( polygon => jscadPoints . push ( `\t[${ polygon [ 0 ] }, ${ polygon [ 1 ] }]` ) ) ; return `let \${name:poly} = polygon([\n${ jscadPoints . join ( ',\n' ) }\n]);$0` ; } }