Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/brave-otters-dance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@shopify/theme-language-server-common": patch
---

Queue debounced theme checks so triggers are not dropped and asynchronous runs do not overlap.
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ export function startServer(
themeGraphManager,
}),
100,
(previous, next): [string[]] => [[...new Set([...previous[0], ...next[0]])]],
);

const getTranslationsForURI: GetTranslationsForURI = async (uri) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { debounce } from './debounce';

const mergeValues = (previous: [string[]], next: [string[]]): [string[]] => [
[...new Set([...previous[0], ...next[0]])],
];

describe('debounce', () => {
afterEach(() => {
vi.useRealTimers();
});

it('merges calls made before a forced run', async () => {
vi.useFakeTimers();
const run = vi.fn<(values: string[]) => void>();
const debouncedRun = debounce(run, 100, mergeValues);

debouncedRun(['first']);
debouncedRun.force(['second']);
debouncedRun(['third']);

await vi.advanceTimersByTimeAsync(100);

expect(run).toHaveBeenCalledOnce();
expect(run).toHaveBeenCalledWith(['first', 'second', 'third']);
});

it('queues calls made while an asynchronous invocation is running', async () => {
vi.useFakeTimers();
let finishFirstRun!: () => void;
const firstRun = new Promise<void>((resolve) => {
finishFirstRun = resolve;
});
const run = vi
.fn<(values: string[]) => Promise<void>>()
.mockImplementationOnce(() => firstRun)
.mockResolvedValue(undefined);
const debouncedRun = debounce(run, 100, mergeValues);

debouncedRun(['first']);
await vi.advanceTimersByTimeAsync(100);
expect(run).toHaveBeenCalledOnce();

debouncedRun(['during-run']);
debouncedRun.force(['forced-during-run']);
await vi.advanceTimersByTimeAsync(500);
expect(run).toHaveBeenCalledOnce();

finishFirstRun();
await Promise.resolve();
await Promise.resolve();
await vi.advanceTimersByTimeAsync(100);

expect(run).toHaveBeenCalledTimes(2);
expect(run).toHaveBeenLastCalledWith(['during-run', 'forced-during-run']);
});
});
77 changes: 55 additions & 22 deletions packages/theme-language-server-common/src/utils/debounce.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,23 @@ import { ArgumentTypes } from '@shopify/theme-check-common';

export interface DebouncedFunction<F extends Function> {
/**
* A function that will execute on the trailing edge of a timer with the
* last arguments it was called with (unless forced)
* A function that executes after the debounce interval. Calls made while a
* previous invocation is running are queued for a later invocation.
*/
(...args: ArgumentTypes<F>): void;

/**
* Debounced version of a function but making sure that it is called with
* this specific set of arguments.
*
* Subsequent calls will be ignored until the timer has expired and the
* function has executed.
* Mark this call as forced. Later calls may be queued, but do not replace
* this call while it is waiting for the timer.
*/
force(...args: ArgumentTypes<F>): void;
}

/**
* debounce(fn, ms)
*
* A debounced function only executes once after a timer has expired. Repeated
* call to the debounced function before its timer has expired result in a delayed
* execution of the function.
* Calls made before the timer expires are debounced. Calls made while the
* function is running are queued and run after the current invocation finishes.
*
* This is useful in cases where you have an "expensive" function that you only want
* to execute after the user is idle for a little bit.
Expand All @@ -35,26 +31,63 @@ export interface DebouncedFunction<F extends Function> {
*
* @param fn a function that should be debounced
* @param ms milliseconds after last function call for it to execute
* @returns a function that will execute on the trailing edge of a timer with the last argument it was called with
* @param mergeArguments how to combine pending arguments. By default, the
* arguments from the latest call are used.
* @returns a debounced function
*/
export function debounce<F extends Function>(fn: F, ms?: number): DebouncedFunction<F> {
export function debounce<F extends Function>(
fn: F,
ms?: number,
mergeArguments: (previous: ArgumentTypes<F>, next: ArgumentTypes<F>) => ArgumentTypes<F> = (
_previous,
next,
) => next,
): DebouncedFunction<F> {
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let force = false; // force use a certain set of arguments in the next call
let pendingArgs: ArgumentTypes<F> | null = null;
let running = false;
let forcePending = false;

const debouncedFn = (...args: ArgumentTypes<F>): void => {
if (timeoutId !== null && force) return;
if (timeoutId !== null) clearTimeout(timeoutId);
timeoutId = setTimeout(async () => {
await Promise.resolve(fn(...args));
const schedule = () => {
if (running || timeoutId !== null || pendingArgs === null) return;

timeoutId = setTimeout(() => {
timeoutId = null;
force = false;
const args = pendingArgs;
pendingArgs = null;
forcePending = false;
if (args === null) return;

running = true;
Promise.resolve()
.then(() => fn(...args))
.finally(() => {
running = false;
schedule();
});
}, ms);
};

debouncedFn.force = (...args: ArgumentTypes<F>): void => {
debouncedFn(...args);
force = true;
const enqueue = (args: ArgumentTypes<F>, force: boolean) => {
pendingArgs = pendingArgs === null ? args : mergeArguments(pendingArgs, args);

if (running) {
if (force) forcePending = true;
return;
}

if (timeoutId !== null) {
if (forcePending && !force) return;
clearTimeout(timeoutId);
timeoutId = null;
}

schedule();
if (force) forcePending = true;
};

const debouncedFn = (...args: ArgumentTypes<F>): void => enqueue(args, false);
debouncedFn.force = (...args: ArgumentTypes<F>): void => enqueue(args, true);

return debouncedFn;
}
Loading