import { SvgPath, SvgItem } from "./svg"; import { optimizePath } from "./optimize-path"; import { getSubPathBounds } from "./get-sub-path-bounds"; export const changePathOrigin = (svg: SvgPath, newOriginIndex: number, subpath?: boolean)=> { if(svg.path.length <= newOriginIndex || newOriginIndex === 0) { return; } const {start, end} = getSubPathBounds(svg, subpath ? newOriginIndex : undefined); const l = end - start; const isBeforeRelative = end < svg.path.length && svg.path[end].relative; if(isBeforeRelative) { svg.path[end].setRelative(false); } const newFirstItem = svg.path[newOriginIndex]; const newLastItem = svg.path[newOriginIndex - 1]; switch(newFirstItem.getType().toUpperCase()) { // Shorthands must be converted to be used as origin case 'S': svg.changeType(newFirstItem, newFirstItem.relative ? 'c' : 'C'); break; case 'T': svg.changeType(newFirstItem, newFirstItem.relative ? 'q' : 'Q'); break; } for(let i=newOriginIndex ; i idx > 0 && i.getType().toUpperCase() === 'M'); const firstZ = subPath.findIndex(i => i.getType().toUpperCase() === 'Z'); if(firstZ === -1 || (followingM !== -1 && firstZ > followingM)) { // We can remove inital M if there is no Z in the following subpath continue; } } } outputPath.push(subPath[(newOriginIndex - start + i)%l]); } svg.path = [ ...svg.path.slice(0, start), ...outputPath, ...svg.path.slice(end), ]; svg.refreshAbsolutePositions(); if(isBeforeRelative) { svg.path[start + outputPath.length].setRelative(true); } optimizePath(svg, { removeUselessCommands: true, useShorthands: true, useClosePath: true, }); };