|
| 1 | +import { API, FileInfo, Options } from 'jscodeshift'; |
| 2 | + |
| 3 | +export default function transformer( |
| 4 | + file: FileInfo, |
| 5 | + { jscodeshift: j }: API, |
| 6 | + options: Options, |
| 7 | +) { |
| 8 | + const isSpreadElement = prop => prop && prop.type === 'SpreadElement'; |
| 9 | + const isValue = prop => prop && prop.type !== 'SpreadElement'; |
| 10 | + const getPropName = prop => |
| 11 | + (prop.key && (prop.key.name || prop.key.value)) || ''; |
| 12 | + const sortByPropName = (a, b) => { |
| 13 | + if (a < b) return -1; |
| 14 | + if (a > b) return 1; |
| 15 | + return 0; |
| 16 | + }; |
| 17 | + const sortProps = props => { |
| 18 | + props.sort((a, b) => sortByPropName(getPropName(a), getPropName(b))); |
| 19 | + }; |
| 20 | + |
| 21 | + return j(file.source) |
| 22 | + .find(api.jscodeshift.ObjectExpression) |
| 23 | + .forEach(path => { |
| 24 | + const chunks = []; |
| 25 | + const nextProperties = []; |
| 26 | + const objectExpression = path.value; |
| 27 | + |
| 28 | + objectExpression.properties.forEach((prop, i, props) => { |
| 29 | + if (isValue(prop)) { |
| 30 | + const prev = props[i - 1]; |
| 31 | + const next = props[i + 1]; |
| 32 | + const isChunkStart = !isValue(prev); |
| 33 | + const isChunkEnd = !isValue(next); |
| 34 | + |
| 35 | + isChunkStart && chunks.push([]); |
| 36 | + const [chunk] = chunks.slice(-1); |
| 37 | + chunk.push(prop); |
| 38 | + |
| 39 | + if (isChunkEnd) { |
| 40 | + sortProps(chunk); |
| 41 | + nextProperties.push(...chunk); |
| 42 | + } |
| 43 | + } else if (isSpreadElement(prop)) { |
| 44 | + nextProperties.push(prop); |
| 45 | + } |
| 46 | + }); |
| 47 | + |
| 48 | + objectExpression.properties = nextProperties; |
| 49 | + }) |
| 50 | + .toSource(options.printOptions); |
| 51 | +} |
0 commit comments