refactor: adopt preact and restructure the codebase

This commit is contained in:
Pionxzh
2023-01-12 00:29:11 +08:00
parent 7881d89c20
commit c8626c0894
23 changed files with 1188 additions and 498 deletions

View File

@@ -1,11 +1,12 @@
module.exports = {
root: true,
extends: [
'@pionxzh/eslint-config-ts',
'@pionxzh/eslint-config-react',
],
rules: {
'no-console': 'off',
'no-alert': 'off',
'react/prop-types': 'off',
'@typescript-eslint/ban-ts-comment': 'off',
'@typescript-eslint/no-unused-vars': 'off',
},

1
.npmrc Normal file
View File

@@ -0,0 +1 @@
auto-install-peers=true

View File

@@ -27,7 +27,7 @@
"devDependencies": {
"@commitlint/cli": "^17.3.0",
"@commitlint/config-conventional": "^17.3.0",
"@pionxzh/eslint-config-ts": "^0.1.1",
"@pionxzh/eslint-config-react": "^0.1.1",
"@types/node": "^18.11.17",
"cpy-cli": "^4.2.0",
"eslint": "^8.30.0",

View File

@@ -17,10 +17,12 @@
},
"dependencies": {
"html2canvas": "^1.4.1",
"preact": "^10.11.3",
"sentinel-js": "^0.0.5",
"vite-plugin-monkey": "^2.10.0"
},
"devDependencies": {
"@preact/preset-vite": "^2.5.0",
"vite": "^4.0.3"
}
}

View File

@@ -0,0 +1,79 @@
import { ChatGPTAvatar } from '../icons'
import { getConversation } from '../parser'
import { timestamp } from '../utils/utils'
import { downloadFile } from '../utils/download'
import templateHtml from '../template.html?raw'
export function exportToHtml() {
const conversations = getConversation()
if (conversations.length === 0) return alert('No conversation found. Please send a message first.')
const lang = document.documentElement.lang ?? 'en'
const conversationHtml = conversations.map((item) => {
const { author: { name, avatar }, lines } = item
const avatarEl = name === 'ChatGPT'
? `${ChatGPTAvatar}`
: `<img src="${avatar}" alt="${name}" />`
const linesHtml = lines.map((line) => {
const lineHtml = line.map((item) => {
switch (item.type) {
case 'text':
return escapeHtml(item.text)
case 'image':
return `<img src="${item.src}" referrerpolicy="no-referrer" />`
case 'code':
return `<code>${escapeHtml(item.code)}</code>`
case 'code-block':
return `<pre><code class="language-${item.lang}">${escapeHtml(item.code)}</code></pre>`
case 'link':
return `<a href="${item.href}" target="_blank" rel="noopener noreferrer">${escapeHtml(item.text)}</a>`
case 'ordered-list-item':
return `<ol>${item.items.map(item => `<li>${escapeHtml(item)}</li>`).join('')}</ol>`
case 'unordered-list-item':
return `<ul>${item.items.map(item => `<li>${escapeHtml(item)}</li>`).join('')}</ul>`
case 'table': {
const header = item.headers.map(item => `<th>${escapeHtml(item)}</th>`).join('')
const body = item.rows.map(row => `<tr>${row.map(item => `<td>${escapeHtml(item)}</td>`).join('')}</tr>`).join('')
return `<table><thead><tr>${header}</tr></thead><tbody>${body}</tbody></table>`
}
default:
return ''
}
}).join('')
const skipTags = ['pre', 'ul', 'ol', 'table']
if (skipTags.some(tag => lineHtml.startsWith(`<${tag}>`))) return lineHtml
return `<p>${lineHtml}</p>`
}).join('')
return `
<div class="conversation-item">
<div class="author">
${avatarEl}
</div>
<div class="conversation-content">
${linesHtml}
</div>
</div>`
}).join('')
const html = templateHtml
.replace('{{time}}', new Date().toISOString())
.replace('{{lang}}', lang)
.replace('{{content}}', conversationHtml)
const fileName = `ChatGPT-${timestamp()}.html`
downloadFile(fileName, 'text/html', html)
}
function escapeHtml(html: string) {
return html
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;')
}

View File

@@ -0,0 +1,28 @@
import html2canvas from 'html2canvas'
import { downloadUrl } from '../utils/download'
import { sleep, timestamp } from '../utils/utils'
export async function exportToPng() {
const thread = document.querySelector('main .group')?.parentElement as HTMLElement
if (!thread || thread.children.length === 0) return
// hide bottom bar
thread.children[thread.children.length - 1].classList.add('hidden')
await sleep(100)
const canvas = await html2canvas(thread, {
scrollX: -window.scrollX,
scrollY: -window.scrollY,
windowWidth: thread.scrollWidth,
windowHeight: thread.scrollHeight,
})
// restore the layout
thread.children[thread.children.length - 1].classList.remove('hidden')
const dataUrl = canvas.toDataURL('image/png', 1)
.replace(/^data:image\/[^;]/, 'data:application/octet-stream')
const fileName = `ChatGPT-${timestamp()}.png`
downloadUrl(fileName, dataUrl)
}

View File

@@ -0,0 +1,21 @@
import { getConversation } from '../parser'
import type { Conversation } from '../type'
import { downloadFile } from '../utils/download'
import { timestamp } from '../utils/utils'
import { lineToText } from './text'
export function exportToMarkdown() {
const conversations = getConversation()
if (conversations.length === 0) return alert('No conversation found. Please send a message first.')
const text = conversationToMarkdown(conversations)
downloadFile(`chatgpt-${timestamp()}.md`, 'text/markdown', text)
}
function conversationToMarkdown(conversation: Conversation[]) {
return conversation.map((item) => {
const { author: { name }, lines } = item
const text = lines.map(line => lineToText(line)).join('\r\n\r\n')
return `#### ${name}:\r\n${text}`
}).join('\r\n\r\n')
}

View File

