UNPKG

3.02 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 local = 'en',
22 src,
23 tools = false,
24 track = false,
25 verbose = true,
26}) {
27 let state = {
28 as,
29 local,
30 src,
31 tools,
32 track,
33 verbose,
34 customFonts: new Map(),
35 viewsById: new Map(),
36 viewsToFiles: new Map(),
37 }
38
39 state.processFiles = async function processFiles({
40 filesFontCustom = new Set(),
41 filesView = new Set(),
42 filesViewCustom = new Set(),
43 filesViewLogic = new Set(),
44 }) {
45 if (filesFontCustom.size > 0) {
46 processCustomFonts({
47 customFonts: state.customFonts,
48 filesFontCustom,
49 })
50 }
51
52 // detect .view files
53 await processViewFiles({
54 filesView,
55 filesViewLogic,
56 viewsById: state.viewsById,
57 viewsToFiles: state.viewsToFiles,
58 })
59
60 // detect .js files meant to be custom views with "// @view" at the top
61 processViewCustomFiles({
62 filesViewCustom,
63 viewsById: state.viewsById,
64 viewsToFiles: state.viewsToFiles,
65 })
66
67 // TODO optimise
68 // parse views
69 parseViews({
70 customFonts: state.customFonts,
71 filesView,
72 src: state.src,
73 verbose: state.verbose,
74 viewsById: state.viewsById,
75 viewsToFiles: state.viewsToFiles,
76 })
77
78 let morphedFonts = morphAllFonts({
79 as: state.as,
80 customFonts: state.customFonts,
81 filesView,
82 src: state.src,
83 viewsToFiles: state.viewsToFiles,
84 })
85
86 // TODO optimise
87 // morph views
88 let morphedViews = morphAllViews({
89 as: state.as,
90 filesView,
91 getFontImport: makeGetFontImport(state.src),
92 getSystemImport: makeGetSystemImport(state.src),
93 local: state.local,
94 tools: state.tools,
95 track: state.track,
96 viewsById: state.viewsById,
97 viewsToFiles: state.viewsToFiles,
98 })
99
100 let filesToWrite = [
101 ...morphedFonts,
102 ...morphedViews,
103 // TODO optimise, only if they changed, cache, etc
104 await ensureData(state),
105 await ensureFlow(state),
106 await ensureTools(state),
107 await ensureIsBefore(state),
108 await ensureIsHovered(state),
109 await ensureIsMedia(state),
110 ].filter(Boolean)
111
112 await Promise.all(
113 filesToWrite.map(({ file, content }) =>
114 fs.writeFile(file, content, 'utf-8')
115 )
116 )
117 }
118
119 return state
120}