1 | const chokidar = require('chokidar');
|
2 | const path = require('path');
|
3 |
|
4 | const { writeRequires, getMain, getFilePathExtension } = require('./loader');
|
5 |
|
6 | const { getArguments } = require('./handle-args');
|
7 |
|
8 | const args = getArguments();
|
9 | const log = console.log.bind(console);
|
10 |
|
11 | const mainExt = getFilePathExtension(args, 'main');
|
12 | const previewExt = getFilePathExtension(args, 'preview');
|
13 |
|
14 | const watchPaths = [`./main.${mainExt}`];
|
15 |
|
16 | if (previewExt) {
|
17 | watchPaths.push(`./preview.${previewExt}`);
|
18 | }
|
19 |
|
20 | const updateRequires = (event, watchPath) => {
|
21 | if (typeof watchPath === 'string') {
|
22 | log(`event ${event} for file ${path.basename(watchPath)}`);
|
23 | }
|
24 | writeRequires(args);
|
25 | };
|
26 |
|
27 | const globs = getMain(args).stories;
|
28 |
|
29 | chokidar
|
30 | .watch(watchPaths, { cwd: args.configPath })
|
31 | .on('change', (watchPath) => updateRequires('change', watchPath));
|
32 |
|
33 | let isReady = false;
|
34 |
|
35 | chokidar
|
36 | .watch(globs, { cwd: args.configPath })
|
37 | .on('ready', () => {
|
38 | log('Watcher is ready, performing initial write');
|
39 | writeRequires(args);
|
40 | log('Waiting for changes, press r to manually re-write');
|
41 | isReady = true;
|
42 | })
|
43 | .on('add', (watchPath) => {
|
44 | if (isReady) {
|
45 | updateRequires('add', watchPath);
|
46 | }
|
47 | })
|
48 | .on('unlink', (watchPath) => {
|
49 | if (isReady) {
|
50 | updateRequires('unlink', watchPath);
|
51 | }
|
52 | });
|
53 |
|
54 | const readline = require('readline');
|
55 | readline.emitKeypressEvents(process.stdin);
|
56 | process.stdin.setRawMode(true);
|
57 | process.stdin.on('keypress', (str, key) => {
|
58 | if (key.ctrl && key.name === 'c') {
|
59 | process.exit();
|
60 | }
|
61 | if (key.name === 'r') {
|
62 | log('Detected "r" keypress, rewriting story imports...');
|
63 | writeRequires(args);
|
64 | }
|
65 | });
|