JSFiddle - React, Tailwind, and code Playground

by Hemanth HM

JavaScript

import { marked } from 'marked';

class MarkdownTransformStream extends TransformStream {
  constructor() {
    let buffer = '';
    const textDecoder = new TextDecoder();
    const textEncoder = new TextEncoder();

    super({
      transform(chunk, controller) {
        // Check if the chunk is already a string
        const textChunk = typeof chunk === 'string' 
          ? chunk 
          : textDecoder.decode(chunk, { stream: true });

        // Add the new text to the buffer
        buffer += textChunk;

        // Split the buffer into lines
        const lines = buffer.split('\n');

        // Keep the last (possibly incomplete) line in the buffer
        buffer = lines.pop();

        // Process complete lines
        for (const line of lines) {
          const html = marked.parse(line);
          controller.enqueue(textEncoder.encode(html));
        }
      },

      flush(controller) {
        // Process any remaining content in the buffer
        if (buffer) {
          const html = marked.parse(buffer);
          controller.enqueue(textEncoder.encode(html));
        }
      }
    });
  }
}

// Usage example
async function streamMarkdownToHTML(markdownStream) {
  const markdownTransformStream = new MarkdownTransformStream();
  return markdownStream.pipeThrough(markdownTransformStream);
}

// Example of how to use the streamMarkdownToHTML function
async function displayStreamInDiv(stream, divId) {
  const contentDiv = document.getElementById(divId);
  const reader = stream.getReader();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    
    const decodedChunk = new TextDecoder().decode(value);
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = decodedChunk;
    contentDiv.appendChild(tempDiv);
  }
}

// Assuming you have a ReadableStream of Markdown content
const markdownStream = getMarkdownStreamSomehow();

// Convert Markdown stream to HTML stream and display...