@@ -0,0 +1,33 @@
import type { ConversationLine } from '../type'
import { getConversation } from '../parser'
import { copyToClipboard } from '../utils/clipboard'
import { tableToMarkdown } from '../utils/markdown'
export function exportToText() {
const conversations = getConversation()
if (conversations.length === 0) return alert('No conversation found. Please send a message first.')
const text = conversations.map((item) => {
const { author: { name }, lines } = item
const text = lines.map(line => lineToText(line)).join('\r\n\r\n')
return `${name}:\r\n${text}`
}).join('\r\n\r\n')
copyToClipboard(text)
}
export function lineToText(line: ConversationLine): string {
return line.map((item) => {
switch (item.type) {
case 'text': return item.text
case 'image': return '[image]'
case 'link': return `[${item.text}](${item.href})`
case 'ordered-list-item': return item.items.map((item, index) => `${index + 1}. ${item}`).join('\r\n')
case 'unordered-list-item': return item.items.map(item => `- ${item}`).join('\r\n')
case 'code': return `\`${item.code}\``
case 'code-block': return `\`\`\`${item.lang}\r\n${item.code}\`\`\``
case 'table': return tableToMarkdown(item.headers, item.rows)
default: return ''
}
}).join('')
}

View File

@@ -1,19 +0,0 @@
// source: fontawesome: file-lines
export const fileLines = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512" class="w-4 h-4" fill="currentColor"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M64 0C28.7 0 0 28.7 0 64V448c0 35.3 28.7 64 64 64H320c35.3 0 64-28.7 64-64V160H256c-17.7 0-32-14.3-32-32V0H64zM256 0V128H384L256 0zM112 256H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16zm0 64H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16zm0 64H272c8.8 0 16 7.2 16 16s-7.2 16-16 16H112c-8.8 0-16-7.2-16-16s7.2-16 16-16z"/></svg>'
// source: fontawesome: file-code
export const fileCode = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512" class="w-4 h-4" fill="currentColor"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M64 0C28.7 0 0 28.7 0 64V448c0 35.3 28.7 64 64 64H320c35.3 0 64-28.7 64-64V160H256c-17.7 0-32-14.3-32-32V0H64zM256 0V128H384L256 0zM153 289l-31 31 31 31c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0L71 337c-9.4-9.4-9.4-24.6 0-33.9l48-48c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9zM265 255l48 48c9.4 9.4 9.4 24.6 0 33.9l-48 48c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l31-31-31-31c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0z"/></svg>'
// source: fontawesome: file-image
export const iconCamera = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="w-4 h-4" fill="currentColor"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M149.1 64.8L138.7 96H64C28.7 96 0 124.7 0 160V416c0 35.3 28.7 64 64 64H448c35.3 0 64-28.7 64-64V160c0-35.3-28.7-64-64-64H373.3L362.9 64.8C356.4 45.2 338.1 32 317.4 32H194.6c-20.7 0-39 13.2-45.5 32.8zM256 384c-53 0-96-43-96-96s43-96 96-96s96 43 96 96s-43 96-96 96z"/></svg>'
// source: fontawesome: markdown
export const iconMarkdown = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512" class="w-4 h-4" fill="currentColor"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M593.8 59.1H46.2C20.7 59.1 0 79.8 0 105.2v301.5c0 25.5 20.7 46.2 46.2 46.2h547.7c25.5 0 46.2-20.7 46.1-46.1V105.2c0-25.4-20.7-46.1-46.2-46.1zM338.5 360.6H277v-120l-61.5 76.9-61.5-76.9v120H92.3V151.4h61.5l61.5 76.9 61.5-76.9h61.5v209.2zm135.3 3.1L381.5 256H443V151.4h61.5V256H566z"/></svg>'
// source: fontawesome: copy
export const iconCopy = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="w-4 h-4" fill="currentColor"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z"/></svg>'
// source: fontawesome: arrow-right-from-bracket
export const iconArrowRightFromBracket = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" class="w-4 h-4" fill="currentColor"><!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --><path d="M534.6 278.6c12.5-12.5 12.5-32.8 0-45.3l-128-128c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L434.7 224 224 224c-17.7 0-32 14.3-32 32s14.3 32 32 32l210.7 0-73.4 73.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l128-128zM192 96c17.7 0 32-14.3 32-32s-14.3-32-32-32l-64 0c-53 0-96 43-96 96l0 256c0 53 43 96 96 96l64 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-64 0c-17.7 0-32-14.3-32-32l0-256c0-17.7 14.3-32 32-32l64 0z"/></svg>'
export const chatGPTAvatarSVG = '<svg width="1.5rem" height="1.5rem" viewBox="0 0 41 41" fill="none" xmlns="http://www.w3.org/2000/svg" stroke-width="1.5"><path d="M37.5324 16.8707C37.9808 15.5241 38.1363 14.0974 37.9886 12.6859C37.8409 11.2744 37.3934 9.91076 36.676 8.68622C35.6126 6.83404 33.9882 5.3676 32.0373 4.4985C30.0864 3.62941 27.9098 3.40259 25.8215 3.85078C24.8796 2.7893 23.7219 1.94125 22.4257 1.36341C21.1295 0.785575 19.7249 0.491269 18.3058 0.500197C16.1708 0.495044 14.0893 1.16803 12.3614 2.42214C10.6335 3.67624 9.34853 5.44666 8.6917 7.47815C7.30085 7.76286 5.98686 8.3414 4.8377 9.17505C3.68854 10.0087 2.73073 11.0782 2.02839 12.312C0.956464 14.1591 0.498905 16.2988 0.721698 18.4228C0.944492 20.5467 1.83612 22.5449 3.268 24.1293C2.81966 25.4759 2.66413 26.9026 2.81182 28.3141C2.95951 29.7256 3.40701 31.0892 4.12437 32.3138C5.18791 34.1659 6.8123 35.6322 8.76321 36.5013C10.7141 37.3704 12.8907 37.5973 14.9789 37.1492C15.9208 38.2107 17.0786 39.0587 18.3747 39.6366C19.6709 40.2144 21.0755 40.5087 22.4946 40.4998C24.6307 40.5054 26.7133 39.8321 28.4418 38.5772C30.1704 37.3223 31.4556 35.5506 32.1119 33.5179C33.5027 33.2332 34.8167 32.6547 35.9659 31.821C37.115 30.9874 38.0728 29.9178 38.7752 28.684C39.8458 26.8371 40.3023 24.6979 40.0789 22.5748C39.8556 20.4517 38.9639 18.4544 37.5324 16.8707ZM22.4978 37.8849C20.7443 37.8874 19.0459 37.2733 17.6994 36.1501C17.7601 36.117 17.8666 36.0586 17.936 36.0161L25.9004 31.4156C26.1003 31.3019 26.2663 31.137 26.3813 30.9378C26.4964 30.7386 26.5563 30.5124 26.5549 30.2825V19.0542L29.9213 20.998C29.9389 21.0068 29.9541 21.0198 29.9656 21.0359C29.977 21.052 29.9842 21.0707 29.9867 21.0902V30.3889C29.9842 32.375 29.1946 34.2791 27.7909 35.6841C26.3872 37.0892 24.4838 37.8806 22.4978 37.8849ZM6.39227 31.0064C5.51397 29.4888 5.19742 27.7107 5.49804 25.9832C5.55718 26.0187 5.66048 26.0818 5.73461 26.1244L13.699 30.7248C13.8975 30.8408 14.1233 30.902 14.3532 30.902C14.583 30.902 14.8088 30.8408 15.0073 30.7248L24.731 25.1103V28.9979C24.7321 29.0177 24.7283 29.0376 24.7199 29.0556C24.7115 29.0736 24.6988 29.0893 24.6829 29.1012L16.6317 33.7497C14.9096 34.7416 12.8643 35.0097 10.9447 34.4954C9.02506 33.9811 7.38785 32.7263 6.39227 31.0064ZM4.29707 13.6194C5.17156 12.0998 6.55279 10.9364 8.19885 10.3327C8.19885 10.4013 8.19491 10.5228 8.19491 10.6071V19.808C8.19351 20.0378 8.25334 20.2638 8.36823 20.4629C8.48312 20.6619 8.64893 20.8267 8.84863 20.9404L18.5723 26.5542L15.206 28.4979C15.1894 28.5089 15.1703 28.5155 15.1505 28.5173C15.1307 28.5191 15.1107 28.516 15.0924 28.5082L7.04046 23.8557C5.32135 22.8601 4.06716 21.2235 3.55289 19.3046C3.03862 17.3858 3.30624 15.3413 4.29707 13.6194ZM31.955 20.0556L22.2312 14.4411L25.5976 12.4981C25.6142 12.4872 25.6333 12.4805 25.6531 12.4787C25.6729 12.4769 25.6928 12.4801 25.7111 12.4879L33.7631 17.1364C34.9967 17.849 36.0017 18.8982 36.6606 20.1613C37.3194 21.4244 37.6047 22.849 37.4832 24.2684C37.3617 25.6878 36.8382 27.0432 35.9743 28.1759C35.1103 29.3086 33.9415 30.1717 32.6047 30.6641C32.6047 30.5947 32.6047 30.4733 32.6047 30.3889V21.188C32.6066 20.9586 32.5474 20.7328 32.4332 20.5338C32.319 20.3348 32.154 20.1698 31.955 20.0556ZM35.3055 15.0128C35.2464 14.9765 35.1431 14.9142 35.069 14.8717L27.1045 10.2712C26.906 10.1554 26.6803 10.0943 26.4504 10.0943C26.2206 10.0943 25.9948 10.1554 25.7963 10.2712L16.0726 15.8858V11.9982C16.0715 11.9783 16.0753 11.9585 16.0837 11.9405C16.0921 11.9225 16.1048 11.9068 16.1207 11.8949L24.1719 7.25025C25.4053 6.53903 26.8158 6.19376 28.2383 6.25482C29.6608 6.31589 31.0364 6.78077 32.2044 7.59508C33.3723 8.40939 34.2842 9.53945 34.8334 10.8531C35.3826 12.1667 35.5464 13.6095 35.3055 15.0128ZM14.2424 21.9419L10.8752 19.9981C10.8576 19.9893 10.8423 19.9763 10.8309 19.9602C10.8195 19.9441 10.8122 19.9254 10.8098 19.9058V10.6071C10.8107 9.18295 11.2173 7.78848 11.9819 6.58696C12.7466 5.38544 13.8377 4.42659 15.1275 3.82264C16.4173 3.21869 17.8524 2.99464 19.2649 3.1767C20.6775 3.35876 22.0089 3.93941 23.1034 4.85067C23.0427 4.88379 22.937 4.94215 22.8668 4.98473L14.9024 9.58517C14.7025 9.69878 14.5366 9.86356 14.4215 10.0626C14.3065 10.2616 14.2466 10.4877 14.2479 10.7175L14.2424 21.9419ZM16.071 17.9991L20.4018 15.4978L24.7325 17.9975V22.9985L20.4018 25.4983L16.071 22.9985V17.9991Z" fill="currentColor"></path></svg>'

