All files / player-terminal/src/node deferred-ui-flush.ts

89.28% Statements 25/28
72.22% Branches 13/18
100% Functions 6/6
89.28% Lines 25/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                            13x 13x 13x     13x 5x 5x       5x       5x 5x   5x       5x   5x         13x 30x 17x   13x     13x   18x 18x     12x 12x     11x 11x 8x 8x          
import { clearImmediate, setImmediate } from 'node:timers';
 
export interface DeferredUIFlushState {
  frame: boolean;
  commands: boolean;
}
 
export interface DeferredUIFlush {
  markFrameDirty: () => void;
  markCommandsDirty: () => void;
  dispose: () => void;
}
 
export function createDeferredUIFlush(flush: (state: Readonly<DeferredUIFlushState>) => void): DeferredUIFlush {
  let framePending = false;
  let commandsPending = false;
  let disposed = false;
  let handle: ReturnType<typeof setImmediate> | undefined;
 
  const run = (): void => {
    handle = undefined;
    Iif (disposed) {
      return;
    }
 
    const pendingState: DeferredUIFlushState = {
      frame: framePending,
      commands: commandsPending,
    };
    framePending = false;
    commandsPending = false;
 
    Iif (!pendingState.frame && !pendingState.commands) {
      return;
    }
 
    flush(pendingState);
 
    Iif (!disposed && (framePending || commandsPending) && handle === undefined) {
      handle = setImmediate(run);
    }
  };
 
  const schedule = (): void => {
    if (disposed || handle !== undefined) {
      return;
    }
    handle = setImmediate(run);
  };
 
  return {
    markFrameDirty: () => {
      framePending = true;
      schedule();
    },
    markCommandsDirty: () => {
      commandsPending = true;
      schedule();
    },
    dispose: () => {
      disposed = true;
      if (handle !== undefined) {
        clearImmediate(handle);
        handle = undefined;
      }
    },
  };
}