go htmx stream

原始地址:https://github.com/alarbada/htmx-stream

window.htmx.defineExtension("stream", {
  onEvent: (name, evt) => {
    if (name === "htmx:beforeRequest") {
      let element = evt.detail.elt;
      if (evt.detail.requestConfig.target) {
        element.__target = evt.detail.requestConfig.target;
        element = evt.detail.requestConfig.target;
      }

      const xhr = evt.detail.xhr;

      let lastLength = 0;
      xhr.addEventListener('readystatechange', () => {
        if (xhr.readyState === 2 || xhr.readyState === 3) {
          const newText = xhr.responseText.substring(lastLength);
          element.__streamedChars = lastLength;
          lastLength = xhr.responseText.length;
          element.innerHTML = newText;
        }
      });
    }
    return true;
  },
  transformResponse: (text, _xhr, elt) => {
    let lastLength = elt.__streamedChars;
    const target = elt.__target;
    if (target) {
      lastLength = target.__streamedChars;
    }

    if (lastLength) {
      const newText = text.substring(lastLength);
      return newText;
    }

    return text;
  }
});
posted @ 2024-10-16 18:38  卓能文  阅读(6)  评论(0编辑  收藏  举报