|
| 1 | +var path = require("path"); |
| 2 | +var compileElm = require("node-elm-compiler").compile; |
| 3 | +var { |
| 4 | + unindent, |
| 5 | + writeFile, |
| 6 | + withTmpDir, |
| 7 | + assertKeysPresent |
| 8 | +} = require("./js/utils.js"); |
| 9 | + |
| 10 | +var requiredOptions = ["stylesheetModule", "stylesheetFunction"]; |
| 11 | + |
| 12 | +function generateCss(opts) { |
| 13 | + assertKeysPresent(opts, requiredOptions, missingOptions => { |
| 14 | + throw new Error(`Missing options: ${missingOptions.join(", ")}`); |
| 15 | + }); |
| 16 | + |
| 17 | + return withTmpDir().then(tmpDirPath => { |
| 18 | + var emitterSourceFile = path.join(tmpDirPath, "StyleElementsEmitter.elm"); |
| 19 | + var emitterWorkerFile = path.join(tmpDirPath, "style-elements-emitter.js"); |
| 20 | + var emitterTemplate = buildEmitterTemplate( |
| 21 | + opts.stylesheetModule, |
| 22 | + opts.stylesheetFunction |
| 23 | + ); |
| 24 | + |
| 25 | + return writeFile(emitterSourceFile, emitterTemplate) |
| 26 | + .then(() => compile(emitterSourceFile, { output: emitterWorkerFile, yes: true })) |
| 27 | + .then(() => extractCssResults(emitterWorkerFile)); |
| 28 | + }); |
| 29 | +} |
| 30 | + |
| 31 | +function buildEmitterTemplate(stylesheetModule, stylesheetFunction) { |
| 32 | + return unindent( |
| 33 | + ` |
| 34 | + port module StyleElementsEmitter exposing (..) |
| 35 | +
|
| 36 | + import ${stylesheetModule} |
| 37 | +
|
| 38 | +
|
| 39 | + port result : String -> Cmd msg |
| 40 | +
|
| 41 | +
|
| 42 | + stylesheet = |
| 43 | + ${stylesheetModule}.${stylesheetFunction} |
| 44 | +
|
| 45 | +
|
| 46 | + main : Program Never () Never |
| 47 | + main = |
| 48 | + Platform.program |
| 49 | + { init = ( (), result stylesheet.css ) |
| 50 | + , update = \\_ _ -> ( (), Cmd.none ) |
| 51 | + , subscriptions = \\_ -> Sub.none |
| 52 | + } |
| 53 | + ` |
| 54 | + ); |
| 55 | +} |
| 56 | + |
| 57 | +function compile(src, options) { |
| 58 | + return new Promise(function(resolve, reject) { |
| 59 | + compileElm(src, options).on("close", function(exitCode) { |
| 60 | + if (exitCode === 0) { |
| 61 | + resolve(); |
| 62 | + } else { |
| 63 | + reject("Errored with exit code " + exitCode); |
| 64 | + } |
| 65 | + }); |
| 66 | + }); |
| 67 | +} |
| 68 | + |
| 69 | +function extractCssResults(destFile) { |
| 70 | + var emitter = require(destFile).StyleElementsEmitter; |
| 71 | + var worker = emitter.worker(); |
| 72 | + |
| 73 | + return new Promise(resolve => worker.ports.result.subscribe(resolve)); |
| 74 | +} |
| 75 | + |
| 76 | +module.exports = generateCss; |
0 commit comments