View File

@@ -0,0 +1,27 @@
// source: fontawesome: file-code
export function FileCode() {
return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512" className="w-4 h-4" fill="currentColor">{/* <!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --> */}<path d="M64 0C28.7 0 0 28.7 0 64V448c0 35.3 28.7 64 64 64H320c35.3 0 64-28.7 64-64V160H256c-17.7 0-32-14.3-32-32V0H64zM256 0V128H384L256 0zM153 289l-31 31 31 31c9.4 9.4 9.4 24.6 0 33.9s-24.6 9.4-33.9 0L71 337c-9.4-9.4-9.4-24.6 0-33.9l48-48c9.4-9.4 24.6-9.4 33.9 0s9.4 24.6 0 33.9zM265 255l48 48c9.4 9.4 9.4 24.6 0 33.9l-48 48c-9.4 9.4-24.6 9.4-33.9 0s-9.4-24.6 0-33.9l31-31-31-31c-9.4-9.4-9.4-24.6 0-33.9s24.6-9.4 33.9 0z" /></svg>
}
// source: fontawesome: file-image
export function IconCamera() {
return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" className="w-4 h-4" fill="currentColor">{/* <!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --> */}<path d="M149.1 64.8L138.7 96H64C28.7 96 0 124.7 0 160V416c0 35.3 28.7 64 64 64H448c35.3 0 64-28.7 64-64V160c0-35.3-28.7-64-64-64H373.3L362.9 64.8C356.4 45.2 338.1 32 317.4 32H194.6c-20.7 0-39 13.2-45.5 32.8zM256 384c-53 0-96-43-96-96s43-96 96-96s96 43 96 96s-43 96-96 96z" /></svg>
}
// source: fontawesome: markdown
export function IconMarkdown() {
return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512" className="w-4 h-4" fill="currentColor">{/* <!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --> */}<path d="M593.8 59.1H46.2C20.7 59.1 0 79.8 0 105.2v301.5c0 25.5 20.7 46.2 46.2 46.2h547.7c25.5 0 46.2-20.7 46.1-46.1V105.2c0-25.4-20.7-46.1-46.2-46.1zM338.5 360.6H277v-120l-61.5 76.9-61.5-76.9v120H92.3V151.4h61.5l61.5 76.9 61.5-76.9h61.5v209.2zm135.3 3.1L381.5 256H443V151.4h61.5V256H566z" /></svg>
}
// source: fontawesome: copy
export function IconCopy() {
return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" className="w-4 h-4" fill="currentColor">{/* <!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --> */}<path d="M502.6 70.63l-61.25-61.25C435.4 3.371 427.2 0 418.7 0H255.1c-35.35 0-64 28.66-64 64l.0195 256C192 355.4 220.7 384 256 384h192c35.2 0 64-28.8 64-64V93.25C512 84.77 508.6 76.63 502.6 70.63zM464 320c0 8.836-7.164 16-16 16H255.1c-8.838 0-16-7.164-16-16L239.1 64.13c0-8.836 7.164-16 16-16h128L384 96c0 17.67 14.33 32 32 32h47.1V320zM272 448c0 8.836-7.164 16-16 16H63.1c-8.838 0-16-7.164-16-16L47.98 192.1c0-8.836 7.164-16 16-16H160V128H63.99c-35.35 0-64 28.65-64 64l.0098 256C.002 483.3 28.66 512 64 512h192c35.2 0 64-28.8 64-64v-32h-47.1L272 448z" /></svg>
}
// source: fontawesome: arrow-right-from-bracket
export function IconArrowRightFromBracket() {
return <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" className="w-4 h-4" fill="currentColor">{/* <!--! Font Awesome Pro 6.2.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2022 Fonticons, Inc. --> */}<path d="M534.6 278.6c12.5-12.5 12.5-32.8 0-45.3l-128-128c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L434.7 224 224 224c-17.7 0-32 14.3-32 32s14.3 32 32 32l210.7 0-73.4 73.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0l128-128zM192 96c17.7 0 32-14.3 32-32s-14.3-32-32-32l-64 0c-53 0-96 43-96 96l0 256c0 53 43 96 96 96l64 0c17.7 0 32-14.3 32-32s-14.3-32-32-32l-64 0c-17.7 0-32-14.3-32-32l0-256c0-17.7 14.3-32 32-32l64 0z" /></svg>
}
export const ChatGPTAvatar = '<svg width="1.5rem" height="1.5rem" viewBox="0 0 41 41" fill="none" xmlns="http://www.w3.org/2000/svg" strokeWidth="1.5"><path d="M37.5324 16.8707C37.9808 15.5241 38.1363 14.0974 37.9886 12.6859C37.8409 11.2744 37.3934 9.91076 36.676 8.68622C35.6126 6.83404 33.9882 5.3676 32.0373 4.4985C30.0864 3.62941 27.9098 3.40259 25.8215 3.85078C24.8796 2.7893 23.7219 1.94125 22.4257 1.36341C21.1295 0.785575 19.7249 0.491269 18.3058 0.500197C16.1708 0.495044 14.0893 1.16803 12.3614 2.42214C10.6335 3.67624 9.34853 5.44666 8.6917 7.47815C7.30085 7.76286 5.98686 8.3414 4.8377 9.17505C3.68854 10.0087 2.73073 11.0782 2.02839 12.312C0.956464 14.1591 0.498905 16.2988 0.721698 18.4228C0.944492 20.5467 1.83612 22.5449 3.268 24.1293C2.81966 25.4759 2.66413 26.9026 2.81182 28.3141C2.95951 29.7256 3.40701 31.0892 4.12437 32.3138C5.18791 34.1659 6.8123 35.6322 8.76321 36.5013C10.7141 37.3704 12.8907 37.5973 14.9789 37.1492C15.9208 38.2107 17.0786 39.0587 18.3747 39.6366C19.6709 40.2144 21.0755 40.5087 22.4946 40.4998C24.6307 40.5054 26.7133 39.8321 28.4418 38.5772C30.1704 37.3223 31.4556 35.5506 32.1119 33.5179C33.5027 33.2332 34.8167 32.6547 35.9659 31.821C37.115 30.9874 38.0728 29.9178 38.7752 28.684C39.8458 26.8371 40.3023 24.6979 40.0789 22.5748C39.8556 20.4517 38.9639 18.4544 37.5324 16.8707ZM22.4978 37.8849C20.7443 37.8874 19.0459 37.2733 17.6994 36.1501C17.7601 36.117 17.8666 36.0586 17.936 36.0161L25.9004 31.4156C26.1003 31.3019 26.2663 31.137 26.3813 30.9378C26.4964 30.7386 26.5563 30.5124 26.5549 30.2825V19.0542L29.9213 20.998C29.9389 21.0068 29.9541 21.0198 29.9656 21.0359C29.977 21.052 29.9842 21.0707 29.9867 21.0902V30.3889C29.9842 32.375 29.1946 34.2791 27.7909 35.6841C26.3872 37.0892 24.4838 37.8806 22.4978 37.8849ZM6.39227 31.0064C5.51397 29.4888 5.19742 27.7107 5.49804 25.9832C5.55718 26.0187 5.66048 26.0818 5.73461 26.1244L13.699 30.7248C13.8975 30.8408 14.1233 30.902 14.3532 30.902C14.583 30.902 14.8088 30.8408 15.0073 30.7248L24.731 25.1103V28.9979C24.7321 29.0177 24.7283 29.0376 24.7199 29.0556C24.7115 29.0736 24.6988 29.0893 24.6829 29.1012L16.6317 33.7497C14.9096 34.7416 12.8643 35.0097 10.9447 34.4954C9.02506 33.9811 7.38785 32.7263 6.39227 31.0064ZM4.29707 13.6194C5.17156 12.0998 6.55279 10.9364 8.19885 10.3327C8.19885 10.4013 8.19491 10.5228 8.19491 10.6071V19.808C8.19351 20.0378 8.25334 20.2638 8.36823 20.4629C8.48312 20.6619 8.64893 20.8267 8.84863 20.9404L18.5723 26.5542L15.206 28.4979C15.1894 28.5089 15.1703 28.5155 15.1505 28.5173C15.1307 28.5191 15.1107 28.516 15.0924 28.5082L7.04046 23.8557C5.32135 22.8601 4.06716 21.2235 3.55289 19.3046C3.03862 17.3858 3.30624 15.3413 4.29707 13.6194ZM31.955 20.0556L22.2312 14.4411L25.5976 12.4981C25.6142 12.4872 25.6333 12.4805 25.6531 12.4787C25.6729 12.4769 25.6928 12.4801 25.7111 12.4879L33.7631 17.1364C34.9967 17.849 36.0017 18.8982 36.6606 20.1613C37.3194 21.4244 37.6047 22.849 37.4832 24.2684C37.3617 25.6878 36.8382 27.0432 35.9743 28.1759C35.1103 29.3086 33.9415 30.1717 32.6047 30.6641C32.6047 30.5947 32.6047 30.4733 32.6047 30.3889V21.188C32.6066 20.9586 32.5474 20.7328 32.4332 20.5338C32.319 20.3348 32.154 20.1698 31.955 20.0556ZM35.3055 15.0128C35.2464 14.9765 35.1431 14.9142 35.069 14.8717L27.1045 10.2712C26.906 10.1554 26.6803 10.0943 26.4504 10.0943C26.2206 10.0943 25.9948 10.1554 25.7963 10.2712L16.0726 15.8858V11.9982C16.0715 11.9783 16.0753 11.9585 16.0837 11.9405C16.0921 11.9225 16.1048 11.9068 16.1207 11.8949L24.1719 7.25025C25.4053 6.53903 26.8158 6.19376 28.2383 6.25482C29.6608 6.31589 31.0364 6.78077 32.2044 7.59508C33.3723 8.40939 34.2842 9.53945 34.8334 10.8531C35.3826 12.1667 35.5464 13.6095 35.3055 15.0128ZM14.2424 21.9419L10.8752 19.9981C10.8576 19.9893 10.8423 19.9763 10.8309 19.9602C10.8195 19.9441 10.8122 19.9254 10.8098 19.9058V10.6071C10.8107 9.18295 11.2173 7.78848 11.9819 6.58696C12.7466 5.38544 13.8377 4.42659 15.1275 3.82264C16.4173 3.21869 17.8524 2.99464 19.2649 3.1767C20.6775 3.35876 22.0089 3.93941 23.1034 4.85067C23.0427 4.88379 22.937 4.94215 22.8668 4.98473L14.9024 9.58517C14.7025 9.69878 14.5366 9.86356 14.4215 10.0626C14.3065 10.2616 14.2466 10.4877 14.2479 10.7175L14.2424 21.9419ZM16.071 17.9991L20.4018 15.4978L24.7325 17.9975V22.9985L20.4018 25.4983L16.071 22.9985V17.9991Z" fill="currentColor"></path></svg>'

