UNPKG

2.91 kBJavaScriptView Raw
1import {
2 makeGetFontImport,
3 morphAllFonts,
4 processCustomFonts,
5} from './fonts.js'
6import { promises as fs } from 'fs'
7import ensureData from './ensure-data.js'
8import ensureFlow from './ensure-flow.js'
9import ensureIsBefore from './ensure-is-before.js'
10import ensureIsHovered from './ensure-is-hovered.js'
11import ensureIsMedia from './ensure-is-media.js'
12import ensureTools from './ensure-tools.js'
13import makeGetSystemImport from './make-get-system-import.js'
14import morphAllViews from './morph-all-views.js'
15import parseViews from './parse-views.js'
16import processViewCustomFiles from './process-view-custom-files.js'
17import processViewFiles from './process-view-files.js'
18
19export default function makeMorpher({
20 as = 'react-dom',
21 src,
22 tools = false,
23 verbose = true,
24}) {
25 let state = {
26 as,
27 src,
28 tools,
29 verbose,
30 customFonts: new Map(),
31 viewsById: new Map(),
32 viewsToFiles: new Map(),
33 }
34
35 state.processFiles = async function processFiles({
36 filesFontCustom = new Set(),
37 filesView = new Set(),
38 filesViewCustom = new Set(),
39 filesViewLogic = new Set(),
40 }) {
41 if (filesFontCustom.size > 0) {
42 processCustomFonts({
43 customFonts: state.customFonts,
44 filesFontCustom,
45 })
46 }
47
48 // detect .view files
49 await processViewFiles({
50 filesView,
51 filesViewLogic,
52 viewsById: state.viewsById,
53 viewsToFiles: state.viewsToFiles,
54 })
55
56 // detect .js files meant to be custom views with "// @view" at the top
57 processViewCustomFiles({
58 filesViewCustom,
59 viewsById: state.viewsById,
60 viewsToFiles: state.viewsToFiles,
61 })
62
63 // TODO optimise
64 // parse views
65 parseViews({
66 customFonts: state.customFonts,
67 filesView,
68 src: state.src,
69 verbose: state.verbose,
70 viewsById: state.viewsById,
71 viewsToFiles: state.viewsToFiles,
72 })
73
74 let morphedFonts = morphAllFonts({
75 as: state.as,
76 customFonts: state.customFonts,
77 filesView,
78 src: state.src,
79 viewsToFiles: state.viewsToFiles,
80 })
81
82 // TODO optimise
83 // morph views
84 let morphedViews = morphAllViews({
85 as: state.as,
86 filesView,
87 getFontImport: makeGetFontImport(state.src),
88 getSystemImport: makeGetSystemImport(state.src),
89 tools: state.tools,
90 viewsById: state.viewsById,
91 viewsToFiles: state.viewsToFiles,
92 })
93
94 let filesToWrite = [
95 ...morphedFonts,
96 ...morphedViews,
97 // TODO optimise, only if they changed, cache, etc
98 await ensureData(state),
99 await ensureFlow(state),
100 await ensureTools(state),
101 await ensureIsBefore(state),
102 await ensureIsHovered(state),
103 await ensureIsMedia(state),
104 ].filter(Boolean)
105
106 await Promise.all(
107 filesToWrite.map(({ file, content }) =>
108 fs.writeFile(file, content, 'utf-8')
109 )
110 )
111 }
112
113 return state
114}