UNPKG

2.03 kBJavaScriptView Raw
1const chokidar = require('chokidar');
2const path = require('path');
3
4const { writeRequires, getMain, getFilePathExtension } = require('./loader');
5
6const { getArguments } = require('./handle-args');
7
8const args = getArguments();
9
10if (!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
18const log = console.log.bind(console);
19
20const mainExt = getFilePathExtension(args, 'main');
21const previewExt = getFilePathExtension(args, 'preview');
22
23const watchPaths = [`./main.${mainExt}`];
24
25if (previewExt) {
26 watchPaths.push(`./preview.${previewExt}`);
27}
28
29console.log(watchPaths);
30
31const updateRequires = (event, watchPath) => {
32 if (typeof watchPath === 'string') {
33 log(`event ${event} for file ${path.basename(watchPath)}`);
34 }
35 writeRequires(args);
36};
37
38const globs = getMain(args).stories;
39// directory
40// files
41const 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
48chokidar
49 .watch(watchPaths, { cwd: args.configPath })
50 .on('change', (watchPath) => updateRequires('change', watchPath));
51
52let isReady = false;
53
54chokidar
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
73const readline = require('readline');
74readline.emitKeypressEvents(process.stdin);
75process.stdin.setRawMode(true);
76process.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});