-
Notifications
You must be signed in to change notification settings - Fork 0
/
ensure-flow.js
110 lines (97 loc) · 2.6 KB
/
ensure-flow.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import { promises as fs } from 'fs'
import crypto from 'crypto'
import ensureFile from './ensure-file.js'
import getViewRelativeToView from './get-view-relative-to-view.js'
import path from 'path'
function maybeReactNative(as, content) {
return as === 'react-native'
? content.replace(
'import',
`import { URL } from 'react-native-url-polyfill'\nimport`
)
: content
}
async function makeFlow({ as, viewsById, viewsToFiles }) {
let flowJson = makeFlowJson({ viewsById, viewsToFiles })
let content = await fs.readFile(
path.join(__dirname, 'views', 'Flow.js'),
'utf8'
)
return maybeReactNative(as, content).replace(
'export let flowDefinition = {}',
`export let flowDefinition = ${flowJson.flowDefinitionString}`
)
}
async function makeFlowTools({ as }) {
let content = await fs.readFile(
path.join(__dirname, 'views', 'Flow.tools.js'),
'utf8'
)
return maybeReactNative(as, content)
}
let prevHash = null
function makeFlowJson({ viewsById, viewsToFiles }) {
let flowDefinition = {}
for (let view of viewsToFiles.values()) {
if (!view || view.custom || !view.parsed.view.isView) continue
let states = []
for (let id of view.parsed.view.views) {
let viewInView = getViewRelativeToView({
id,
view,
viewsById,
viewsToFiles,
})
if (viewInView && !viewInView.custom && viewInView.parsed.view.isView) {
states.push(id)
}
}
if (view.parsed.view.flow !== 'separate') continue
flowDefinition[view.parsed.view.viewPath] = states
}
let flowDefinitionString = JSON.stringify(flowDefinition)
let hash = crypto
.createHash('sha1')
.update(flowDefinitionString)
.digest('hex')
let changed = prevHash !== hash
if (changed) {
prevHash = hash
}
return { hash, changed, flowDefinition, flowDefinitionString }
}
export default function ensureFlow({
as,
pass,
src,
tools,
viewsById,
viewsToFiles,
}) {
if (tools) {
let flowJson = makeFlowJson({ viewsById, viewsToFiles })
return [
pass === 0 &&
makeFlowTools({ as }).then((content) =>
ensureFile({
file: path.join(src, 'Views', 'Flow.js'),
content,
})
),
flowJson.changed &&
ensureFile({
file: path.join(src, 'Views', 'Flow.json'),
content: flowJson.flowDefinitionString,
}),
]
} else {
return [
makeFlow({ as, viewsById, viewsToFiles }).then((content) =>
ensureFile({
file: path.join(src, 'Views', 'Flow.js'),
content,
})
),
]
}
}