Skip to content

Commit 6caed79

Browse files
committed
fixed file watch to debounce sourcebit refresh
1 parent c00584d commit 6caed79

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

src/index.js

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ module.exports.bootstrap = async ({ setPluginContext, options, refresh }) => {
3131
const stackbitYamlPath = path.resolve(stackbitYamlFileName);
3232
const stackbitYamlExists = await fse.pathExists(stackbitYamlPath);
3333
if (stackbitYamlExists) {
34+
log('loading stackbit.yaml and models...');
3435
const { models, stackbitYaml } = await loadStackbitYaml(stackbitYamlPath)
3536
setPluginContext({ models, stackbitYaml });
3637

@@ -52,18 +53,36 @@ module.exports.bootstrap = async ({ setPluginContext, options, refresh }) => {
5253
setPluginContext({ files });
5354

5455
if (watch) {
55-
const update = async (eventName, path) => {
56-
log(`file '${path}' has been ${eventName}, reloading files...`);
56+
let changedFilePaths = [];
5757

58-
if (path === stackbitYamlFileName) {
59-
const { models, stackbitYaml } = loadStackbitYaml(stackbitYamlPath)
58+
// don't call refresh on every file change, as multiple files could be written at once.
59+
// instead, debounce the update function for 50ms, up to 200ms
60+
const debouncedUpdate = _.debounce(async () => {
61+
log(`reload files and refresh sourcebit plugins...`);
62+
63+
const filePathsCopy = changedFilePaths.slice();
64+
changedFilePaths = [];
65+
66+
if (filePathsCopy.includes(stackbitYamlFileName)) {
67+
log('reloading stackbit.yaml and models...');
68+
const { models, stackbitYaml } = await loadStackbitYaml(stackbitYamlPath)
6069
setPluginContext({ models, stackbitYaml });
61-
} else {
70+
}
71+
72+
if (_.some(filePathsCopy, filePath => filePath !== stackbitYamlFileName)) {
73+
log('reloading content files...');
6274
const files = await readFiles(sources);
75+
log(`loaded ${files.length} files`);
6376
setPluginContext({ files });
6477
}
6578

6679
refresh();
80+
}, 50, {maxWait: 200});
81+
82+
const update = async (eventName, filePath) => {
83+
log(`file '${filePath}' has been ${eventName}, reloading files...`);
84+
changedFilePaths.push(filePath);
85+
await debouncedUpdate();
6786
};
6887

6988
const watchPaths = _.map(sources, _.property('path'));

0 commit comments

Comments
 (0)