-
Notifications
You must be signed in to change notification settings - Fork 1
/
State.js
392 lines (323 loc) · 10.2 KB
/
State.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
import crypto from 'crypto'
import isPlainObject from 'lodash/isPlainObject'
import isArray from 'lodash/isArray'
import findIndex from 'lodash/findIndex'
import set from 'lodash/set'
import get from 'lodash/get'
import merge from 'lodash/merge'
import remove from 'lodash/remove'
import path from 'path'
import fs from 'fs-extra'
import mime from 'mime-types'
import themeSerif from '@canopycanopycanopy/b-ber-theme-serif'
import themeSans from '@canopycanopycanopy/b-ber-theme-sans'
import log from '@canopycanopycanopy/b-ber-logger'
import Yaml from './Yaml'
import Config from './Config'
import Spine from './Spine'
const themes = {
'b-ber-theme-serif': themeSerif,
'b-ber-theme-sans': themeSans,
}
const randomHash = () => crypto.randomBytes(20).toString('hex')
const skipInitialization = () => {
const { argv } = process
// prettier-ignore
return (
argv.includes('--help') || // if a help flag is set
argv.includes('-h') || // if a help alias is set
argv.length < 3 || // if there are insufficient arguments
argv.includes('new') // if it's a new project
)
}
const SRC_DIR_IMAGES = '_images'
const SRC_DIR_MARKDOWN = '_markdown'
const SRC_DIR_STYLESHEETS = '_stylesheets'
const SRC_DIR_JAVASCRIPTS = '_javascripts'
const SRC_DIR_FONTS = '_fonts'
const SRC_DIR_MEDIA = '_media'
const DIST_DIR_OPS = 'OPS'
const DIST_DIR_TEXT = 'text'
const DIST_DIR_IMAGES = 'images'
const DIST_DIR_STYLESHEETS = 'stylesheets'
const DIST_DIR_JAVASCRIPTS = 'javascripts'
const DIST_DIR_FONTS = 'fonts'
const DIST_DIR_MEDIA = 'media'
class State {
static get defaults() {
return {
build: 'epub',
sequence: [],
hash: randomHash(),
}
}
metadata = { json: () => [{}] } // mocks the YAML api
theme = {}
video = []
audio = []
build = 'epub'
sequence = []
hash = randomHash()
builds = {
sample: {},
epub: {},
mobi: {},
pdf: {},
web: {},
reader: {},
}
get spine() {
return this.builds[this.build].spine
}
set spine(val) {
this.builds[this.build].spine = val
}
get guide() {
return this.builds[this.build].guide
}
set guide(val) {
this.builds[this.build].guide = val
}
get figures() {
return this.builds[this.build].figures
}
set figures(val) {
this.builds[this.build].figures = val
}
get footnotes() {
return this.builds[this.build].footnotes
}
set footnotes(val) {
this.builds[this.build].footnotes = val
}
get cursor() {
return this.builds[this.build].cursor
}
set cursor(val) {
this.builds[this.build].cursor = val
}
get toc() {
return this.builds[this.build].toc
}
set toc(val) {
this.builds[this.build].toc = val
}
get remoteAssets() {
return this.builds[this.build].remoteAssets
}
set remoteAssets(val) {
this.builds[this.build].remoteAssets = val
}
get loi() {
return this.builds[this.build].loi
}
set loi(val) {
this.builds[this.build].loi = val
}
get srcDir() {
return this.config.src
}
set srcDir(val) {
this.config.src = val
}
get distDir() {
if (this.build && this.builds && this.builds[this.build]) {
return this.builds[this.build].dist
}
return this.config.dist
}
set distDir(val) {
this.config.dist = val
}
// eslint-disable-next-line class-methods-use-this
get env() {
return process.env.NODE_ENV || 'development'
}
set env(val) {
this.config.env = val
}
src = {
root: (...args) => path.join(this.srcDir, ...args),
images: (...args) => path.join(this.srcDir, SRC_DIR_IMAGES, ...args),
markdown: (...args) => path.join(this.srcDir, SRC_DIR_MARKDOWN, ...args),
stylesheets: (...args) =>
path.join(this.srcDir, SRC_DIR_STYLESHEETS, ...args),
javascripts: (...args) =>
path.join(this.srcDir, SRC_DIR_JAVASCRIPTS, ...args),
fonts: (...args) => path.join(this.srcDir, SRC_DIR_FONTS, ...args),
media: (...args) => path.join(this.srcDir, SRC_DIR_MEDIA, ...args),
}
dist = {
root: (...args) => path.join(this.distDir, ...args),
ops: (...args) => path.join(this.distDir, DIST_DIR_OPS, ...args),
text: (...args) =>
path.join(this.distDir, DIST_DIR_OPS, DIST_DIR_TEXT, ...args),
images: (...args) =>
path.join(this.distDir, DIST_DIR_OPS, DIST_DIR_IMAGES, ...args),
stylesheets: (...args) =>
path.join(this.distDir, DIST_DIR_OPS, DIST_DIR_STYLESHEETS, ...args),
javascripts: (...args) =>
path.join(this.distDir, DIST_DIR_OPS, DIST_DIR_JAVASCRIPTS, ...args),
fonts: (...args) =>
path.join(this.distDir, DIST_DIR_OPS, DIST_DIR_FONTS, ...args),
media: (...args) =>
path.join(this.distDir, DIST_DIR_OPS, DIST_DIR_MEDIA, ...args),
}
constructor() {
let version
// for testing, since our directory structure is different in dist
try {
;({ version } = fs.readJSONSync(require.resolve('./package.json')))
} catch (err) {
;({ version } = fs.readJSONSync(require.resolve('../package.json')))
}
set(this, 'version', version)
set(this, 'config', new Config())
this.reset()
this.loadMetadata()
this.loadMedia()
this.loadBuilds()
this.loadTheme()
}
reset = () => {
Object.entries(State.defaults).forEach(([key, val]) => set(this, key, val))
this.loadConfig()
}
add = (prop, value) => {
const prevValue = get(this, prop)
if (isArray(prevValue)) {
set(this, prop, [...prevValue, value])
} else if (isPlainObject(prevValue)) {
set(this, prop, { ...prevValue, value })
} else if (typeof prevValue === 'string') {
set(this, prop, `${prevValue}${value}`)
} else {
log.error(`Cannot add [${value}] to [state.${prop}]`)
}
}
remove = (prop, value) => {
const prevValue = get(this, prop)
if (isArray(prevValue)) {
const arr = [...prevValue]
remove(arr, value)
set(this, prop, arr)
} else if (isPlainObject(prevValue)) {
const { [value]: _, ...rest } = prevValue // eslint-disable-line no-unused-vars
set(this, prop, rest)
} else {
log.error(`Cannot remove [${value}] from [state.${prop}]`)
}
}
merge = (prop, value) => {
const oldValue = get(this, prop)
set(this, prop, merge(oldValue, value))
}
update = (prop, val) => {
set(this, prop, val)
}
contains = (coll, value) => this.indexOf(coll, value) > -1
indexOf = (coll, pred) => {
const collection = get(this, coll)
return findIndex(collection, pred)
}
loadConfig = () => {
if (!fs.existsSync(path.resolve('config.yml'))) return
const config = new Yaml('config')
config.load(path.resolve('config.yml'))
// not necessary right now to pass around a YAWN instance since we'er
// not writing back to config.yml, but may be necessary at some point
set(this, 'config', new Config(config.json()))
}
loadMetadata = () => {
const fpath = path.resolve(this.config.src, 'metadata.yml')
if (!fs.existsSync(fpath)) return
set(this, 'metadata', new Yaml('metadata'))
this.metadata.load(fpath)
}
loadTheme = () => {
// ensure themes dir exists unless running `new` command, as it's the
// only command that's run outside of a project directory
if (skipInitialization()) return
const userThemesPath = path.resolve(this.config.themes_directory)
fs.ensureDirSync(userThemesPath)
// theme is set, using a built-in theme
if (themes[this.config.theme]) {
log.info(`Loaded theme [${this.config.theme}]`)
set(this, 'theme', themes[this.config.theme])
return
}
// possibly a user defined theme, check if the directory exists
try {
if (
(this.theme = require(path.resolve(userThemesPath, this.config.theme))) // eslint-disable-line global-require, import/no-dynamic-require
) {
log.info(`Loaded theme [${this.config.theme}]`)
return
}
} catch (_) {
// noop
}
// possibly a theme installed with npm, test the project root
try {
set(
this,
'theme',
require(path.resolve('node_modules', this.config.theme)) // eslint-disable-line global-require, import/no-dynamic-require
) // require.resolve?
} catch (err) {
log.warn(`There was an error during require [${this.config.theme}]`)
log.warn('Using default theme [b-ber-theme-serif]')
log.warn(err.message)
// error loading theme, set to default
set(this, 'theme', themes['b-ber-theme-serif'])
}
}
loadMedia = () => {
if (skipInitialization()) return
const mediaPath = path.resolve(this.config.src, '_media')
fs.ensureDirSync(mediaPath)
const media = fs.readdirSync(mediaPath)
const video = media.filter(a => /^video/.test(mime.lookup(a)))
const audio = media.filter(a => /^audio/.test(mime.lookup(a)))
set(this, 'video', video)
set(this, 'audio', audio)
}
loadBuildSettings = type => {
if (skipInitialization()) return
const { src, dist } = this.config
const projectDir = path.resolve(src)
if (!fs.existsSync(projectDir))
log.error(`Project directory [${projectDir}] does not exist`)
// One TOC to rule them all (toc.yml). A user can override the TOC for a
// specific build by including a <type>.yml file, which will be loaded
// instead of toc.yml below.
const navigationConfigFileDefaultPath = path.resolve(src, 'toc.yml')
const navigationConfigFilePath = path.resolve(src, `${type}.yml`)
const navigationConfigFile = fs.existsSync(navigationConfigFilePath)
? navigationConfigFilePath
: navigationConfigFileDefaultPath
const spine = new Spine({ src, buildType: type, navigationConfigFile })
// Build-specific config. gets merged into base config during build step
const config = this.config[type] ? { ...this.config[type] } : {}
return {
src,
dist: `${dist}-${type}`,
config,
guide: [],
spine,
toc: spine.nested,
cursor: [],
figures: [],
footnotes: [],
remoteAssets: [],
loi: [],
}
}
loadBuilds = () => {
const builds = ['sample', 'epub', 'mobi', 'pdf', 'web', 'reader', 'xml']
builds.forEach(build =>
set(this.builds, build, this.loadBuildSettings(build))
)
}
}
export default new State()