initial commit
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
export function generateId(prefix = 'id'): string {
|
||||
return `${prefix}-${Date.now()}-${Math.random().toString(16).slice(2, 10)}`
|
||||
}
|
||||
|
||||
export function formatTime(timestamp: number): string {
|
||||
const date = new Date(timestamp)
|
||||
const year = date.getFullYear()
|
||||
const month = `${date.getMonth() + 1}`.padStart(2, '0')
|
||||
const day = `${date.getDate()}`.padStart(2, '0')
|
||||
const hours = `${date.getHours()}`.padStart(2, '0')
|
||||
const minutes = `${date.getMinutes()}`.padStart(2, '0')
|
||||
return `${year}-${month}-${day} ${hours}:${minutes}`
|
||||
}
|
||||
|
||||
export function buildSessionTitle(message: string): string {
|
||||
const normalized = message.replace(/\s+/g, ' ').trim()
|
||||
if (!normalized) return '新对话'
|
||||
|
||||
return normalized.length > 20 ? `${normalized.slice(0, 20)}...` : normalized
|
||||
}
|
||||
|
||||
export function getErrorMessage(error: unknown): string {
|
||||
if (!error) return '未知错误'
|
||||
|
||||
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||
return '请求已停止'
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message || '请求失败,请稍后重试'
|
||||
}
|
||||
|
||||
return '请求失败,请稍后重试'
|
||||
}
|
||||
|
||||
export function validateHttpUrl(url: string): boolean {
|
||||
try {
|
||||
const parsedUrl = new URL(url)
|
||||
return ['http:', 'https:'].includes(parsedUrl.protocol)
|
||||
} catch (_error) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* 页面处于隐藏状态时,拦截原生 `history.replaceState`。
|
||||
*
|
||||
* ── 起因 ────────────────────────────────────────────────────────────────
|
||||
* vue-router 4.6.4 在创建 history 时**无条件**注册(源码见
|
||||
* node_modules/vue-router/dist/vue-router.mjs 的 createRouterHistory,
|
||||
* 不受是否配置 `scrollBehavior` 影响):
|
||||
*
|
||||
* document.addEventListener('visibilitychange', beforeUnloadListener)
|
||||
*
|
||||
* 该监听器在每次「切标签 / 最小化窗口 / 切到后台」时执行:
|
||||
*
|
||||
* if (document.visibilityState === 'hidden') {
|
||||
* if (!history.state) return
|
||||
* history.replaceState({ ...state, scroll: getScroll() }, '')
|
||||
* }
|
||||
*
|
||||
* 而 Edge 对「文档处于 hidden 状态时写入 history」会做出反应 ——
|
||||
* **把最小化的窗口拉回前台**。表现为:功能完全正常、无任何报错或日志,
|
||||
* 但浏览器一最小化就立刻自动还原;无痕窗口不复现;换任何其他站点也不复现。
|
||||
*
|
||||
* 本项目并没有配置 `scrollBehavior`,这次写入完全无用,因此直接拦掉。
|
||||
*
|
||||
* ── 为什么拦在原语这一层,而不是拦 vue-router ───────────────────────────
|
||||
* vue-router 的 `u()` 照常运行、照常调用 replaceState;被替换的只是
|
||||
* `history.replaceState` 这个原生 API 本身 —— 最后一道边界。拦在原语上意味着
|
||||
* 无论将来 vue-router 换实现,还是我们自己写了别的代码想在页面隐藏时改动
|
||||
* history,都会被同样拦住。这才是要守住的规则本身:「页面不可见时不要改动
|
||||
* 浏览器历史记录」。
|
||||
*
|
||||
* ── ⚠️ Phase 3 接入 CEF 前必须保留本文件 ────────────────────────────────
|
||||
* CEF 窗口同样会跑 vue-router、同样会触发这条路径。桌面程序的窗口自己弹回
|
||||
* 前台是严重缺陷,不是观感问题,所以这个修复是 Phase 3 的前置条件。
|
||||
*
|
||||
* 排查过程见 `.scratch/改造计划.md`。
|
||||
*/
|
||||
|
||||
if (typeof window !== 'undefined' && typeof history !== 'undefined') {
|
||||
const originalReplaceState = history.replaceState.bind(history)
|
||||
|
||||
history.replaceState = function patchedReplaceState(
|
||||
state: Parameters<History['replaceState']>[0],
|
||||
unused: Parameters<History['replaceState']>[1],
|
||||
url?: Parameters<History['replaceState']>[2],
|
||||
): void {
|
||||
if (document.visibilityState === 'hidden') {
|
||||
// 页面不可见时改动 history 会让 Edge 把最小化的窗口拉回前台
|
||||
return
|
||||
}
|
||||
originalReplaceState(state, unused, url)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import MarkdownIt from 'markdown-it'
|
||||
import hljs from 'highlight.js/lib/core'
|
||||
import javascript from 'highlight.js/lib/languages/javascript'
|
||||
import json from 'highlight.js/lib/languages/json'
|
||||
import 'highlight.js/styles/github.css'
|
||||
|
||||
hljs.registerLanguage('javascript', javascript)
|
||||
hljs.registerLanguage('json', json)
|
||||
|
||||
const CODE_LANGUAGES = ['sql', 'javascript', 'typescript', 'java', 'python', 'json', 'html', 'css', 'bash', 'shell', 'vue', 'xml', 'yaml', 'markdown']
|
||||
const LANGUAGE_ALIASES: Record<string, string> = {
|
||||
js: 'javascript',
|
||||
jsx: 'javascript',
|
||||
ts: 'typescript',
|
||||
tsx: 'typescript',
|
||||
sh: 'bash',
|
||||
shell: 'bash',
|
||||
zsh: 'bash',
|
||||
yml: 'yaml',
|
||||
md: 'markdown',
|
||||
text: 'plaintext',
|
||||
}
|
||||
const CODE_FENCE_PATTERN = /```[\s\S]*?```/
|
||||
const CODE_FENCE_LINE_PATTERN = /^```/gm
|
||||
const SQL_KEYWORDS = /\b(select|insert|update|delete|create|alter|drop|from|where|join|group by|order by|limit)\b/i
|
||||
const CODE_STRUCTURE_PATTERN = /[{};<>]|\b(function|const|let|var|public|private|class|interface|return|import|export|try|catch|async|await)\b/
|
||||
|
||||
function escapeCodeHtml(code: string): string {
|
||||
return code
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
function escapeAttribute(value: string): string {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
}
|
||||
|
||||
function normalizeLanguage(language = ''): string {
|
||||
const normalized = language.trim().toLowerCase()
|
||||
return LANGUAGE_ALIASES[normalized] || normalized || 'plaintext'
|
||||
}
|
||||
|
||||
function getDisplayLanguage(language: string): string {
|
||||
return language === 'plaintext' ? 'text' : language
|
||||
}
|
||||
|
||||
function detectCodeLanguage(content: string): string {
|
||||
const normalized = content.trim().toLowerCase()
|
||||
|
||||
if (SQL_KEYWORDS.test(normalized)) return 'sql'
|
||||
if (/^\s*[{[]/.test(content) && /[}\]]\s*$/.test(content)) return 'json'
|
||||
if (/<[a-z][\s\S]*?>/i.test(content)) return 'html'
|
||||
if (/\b(interface|type|implements|readonly|enum)\b/.test(normalized)) return 'typescript'
|
||||
if (/\b(system\.out\.println|public static void main|new \w+\()/i.test(content)) return 'java'
|
||||
if (/\b(def |import |from .+ import |print\()/i.test(content)) return 'python'
|
||||
if (/\b(const|let|var|function|=>|console\.log)\b/.test(normalized)) return 'javascript'
|
||||
if (/\b(selectors?|padding|margin|color|background|display|flex)\s*:/i.test(content)) return 'css'
|
||||
if (/^(npm|pnpm|yarn|git|curl|docker|cd|ls|dir)\b/im.test(content)) return 'bash'
|
||||
|
||||
return 'plaintext'
|
||||
}
|
||||
|
||||
function shouldRenderAsCode(content: string): boolean {
|
||||
const trimmed = content.trim()
|
||||
if (!trimmed || CODE_FENCE_PATTERN.test(trimmed)) return false
|
||||
|
||||
const lines = trimmed.split(/\r?\n/).filter((line) => line.trim())
|
||||
if (lines.length >= 2 && (SQL_KEYWORDS.test(trimmed) || CODE_STRUCTURE_PATTERN.test(trimmed))) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (lines.length === 1) {
|
||||
return /^(select|insert|update|delete)\b/i.test(trimmed) || /^[{[]/.test(trimmed)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function normalizeMarkdownContent(content: string): string {
|
||||
if (!shouldRenderAsCode(content)) {
|
||||
return content
|
||||
}
|
||||
|
||||
const language = detectCodeLanguage(content)
|
||||
if (CODE_LANGUAGES.includes(language) || language === 'plaintext') {
|
||||
return `\n\n\`\`\`${language}\n${content.trim()}\n\`\`\`\n\n`
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
function closeUnclosedCodeFence(content: string): string {
|
||||
const fenceCount = content.match(CODE_FENCE_LINE_PATTERN)?.length || 0
|
||||
return fenceCount % 2 === 1 ? `${content}\n\`\`\`` : content
|
||||
}
|
||||
|
||||
const markdown: MarkdownIt = new MarkdownIt({
|
||||
html: false,
|
||||
linkify: true,
|
||||
breaks: true,
|
||||
typographer: true,
|
||||
highlight(code: string, language: string): string {
|
||||
const normalizedLanguage = normalizeLanguage(language)
|
||||
const languageLabel = hljs.getLanguage(normalizedLanguage) ? normalizedLanguage : 'plaintext'
|
||||
const displayLanguage = getDisplayLanguage(languageLabel)
|
||||
const highlightedCode = hljs.getLanguage(languageLabel)
|
||||
? hljs.highlight(code, { language: languageLabel }).value
|
||||
: escapeCodeHtml(code)
|
||||
|
||||
return `
|
||||
<div class="md-code-block" data-language="${escapeAttribute(displayLanguage)}">
|
||||
<div class="md-code-block__toolbar">
|
||||
<span class="md-code-block__language">${escapeAttribute(displayLanguage)}</span>
|
||||
<button type="button" class="md-code-block__copy" aria-label="复制代码">复制代码</button>
|
||||
</div>
|
||||
<pre class="hljs"><code>${highlightedCode}</code></pre>
|
||||
</div>
|
||||
`
|
||||
},
|
||||
})
|
||||
|
||||
const defaultLinkOpenRenderer = markdown.renderer.rules.link_open
|
||||
markdown.renderer.rules.link_open = (tokens, index, options, env, self) => {
|
||||
const token = tokens[index]
|
||||
const hrefIndex = token.attrIndex('href')
|
||||
|
||||
if (hrefIndex >= 0) {
|
||||
token.attrSet('target', '_blank')
|
||||
token.attrSet('rel', 'noopener noreferrer')
|
||||
}
|
||||
|
||||
return defaultLinkOpenRenderer ? defaultLinkOpenRenderer(tokens, index, options, env, self) : self.renderToken(tokens, index, options)
|
||||
}
|
||||
|
||||
markdown.renderer.rules.table_open = () => '<div class="md-table-wrapper"><table>\n'
|
||||
markdown.renderer.rules.table_close = () => '</table></div>\n'
|
||||
|
||||
export function renderMarkdown(content = ''): string {
|
||||
const normalizedContent = normalizeMarkdownContent(content)
|
||||
return markdown.render(closeUnclosedCodeFence(normalizedContent))
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
function notifyStorageError(action: string, key: string, error: unknown): void {
|
||||
const isQuotaExceeded = error instanceof DOMException && (
|
||||
error.name === 'QuotaExceededError' ||
|
||||
error.name === 'NS_ERROR_DOM_QUOTA_REACHED' ||
|
||||
error.code === 22 ||
|
||||
error.code === 1014
|
||||
)
|
||||
|
||||
const message = isQuotaExceeded
|
||||
? '本地存储空间不足,保存失败。建议删除部分历史会话、减少图片附件或导出备份后清理数据。'
|
||||
: `${action}失败:${key}`
|
||||
|
||||
ElMessage.error(message)
|
||||
console.error(`${action}本地存储失败: ${key}`, error)
|
||||
}
|
||||
|
||||
export function loadLocalStorage<T>(key: string, defaultValue: T): T {
|
||||
try {
|
||||
const rawValue = localStorage.getItem(key)
|
||||
return rawValue ? (JSON.parse(rawValue) as T) : defaultValue
|
||||
} catch (error) {
|
||||
notifyStorageError('读取', key, error)
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
export function saveLocalStorage<T>(key: string, value: T): void {
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value))
|
||||
} catch (error) {
|
||||
notifyStorageError('保存', key, error)
|
||||
}
|
||||
}
|
||||
|
||||
export function removeLocalStorage(key: string): void {
|
||||
try {
|
||||
localStorage.removeItem(key)
|
||||
} catch (error) {
|
||||
notifyStorageError('删除', key, error)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user