File size: 1,408 Bytes
e454383
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { convertMarkdownToDocx, downloadDocx } from "@mohtasham/md-to-docx";
import type { Chat } from "./types";

export async function downloadChatAsMarkdown(chat: Chat): Promise<void> {
  try {
    const markdown = generateMarkdownFromChat(chat);
    const blob = await convertMarkdownToDocx(markdown);
    const filename = `${chat.title || "Chat"}_${
      new Date().toISOString().split("T")[0]
    }.docx`;
    downloadDocx(blob, filename);
  } catch (error) {
    console.error("Failed to download chat as markdown:", error);
    throw error;
  }
}

function generateMarkdownFromChat(chat: Chat): string {
  let markdown = `# ${chat.title || "Chat Export"}\n\n`;
  markdown += `**Date:** ${new Date(chat.date).toLocaleDateString()}\n\n`;
  markdown += `[TOC]\n\n`;

  // Filter out system messages and process user/assistant pairs
  const nonSystemMessages = chat.messages.filter(
    (msg) => msg.role !== "system"
  );

  for (let i = 0; i < nonSystemMessages.length; i++) {
    const message = nonSystemMessages[i];

    if (message.role === "user") {
      markdown += ` ## ${message.content}\n\n`;
    } else if (message.role === "assistant") {
      markdown += `${message.content}\n\n`;

      // Add page break after each question-answer pair, except for the last one
      if (i < nonSystemMessages.length - 1) {
        markdown += `\\pagebreak\n\n`;
      }
    }
  }

  return markdown;
}