View File

@@ -1,370 +0,0 @@
import html2canvas from 'html2canvas'
import sentinel from 'sentinel-js'
import { chatGPTAvatarSVG, fileCode, iconArrowRightFromBracket, iconCamera, iconCopy, iconMarkdown } from './icons'
import { copyToClipboard, downloadFile, downloadUrl, escapeHtml, getBase64FromImg, onloadSafe, sleep, timestamp } from './utils'
import templateHtml from './template.html?raw'
import './style.css'
type ConversationLineNode = |
{ type: 'text'; text: string } |
{ type: 'image'; src: string } |
{ type: 'code'; code: string } |
{ type: 'code-block'; lang: string; code: string } |
{ type: 'link'; text: string; href: string } |
{ type: 'ordered-list-item'; items: string[] } |
{ type: 'unordered-list-item'; items: string[] } |
{ type: 'table'; headers: string[]; rows: string[][] }
type ConversationLine = ConversationLineNode[]
interface Conversation {
author: {
name: string
avatar: string
}
lines: ConversationLine[]
}
main()
function main() {
onloadSafe(() => {
const copyHtml = `${iconCopy}Copy Text`
const copiedHtml = `${iconCopy}Copied`
const onCopyText = (e: MouseEvent) => {
const items = getConversation()
if (items.length === 0) return alert('No conversation found. Please send a message first.')
const text = conversationToText(items)
copyToClipboard(text)
const menuItem = e.target as HTMLAnchorElement
menuItem.innerHTML = copiedHtml
setTimeout(() => {
menuItem.innerHTML = copyHtml
}, 3000)
}
const divider = createDivider()
const exportButton = createMenuItem(iconArrowRightFromBracket, 'Export', () => {})
const dropdown = document.createElement('div')
dropdown.classList.add('dropdown-menu', 'bg-gray-900')
const textExport = createMenuItem(iconCopy, 'Copy Text', onCopyText)
const pngExport = createMenuItem(iconCamera, 'Screenshot', exportToPng)
const mdExport = createMenuItem(iconMarkdown, 'Markdown', exportToMarkdown)
const htmlExport = createMenuItem(fileCode, 'WebPage (HTML)', exportToHtml)
const container = createMenuContainer()
dropdown.append(textExport, pngExport, mdExport, htmlExport)
container.append(exportButton, dropdown, divider)
})
}
function createMenuContainer() {
const container = document.createElement('div')
container.id = 'exporter-menu'
container.className = 'pt-1 relative'
sentinel.on('nav', (nav) => {
const chatList = document.querySelector('nav > div.overflow-y-auto')
if (chatList) {
chatList.after(container)
}
else {
nav.append(container)
}
})
return container
}
function createDivider() {
const divider = document.createElement('div')
divider.className = 'border-b border-white/20'
return divider
}
function createMenuItem(icon: string, title: string, onClick: (e: MouseEvent) => void) {
const menuItem = document.createElement('a')
menuItem.className = 'flex py-3 px-3 items-center gap-3 rounded-md hover:bg-gray-500/10 transition-colors duration-200 text-white cursor-pointer text-sm mb-2 flex-shrink-0 border border-white/20'
menuItem.removeAttribute('href')
menuItem.innerHTML = `${icon}${title}`
menuItem.addEventListener('click', onClick)
return menuItem
}
function exportToMarkdown() {
const items = getConversation()
if (items.length === 0) return alert('No conversation found. Please send a message first.')
const text = conversationToMarkdown(items)
downloadFile(`chatgpt-${timestamp()}.md`, 'text/markdown', text)
}
function exportToHtml() {
const items = getConversation()
if (items.length === 0) return alert('No conversation found. Please send a message first.')
const lang = document.documentElement.lang ?? 'en'
const conversationHtml = items.map((item) => {
const { author: { name, avatar }, lines } = item
const avatarEl = name === 'ChatGPT'
? `${chatGPTAvatarSVG}`
: `<img src="${avatar}" alt="${name}" />`
const linesHtml = lines.map((line) => {
const lineHtml = line.map((item) => {
switch (item.type) {
case 'text':
return escapeHtml(item.text)
case 'image':
return `<img src="${item.src}" referrerpolicy="no-referrer" />`
case 'code':
return `<code>${escapeHtml(item.code)}</code>`
case 'code-block':
return `<pre><code class="language-${item.lang}">${escapeHtml(item.code)}</code></pre>`
case 'link':
return `<a href="${item.href}" target="_blank" rel="noopener noreferrer">${escapeHtml(item.text)}</a>`
case 'ordered-list-item':
return `<ol>${item.items.map(item => `<li>${escapeHtml(item)}</li>`).join('')}</ol>`
case 'unordered-list-item':
return `<ul>${item.items.map(item => `<li>${escapeHtml(item)}</li>`).join('')}</ul>`
case 'table': {
const header = item.headers.map(item => `<th>${escapeHtml(item)}</th>`).join('')
const body = item.rows.map(row => `<tr>${row.map(item => `<td>${escapeHtml(item)}</td>`).join('')}</tr>`).join('')
return `<table><thead><tr>${header}</tr></thead><tbody>${body}</tbody></table>`
}
default:
return ''
}
}).join('')
const skipTags = ['pre', 'ul', 'ol', 'table']
if (skipTags.some(tag => lineHtml.startsWith(`<${tag}>`))) return lineHtml
return `<p>${lineHtml}</p>`
}).join('')
return `
<div class="conversation-item">
<div class="author">
${avatarEl}
</div>
<div class="conversation-content">
${linesHtml}
</div>
</div>`
}).join('')
const html = templateHtml
.replace('{{time}}', new Date().toISOString())
.replace('{{lang}}', lang)
.replace('{{content}}', conversationHtml)
const fileName = `ChatGPT-${timestamp()}.html`
downloadFile(fileName, 'text/html', html)
}
async function exportToPng() {
const thread = document.querySelector('main .group')?.parentElement as HTMLElement
if (!thread || thread.children.length === 0) return
// hide bottom bar
thread.children[thread.children.length - 1].classList.add('hidden')
await sleep(100)
const canvas = await html2canvas(thread, {
scrollX: -window.scrollX,
scrollY: -window.scrollY,
windowWidth: thread.scrollWidth,
windowHeight: thread.scrollHeight,
})
// restore the layout
thread.children[thread.children.length - 1].classList.remove('hidden')
const dataUrl = canvas.toDataURL('image/png', 1)
.replace(/^data:image\/[^;]/, 'data:application/octet-stream')
const fileName = `ChatGPT-${timestamp()}.png`
downloadUrl(fileName, dataUrl)
}
function getConversation(): Conversation[] {
const items: Conversation[] = []
document.querySelectorAll('main .group').forEach((item) => {
const avatarEl = item.querySelector<HTMLImageElement>('span img:not([aria-hidden="true"])')
// actually we can get the name from the avatar's alt
// but let's keep it anonymous for privacy reasons
const name = avatarEl?.getAttribute('alt') ? 'You' : 'ChatGPT'
const avatar = avatarEl ? getBase64FromImg(avatarEl) : ''
const textNode = <HTMLDivElement>item.querySelector('.markdown') ?? item.querySelector('.w-full .whitespace-pre-wrap')
if (!textNode) return
const lines = parseTextNode(textNode)
items.push({ author: { name, avatar }, lines })
})
return items
}
function parseTextNode(textNode: HTMLDivElement): ConversationLine[] {
const warningClassName = 'bg-orange-500/10'
const dangerClassName = 'bg-red-500/10'
const childNodes = textNode.childNodes ? Array.from(textNode.childNodes) : []
const validChildNodes = childNodes.filter((c) => {
if (c instanceof Text) return true
// filter out the alert box
if (c instanceof Element) {
return !(c.classList.contains(warningClassName) || c.classList.contains(dangerClassName))
}
// other nodes are not supported
return false
})
if (validChildNodes.length === 0) return [[{ type: 'text', text: textNode.textContent ?? '' }]]
if (validChildNodes.length === 1 && validChildNodes[0] instanceof Text) return [[{ type: 'text', text: validChildNodes[0].textContent ?? '' }]]
const lines: ConversationLine[] = []
Array.from(textNode.children).forEach((child) => {
if (child.classList.contains(warningClassName)) return
if (child.classList.contains(dangerClassName)) return
switch (child.tagName.toUpperCase()) {
case 'PRE': {
const codeEl = child.querySelector('code')
if (codeEl) {
const code = codeEl.textContent ?? ''
const classList = Array.from(codeEl.classList)
const lang = classList.find(c => c.startsWith('language-'))?.replace('language-', '') ?? ''
lines.push([{ type: 'code-block', lang, code }])
}
break
}
case 'OL': {
const items = Array.from(child.children).map(item => item.textContent ?? '')
lines.push([{ type: 'ordered-list-item', items }])
break
}
case 'UL': {
const items = Array.from(child.children).map(item => item.textContent ?? '')
lines.push([{ type: 'unordered-list-item', items }])
break
}
case 'TABLE': {
const headers = Array.from(child.querySelector('thead tr')?.children ?? []).map(item => item.textContent ?? '')
const rows = Array.from(child.querySelector('tbody')?.children ?? []).map(row => Array.from(row.children).map(item => item.textContent ?? ''))
lines.push([{ type: 'table', headers, rows }])
break
}
case 'P':
default: {
const line: ConversationLine = []
const nodes = Array.from(child.childNodes)
if (nodes.length === 0) {
const text = child.textContent ?? ''
line.push({ type: 'text', text })
}
else {
nodes.forEach((item) => {
switch (item.nodeType) {
// code
case 1: {
// detect is it a link
if ('href' in item) {
const href = (<HTMLAnchorElement>item).getAttribute('href') ?? ''
const text = item.textContent ?? href
line.push({ type: 'link', text, href })
}
// detect is it an image
else if ((<HTMLImageElement>item).tagName?.toUpperCase() === 'IMG') {
const src = (<HTMLImageElement>item).getAttribute('src') ?? ''
line.push({ type: 'image', src })
}
else {
const text = item.textContent ?? ''
line.push({ type: 'code', code: text })
}
break
}
// text
case 3:
default: {
const text = item.textContent ?? ''
line.push({ type: 'text', text })
break
}
}
})
}
lines.push(line)
break
}
}
})
return lines
}
function conversationToText(conversation: Conversation[]) {
return conversation.map((item) => {
const { author: { name }, lines } = item
const text = lines.map(line => lineToText(line)).join('\r\n\r\n')
return `${name}:\r\n${text}`
}).join('\r\n\r\n')
}
function conversationToMarkdown(conversation: Conversation[]) {
return conversation.map((item) => {
const { author: { name }, lines } = item
const text = lines.map(line => lineToText(line)).join('\r\n\r\n')
return `#### ${name}:\r\n${text}`
}).join('\r\n\r\n')
}
function lineToText(line: ConversationLine): string {
return line.map((item) => {
switch (item.type) {
case 'text': return item.text
case 'image': return '[image]'
case 'link': return `[${item.text}](${item.href})`
case 'ordered-list-item': return item.items.map((item, index) => `${index + 1}. ${item}`).join('\r\n')
case 'unordered-list-item': return item.items.map(item => `- ${item}`).join('\r\n')
case 'code': return `\`${item.code}\``
case 'code-block': return `\`\`\`${item.lang}\r\n${item.code}\`\`\``
case 'table': return transformTableToMarkdown(item.headers, item.rows)
default: return ''
}
}).join('')
}
function transformTableToMarkdown(headers: string[], rows: string[][]): string {
let markdown = ''
// Find the maximum width of each column
const columnWidths: number[] = []
for (let i = 0; i < headers.length; i++) {
let maxWidth = headers[i].length
rows.forEach((row) => {
maxWidth = Math.max(maxWidth, row[i].length)
})
columnWidths.push(maxWidth)
}
// Add the headers
markdown += `${headers.map((header, i) => header.padEnd(columnWidths[i])).join(' | ')}\n`
markdown += `${headers.map((_header, i) => '-'.repeat(columnWidths[i])).join(' | ')}\n`
// Add the rows
rows.forEach((row) => {
markdown += `${row.map((cell, i) => cell.padEnd(columnWidths[i])).join(' | ')}\n`
})
return markdown
}

View File

@@ -0,0 +1,24 @@
import sentinel from 'sentinel-js'
import { render } from 'preact'
import { Menu } from './menu'
import { onloadSafe } from './utils/utils'
main()
function main() {
onloadSafe(() => {
const container = document.createElement('div')
render(<Menu />, container)
sentinel.on('nav', (nav) => {
const chatList = document.querySelector('nav > div.overflow-y-auto')
if (chatList) {
chatList.after(container)
}
else {
// fallback to the bottom of the nav
nav.append(container)
}
})
})
}

View File

@@ -0,0 +1,63 @@
import type { FunctionComponent } from 'preact'
import { exportToText } from './exporter/text'
import { exportToPng } from './exporter/image'
import { exportToMarkdown } from './exporter/markdown'
import { exportToHtml } from './exporter/html'
import { FileCode, IconArrowRightFromBracket, IconCamera, IconCopy, IconMarkdown } from './icons'
import './style.css'
type FC<P = {}> = FunctionComponent<P>
interface MenuItemProps {
onClick?: () => void
}
const MenuItem: FC<MenuItemProps> = ({ children, onClick }) => {
return (
<div
className="flex py-3 px-3 items-center gap-3 rounded-md hover:bg-gray-500/10 transition-colors duration-200 text-white cursor-pointer text-sm mb-2 flex-shrink-0 border border-white/20"
onClick={onClick}
>
{children}
</div>
)
}
const Dropdown: FC = ({ children }) => {
return (
<div className="dropdown-menu bg-gray-900">
{children}
</div>
)
}
const Divider = () => <div className="border-b border-white/20"></div>
export function Menu() {
return (
<div id="exporter-menu" className="pt-1 relative">
<MenuItem>
<IconArrowRightFromBracket />
Export
</MenuItem>
<Dropdown>
<MenuItem onClick={exportToText}>
<IconCopy />
Copy Text
</MenuItem>
<MenuItem onClick={exportToPng}>
<IconCamera />
Screenshot
</MenuItem>
<MenuItem onClick={exportToMarkdown}>
<IconMarkdown />
Markdown
</MenuItem>
<MenuItem onClick={exportToHtml}>
<FileCode />
WebPage (HTML)
</MenuItem>
</Dropdown>
<Divider />
</div>
)
}

View File

@@ -0,0 +1,130 @@
import type { Conversation, ConversationLine } from './type'
export function getConversation(): Conversation[] {
const items: Conversation[] = []
document.querySelectorAll('main .group').forEach((item) => {
const avatarEl = item.querySelector<HTMLImageElement>('span img:not([aria-hidden="true"])')
// actually we can get the name from the avatar's alt
// but let's keep it anonymous for privacy reasons
const name = avatarEl?.getAttribute('alt') ? 'You' : 'ChatGPT'
const avatar = avatarEl ? getBase64FromImg(avatarEl) : ''
const textNode = item.querySelector<HTMLDivElement>('.markdown') ?? item.querySelector('.w-full .whitespace-pre-wrap')
if (!textNode) return
const lines = parseTextNode(textNode)
items.push({ author: { name, avatar }, lines })
})
return items
}
function parseTextNode(textNode: HTMLDivElement): ConversationLine[] {
const warningClassName = 'bg-orange-500/10'
const dangerClassName = 'bg-red-500/10'
const childNodes = textNode.childNodes ? Array.from(textNode.childNodes) : []
const validChildNodes = childNodes.filter((c) => {
if (c instanceof Text) return true
// filter out the alert box
if (c instanceof Element) {
return !(c.classList.contains(warningClassName) || c.classList.contains(dangerClassName))
}
// other nodes are not supported
return false
})
if (validChildNodes.length === 0) return [[{ type: 'text', text: textNode.textContent ?? '' }]]
if (validChildNodes.length === 1 && validChildNodes[0] instanceof Text) return [[{ type: 'text', text: validChildNodes[0].textContent ?? '' }]]
const lines: ConversationLine[] = []
Array.from(textNode.children).forEach((child) => {
if (child.classList.contains(warningClassName)) return
if (child.classList.contains(dangerClassName)) return
switch (child.tagName.toUpperCase()) {
case 'PRE': {
const codeEl = child.querySelector('code')
if (codeEl) {
const code = codeEl.textContent ?? ''
const classList = Array.from(codeEl.classList)
const lang = classList.find(c => c.startsWith('language-'))?.replace('language-', '') ?? ''
lines.push([{ type: 'code-block', lang, code }])
}
break
}
case 'OL': {
const items = Array.from(child.children).map(item => item.textContent ?? '')
lines.push([{ type: 'ordered-list-item', items }])
break
}
case 'UL': {
const items = Array.from(child.children).map(item => item.textContent ?? '')
lines.push([{ type: 'unordered-list-item', items }])
break
}
case 'TABLE': {
const headers = Array.from(child.querySelector('thead tr')?.children ?? []).map(item => item.textContent ?? '')
const rows = Array.from(child.querySelector('tbody')?.children ?? []).map(row => Array.from(row.children).map(item => item.textContent ?? ''))
lines.push([{ type: 'table', headers, rows }])
break
}
case 'P':
default: {
const line: ConversationLine = []
const nodes = Array.from(child.childNodes)
if (nodes.length === 0) {
const text = child.textContent ?? ''
line.push({ type: 'text', text })
}
else {
nodes.forEach((item) => {
switch (item.nodeType) {
// code
case 1: {
// detect is it a link
if ('href' in item) {
const href = (item as HTMLAnchorElement).getAttribute('href') ?? ''
const text = item.textContent ?? href
line.push({ type: 'link', text, href })
}
// detect is it an image
else if ((item as HTMLImageElement).tagName?.toUpperCase() === 'IMG') {
const src = (item as HTMLImageElement).getAttribute('src') ?? ''
line.push({ type: 'image', src })
}
else {
const text = item.textContent ?? ''
line.push({ type: 'code', code: text })
}
break
}
// text
case 3:
default: {
const text = item.textContent ?? ''
line.push({ type: 'text', text })
break
}
}
})
}
lines.push(line)
break
}
}
})
return lines
}
function getBase64FromImg(el: HTMLImageElement) {
const canvas = document.createElement('canvas')
canvas.width = el.naturalWidth
canvas.height = el.naturalHeight
const ctx = canvas.getContext('2d')
if (!ctx) return ''
ctx.drawImage(el, 0, 0)
return canvas.toDataURL('image/png')
}

View File

@@ -0,0 +1,19 @@
export type ConversationLineNode = |
{ type: 'text'; text: string } |
{ type: 'image'; src: string } |
{ type: 'code'; code: string } |
{ type: 'code-block'; lang: string; code: string } |
{ type: 'link'; text: string; href: string } |
{ type: 'ordered-list-item'; items: string[] } |
{ type: 'unordered-list-item'; items: string[] } |
{ type: 'table'; headers: string[]; rows: string[][] }
export type ConversationLine = ConversationLineNode[]
export interface Conversation {
author: {
name: string
avatar: string
}
lines: ConversationLine[]
}

View File

@@ -1,70 +0,0 @@
export function onloadSafe(fn: () => void) {
if (document.readyState === 'complete') {
fn()
}
else {
window.addEventListener('load', fn)
}
}
export function copyToClipboard(text: string) {
try {
// modern browsers
navigator.clipboard.writeText(text)
}
catch {
const textarea = document.createElement('textarea')
textarea.value = text
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}
}
export function downloadFile(filename: string, type: string, content: string) {
const blob = new Blob([content], { type })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
export function downloadUrl(filename: string, url: string) {
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
export function getBase64FromImg(el: HTMLImageElement) {
const canvas = document.createElement('canvas')
canvas.width = el.naturalWidth
canvas.height = el.naturalHeight
const ctx = canvas.getContext('2d')
if (!ctx) return ''
ctx.drawImage(el, 0, 0)
return canvas.toDataURL('image/png')
}
export function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms))
}
export function timestamp() {
return new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '')
}
export function escapeHtml(html: string) {
return html
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;')
}

