Last active
May 20, 2019 16:44
-
-
Save rusty-key/20d228a416fc70d31a71056bb03c9853 to your computer and use it in GitHub Desktop.
jsx2 wrapper for jsx3 bindings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// requires node 12.* | |
const fs = require('fs') | |
const path = require('path') | |
const refmt = require('reason'); | |
const dir = path.resolve(process.argv[2]) | |
if (!fs.existsSync(dir)) { | |
console.error(`${dir} doesn't exist`); | |
return | |
} | |
fs.readdirSync(dir) | |
.filter(fileName => fileName.endsWith(".re")) | |
.forEach(fileName => { | |
console.log(`working on ${fileName}...`) | |
const filePath = path.join(dir, fileName) | |
const content = fs.readFileSync(filePath, 'utf-8') | |
const lines = content.split(/[\n\r]/) | |
const props = lines.flatMap(line => { | |
const matches = line.match(/(~(.+?): (.+?),)/g) | |
if (!matches) return [] | |
return matches.map(match => { | |
const m = match.split(/[~:,]/) | |
return { | |
name: m[1].trim(), | |
isOptional: m[2].trim().endsWith("?") | |
} | |
}) | |
}) | |
if (!props.length) return true | |
const propsStr = props | |
.map(prop => { | |
const isChildren = prop.name == "children" | |
return `${isChildren ? "" : "~"}${prop.name}${prop.isOptional && !isChildren ? "=?" : ""}` | |
}) | |
.join(","); | |
const makePropsStr = props | |
.map(prop => `~${prop.name}${prop.isOptional && prop.name != "children" ? "?" : ""}`) | |
.join(","); | |
const hasChildren = props.some(prop => prop.name == "children") | |
const jsx2 = ` | |
module Jsx2 = { | |
let component = ReasonReact.statelessComponent(__MODULE__); | |
let make = (${propsStr}) => { | |
${hasChildren ? "let children = React.array(children);" : ""} | |
ReasonReactCompat.wrapReactForReasonReact( | |
make, | |
makeProps(${makePropsStr}, ()), | |
children, | |
); | |
}; | |
}; | |
` | |
const parsedJsx2 = refmt.parseRE(jsx2); | |
const formattedJsx2 = refmt.printRE(parsedJsx2); | |
fs.appendFileSync(filePath, '\n' + formattedJsx2); | |
console.log(`${fileName} updated!`) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment