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 |
|
10 | if (!args.v6Store) {
|
11 | console.log(
|
12 | "in v7 you don't need the watcher anymore, if you are using v6 compat mode then pass the -v6 flag"
|
13 | );
|
14 |
|
15 | process.exit(0);
|
16 | }
|
17 |
|
18 | const log = console.log.bind(console);
|
19 |
|
20 | const mainExt = getFilePathExtension(args, 'main');
|
21 | const previewExt = getFilePathExtension(args, 'preview');
|
22 |
|
23 | const watchPaths = [`./main.${mainExt}`];
|
24 |
|
25 | if (previewExt) {
|
26 | watchPaths.push(`./preview.${previewExt}`);
|
27 | }
|
28 |
|
29 | console.log(watchPaths);
|
30 |
|
31 | const updateRequires = (event, watchPath) => {
|
32 | if (typeof watchPath === 'string') {
|
33 | log(`event ${event} for file ${path.basename(watchPath)}`);
|
34 | }
|
35 | writeRequires(args);
|
36 | };
|
37 |
|
38 | const globs = getMain(args).stories;
|
39 |
|
40 |
|
41 | const globsStrings = globs.map((g) => {
|
42 | if (typeof g === 'string') return g;
|
43 | if (g.directory && g.files) {
|
44 | return `${g.directory}/${g.files}`;
|
45 | }
|
46 | });
|
47 |
|
48 | chokidar
|
49 | .watch(watchPaths, { cwd: args.configPath })
|
50 | .on('change', (watchPath) => updateRequires('change', watchPath));
|
51 |
|
52 | let isReady = false;
|
53 |
|
54 | chokidar
|
55 | .watch(globsStrings, { cwd: args.configPath })
|
56 | .on('ready', () => {
|
57 | log('Watcher is ready, performing initial write');
|
58 | writeRequires(args);
|
59 | log('Waiting for changes, press r to manually re-write');
|
60 | isReady = true;
|
61 | })
|
62 | .on('add', (watchPath) => {
|
63 | if (isReady) {
|
64 | updateRequires('add', watchPath);
|
65 | }
|
66 | })
|
67 | .on('unlink', (watchPath) => {
|
68 | if (isReady) {
|
69 | updateRequires('unlink', watchPath);
|
70 | }
|
71 | });
|
72 |
|
73 | const readline = require('readline');
|
74 | readline.emitKeypressEvents(process.stdin);
|
75 | process.stdin.setRawMode(true);
|
76 | process.stdin.on('keypress', (str, key) => {
|
77 | if (key.ctrl && key.name === 'c') {
|
78 | process.exit();
|
79 | }
|
80 | if (key.name === 'r') {
|
81 | log('Detected "r" keypress, rewriting story imports...');
|
82 | writeRequires(args);
|
83 | }
|
84 | });
|