UNPKG

1.65 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();
9const log = console.log.bind(console);
10
11const mainExt = getFilePathExtension(args, 'main');
12const previewExt = getFilePathExtension(args, 'preview');
13
14const watchPaths = [`./main.${mainExt}`];
15
16if (previewExt) {
17 watchPaths.push(`./preview.${previewExt}`);
18}
19
20const updateRequires = (event, watchPath) => {
21 if (typeof watchPath === 'string') {
22 log(`event ${event} for file ${path.basename(watchPath)}`);
23 }
24 writeRequires(args);
25};
26
27const globs = getMain(args).stories;
28
29chokidar
30 .watch(watchPaths, { cwd: args.configPath })
31 .on('change', (watchPath) => updateRequires('change', watchPath));
32
33let isReady = false;
34
35chokidar
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
54const readline = require('readline');
55readline.emitKeypressEvents(process.stdin);
56process.stdin.setRawMode(true);
57process.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});