View File

@@ -0,0 +1,14 @@
export function copyToClipboard(text: string) {
try {
// for modern browsers
navigator.clipboard.writeText(text)
}
catch {
const textarea = document.createElement('textarea')
textarea.value = text
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}
}

View File

@@ -0,0 +1,19 @@
export function downloadFile(filename: string, type: string, content: string) {
const blob = new Blob([content], { type })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
export function downloadUrl(filename: string, url: string) {
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}

View File

@@ -0,0 +1,24 @@
export function tableToMarkdown(headers: string[], rows: string[][]): string {
let markdown = ''
// Find the maximum width of each column
const columnWidths: number[] = []
for (let i = 0; i < headers.length; i++) {
let maxWidth = headers[i].length
rows.forEach((row) => {
maxWidth = Math.max(maxWidth, row[i].length)
})
columnWidths.push(maxWidth)
}
// Add the headers
markdown += `${headers.map((header, i) => header.padEnd(columnWidths[i])).join(' | ')}\n`
markdown += `${headers.map((_header, i) => '-'.repeat(columnWidths[i])).join(' | ')}\n`
// Add the rows
rows.forEach((row) => {
markdown += `${row.map((cell, i) => cell.padEnd(columnWidths[i])).join(' | ')}\n`
})
return markdown
}

View File

@@ -0,0 +1,17 @@
export function onloadSafe(fn: () => void) {
if (document.readyState === 'complete') {
fn()
}
else {
window.addEventListener('load', fn)
}
}
export function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms))
}
export function timestamp() {
return new Date().toISOString().replace(/:/g, '-').replace(/\..+/, '')
}

View File

@@ -2,7 +2,9 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"types": ["vite/client"]
"types": ["vite/client"],
"jsx": "react-jsx",
"jsxImportSource": "preact",
},
"include": [
"src",

View File

@@ -1,5 +1,6 @@
import { defineConfig } from 'vite'
import monkey from 'vite-plugin-monkey'
import preact from '@preact/preset-vite'
import packageJson from './package.json'
// https://vitejs.dev/config/
@@ -9,8 +10,12 @@ export default defineConfig({
charset: 'utf8',
},
plugins: [
preact({
devToolsEnabled: false,
devtoolsInProd: false,
}),
monkey({
entry: 'src/main.ts',
entry: 'src/main.tsx',
userscript: {
'name': packageJson.title,
'author': packageJson.author,

710
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff