import buffer from '../buffer';

function eventsource({ url, bufferTime = 0 }, { feed, reset, onFinish }) {
  let es;
  let buf;

  function initBuffer() {
    if (buf !== undefined) buf.stop();
    buf = buffer(feed, bufferTime);
  }

  return {
    start: () => {
      es = new EventSource(url);

      es.addEventListener('open', () => {
        console.debug('eventsource: opened');
        initBuffer();
      });

      es.addEventListener('message', event => {
        const e = JSON.parse(event.data);

        if (e.cols !== undefined || e.width !== undefined) {
          initBuffer();
          reset(e.cols ?? e.width, e.rows ?? e.height);
        } else {
          buf.pushEvent(e);
        }
      });

      es.addEventListener('done', () => {
        console.debug('eventsource: closed');
        es.close();
        onFinish();
      });
    },

    stop: () => {
      if (buf !== undefined) buf.stop();
      if (es !== undefined) es.close();
    }
  }
}

export { eventsource };

@@ -86,16 +86,28 @@
 , reset,
+ setWaiting,
  onFinis
@@ -397,35 +397,214 @@
 ');%0A        
-initBuffer(
+setWaiting(false);%0A        initBuffer();%0A      %7D);%0A%0A      es.addEventListener('error', e =%3E %7B%0A        console.debug('eventsource: errored');%0A        console.debug(e);%0A        setWaiting(true
 );%0A      %7D);

Use loading indicator with EventSource (SSE) driver